Thursday, April 8, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


react-native can't found android-studio

Posted: 08 Apr 2021 08:51 AM PDT

Hello I already start working with react-native, I faced a problem react-native can not find android-studio I can't figure it out, Android studio already installed on my OS using snap, if someone can help with this !!

$> react-native doctor  Common   ✓ Node.js   ✓ npm    Android   ✓ JDK   ✖ Android Studio - Required for building and installing your app on Android   ✓ Android SDK - Required for building and installing your app on Android   ✓ ANDROID_HOME    Errors:   1  Warnings: 0    Usage   › Press f to try to fix issues.   › Press e to try to fix errors.   › Press w to try to fix warnings.   › Press Enter to exit.  

Spring singleton bean's values are sharing with users

Posted: 08 Apr 2021 08:51 AM PDT

I have a Spring webapp which has following beans. When 2 users come in to the system at the same time, then both get the same services, whereas it should show each users's own service. shouldn't mix up.

How to do this in current code? CommonWSServiceClass is singleton scope by default.

  1. I can remove the instance field private List<Services> exSVCList = null; and make it method local (declare it in retrieveExistingService() method). In this way it resolve the issue somewhat I believe. But see below question.

  2. After making the above variable to method local, what will happen if two users come at the same time. Both threads are inside method retrieveExistingService(), but user_1 is at the return exSVCList; line. Just about to exit from the method. But user_2 come and executing the same method, line exSVCList = new ArrayList();. So in this case, when the user_1 finish the execution of method retrieveExistingService(), he will get an empty arrayList, isn't it ? As the bean is singleton, hence only one bean is there. So the size of the arraylist is empty. Because user_2 updated the same variable.

Is my understanding correct? If this is the case, how to handle this in Spring?

    @Component      @Scope(value = "session")      public class ServiceClass {           @Autowired         private CommonWSServiceClass webservices;           public services[] getExServices(){                         List<Services> list =  webservices.retrieveExistingService()         }      }           @Service      public class CommonWSServiceClass {          private List<Services> exSVCList = null;          public List<Services> retrieveExistingService() {                    exSVCList = new ArrayList();          exSVCList.add(addSomeObj);            updateList();                exSVCList.add(addAnotherObj);            return exSVCList;         }         private void updateList() {                 exSVCList.add(Call a Webservice to get the item list.);           }       }  

Vuetify's v-expand-transition without v-show/v-if?

Posted: 08 Apr 2021 08:51 AM PDT

Is there anyway to animate a div, with Vuetify's expand-transition, without it being hidden in the first place?

The expand-transition and all transitions in vuetify demands that the element that is given the animation is hidden initially.

The component that I want to use expand-transition on grows in size dynamically. In my case, there is text inside a div that grows dynamically. When text is added to the already existing text, I want the div to expand with the animation that v-expand-transition gives.

Any ideas how this can be done? One lazy and not good CSS-solution I found was to do something like this:

.text-wrapper {      max-height: 150px;      overflow: hidden;      transition: max-height 0.5s ease-in-out;      &.expanded {          max-height: 500px;      }  }  

This is not the way I want to go! If I can instead use the vuetify library to achieve something similar I would be much happy!

How to add Custom Script Codes in Nuxt Head and Body dynamically?

Posted: 08 Apr 2021 08:51 AM PDT

I need to add Tracking Codes in my app like

  1. Google Analytics
  2. Google Tag Manager
  3. Facebook Pixel

I've seen that there are packages for the 3 of them. But these packages need the ID to be passed in the configuration part.

In my use case I've to make an API request and then decide which tags to add, also I might be adding lot of other scripts dynamically. What's the right way to append customer script codes like these in either Head or Body tags?

<!-- Global site tag (gtag.js) - Google Analytics -->  <script async src="https://www.googletagmanager.com/gtag/js?id=G-DYXWW9MGJC"></script>  <script>     window.dataLayer = window.dataLayer || [];     function gtag(){dataLayer.push(arguments);}     gtag('js', new Date());       gtag('config', 'G-DYXWW9MGJC');  </script>    

Can I pass this entire script as a variable and append it to the Head or Body according to the Script requirement? What's the right way to achieve this in Nuxt?

Splitting a row into several rows based off it's start and end date

Posted: 08 Apr 2021 08:51 AM PDT

I have an absence table that holds one record per employee absence, it has the absence start and end date in it. e.g.

Person Ref, Start Date, End Date 1234, 01/01/2021, 05/01/2021

I want to split this row into several rows based upon the date range, so instead of one row representing the absence, it would have a row for each day of absence, like this:

Person Ref, Start Date, End Date 1234, 01/01/2021, 01/01/2021 1234, 02/01/2021, 02/01/2021 1234, 03/01/2021, 03/01/2021 1234, 04/01/2021, 04/01/2021 1234, 05/01/2021, 05/01/2021

