Monday, April 12, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


poruqe se corta la conexion al utilizar ipdinamica con duckdns

Posted: 12 Apr 2021 08:07 AM PDT

tengo un sitio desde mi pc el cual lo publico por medio de xampp y como tengo ipdinamica utilizo duckdns, problema:

  1. mas o menos cada 2 minutos se corta la conexión y presenta

    502 Bad Gateway

    502 Bad Gateway

he observado la trazabilidad de la red pero no he visto nada raro

Ignoring header X-Firebase-Locale because its value was null. problem flutter

Posted: 12 Apr 2021 08:07 AM PDT

firstly i saw this subject in the other pages, but i can't solve with them's solutions. Now, everything is okey (i think) but system gives this error: Ignoring header X-W/System (14532): Ignoring header X-Firebase-Locale because its value was null.

Why it gives this error? Please help me...

Unknown column in foreign key definition

Posted: 12 Apr 2021 08:07 AM PDT

I'm trying to add a new table to an already existing database but it keeps giving me an error "Unknown column 'product_id' in foreign key definition".

CREATE TABLE product_review (      prod_review_ref_no INTEGER PRIMARY KEY AUTOINCREMENT,      review TEXT NOT NULL,      comment TEXT NOT NULL,      date TEXT NOT NULL,      time TEXT NOT NULL,      FOREIGN KEY (product_id) REFERENCES products(product_id)  );  

Any help would be appreciated, kind regards

Django admin dependent drop down (no models)

Posted: 12 Apr 2021 08:07 AM PDT

models.py

class Document(models.Model):    word_type = models.CharField(max_length=255, choices=[('noun', 'noun'), ('verb', 'verb'),                       ('adjektive', 'adjektive')], default='noun')  word = models.CharField(max_length=255)  article = models.CharField(max_length=255, choices=Static.article_choices, default='')  

forms.py

class DocumentForm(forms.ModelForm):  class Meta:      model = Document      fields = ['word_type', 'word', 'article', 'audio']    def __init__(self, *args, **kwargs):      super(DocumentForm, self).__init__(*args, **kwargs)      if self.instance.word_type == "noun":          self.fields['article'].choices = [('the', 'the')]      else:          self.fields['article'].choices = [('-', '-')]  

I have a model 'document'. When creating a document object in django admin, I want the article dropdown (actual language has several articles) only to show up when 'noun' is selected as word type. Currently I got it working to update the choices to '-' if it's not a noun, but the dropdown only updates with init. So I'm looking for a way to update the article dropdown automatically when word type changes. Maybe there is another (better) way of doing it, would be great if there was a solution to make article dropdown completely disappear when 'verb' or 'adjective' is selected as word type. I'm fairly new to django, couldn't find a solution for this since most tutorials assume article and word_type are dependent models, which is not the case for me.

Implementation of Group seasonal indices GSI method in python

Posted: 12 Apr 2021 08:07 AM PDT

I need to group time series of different SKUs with the same seasonal patterns. Please any practical seggetions. I found many papers describing such methods (group seasonal indices (GSI)) , I'm asking whether there is any implementation of such methods in Python.