Is it possible to split the row based upon the date range into separate rows? Thanks in advance.

Visual Studio 2019 ; Bootstrap command ."class name" dosen't work

Posted: 08 Apr 2021 08:50 AM PDT

Don't know why I've started to have small issue with Bootstrap in my VisualStudio. Normaly div.container creates div with class container after pressing TAB twice. It stopped working along with div 2xTAB creating div. After looking for some answers and not finding much, I've reinstalled VS. Div 2xTAB works just fine. But not with Bootstrap class names.

Anyone had problem like that? How did you manage to repair that? Thanks in advance :)

Have a nice day !

MPS/GLOP models for LP

Posted: 08 Apr 2021 08:50 AM PDT

I am looking for small and meaningful models of linear programming problems, either in the MPS file format or written in python with GLOP. Maybe benchmark suites or a collection of famous problems in operations research would be good, but I really have no idea where to find them. Anybody working in the field has any pointers?

How to make my Discord Bot reply with a mention?

Posted: 08 Apr 2021 08:50 AM PDT

For example I want that someone sends in: "make my friend @FreezyGuy" Then my bot responds that: "making @FreezyGuy you friend is in progress..."

I even want my bot go back after 10 seconds and edit the message to: "@FreezyGuy is your friend now!"

If you can help with this second part you are awesome, but if you can with the mention that would be great as well.

client.on("message", function(message) {    if (message.content === `make my friend` @mention)       if (message.author.bot) return;            else if(message.content === `make my friend` @mention){          message.channel.send(`making @mention your friend is in progress...`)  }});  

Add length to label in Phylogenetic tree

Posted: 08 Apr 2021 08:50 AM PDT

I wish to visualize the a phylogenetic tree that I have saved in a .ph format using R. Currently I have been successful in visualizing the Tree and am also able to have the lengths of the branches of the phylogenetic be proportional to the actual lengths in the .ph file. I am using the following code

protien1Tree <- ape::read.tree(file="tree.ph")  jpeg("tree.jpg", width = 700, height = 700)  plot(protien1Tree,use.edge.length=TRUE)  dev.off()  

This code generates a tree as follows

Sample plot image

The tree does not contain the values of the distances assosiate with the branches. I looked through the documentation of the plot function as mentioned here and found no way to add the distances to the tree

Any guidance on how to proceed would be appreciated

P.S. I have added a sample of my required output format and a .ph file for any further reference

Required format

A sample .ph file

((NZ_CP014692.1:0.369708,((  NZ_CP022699.1:0.338805,  NZ_LN609302.1:0.338805):0.364576,  (  NZ_CP015168.1:0.129678,  NZ_AP018515.1:0.129678):0.364576):0.369708):0.374165,  (((  NZ_CP023657.1:0.0396982,  NZ_CP021524.1:0.0396982):0.358596,  NZ_CP023189.1:0.358596):0.368288,  (((  NZ_CP014687.1:0.293635,  NZ_LN606600.1:0.293635):0.342745,  ((  NZ_CP011120.1:0.0026264,  NZ_CP022374.1:0.0026264):0.0458183,  (((((((  NC_017100.1:0,  NC_017121.1:0):0,  NC_017125.1:0):0,  NC_017146.1:0):0,  NC_017111.1:0):0,  NC_017150.1:0):0,  NC_017108.1:0):0.00525279,  NZ_AP014881.1:0.00525279):0.0458183):0.342745):0.358053,  NZ_CP015164.1:0.358053):0.368288):0.374165):0.374165;  

extract the nodes in a path ordered by a relation from a graph

Posted: 08 Apr 2021 08:50 AM PDT

I'm new to Neo4j and graphs in general, so apart some queries in a browser or other visual tool, I did very little.

Now I'm tasked to find a path and process the nodes in it, respecting their order in that same path (so the order is relation-induced).

Given a graph with the following nodes:

CREATE (a:temporary {name: 'm2'});  CREATE (a:temporary {name: 'f1'});  CREATE (a:temporary {name: 'b3'});  CREATE (a:temporary {name: 'd4'});    CREATE (a:temporary {name: 'p5'});  CREATE (a:temporary {name: 'p6'});  CREATE (a:temporary {name: 'p7'});    CREATE (a:temporary {name: 'k1'});  CREATE (a:temporary {name: 'k2'});  

and the following relations:

MATCH (a) WHERE a.name = 'b3' MATCH (b) where b.name = 'm2' CREATE (a)-[:KNOWS {type: 'sibling'}]->(b);  MATCH (a) WHERE a.name = 'm2' MATCH (b) where b.name = 'f1' CREATE (a)-[:KNOWS {type: 'friend'}]->(b);  MATCH (a) WHERE a.name = 'd4' MATCH (b) where b.name = 'b3' CREATE (a)-[:KNOWS {type: 'coworker'}]->(b);    MATCH (a) WHERE a.name = 'p7' MATCH (b) where b.name = 'p6' CREATE (a)-[:KNOWS {type: 'friend'}]->(b);  MATCH (a) WHERE a.name = 'p6' MATCH (b) where b.name = 'p5' CREATE (a)-[:KNOWS {type: 'coworker'}]->(b);    MATCH (a) WHERE a.name = 'k1' MATCH (b) where b.name = 'b3' CREATE (a)-[:HAS]->(b);  MATCH (a) WHERE a.name = 'k1' MATCH (b) where b.name = 'd4' CREATE (a)-[:HAS]->(b);  MATCH (a) WHERE a.name = 'k1' MATCH (b) where b.name = 'm2' CREATE (a)-[:HAS]->(b);  MATCH (a) WHERE a.name = 'k1' MATCH (b) where b.name = 'f1' CREATE (a)-[:HAS]->(b);    MATCH (a) WHERE a.name = 'k2' MATCH (b) where b.name = 'p5' CREATE (a)-[:HAS]->(b);  MATCH (a) WHERE a.name = 'k2' MATCH (b) where b.name = 'p7' CREATE (a)-[:HAS]->(b);  MATCH (a) WHERE a.name = 'k2' MATCH (b) where b.name = 'p6' CREATE (a)-[:HAS]->(b);  

Order of creations matters because I saw that Neo4j sorts results by id when no other ordering is in place, and that can give an hint: when the issued query is wrong nodes are returned in the wrong order.

You should come up with the following graphical representation:

I need to extract the nodes owned by k1 (and only those), in the order given by knows, so:

f1 <- m2 <- b3 <- d4  

My aim is to obtain a result that can be processed by a program, so my first idea is an array like: [f1, m2, b3, d4], but of course this may not be the best or be supported at all.

Please note that I need the head of the path too, f1, the node that has no outgoing knows relations.

The next step will be a query that returns pairs (node, relation props), because in the real graph the above is derived from, relations have properties that I need to process too.

So the complete result I want to obtain from the graph should be something like: [[f1, {}], [m2, {type: friend}], [b3, {type: sibling}], [d4, {type: coworker}]]

However, any result format that can be processed like in the below pseudocode will be fine:

for x in [result] do:      if(x.type.isEmpty) {          // process the head      } else if (x.type == "friend") {          // do something knowing this node is a friend of the preceding one      } else ...  

Be

OR results from series of boolean-returning methods

Posted: 08 Apr 2021 08:50 AM PDT

I have a series of methods, each processing unique business rules, and each return a boolean result. I need ALL the methods executed, but if any one of them returns a true, then additional processing is required on dependent data. So, I can't just do:

boolean bizRuleFailed = false;  bizRuleFailed = methOneRule(data) || methTwoRule(data) || methThreeRule(data);  

because it would stop after the first true-result method. So I am doing this:

boolean bizRuleFailed = false;  bizRuleFailed = methOneRule(data) || bizRuleFailed;  bizRuleFailed = methTwoRule(data) || bizRuleFailed;  bizRuleFailed = methThreeRule(data) || bizRuleFailed;  

, which is far from ideal. What's a good way to do this instead? Thanks

Express js - : Error -Cannot set headers after they are sent to the client

Posted: 08 Apr 2021 08:50 AM PDT

When I am adding a new user to the database with the same credentials it should reload the index page but rather I'm being redirected to the login page and an error is shown. I do not know why this is happening can anyone please help me out.

//this is my server.js file

 const express = require('express'),    bodyParser = require('body-parser'),    mongoose      = require('mongoose'),    User      = require('./views/user.js');      const app = express();   mongoose.connect('mongodb://localhost/example_db', {   useNewUrlParser: true,   useUnifiedTopology: true,   useFindAndModify: false,   useCreateIndex: true   });         app.set("view engine", "ejs");   app.use(bodyParser.json());   app.use(bodyParser.urlencoded({ extended: true }));       app.get('/', function(req,res){   res.render('index');   })  app.post('/signup',function(req,res){  var username = req.body.username;  var password = req.body.password;  console.log(username);  console.log(password);  User.findOne({username: username}).then((user) =>{      if(user){          return res.render('index')      }      else{          const newUser = new User({              username: username,              password: password,          });          newUser.save();          return res.redirect('login');        }      })       })        app.get('/login',function(req,res){     res.render('login');    })       app.listen(5000,console.log("server is starting!!"));  

//my login form

<!DOCTYPE html>  <html lang="en">  <head>  <meta charset="UTF-8">  <title>Login route</title>   </head>     <body>      <h4>this is login page</h4>        <form action="/login" method="POST">           <input type="text" name="username" placeholder="uername">           <input type="password" name="password" placeholder="password">           <button type="submit">login</button>        </form>     </body>  </html>  

//my signup form -- index page

        <!DOCTYPE html>      <html lang="en">      <head>      <meta charset="UTF-8">      <meta http-equiv="X-UA-Compatible" content="IE=edge">      <title>signup</title>      </head>      <body>      <form action="signup" method="POST" >      <input type="text" name="username" placeholder="username" >      <input type="password" name="password" placeholder="password">      <button type="submit">submit</button>      </form>        </body>      </html>  

// my user model schema

    var mongoose              = require("mongoose");        var UserSchema = mongoose.Schema({          username: String,          password: String,      });          module.exports = mongoose.model("User", UserSchema);  

Is there a way to create illusion that text in a plot is "highlighted"?

Posted: 08 Apr 2021 08:50 AM PDT

Is there anyway to highlight parts of text in a plot - whether the title, subtitle, text in text box, legend text, etc.,etc.?

I plot then save as PDFs a lot of investment strategy simulations with each one being labelled "[<Strategy_XY[045]" (45 - 45th simulation of strategy "XY") and was hoping I could highlight (create proxy thereof) that part of the text on a plot.

Thanks in advance.

MongoDb index reference to original table

Posted: 08 Apr 2021 08:50 AM PDT

I testing how indexes work in MongoDB and don't understand one moment.

I have a test collection with data (10000 rows): test collection

Also I creating new index:

collection.createIndex({ SomeValue1: 1, SomeValue2: -1 })  

And I don't understand how the index maps its own entries to the original table.
I thought that it uses the '_id' column but these two queries said me that this isn't true:


#1:

collection  .find()  .sort({ SomeValue1: 1, SomeValue2: -1 })  .projection({ SomeValue1: 1, SomeValue2: 1 })  .explain("allPlansExecution")  

#2:

collection  .find()  .sort({ SomeValue1: 1, SomeValue2: -1 })  .projection({ SomeValue1: 1, SomeValue2: 1, _id: 0 })  .explain("allPlansExecution")  

At #1 query execution plan says:

"totalKeysExamined": 10000,  "totalDocsExamined": 10000,  

At #2:

"totalKeysExamined": 10000,  "totalDocsExamined": 0,  

I was expecting that both variants don't use the original table.
Found this information on official documentation: link

But still don't understand how to index entry matches entry from the original table if it (index table) doesn't use the '_id' field?

Read chat text from Minecraft [closed]

Posted: 08 Apr 2021 08:50 AM PDT

I need to read chat text from Minecraft. image

How can i do this on C++?

How to filter on a string numpy array column in pyspark

Posted: 08 Apr 2021 08:50 AM PDT

I have a pyspark dataframe

import pandas as pd  foo = pd.DataFrame({'col':[['a_b', 'bad'],['a_a', 'good'],[]]})  

I would like to filter out all the rows for which 'bad' is in the list of col

I have tried to first create a binary column and then filter on this one:

from pyspark.sql import functions as f  foo = foo.withColumn('at_least_one_bad', f.when(f.col("col").array_contains("bad"),f.lit(1)).otherwise(f.lit(0)))  

but I get an error

TypeError: 'Column' object is not callable

Any ideas?

Input after text heading

Posted: 08 Apr 2021 08:50 AM PDT

I am trying to put an input right after a text ends. (Not after the div that contains the text).

Something like this: example

But I don't know how to do it. I tried to place it with an absolute position but when I resize the window it overlaps the text and input.

This is my css:

  .div-heading {        position: relative;      }      .heading-2 {      font-size: 52px;    }          .search{        position: absolute;        display: -webkit-box;        display: -webkit-flex;        display: -ms-flexbox;        display: flex;        margin-top: -89px;        margin-left: 239px;        padding-left: 10px;      }  

Any ideas?

How to create a dictionary given values and keys as tuples of tuples

Posted: 08 Apr 2021 08:50 AM PDT

I'm trying to code a function which would create a dictionary given values and keys as tuples of tuples. E.g.

long2wide ( ((" apple ","red "),(" banana "," yellow "),(" banana "," green "),  (" apple "," green "),(" cherry "," red "))  , (" fruit ", " colour ") )  

returns

{'fruit': ['apple', 'banana', 'banana', 'apple', 'cherry'], 'colour': ['red', 'yellow', 'green', 'green', 'red']}  

Here's the (erroneous) code I have now:

def long2wide(data, headers):      dictionary = {}      for entry in headers:          for i in range(len(data)): #Iterate through each row of data              for j in range(len(data[0])): #Iterate through each column of data                  dictionary[(headers)] = data[i][j]      return dictionary  

My current output is {'fruit': 'red', 'colour': 'red'}

:(

Would really appreciate if anyone could help debug/resolve this. Thanks!!

Get repeating objects from object array

Posted: 08 Apr 2021 08:51 AM PDT

I have this initial array and want to extract the repeating flights based on from.flightNo and to.flightNo

const myArray = [          { from: { flightNo: 'A11' }, to: { flightNo: 'B11' }, code: 23 },          { from: { flightNo: 'A12' }, to: { flightNo: 'B45' }, code: 22 },          { from: { flightNo: 'A12' }, to: { flightNo: 'B52' }, code: 21 },          { from: { flightNo: 'A11' }, to: { flightNo: 'B11' }, code: 20 },          { from: { flightNo: 'A14' }, to: { flightNo: 'B44' }, code: 25 },          { from: { flightNo: 'A15' }, to: { flightNo: 'B69' }, code: 24 },          { from: { flightNo: 'A14' }, to: { flightNo: 'B44' }, code: 26 },        ];      result:    [      { from: { flightNo: 'A11' }, to: { flightNo: 'B11' }, code: 23 },      { from: { flightNo: 'A11' }, to: { flightNo: 'B11' }, code: 20 },      { from: { flightNo: 'A14' }, to: { flightNo: 'B44' }, code: 25 },      { from: { flightNo: 'A14' }, to: { flightNo: 'B44' }, code: 26 },    ]  

I wrote this but I can only get the first repeating one and doesn't look very pretty.

  const duplicates = myArray      .map((item) => {        let count = 0;        for (let i = 0; i < myArray.length; i++) {          if (count > 1) {            count = 0;            return item;          }          if (            myArray[i]?.from?.flightNo == item?.from?.flightNo &&            myArray[i]?.to?.flightNo == item?.to?.flightNo          )            count++;        }      })      .filter((notUndefined) => notUndefined !== undefined);  

Any suggestions?

ToLongDateString() showing wrong date in Arabic

Posted: 08 Apr 2021 08:51 AM PDT

In my ASP NET MVC Entity Framework project I pass from database date and time information. When I display the date in the Arabic format CultureInfo("ar-AR") I get an incorrect date from what is entered in the database.

My code so far:

datetime_created.ToLongDateString();  // The date I pass is:- 2020-12-10  // CultureInfo("en-US") in en-US culture it displays the date as it is in a database:- Thursday, December 10, 2020  // CultureInfo("ar-AR") in ar-AE culture it displays another date:- 1442/ربيع الثاني/25  

Any ideas why this happens?

How to resolve "Login failed for user 'NT AUTHORITY\SYSTEM'. Reason: Failed to open the explicitly specified database 'TestTable1'"?

Posted: 08 Apr 2021 08:51 AM PDT

I'm developing a VB.NET windows service which connects with some SQL databases. When I try to start the windows service it throws me these errors in the windows event viewer.

ERROR 1

Service cannot be started. System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'EDGEMAN\STLWKSENG11$'.     at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager)     at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)     at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions us...  