''Estimating seasonal variations in demand is a challenging task faced by many organisations. There may be many stock-keeping units (SKUs) to forecast, but often data histories are short, with very few complete seasonal cycles. It has been suggested in the literature that group seasonal indices (GSI) methods should be used to take advantage of information on similar SKUs.''' Formation of seasonal groups and application of seasonal indices

Thank you in advance

javascript variable cannot been redeclared but cannot been accesed, too

Posted: 12 Apr 2021 08:07 AM PDT

I'm a newcomer in Javascript. I have two files with js code. file a.js contains

const words = ["Alpha", "Bita", "Gama"];  console.log(words);  

file b.js contains

//@ts-check  const words = ["Alpha", "Bita", "Gama"];  console.log(words);  

Both a.js and b.js are located in folder src under the root In the root, I also have a jsconfig.json

{      "compilerOptions": {          "outDir": "./built",          "module": "commonjs",          "target": "es6",               },      "exclude": [          "node_modules",          "**/node_modules/*"      ]  }  

In file b.js, I receive an error "Cannot redeclare block-scoped variable 'words'." When I comment out the declaration of words in b.js, I don't receive any error, but when running file b.js, I receive a "ReferenceError: words is not defined".

I know that erasing the //@ts-check in b.js will fix the problem, but I cannot understand why type checking produces this behaviour. What is the meaning to keep a variable in scope if you are not allowed to access it? I use Visual Studio Code and run with node.

VB .net datagridview properties via variable

Posted: 12 Apr 2021 08:07 AM PDT

This may be a weird question. Just out of curiosity asking it to learn/check if this can be really achieved or not? Normally we can change the datagridview(name of the grid is dgv) properties like below

Prp_Value = 150  dgv.Columns(columnName).Width = Prp_Value  Prp_Value = "Header Text"  dgv.Columns(columnName).HeaderText = Prp_Value  Prp_Value = 0  dgv.Columns(columnName).DisplayIndex = Prp_Value  Prp_Value = True  dgv.Columns(columnName).Visible = Prp_Value  

What I am checking here is that can we able to access the properties via variable (as something like below):

Dim Prp_Type as String   Prp_Type = "Width"  Prp_Value = 150  dgv.Columns(columnName).&"'" Prp_Type &"'" =  Prp_Value  Prp_Type = "HeaderText"  Prp_Value = "Header Text"  dgv.Columns(columnName).&"'" Prp_Type &"'" =  Prp_Value  Prp_Type = "DisplayIndex"  Prp_Value = 0  dgv.Columns(columnName).&"'" Prp_Type &"'" =  Prp_Value  

and so on, because trying to set the datagridview properties by reading the info from XML file. Were xml file content like below (It may have some properties or not like below ex for AutoSizeMode [1st column no AutoSizeMode but for 2nd column its set as true])

      <Name>columnName</Name>        <width>100</width>        <Headertext>ID</Headertext>        <DisplayIndex >0</DisplayIndex >        <Visible >False</Visible>      </column>  <column>        <Name> columnName2 </Name>        <width>102</width>        <Headertext>ID</Headertext>        <DisplayIndex >1</DisplayIndex>        <Visible >True</Visible>        <AutoSizeMode>True</AutoSizeMode>  </column>```    So, let me know whether it is possible or not.    Thank you  

How can I get a custom processing status screen to show progress or records processed

Posted: 12 Apr 2021 08:07 AM PDT

I have a custom process screen which works pretty much as expected, except that the status / monitor screen that pops up during processing doesn't show the progress, or the records processed as it does on other, stock processing screens.

Here's what a stock processing popup looks like:

enter image description here

And here's what my custom popup looks like. It doesn't show 'Remaining' and pretty much just looks like this until it's finished:

enter image description here

And then shows this when finished:

enter image description here

Is there something I need to add to my processing screen to get this functionality?

Thanks much...

Area path error when Source and Target Area Paths are different while migrating Work Items from TFS to Azure through VSTS

Posted: 12 Apr 2021 08:07 AM PDT

Below is the structure in source: Drug Library Editor

Below is the structure in Target: DaVinci\xx\yy\zz\Drug Library

Below is what I have for the query :

"WIQLQueryBit": "AND [System.WorkItemType] = 'Specification' AND [System.AreaPath] Under 'DaVinci\\xx\\yy\\zz\\Drug Library' ",  

Below is the error I get when I am executing the processor, it fails when running the query on the target system to find if the work item has already been migrated:

[07:52:38 DBG] WorkItemQuery: Query: SELECT [System.Id], [System.Tags] FROM WorkItems WHERE [System.TeamProject] = 'DaVinci' AND [System.WorkItemType] = 'Specification' AND [System.AreaPath] Under 'DaVinci\Infusion\Neo\Connectivity\Drug Library'  ORDER BY [System.ChangedDate] desc  [07:52:38 DBG] WorkItemQuery: Paramiters: {"TeamProject": "DaVinci"}  [07:52:38 DBG] WorkItemQuery: TeamProject: DaVinci  [07:54:31 INF] Replay all revisions of 748 work items?  [07:54:31 INF] Found target project as Test_Connectivity  [07:54:31 INF] [FilterWorkItemsThatAlreadyExistInTarget] is enabled. Searching for work items that have already been migrated to the target...  [07:54:31 DBG] FilterExistingWorkItems: START |  [07:54:31 DBG] FilterByTarget: Query Execute...  [07:54:31 DBG] WorkItemQuery: ===========GetWorkItems=============  [07:54:31 DBG] WorkItemQuery: TeamProjectCollection: https://dev.azure.com/BD-MMS-Connectivity/  [07:54:31 DBG] WorkItemQuery: Query: SELECT [System.Id], [Custom.TFSID] FROM WorkItems WHERE [System.TeamProject] = 'Test_Connectivity' AND [System.WorkItemType] = 'Specification' AND [System.AreaPath] Under 'DaVinci\Infusion\Neo\Connectivity\Drug Library'  ORDER BY [System.ChangedDate] desc  [07:54:31 DBG] WorkItemQuery: Paramiters: {"TeamProject": "Test_Connectivity"}  [07:54:31 DBG] WorkItemQuery: TeamProject: Test_Connectivity  [07:54:31 ERR]  Error running query  Microsoft.TeamFoundation.WorkItemTracking.Client.ValidationException: TF51011: The specified area path does not exist. The error is caused by «'DaVinci\Infusion\Neo\Connectivity\Drug Library'».  at Microsoft.TeamFoundation.WorkItemTracking.Client.Query.Initialize(WorkItemStore store, String wiql, IDictionary context, Int32[] ids, Int32[] revs, Boolean dayPrecision)  at Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore.Query(String wiql, IDictionary context)  at MigrationTools._EngineV1.Clients.TfsWorkItemQuery.GetWorkItemsFromQuery(TfsWorkItemMigrationClient wiClient) in D:\a\1\s\src\MigrationTools.Clients.AzureDevops.ObjectModel\_EngineV1\Clients\TfsWorkItemQuery.cs:line 40  [07:54:31 FTL] Error while running WorkItemMigration  Microsoft.TeamFoundation.WorkItemTracking.Client.ValidationException: TF51011: The specified area path does not exist. The error is caused by «'DaVinci\Infusion\Neo\Connectivity\Drug Library'».  at Microsoft.TeamFoundation.WorkItemTracking.Client.Query.Initialize(WorkItemStore store, String wiql, IDictionary context, Int32[] ids, Int32[] revs, Boolean dayPrecision)  at Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore.Query(String wiql, IDictionary context)  at MigrationTools._EngineV1.Clients.TfsWorkItemQuery.GetWorkItemsFromQuery(TfsWorkItemMigrationClient wiClient) in D:\a\1\s\src\MigrationTools.Clients.AzureDevops.ObjectModel\_EngineV1\Clients\TfsWorkItemQuery.cs:line 72  at MigrationTools._EngineV1.Clients.TfsWorkItemQuery.GetWorkItems() in D:\a\1\s\src\MigrationTools.Clients.AzureDevops.ObjectModel\_EngineV1\Clients\TfsWorkItemQuery.cs:line 28  at MigrationTools._EngineV1.Clients.TfsWorkItemMigrationClient.FilterExistingWorkItems(List`1 sourceWorkItems, TfsWiqlDefinition wiqlDefinition, TfsWorkItemMigrationClient sourceWorkItemMigrationClient) in D:\a\1\s\src\MigrationTools.Clients.AzureDevops.ObjectModel\_EngineV1\Clients\TfsWorkItemMigrationClient.cs:line 51  at VstsSyncMigrator.Engine.WorkItemMigrationContext.InternalExecute() in D:\a\1\s\src\VstsSyncMigrator.Core\Execution\MigrationContext\WorkItemMigrationContext.cs:line 117  at MigrationTools._EngineV1.Processors.MigrationProcessorBase.Execute() in D:\a\1\s\src\MigrationTools\_EngineV1\Processors\MigrationProcessorBase.cs:line 47  [07:54:31 ERR] WorkItemMigration The Processor MigrationEngine entered the failed state...stopping run  [07:54:31 INF] Application is shutting down...  [07:54:31 DBG] Hosting stopping  [07:54:31 DBG] Exiting with return code: 0  ``  Of course source Area Path does not exist in Target project. How to resolve this?  Is there a way for the query to use one Area Path when executing in source and another Area path in Target.     

Want Common Nginx configuration on top of all Nginx configs

Posted: 12 Apr 2021 08:06 AM PDT

I have a server where nearly 50 different websites are hosted. Each of them has a separate Nginx config file all of them are listening on port 443 with a different server_name and I want to block a certain location for all websites.

Is there a way that I can add a rule in nginx.conf which is being applied for all the websites, like a parent rule. I tried listening on 443 in nginx.conf without any server_name, it blocked all the other configs.

Please suggest a solution such I can block the .git folder and all path starting with dot to be blocked by Nginx for all website instead of changing in each and every config file.

Read and Write Tab Delimited data in C++ [duplicate]

Posted: 12 Apr 2021 08:06 AM PDT

I have a .txt file with 8760 rows and about 26 columns of tab delimited double format data. What would be the best way to read data in double format from the file, process it and write it back on a different file in the same manner in C++. Thank you.

How to change background color in javascript

Posted: 12 Apr 2021 08:06 AM PDT

Is there any what I could change the background color with javascript? For example:

<div id="factboxes">          <div id="counter">             <div class="factbox">                  <div class="counter-value "><?php echo end($total); ?></div>                  <p>Total Number Of Human Count</p>            </div>                         <div class="factbox factboxgap">                  <div class="counter-value "><?php echo end($current); ?></div>                  <p>Current Number Of Human Count</p>             </div>                          <div class="factbox factboxgap">                  <div class="counter-value "><?php echo count($reserve); ?> </div>                  <p>Total Number of Reservation</p>             </div>          </div>      </div>        <script>          if (<?php $total?> < 85){              document.div.factbox.backgroundColor = "green";          }      </script>  

If the total is less than 85 then the background color will be green. I tried to code in this way but nothing happen. I'm still new with javascript, hope someone could help me and explain how should it be done. Thank you

Unable to bind the parameter in the dropdown of child component in Blazor

Posted: 12 Apr 2021 08:07 AM PDT

I am working on an ASP.NET Core (.NET 5.0) Server-side Blazor app. I am trying to add/edit users in a modal and assign roles to the user in another modal. So, I have a parent component and two child components.

Parent Component:

@if (ShowPopup)  {          <!-- This is the popup to create or edit user -->      <EditUserModal ClosePopup="ClosePopup" CurrentUserRoles="" DeleteUser="DeleteUser" objUser="objUser" SaveUser="SaveUser" strError="@strError" />  }    @if (ShowUserRolesPopup)  {      <!-- This is the popup to create or edit user roles -->      <EditUserRolesModal AddRoleToUser="AddRoleToUser" AllRoles="AllRoles" ClosePopup="ClosePopup" CurrentUserRoles="@CurrentUserRoles" objUser="objUser" RemoveRoleFromUser="RemoveRoleFromUser" SelectedUserRole="@SelectedUserRole" strError="@strError" _allUsers="_allUsers" _userRoles="UserRoles" />  }    @code {      // Property used to add or edit the currently selected user      ApplicationUser objUser = new ApplicationUser();        // Roles to display in the roles dropdown when adding a role to the user      List<IdentityRole> AllRoles = new List<IdentityRole>();            // Tracks the selected role for the current user      string SelectedUserRole { get; set; }            // To enable showing the Popup      bool ShowPopup = false;        // To enable showing the User Roles Popup      bool ShowUserRolesPopup = false;        ......        }  

The parent component contains the objects that hold the data objects (state) e.g. objUser, SelectedUserRole etc. and the methods that use these objects to implement the business rules e.g. SaveUser and AddRoleToUser.

The child component EditUserModal is used to add/edit users. It takes the objUser as a parameter from the parent component. 'objUser' holds the value of the new/selected user.

<div class="form-group">      <input class="form-control" type="text" placeholder="First Name" @bind="objUser.FirstName" />  </div>  <div class="form-group">      <input class="form-control" type="text" placeholder="Last Name" @bind="objUser.LastName" />  </div>  <div class="form-group">      <input class="form-control" type="text" placeholder="Email" @bind="objUser.Email" />  </div>  <button class="btn btn-primary" @onclick="SaveUser">Save</button>    @code {        [Parameter]      public ApplicationUser objUser { get; set; }            [Parameter]      public EventCallback SaveUser { get; set; }      .......    }  

The objUser object and SaveUser event callback are parameters in the child component. After entering data in the form of the child component and saving it, the SaveUser is called in the parent component and the data binding is automatically done with the objUser object in the parent component. This object holds the currently entered data. This object is then used to call databases services to create/update user data. It runs perfect!

This is how it looks like:

enter image description here

The objUser object has the entered data and it all works fine.

enter image description here

But the issue is in the EditUserRolesModal component where I am doing somewhat a similar thing with a variable. Code of EditUserRolesModal component:

<h5 class="my-3">Add Role</h5>    <div class="row">       <div class="col-md-10">           <div class="form-group">               <input class="form-control" type="text" @bind="objUser.Email" disabled />           </div>           <div class="form-group">               <select class="form-control" @bind="@SelectedUserRole">                    @foreach (var option in AllRoles)                    {                       <option value="@option.Name">@option.Name</option>                    }               </select>           </div>        <button class="btn btn-primary" @onclick="AddRoleToUser">Assign</button>      </div>  </div>        @code {          [Parameter]      public ApplicationUser objUser { get; set; }        [Parameter]      public string SelectedUserRole { get; set; }            [Parameter]      public List<IdentityRole> AllRoles { get; set; }            [Parameter]      public EventCallback AddRoleToUser { get; set; }            ........        }  

Here the parameter SelectedUserRole is used to hold the value of the role to be assigned to the user. It is bind to a dropdown list. When I change the value of the dropdown, the debugging shows that the value is updated in the child component (parameter) object. The following images show it:

enter image description here

The value is set to the SelectedUserRole parameter object in the child component.

enter image description here

Much like, objUser was being used in EditUserModal to hold the value of fields FirstName, LastName and Email of the new/selected user, SelectedUserRole is used in EditUserRolesModal to hold the value of the selected role to be assigned to the user.

But when the Assign button is pressed and the AddRoleToUser event is called in the parent component through the child component, the SelectedUserRole variable contains null in the parent component.

enter image description here

The scenario in both of the child components is the same, where the purpose is that upon the change in the value of the parameters inside the child component, the bound values should be updated and reflected in the parent's state. However, it works in EditUserModal component and not in EditUserRolesModal component. Why? What am I doing wrong?

P.S. I am not experienced in Blazor or component-based web programming.

Exclude folder from redirect

Posted: 12 Apr 2021 08:06 AM PDT

Wordpress redirects everything in wp-content if accessed directly to 404 with the following:

<IfModule mod_rewrite.c>  RewriteEngine On  RewriteBase /  RewriteRule ^index\.php$ - [L]  RewriteCond %{REQUEST_FILENAME} !-f  RewriteCond %{REQUEST_FILENAME} !-d  RewriteRule . /index.php [L]  </IfModule>  

What I want to do is not redirect the contents of a sub folder example.com/wp-content/uploads/event/images/

Any ideas how I can achieve this?

Tjovos Questionroom: transform.localScale.x error: how to fix the error

Posted: 12 Apr 2021 08:06 AM PDT

This is my Code:

transform.localScale.x + 0.1f;  

Hehe, who would have thought it:

Assets\Test.cs(18,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement  

So, to the Question: I want to make a health bar. So a Cube with a texture should just change the Size in the x direction. But I get the error. How to fix the error? Greetings Tjovo studios.

clicked_id doesn't return an id but remains inactive with a messsage Uncaught ReferenceError: clicked_id is not defined at HTMLButtonElement

Posted: 12 Apr 2021 08:07 AM PDT

Why on long press the alert doesn't "fire" and show alert "button", just this one word being an ID? I want to use vanilla js. Here can be an possible answer, but I do not know how to add combine it with a code below?

onClick to get the ID of the clicked button

Currently the returned message is "Uncaught ReferenceError: clicked_id is not defined at HTMLButtonElement.".

<button id="button">click</button>      (function(window, document, undefined){       'use strict';       var start;       var end;       var delta;       var button = document.getElementById("button");                 button.addEventListener("mousedown", function(){         start = new Date();       });             button.addEventListener("mouseup", function() {         end = new Date();         delta = end - start;         if (delta > 0 && delta < 500) {         alert("less than half second:");       }       if (delta > 500 && delta < 1000) {         alert("more than half second and less than a second:");       }       if (delta > 1000) {         alert(this.id);       }       });      })(window, document);      </script>  

Nest.js access process.env at controller

Posted: 12 Apr 2021 08:07 AM PDT

How i can access process.env.SOME_FIELD in nest.js ?

app.module.ts

...  modules: [  ...          ConfigModule.forRoot({              envFilePath: '.env.' + process.env.APP_CODE          }),          CatModule  ...  ]  ...  

CatController.ts in CatModule

// Below line is not working  console.log(process.env.APP_CODE) // process.env.APP_CODE is undefined    export class CatController {      constructor() {          console.log(process.env.APP_CODE) // This is working      }  }  

I need access process.env.APP_CODE at CatController.ts before class definition, but, that is undefined

How I can solve this?

Calculate weekly retention in google big query

Posted: 12 Apr 2021 08:07 AM PDT

I have a big table in google big query and there are two columns on which I want to perform retention:-

Date                           user  2021-02-03 08:35:07 UTC        foo@abc.com  2021-02-03 08:35:07 UTC        foo1@abc.com  2021-02-04 08:35:07 UTC        foo2@abc.com  2021-02-05 08:35:07 UTC        foo@abc.com  2021-02-03 08:35:07 UTC        foo1@abc.com  2021-02-10 08:35:07 UTC        foo@abc.com  2021-02-13 08:35:07 UTC        foo1@abc.com  2021-02-18 08:35:07 UTC        foo3@abc.com  2021-02-21 08:35:07 UTC        foo2@abc.com  2021-02-23 08:35:07 UTC        foo2@abc.com  2021-02-24 08:35:07 UTC        foo5@abc.com  2021-02-24 08:35:07 UTC        foo2@abc.com  

I want to calculate retention on the below condition:-

percentage of unique users for week1 present in week2

percentage of unique users from week2 present in week3 and so on.

The desired out format will be:-

week2  week3   week4   23%    56%     33%   

I want to perform this on a time frame like one month or 6 months and whatever timeframe I choose the output should be in the above format.

Angular Material: Maintaining consistent UI across multiple themes

Posted: 12 Apr 2021 08:07 AM PDT

My project incorporates a theme switcher similar to what you see on the Angular Material UI component website (https://material.angular.io/). However, I keep running into the issue where I want to modify the color or styling of an element. enter image description here

For example, I would like to modify the header of the angular table above so that the header is black when using light themes. I could accomplish this by referencing the mat-header-cell class and just setting the text color. However, that would set the color to be black even when using a dark theme which would not look very good.

How would I go about changing the color/darkening something on one theme but still maintain a different styling on a different theme so that the UI elements look good regardless of the theme?

Turn nested list of str into nested list of respective datatypes

Posted: 12 Apr 2021 08:07 AM PDT

I basically have a nested list which consists of strings - my goal is to turn this list into a list of their respective datatypes. I was successful for strings, dates and floats but my problem is, that the code recognizes integers as floats as well. I tried getting around that with a nested try-except but it doesn't work. Maybe someone finds a solution?

from datetime import datetime      l = [['Middle Management', '5', '5584.10', '2019-02-03', '12', '100'],   ['Lower Management', '2', '3925.52', '2016-04-18', '12', '100'],   ['Upper Management', '1', '7174.46', '2019-01-02', '10', '200'],   ['Middle Management', '5', '2921.92', '2018-02-02', '14', '300'],   ['Middle Management', '7', '2921.92', '2017-09-09', '17', '400'],   ['Upper Management', '10', '2921.92', '2020-01-01', '11', '500'],   ['Lower Management', '2', '2921.92', '2019-08-17', '11', '500'],   ['Middle Management', '5', '2921.92', '2017-11-21', '15', '600'],   ['Upper Management', '7', '2921.92', '2018-08-18', '18', '700']]    columns = len(l[0]) #the number of columns is given by the number of objects in the header list, at least in a clean CSV  without_header = l[1:]    types_list = []  looping_list = []    for x in range(0, columns):          looping_list = [item[x] for item in without_header]          worklist = []          for b in looping_list:              try:                  float(b)                  try:                      b.is_integer() #this is where it fails!                      worklist.append(int)                  except:                      worklist.append(float)              except:                  try:                      b=datetime.strptime(b, "%Y-%m-%d")                      worklist.append(type(b))                  except:                      worklist.append(type(b))          types_list.append(worklist)    types_list  

My output now is:

 [float, float, float, float, float, float, float, float, float],   [float, float, float, float, float, float, float, float, float],   [datetime.datetime,    datetime.datetime,    datetime.datetime,    datetime.datetime,    datetime.datetime,    datetime.datetime,    datetime.datetime,    datetime.datetime,    datetime.datetime],   [float, float, float, float, float, float, float, float, float],   [float, float, float, float, float, float, float, float, float]]  

But what I'd want is:

[[str, str, str, str, str, str, str, str, str],   [int, int, int, int, int, int, int, int, int],   [float, float, float, float, float, float, float, float, float],   [datetime.datetime,    datetime.datetime,    datetime.datetime,    datetime.datetime,    datetime.datetime,    datetime.datetime,    datetime.datetime,    datetime.datetime,    datetime.datetime],   [int, int, int, int, int, int, int, int, int],   [int, int, int, int, int, int, int, int, int]]  ````  

How do i put the file name in the url?

Posted: 12 Apr 2021 08:07 AM PDT

i have dog_001.jpg in image/animal/ directory then i want to put the dog_001.jpgto https://api.example.com/dog/

example: https://api.example.com/dog/ and it will respond https://api.example.com/img/animal/dog_001.jpg i already made it respond with https://api.example.com/img/animal/dog_001.jpg this but it says Cannot get /img/animal/dog_001

here is my current code

my index.js file

global.config = require("./config.json");    const express = require('express');  const helmet = require("helmet");  const cookieParser = require("cookie-parser");    //Animal API app  const animalapp = express();  const animalserver = require('http').createServer(animalapp);  const APIPORT = config.APIPort;  const apihbs = require('hbs');    const bodyParser = require('body-parser');  global.fs = require("fs");  global.chalk = require('chalk');  const axios = require('axios');      //Animal API website  animalapp.use(helmet({      frameguard: false  }));  animalapp.use(cookieParser());    animalapp.use(bodyParser.json());  animalapp.use(bodyParser.urlencoded({      extended: true  }));    animalserver.listen(APIPORT, function () {      console.log(chalk.magenta('[api.example.com] [WEB] ') + chalk.green("Listening on port " + APIPORT));  });    const dogRoute = require("./api/reaction/dog.js");  animalapp.use("/img/sfw/dog/gif", dogRoute);    

my dog.js (./api/reaction/dog.js)

const fs = require('fs');  const Router = require("express").Router();    Router.get("/", (req, res) => {        var files = fs.readdirSync('./src/animal/dog')      let imagenumber = files[Math.floor(Math.random() * files.length)]      let data = {          image: "https://example.com/img/animal/dog/" + imagenumber,          success: true,          status: 200      };        res.json(data);  });    Router.get('*', (req, res) => {      if (fs.existsSync('./src/animal/dog/' + req.path)) {          var img = fs.readFileSync('./src/animal/dog/' + req.path);          res.writeHead(200, {'Content-Type': 'image/gif'});          res.end(img, 'binary')      } else {          res.send('404')      }  })    module.exports = Router;   

Java 2 ArrayLists with same elements in same order returns false on equals check [duplicate]

Posted: 12 Apr 2021 08:07 AM PDT

I have a test case to check my sorting method for a list of objects, I have printed the contents of the two lists after sorting and they have the same elements in the same order. However testList.equals(correctList) returns false. Does anyone know why?

The test case

List<KthPopularNamesReport.KthPopularNames> correctList = new ArrayList<KthPopularNamesReport.KthPopularNames>();          List<KthPopularNamesReport.KthPopularNames> testList = new ArrayList<KthPopularNamesReport.KthPopularNames>();          correctList.add(new KthPopularNamesReport.KthPopularNames("A", 5, 1000, "A"));          correctList.add(new KthPopularNamesReport.KthPopularNames("A", 4, 1000, "A"));          correctList.add(new KthPopularNamesReport.KthPopularNames("A", 3, 1234, "A"));          correctList.add(new KthPopularNamesReport.KthPopularNames("A", 2, 1000, "A"));          correctList.add(new KthPopularNamesReport.KthPopularNames("A", 1, 1000, "A"));          testList.add(new KthPopularNamesReport.KthPopularNames("A", 1, 1000, "A"));          testList.add(new KthPopularNamesReport.KthPopularNames("A", 3, 1234, "A"));          testList.add(new KthPopularNamesReport.KthPopularNames("A", 5, 1000, "A"));          testList.add(new KthPopularNamesReport.KthPopularNames("A", 2, 1000, "A"));          testList.add(new KthPopularNamesReport.KthPopularNames("A", 4, 1000, "A"));          KthPopularNamesReport testReport = new KthPopularNamesReport(testList, "", "", 0, 0);          testReport.sortKthPopularNamesList();          System.out.println(testReport.getKthPopularNamesList().equals(correctList));          for (int i = 0; i < testList.size(); i++)          {              KthPopularNamesReport.KthPopularNames currentName2 = testList.get(i);              KthPopularNamesReport.KthPopularNames currentName = testReport.getKthPopularNamesList().get(i);              System.out.println(currentName.getName()+" "+currentName.getFrequency()+" "+currentName.getOccurrence()+" "+currentName.getPercentage()+" ");              System.out.println(currentName2.getName()+" "+currentName2.getFrequency()+" "+currentName2.getOccurrence()+" "+currentName2.getPercentage()+" ");          }  

The output

false    A 5 1000 A     A 5 1000 A     A 4 1000 A     A 4 1000 A     A 3 1234 A     A 3 1234 A     A 2 1000 A     A 2 1000 A     A 1 1000 A     A 1 1000 A   

MariaDB ODBC on Red Hat Linux

Posted: 12 Apr 2021 08:06 AM PDT

When I try to connect to a Maria DB from Power BI I get this error:

"The 'Driver' property with value '{MariaDB ODBC 3.1 Driver}' doesn't correspond to an installed ODBC driver."  

In the Linux RedHat server itself when I run this command it just hangs, I dont get an error:

$ isql MariaDB  

These are my configs:

in the "odbc.ini" file I just put a random username, password, and port. And the public IP of the linux server itself:

[MariaDB]  Description=MariaDB server  Driver=MariaDB  SERVER=the public IP address of the server where the mariaDB is  USER=random username  PASSWORD=random password  DATABASE=test  PORT=443  

the odbcinst.ini file:

[MariaDB]  Description=MariaDB Connector/ODBC  Driver=/usr/lib64/libmaodbc.so  Setup=/usr/lib64/libodbcmyS.so  Driver64=/usr/lib64/libmaodbc.so  UsageCount=3  

I need help with figuring out what i'm missing? Thank you

These are all the configs I did since I created the server:

yum install mariadb-server.x86_64  systemctl start mariadb  mkdir odbc_package  cd odbc_package  wget https://downloads.mariadb.com/Connectors/odbc/connector-odbc-3.1.7/mariadb-connector-odbc-3.1.7-ga-rhel7-x86_64.tar.gz  tar -xvzf mariadb-connector-odbc-3.1.7-ga-rhel7-x86_64.tar.gz  sudo install lib64/libmaodbc.so /usr/lib64/  sudo install -d /usr/lib64/mariadb/  sudo install -d /usr/lib64/mariadb/plugin/  sudo install lib64/mariadb/plugin/auth_gssapi_client.so /usr/lib64/mariadb/plugin/  sudo install lib64/mariadb/plugin/caching_sha2_password.so /usr/lib64/mariadb/plugin/  sudo install lib64/mariadb/plugin/client_ed25519.so /usr/lib64/mariadb/plugin/  sudo install lib64/mariadb/plugin/dialog.so /usr/lib64/mariadb/plugin/  sudo install lib64/mariadb/plugin/mysql_clear_password.so /usr/lib64/mariadb/plugin/  sudo install lib64/mariadb/plugin/sha256_password.so /usr/lib64/mariadb/plugin/  sudo yum install unixODBC  ##created a template file similar to the following, with a name like MariaDB_odbc_driver_template.ini:  [MariaDB ODBC 3.1 Driver]  Description = MariaDB Connector/ODBC v.3.1  Driver = /usr/lib64/libmaodbc.so  ##And then install it to the system's global /etc/odbcinst.ini file with the following command:  sudo odbcinst -i -d -f MariaDB_odbc_driver_template.ini  #create a template file similar to the following, with a name like MariaDB_odbc_data_source_template.ini:  [MariaDB-server]  Description=MariaDB server  Driver=MariaDB ODBC 3.0 Driver  SERVER=<your server>  USER=<your user>  PASSWORD=<your password>  DATABASE=<your database>  PORT=<your port>  #And then you can install it to the system's global /etc/odbc.ini file with the following command:  sudo odbcinst -i -s -l -f MariaDB_odbc_data_source_template.ini  

Express or Axios Error: socket hang up code: ECONNRESET

Posted: 12 Apr 2021 08:06 AM PDT

This is the first time i post a question here, sorry if some data is missing.

I'm trying to do some web scrapping to get some info of a table. The page only responds with an index.php and when i use the search form, it makes a POST to index.php?go=le with some formData. To avoid the CORS problem, im making the post with my own API running in localhost. I'm pointing my frontend to my API and i get the response from localhost. No problem there.

My problem appears when i try to make a second request to my API. The first GET works fine but after that response it keeps failing.
When i restart the server, it works again but only one time.

Here is my API code. I use nodemon server.js to start my server.

server.js

const express = require("express");  const axios = require("axios");  const scrape = require("scrape-it");  const FormData = require("form-data")  const cors = require("cors")    const app = express();  const PORT = process.env.PORT || 5000;    app.use(cors())    const config = {      headers: {          'Content-type': 'multipart/form-data'      },        }    app.get("/get-projects", async (req,res) => {      const testJSON = await axios.post(baseURL +"/index.php?go=le",formData,config)          .then(res => {                  console.log("Post successfull...");                  return res                  }              )          .catch(err => {              console.log("Server error");              return err              }              );      if(testJSON && testJSON.data){          res.send({status: 200, data: testJSON.data});      }else{          res.status(508).send({status: 508, msg: "Unhandled Server Error", failedResponse: testJSON || "empty"})      }  })      app.listen(PORT,()=>console.log(`App running in port: ${PORT}`))  

And in my front-end i only have a button with an event that makes a get to my API (http://localhost:5000)

This is my fetch.js that is included by a script tag. Nothing fancy there.

fetch.js

const btn = document.getElementById("btn-fetch-proyects")  const axios = window.axios    const fetchProjects = async () => {      console.log("Fetching...")        axios.get("http://localhost:5000/get-projects")      .then(res=>          console.log("The server responded with the following data: ",res.data)        )      .catch(err => console.log("Failed with error: ",err)      )            return null  }    btn.addEventListener("click",fetchProjects);  

In the console where im running the server, i get Server error with this err object:

{      "message": "socket hang up",      "name": "Error",      "stack": "Error: socket hang up\n    at connResetException (internal/errors.js:607:14)\n    at Socket.socketOnEnd (_http_client.js:493:23)\n    at Socket.emit (events.js:327:22)\n    at endReadableNT (internal/streams/readable.js:1327:12)\n    at processTicksAndRejections (internal/process/task_queues.js:80:21)",      "config": {          "url": "http://186.153.176.242:8095/index.php?go=le",          "method": "post",          "data": {              "_overheadLength": 1216,              "_valueLength": 3,              "_valuesToMeasure": [],              "writable": false,              "readable": true,              "dataSize": 0,              "maxDataSize": 2097152,              "pauseStreams": true,              "_released": true,              "_streams": [],              "_currentStream": null,              "_insideLoop": false,              "_pendingNext": false,              "_boundary": "--------------------------935763531826714388665103",              "_events": {                  "error": [                      null,                      null                  ]              },              "_eventsCount": 1          },          "headers": {              "Accept": "application/json, text/plain, */*",              "Content-Type": "multipart/form-data",              "User-Agent": "axios/0.21.1"          },          "transformRequest": [              null          ],          "transformResponse": [              null          ],          "timeout": 0,          "xsrfCookieName": "XSRF-TOKEN",          "xsrfHeaderName": "X-XSRF-TOKEN",          "maxContentLength": -1,          "maxBodyLength": -1      },      "code": "ECONNRESET"  }  

I hope someone has a clue about what's happening. I tried all day and i couldn't solve it.
I tried posting to other sites, and it works fine. I thing the problem is with the form POST.

Thanks for reading!!!

tensorflow LSTM model.predict

Posted: 12 Apr 2021 08:07 AM PDT

I am creating an time series LSTM neural network and had a question about how I should be doing model.predict()

Below is my function to predict:

def predict_ret(self, x, y):      test_x = x      predicted_data = []      for i in test_x:          prediction = (self.model.predict(np.reshape(i, (1, 1, self.input_shape))))          predicted_data.append(np.reshape(prediction, (1,)))      return pd.DataFrame(predicted_data)  

My confusion is that I train the model with a batch size of 72 and when I backtested I just pass the entire test portion into the above function as test_x. I am getting satisfactory results with this, but as soon as I start implementing it predicting one step at a time, or predicting with the number of steps as my training batch size (72) does not perform as well. I am trying to determine why this could be. The model has 100% never seen the test data before. Is there something with the fact that I am passing a whole test set through (about 20,000 points) vs just 1 when implemented? If this does not seem to be a problem, I can search for another cause. Any help would be appreciated!

System Verilog FSM `next state` does not transition when `present state` value in next state combinatorial logic block transitions - ternary operator

Posted: 12 Apr 2021 08:06 AM PDT

in my Verilog code, the ns value does not get assigned to any of the values in the next state logic. As I coded the next state logic to assign a value to the ns state variable whenever there is a transition in the ps.

Here is the FSM code snippet

    // State registers      always@(posedge clk, negedge rst) begin          if(!rst) ps <= S1;          else ps <= ns;      end      assign present_state = ps;      assign next_state = ns;              // Next state logic      always@(ps, start) begin          case(ps)              S1: ns = start ? S2 : S1;              S2: ns = S3;              S3: ns = S1;              //default : ns = S1;          endcase      end  

Here is the tb code snippet

    initial begin           #0 rst = 0; start = 0;          #2 rst = 1;          #10 a = 3; b = 4;          #10 start = 1;  

Finally the waveform output fsm_ns_notransition

My intention is for the ps <= ns to seamlessly transtion from S1 to S2 to S3 back to S1 and so forth, however for some reason despite the always_comb next state logic block, the state change of ps at t=0, does not assign the ns to a valid state ? Resulting in all further ps <= ns assignments to be always 'x states

Is there a flaw in this logic ?

A swift help is much appreciated

Thanks

How to groupby interval index, aggregate mean on a list of lists, and join to another dataframe?

Posted: 12 Apr 2021 08:06 AM PDT

I have two dataframes. They look like this:

df_a       Framecount                                        probability  0           0.0  [0.00019486549333333332, 4.883635666666667e-06...  1           1.0  [0.00104359155, 3.9232405e-05, 0.0015722045000...  2           2.0  [0.00048501002666666667, 1.668179e-05, 0.00052...  3           3.0  [4.994969500000001e-05, 4.0931635e-07, 0.00011...  4           4.0  [0.0004808829, 5.389742e-05, 0.002522127933333...  ..          ...                                                ...  906       906.0  [1.677140566666667e-05, 1.1745095666666665e-06...  907       907.0  [1.5164155000000002e-05, 7.66629575e-07, 0.000...  908       908.0  [8.1334184e-05, 0.00012675669636333335, 0.0028...  909       909.0  [0.00014893802999999998, 1.0407592500000001e-0...  910       910.0  [4.178489e-05, 2.17477925e-06, 0.02094931, 0.0...  

And:

df_b       start    stop  0     12.12   12.47  1     13.44   20.82  2     20.88   29.63  3     31.61   33.33  4     33.44   42.21  ..      ...     ...  228  880.44  887.92  229  888.63  892.07  230  892.13  895.30  231  895.31  900.99  232  907.58  908.35  

I want to merge df_a.probability onto df_b when df_a.Framecount is in between df_b.start and df_b.stop. The aggregation statistic for df_a.probability should be mean, but I run into errors because df_a.probability is dtype np array.

I am trying to using this code:

idx = pd.IntervalIndex.from_arrays(df_text['start'], df_text['stop'])  df_text.join(df_vid.groupby(idx.get_indexer_non_unique(df_vid['Framecount']))['probability'].apply(np.mean), how='left')  

Line 1 creates the index do determine the grouping. In line 2 I am trying to implement the group by and aggregating all of the values in df_a.probability that fall within a groupby index by mean. I want one array per groupby that is the mean of all arrays in the groupby index. This code gives me this error:

---------------------------------------------------------------------------  TypeError                                 Traceback (most recent call last)  <ipython-input-271-19c7d58fb664> in <module>        1 idx = pd.IntervalIndex.from_arrays(df_text['start'], df_text['stop'])        2 f = lambda x: np.mean(np.array(x.tolist()), axis=0)  ----> 3 df_text.join(df_vid.groupby(idx.get_indexer_non_unique(df_vid['Framecount']))['probability'].apply(np.mean), how='left')    ~/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py in groupby(self, by, axis, level, as_index, sort, group_keys, squeeze, observed)     5808             group_keys=group_keys,     5809             squeeze=squeeze,  -> 5810             observed=observed,     5811         )     5812     ~/anaconda3/lib/python3.7/site-packages/pandas/core/groupby/groupby.py in __init__(self, obj, keys, axis, level, grouper, exclusions, selection, as_index, sort, group_keys, squeeze, observed, mutated)      407                 sort=sort,      408                 observed=observed,  --> 409                 mutated=self.mutated,      410             )      411     ~/anaconda3/lib/python3.7/site-packages/pandas/core/groupby/grouper.py in get_grouper(obj, key, axis, level, sort, observed, mutated, validate)      588       589         elif is_in_axis(gpr):  # df.groupby('name')  --> 590             if gpr in obj:      591                 if validate:      592                     obj._check_label_or_level_ambiguity(gpr, axis=axis)    ~/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py in __contains__(self, key)     1848     def __contains__(self, key) -> bool_t:     1849         """True if the key is in the info axis"""  -> 1850         return key in self._info_axis     1851      1852     @property    ~/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in __contains__(self, key)     3898     @Appender(_index_shared_docs["contains"] % _index_doc_kwargs)     3899     def __contains__(self, key) -> bool:  -> 3900         hash(key)     3901         try:     3902             return key in self._engine    TypeError: unhashable type: 'numpy.ndarray'  

I have tried multiple aggregation specifications, including:

df_text.join(df_vid.groupby(idx.get_indexer_non_unique(df_vid['Framecount']))['probability'].apply(lambda x: np.mean(np.array(x.tolist()), axis=0)), how='left')  

or

df_text.join(df_vid.groupby(idx.get_indexer_non_unique(df_vid['Framecount']))['probability'].apply((np.mean), how='left')  

or

df_text.join(df_vid.groupby(idx.get_indexer_non_unique(df_vid['Framecount']))['probability'].mean()), how='left')  

and I get the same error.

How do I accomplish this?

Using OpenCV along with Pyttsx3 using multithreading but the screen in freezing continuously

Posted: 12 Apr 2021 08:07 AM PDT

I am trying to make an application that will use OpenCV to read the live stream from the webcam along with Python Text to speech (Pyttsx3) library which will simultaneously read out the text and give a live video from the webcam but the stream is freezed when it is speaking out text. So I created separate threads to get the stream, show it, and also a separate thread for pyttsx3 but again the video gets freeze when it says out the text.

I have tried this code

from threading import Thread  import cv2  from datetime import datetime  import pyttsx3    class VideoGet:      """      Class that continuously gets frames from a VideoCapture object      with a dedicated thread.      """        def __init__(self, src=0):          self.stream = cv2.VideoCapture(src)          (self.grabbed, self.frame) = self.stream.read()          self.stopped = False                def start(self):              Thread(target=self.get, args=()).start()          return self        def get(self):          while not self.stopped:              if not self.grabbed:                  self.stop()              else:                  (self.grabbed, self.frame) = self.stream.read()        def stop(self):          self.stopped = True                                class VideoShow:      """      Class that continuously shows a frame using a dedicated thread.      """        def __init__(self, frame=None):          self.frame = frame          self.stopped = False                def start(self):          Thread(target=self.show, args=()).start()          return self        def show(self):          while not self.stopped:              cv2.imshow("Video", self.frame)              if cv2.waitKey(1) == ord("q"):                  self.stopped = True        def stop(self):          self.stopped = True         class CountsPerSec:      """      Class that tracks the number of occurrences ("counts") of an      arbitrary event and returns the frequency in occurrences      (counts) per second. The caller must increment the count.      """        def __init__(self):          self._start_time = None          self._num_occurrences = 0        def start(self):          self._start_time = datetime.now()          return self        def increment(self):          self._num_occurrences += 1        def countsPerSec(self):          elapsed_time = (datetime.now() - self._start_time).total_seconds()          #elapsed_time!=0          return self._num_occurrences/elapsed_time               def putIterationsPerSec(frame, iterations_per_sec):      """      Add iterations per second text to lower-left corner of a frame.      """        cv2.putText(frame, "{:.0f} iterations/sec".format(iterations_per_sec),          (10, 450), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255))      return frame          class TextToSpeech:      def __init__(self):          self.engine=pyttsx3.init(debug=True)          #self.engine.startLoop(True)            def start(self):          Thread(target=self.speech("i am "),args=()).start()          return self            def speech(self,saytext):          self.engine.say(saytext)          self.engine.runAndWait()                      def stop(self):          self.stopped=True                 def threadBoth(source=0):      """      Dedicated thread for grabbing video frames with VideoGet object.      Dedicated thread for showing video frames with VideoShow object.       Dedicated thread for text to speech object.      Main thread serves only to pass frames between VideoGet and      VideoShow objects/threads.      """      #tts=TextToSpeech()      tts1=TextToSpeech().start()      video_getter = VideoGet(source).start()      video_shower = VideoShow(video_getter.frame).start()                 cps = CountsPerSec().start()        while True:          if video_getter.stopped or video_shower.stopped:              video_shower.stop()              video_getter.stop()              break          tts1.speech("hey anmol")          frame = video_getter.frame          frame = putIterationsPerSec(frame, cps.countsPerSec())          video_shower.frame = frame    threadBoth(0)                 

Error:INTERNAL firebase functions ,when using it with nodemailer

Posted: 12 Apr 2021 08:06 AM PDT

const transporter = nodemailer.createTransport({      service: 'gmail',      auth: {        user: 'xxxxxx@gmail.com',        pass: 'xxxxxxxx'      } ,      tls: {        rejectUnauthorized: false    },    });      exports.sendMail=functions.https.onCall((req,res)=>{        cors(req,res,()=>{            const email=JSON.parse(req.email)            const mailOptions = {              from: 'xxxxxxxxx@gmail.com',              to: email,              subject: 'Invitation to register your profile in xxxxxxx solutions',              text: `http://xxxxxx/xxxxxxxx`            };              return transporter.sendMail(mailOptions, function(error, info){              if (error) {                return res.send(error);              }                return res.send("Email sent")              });        })    })  

Minimum and maximum values of integer variable

Posted: 12 Apr 2021 08:06 AM PDT

Let's assume a very simple constraint: solve(x > 0 && x < 5).

Can Z3 (or any other SMT solver, or any other automatic technique) compute the minimum and maximum values of (integer) variable x that satisfies the given constraints?

In our case, the minimum is 1 and the maximum is 4.

No comments:

Post a Comment