ERROR 2

Service cannot be started. System.Data.SqlClient.SqlException (0x80131904): Cannot open database "TestTable1" requested by the login. The login failed.  Login failed for user 'NT AUTHORITY\SYSTEM'.     at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager)     at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)     at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbCo...  

I have researched about this errors and read bunch of articles about giving permissions and gave almost all the permissions and tried doing almost every method what they were saying, no luck.

Furthermore detailed version of what I've tried : First I've tried to connect the network databases and then it gave me the below error

Service cannot be started. System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) ---> System.ComponentModel.Win32Exception (0x80004005): The network path was not found     at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager)     at System.Data.SqlClient.SqlConnectionFactory.CreateConnectio...  

Since I thought maybe the issue is with network, I tried to connect local databases just to make sure nothings wrong with the code I wrote. Ended up with the Error1, Error2 which shown above.

SQL Server Logs throws this message : Login failed for user 'EDGEMAN\STLWKSENG11$'. Reason: Could not find a login matching the name provided. [CLIENT: 10.0.15.118]

Appreciate very much your time and consideration all!

How to pass string argument to numba njit python function from inside another whilst specifying signature type?

Posted: 08 Apr 2021 08:51 AM PDT

numba 0.51.2

I'm trying to pass a string argument to a njit function inside another njit function. For example:

import numba as nb      from numba import njit, types    @njit(nb.void(types.unicode_type))  def bar(string):      pass    @njit(nb.void(types.unicode_type))  def foo1(string):      bar(string)    @njit(nb.void(types.unicode_type))  def foo2(string):      bar("Testing")  

I can call foo1("Test") fine, however, foo2("Test") fails with error:

TypingError: Failed in nopython mode pipeline (step: nopython frontend)  Invalid use of type(CPUDispatcher(<function bar at 0x00000258625F0678>)) with parameters (Literal[str](Testing))  Known signatures:   * (unicode_type,) -> none   * parameterized  [1] During: resolving callee type: type(CPUDispatcher(<function bar at 0x00000258625F0678>))  [2] During: typing of call at <ipython-input-4-62a1e466b1c1> (14)      File "<ipython-input-4-62a1e466b1c1>", line 14:  def foo2(string):      bar("Testing")      ^  

I don't have any issues running either function when I try and run the njit function without specifying the signature, however, I intend to use the numba.pycc ahead-of-time compiler which, as fair as I'm aware, requires the signatures.

Any help would be greatly appreciated!

Edit - As a work around I've been able to pass the string through creating a typed.List(['Test']) with signature types.ListType(types.unicode_type) and indexing the first element. Is there a better way?

How to break while loop when a new message arrives?

Posted: 08 Apr 2021 08:50 AM PDT

I have used Python socket in ESP as a server and Laptop as a client. I customized the socket codes from this site. When I send the loop as the client input, I enter a loop on the server. I don't know how the while loop is broken when I send a word other than loop, For example "Hello".

server.py:

import socket    host = ''  port = 5560    def setupServer():      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)      print("Socket created.")      try:          s.bind((host, port))      except socket.error as msg:          print(msg)      print("Socket bind comlete.")      return s    def setupConnection():      s.listen(1)      conn, address = s.accept()      print("Connected to: " + address[0] + ":" + str(address[1]))      return conn    def Hello_():      print('Hello')    def Loop_():      while True:          print('yes')            def dataTransfer(conn):      while True:          data = conn.recv(1024)           data = data.decode('utf-8')          dataMessage = data.split(' ', 1)          command = dataMessage[0]            if command == 'loop':              Loop_()          if command == 'Hello':              Hello_()                   else:              print("X")        conn.close()    s = setupServer()    while True:      try:          conn = setupConnection()          dataTransfer(conn)      except:          break  

client.py

import socket    host = '192.168.56.1'  port = 5560    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  s.connect((host, port))    while True:      command = input("Enter your command: ")      s.send(str.encode(command))        s.close()  

I know your time is valuable and I appreciate your attention for spending time for help me.

jetPack compose Constraint layout issue

Posted: 08 Apr 2021 08:50 AM PDT

jetPack compose Constraint layout recomposes if vale of graphlayer (say alpha or any other property) changes. This shouldn't have been as graphic s layer is meant for animation purposes.

Edited: Here is The code I guess the updating of alph causes recomposition of who sheet which results in slow rendering of BottomSheetScaffold. Same sheet created using Box and Couluns result in best performance

package com.prime.player.audio.sheet    import android.graphics.Typeface  import androidx.compose.foundation.layout.fillMaxSize  import androidx.compose.foundation.layout.padding  import androidx.compose.material.*  import androidx.compose.runtime.Composable  import androidx.compose.ui.Modifier  import androidx.compose.ui.res.painterResource  import androidx.compose.ui.res.stringResource  import androidx.compose.ui.text.SpanStyle  import androidx.compose.ui.text.buildAnnotatedString  import androidx.compose.ui.text.font.FontFamily  import androidx.compose.ui.text.font.FontWeight  import androidx.compose.ui.text.style.TextAlign  import androidx.compose.ui.text.style.TextOverflow  import androidx.compose.ui.text.withStyle  import androidx.compose.ui.unit.dp  import androidx.compose.ui.unit.sp  import androidx.constraintlayout.compose.ChainStyle  import androidx.constraintlayout.compose.ConstraintLayout  import androidx.constraintlayout.compose.Dimension  import com.prime.player.R  import com.prime.player.composables.marqueText.MarqueText  import com.prime.player.theme.PlayerTheme  import dev.chrisbanes.accompanist.insets.statusBarsPadding    private const val TAG = "Sheet"  @OptIn(ExperimentalMaterialApi::class)  @Composable  fun Sheet(      progress: Float  ) {      //val alpha  = if (progress != -1.0f) 1- progress else null      ConstraintLayout(modifier = Modifier.fillMaxSize()) {          val (              mini_player, app_name, close, now_playing, playlist,              artist, artwork, title, play, timer, seekBar, lyrics,              label, upNext,          ) = createRefs()            createVerticalChain(              app_name,              now_playing,              playlist,              artist,              artwork,              title,              lyrics,              timer,              seekBar,              play,                label,              upNext,              chainStyle = ChainStyle.Packed          )                  Text(              text = stringResource(id = R.string.app_name),              maxLines = 1,              fontFamily = FontFamily.Cursive,              style = PlayerTheme.typography.h2,              color = PlayerTheme.colors.onSurface,              modifier = Modifier                  .statusBarsPadding()                  .padding(start = 16.dp)                  .constrainAs(app_name) {                    }          )            IconButton(              onClick = { /*TODO*/ },              modifier = Modifier.constrainAs(close) {                  end.linkTo(parent.end)                  top.linkTo(app_name.top)                  bottom.linkTo(app_name.bottom)              }          ) {              Icon(                  painter = painterResource(id = R.drawable.ic_close),                  contentDescription = "close",              )          }              Text(              text = "Now Playing",              maxLines = 1,              style = PlayerTheme.typography.h6,              fontWeight = FontWeight.Bold,              modifier = Modifier.constrainAs(now_playing) {                  start.linkTo(app_name.start, 16.dp)              }          )            Text(              text = "All Tracks",              maxLines = 1,              style = PlayerTheme.typography.caption,              fontWeight = FontWeight.SemiBold,              overflow = TextOverflow.Ellipsis,              modifier = Modifier.constrainAs(playlist) {                  start.linkTo(parent.start, margin = 26.dp)              }          )          //Artist          Text(              text = "Nusrat Fateh Ali Khan",              maxLines = 1,              style = PlayerTheme.typography.body2,              overflow = TextOverflow.Ellipsis,              modifier = Modifier                  .padding(top = 10.dp)                  .constrainAs(artist) {                      start.linkTo(parent.start, 16.dp)                  }          )              Artwork(              modifier = Modifier                  .padding(top = 16.dp)                  .constrainAs(artwork) {                      start.linkTo(parent.start)                      end.linkTo(parent.end)                      height = Dimension.fillToConstraints                  }          )            MarqueText(              text = "Mere Rashke karmr tune pehli Nazr jub Nazr say Melaie Maza Aa gaya",              textSize = 48f,              typeFace = Typeface.DEFAULT_BOLD,              modifier = Modifier.constrainAs(title) {                  start.linkTo(parent.start, 30.dp)                  end.linkTo(parent.end, 30.dp)                  width = Dimension.fillToConstraints              }          )            Text(              text = buildAnnotatedString {                  withStyle(style = SpanStyle(color = PlayerTheme.colors.onSurface.copy(alpha = 0.7f))) {                      append("Hale Dil Hova aisa, Dil ki lehar jaise\n")                  }                  withStyle(style = SpanStyle(color = PlayerTheme.colors.onSurface,                      fontSize = 20.sp)) {                      append("Jis Ka Na Illage Koie\n")                  }                  withStyle(style = SpanStyle(color = PlayerTheme.colors.onSurface.copy(alpha = 0.7f))) {                      append("Dard ye Zahar jaisa")                  }              },              textAlign = TextAlign.Center,              maxLines = 3,              style = PlayerTheme.typography.caption,              fontWeight = FontWeight.SemiBold,              modifier = Modifier                  .padding(bottom = 10.dp)                  .constrainAs(lyrics) {                      start.linkTo(parent.start, 30.dp)                      end.linkTo(parent.end, 30.dp)                      width = Dimension.fillToConstraints                  }          )            PlayRow(              modifier = Modifier                  .constrainAs(play) {                      start.linkTo(parent.start)                      end.linkTo(parent.end)                      width = Dimension.fillToConstraints                  }          )            Text(              text = "1:30/3:42",              modifier = Modifier                  .padding(bottom = 10.dp)                  .constrainAs(timer) {                      start.linkTo(seekBar.start)                  },              style = PlayerTheme.typography.caption,              fontWeight = FontWeight.Bold          )          LinearProgressIndicator(              progress = 0.1f,              modifier = Modifier                  .padding(bottom = 10.dp)                  .constrainAs(seekBar) {                      start.linkTo(parent.start, 30.dp)                      end.linkTo(parent.end, 30.dp)                      width = Dimension.fillToConstraints                      height =Dimension.preferredValue(1.dp)                  }            )                Text(              text = "Up Next",              style = PlayerTheme.typography.h6,              maxLines = 1,              modifier = Modifier.constrainAs(label) {                  start.linkTo(parent.start, 16.dp)              }          )            NextTrack(Modifier              .padding(16.dp)              .constrainAs(upNext) {                  start.linkTo(parent.start)                  end.linkTo(parent.end)                  width = Dimension.fillToConstraints              })       /*   MiniPlayer(              modifier = Modifier                  .graphicsLayer {                      if (alpha != null)                          this.alpha = alpha                  }                  .constrainAs(mini_player) {                      start.linkTo(parent.start)                      top.linkTo(parent.top)                  }          )*/      }  }  

elsa-workflows Integration with .net framework

Posted: 08 Apr 2021 08:50 AM PDT

I am planning to use elsa workflow in my application. I have below clarifications.

  1. I need to integrate the elsa workflow to my .net framework application (v4.5) is it possible.
  2. Even i have copied code from elsa core project to my .net framework application will it work?.
  3. I have cloned Elsa.Core project from git. And i have set Elsa.Dashboard.Web as startup project. Build and samples are working fine but dashboards are showing error it didn't able to load js and css files referenced

JPA create count query from existing CriteriaQuery

Posted: 08 Apr 2021 08:51 AM PDT

I have a query with some predicates, I need to count total records for paging.

Currently, what I'm doing is declare 2 roots for the query to get result list (1) and the count query (2), then with each predicate, duplicate it with different root like this

        CriteriaBuilder cb = em.getCriteriaBuilder();          CriteriaQuery<A> cq = cb.createQuery(A.class);          Root<A> root = cq.from(A.class);          CriteriaQuery<Long> cq = cb.createQuery(A.class);          Root<A> rootCount = countQuery.from(A.class);            List<Predicate> predicates = new ArrayList<>();          List<Predicate> predicatesCount = new ArrayList<>();                    Predicate p = cb.equal(root.get(A.ID), 1);          predicates.add(p);          Predicate p1 = cb.equal(rootCount.get(A.ID), 1);          predicatesCount.add(p1);          ...          // execute both query to get result    

So the question is:

Is it possible to create count query from query (1)? Or something to reuse the predicates with count query?

Thanks for reading!

PWA Hosted on firebase behaves diffrenly depending on how it's accessed

Posted: 08 Apr 2021 08:50 AM PDT

I am developing a PWA and hosting it on Firebase. The issue is, when deployed to Firebase, the application behaves diffrently, depending on how it's being accessed.

Diffrent ways i'm accessing it and their outcome:

  1. From Chrome browser on Windows. Behaves as expected, showing all pages correctly.

  2. From Chrome browser on Android. Behaves as expected, except for one page not loading content from database. (This data is loading from another page).

  3. From Chrome browser on Android, with the application installed, and opening the installed application from Chrome's three dots and then "Open application". Behaves as example 2, just running as an application (without url at the top etc.).

  4. From homescreen icon on Android device. Shows the splash screen and then shows the json contents of the manifest file?.

This is my manifest.json file:

{      "name": "Smart Sockets",      "short_name": "SmartSockets",      "start_url": "./index.html",      "display": "standalone",      "background_color": "#BBDEFB",      "theme_color": "#BBDEFB",      "orientation": "portrait-primary",      "icons": [{              "src": "/img/icons/Artboard-72.jpg",              "type": "image/png",              "sizes": "72x72"          }      ]  }  

This is my firebase.json file.

{    "hosting": {      "public": "public",      "ignore": [        "firebase.json",        "**/.*",        "**/node_modules/**"      ]    }  }  

I've tried setting "start_ul" to "/", "", "./index.html", same results. And i've tried clearing caching in all the diffrent scenarios, and it does'nt make a diffrence.

What could be the cause of these diffrent behavious?

How can I use Google Benchmark on godbolt

Posted: 08 Apr 2021 08:50 AM PDT

I am trying to run some code on that uses Google Benchmark. I am trying to share it with some colleagues using Godbolt. It seems to support Google Benchmark as a library you can select but I can not get it to compile.

This is the link.
https://godbolt.org/z/dxvl5W

It is using gcc 7.3 with these options:
-std=c++17 -O3 -lbenchmark

I tried adding -lbenchmark and -lbenachmark-main. None resolve the issue.

This is the error I am getting

ASM generation compiler returned: 0    /opt/compiler-explorer/gcc-7.3.0/bin/../lib/gcc/x86_64-linux-gnu/7.3.0/../../../../x86_64-linux-gnu/bin/ld: cannot find -lbenchmark    collect2: error: ld returned 1 exit status    Execution build compiler returned: 1  

How to avoid undefined in string concatenation?

Posted: 08 Apr 2021 08:50 AM PDT

I'm iterating over an object and I want to concatenate the name of the service. This is my code:

var servizi;    for(var i = 0; i < appointment.id_services.length; i++)  {      servizi += appointment.id_services[i].name + " ";  }  

Now the problem's that I got this result:

undefined hair cut

In my object there's only hair and cut, why I get undefined also?

Json.net Async when writing to File

Posted: 08 Apr 2021 08:51 AM PDT

Json.net has the async functions for converting an object to json like:

json = await JsonConvert.DeserializeObjectAsync<T>  

But when I want to write an object to a json file it seems better to me to do it directly using a file Stream.

So i think it should be something like this:

 var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);        using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))      {          using (StreamWriter sw = new StreamWriter(fileStream.AsStreamForWrite()))          {              using (JsonWriter jw = new JsonTextWriter(sw))              {                  jw.Formatting = Formatting.Indented;                    JsonSerializer serializer = new JsonSerializer();                  serializer.Serialize(jw, obj);              }          }  

But on the JsonSerzializer Object I can't find async methods. Also I think that IO operations shouldn't be placed in a own thread.

What is the recommended approach ?

No comments:

Post a Comment