Monday, March 22, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


What could cause NSUbiquitousKeyValueStore.synchronize to fail for certain users?

Posted: 22 Mar 2021 08:07 AM PDT

I use NSUbiquitousKeyValueStore to sync preferences between devices in my app. For a small number of my users (on the order of 0.1%), their preferences do not sync between their devices. The values saved to NSUbiquitousKeyValueStore can be read properly until the app terminates, but when launched again the values are gone.

One clue I have found is that if I call synchronize, it returns false for these users. This seems to be the only reliable indication that anything is going wrong. The documentation states that this function will "...return false if an error occurred. For example, this method returns false if an app was not built with the proper entitlement requests." But since this is working for 99.9% of users, it's hard to imagine it's an entitlement request problem.

I am in contact with one user who has this issue, and they report that there is nothing out of the ordinary about the state of their iCloud account, and they are on the latest version of iOS.

I have tried listening for didChangeExternallyNotification and checking for the various possible NSUbiquitousKeyValueStoreChangeReasonKey that indicate things like being out of storage space, and none of them seem to be triggered for these users.

Are there any other known reasons why synchronize might return false, that might help make sense of why these users cannot sync their preferences?

Gauss 21 Software: how do I install the following packages?

Posted: 22 Mar 2021 08:07 AM PDT

I tried running the code: library optmum, pgraph; optset; graphset;

and obviously it says I need to install the packages and all but I am not sure where exactly I am supposed to go to find these. I went to the Install application and package manager but neither seems to have the packages I am looking for. Ideally, I would like to have these packages in my library and run the command above. How do i proceed with this Gauss software?

Is that possible to import and read xml file using SAS for password protected Linux folder

Posted: 22 Mar 2021 08:07 AM PDT

I wanted to import xml file using SAS from linux password protected folder (which required user,password,Host and recfm).

Currently I can import text file but not xml.

Below is the code which I used to import text file but not able to use same for xml.

filename Fullf ftp "&mytime."   cd='/ABCfile/in/PROD/Step'           user='Auser' pass = 'Pass_123' host='abcdttf.cor.abc.com'           recfm=v prompt;  

Any suggestion would really help. Thank you

BeautifulSoup - name of link

Posted: 22 Mar 2021 08:06 AM PDT

i have this html page:

<ul class="quicklinks">  <li class="subnav_item_main">  <a href="action.html">Action  </a> </li>  <li class="subnav_item_main">  <a href="adventure.html">Adventure  </a> </li>..............  

I succeeded insert all the links to List:

soup=load_soup_object(html_file_name)  mtag=soup.find("ul", attrs={"class" : "quicklinks"})  link_to_pages=[t['href'] for t in mtag.findAll("a")]  

but how can i insert the CATEGORY's NAMES? like this: [Action, Adventure........]

Cannot count elements in a column created with string.split which is supposed to be a list

Posted: 22 Mar 2021 08:06 AM PDT

I am working with a pandas df with info about netflix shows. One of the columns was a string with all the countries involved in the production netflix_df['country']. I created an additional column which is intended to be a list of all the individual countries (because there are coproductions involving more than one country) called netflix_df['list_of_countries'] by using the following code:

netflix_df['list_of_countries']=netflix_df['country'].str.split(',')  

Afterwards, I attempted to create a new column called netflix_df['number_of_countries'] which included the number of countries in the lists of the column netflix_df[list_of_countries] by doing the following:

netflix_df['number_of_countries'] = [len(c) for c in netflix_df['list_of_countries']]  

Nevertheless, I got the following error: TypeError: object of type 'float' has no len()

This doesn't make sense to me, since the column is filled with lists and not floats. What is wrong in my code? I would appreciate some help with this. Thank you very much.

how do you write VBA code for changing font color based on cell fill color

Posted: 22 Mar 2021 08:06 AM PDT

I have a very large report that when someone is finished they fill the cell green (RGB 146,208,80). the font color maybe red due to a conditional formatting of <today()+7...I was trying to create a VBA code that I could use in the conditional formatting formula to create a new rule; Cell A2 =green change font to black.

Here is my attempt at the code: Sub fillcolor(range) Range ("A2").Select.inteior.color Selection.RGB(146,208,80).Select.font.color=RGB(0,0,0) EndSub

I believe if I write the VBA code I don't need a conditional formatting rule.

Please help!

Kotlin - How to increase value of mutableMap

Posted: 22 Mar 2021 08:06 AM PDT

I wanna add 1 to a particular item value of mutableMap in Kotlin laguage. Below is what I made. Is there any way to make this code simple?

enter code here  

map[1] = map[1]?.let {it -> it + 1 } ?: 1

The INSERT statement conflicted with the CHECK constraint when inserting values

Posted: 22 Mar 2021 08:07 AM PDT

Trying to insert data into a table but keep getting the following error: The INSERT statement conflicted with the CHECK constraint "CK__etudiant__dateNa__3D5E1FD2". The conflict occurred in database "gestionAbsEtud", table "dbo.etudiant", column 'dateNaissance'.

create table etudiant(      numInscription int primary key,      nom char(20),      prenom char(20),      sexe char check(sexe in('M','F')),      dateNaissance date check(datediff(year, datenaissance, getdate())  between 15 and 30 ),      email varchar(20),      adresse varchar(20),      idFiliere varchar(10) foreign key references filier);      go  

and this is the value i want to add :

insert  into etudiant values  (1,'elbaraa','HAMMAN','m','20001126','contact@baraa.tk','DI1');  

Include a javascript class in a parent class, rather than in window when it is loaded

Posted: 22 Mar 2021 08:06 AM PDT

For example, we are request jQuery with <script src=". From now on window.jQuery or jQuery will be available.

But I want to prevent it from being used in this way and collect it in a pool.

For example:

container = {     jQuery: (function(){}(), // jQuery' script,     ..,     ..,     ..  };    container.jQuery('.hi').addClass('hello');  container.jQuery(document).on('click', function(){});  

Is it possible to do this?

JavaScript sort an array of objects based array of properties

Posted: 22 Mar 2021 08:07 AM PDT

I have for example this dataset:

const order = [    { key: "job", direction: "ascending" },    { key: "age", direction: "descending" },  ];    const records = [    { name: "christian", age: 40, job: "developer" },    { name: "andrew", age: 48, job: "developer" },    { name: "elisabeth", age: 31, job: "floor manager" },    { name: "oscar", age: 61, job: "floor manager" },    { name: "gisela", age: 51, job: "area manager" },    { name: "buffy", age: 27, job: "trainee" },    { name: "carl", age: 23, job: "trainee" },  ];  

I need to sort the records array according to the criteria from order array. I ended up with this solution:

const sorted = records.sort(    (recordA, recordB) =>      recordA.job.localeCompare(recordB.job) || recordA.age - recordB.age  );  

But I cant understand how can I use the order array instead of hardcoded the job and age properties. The order array can have many properties.

Stop propagation of all events

Posted: 22 Mar 2021 08:07 AM PDT

I am trying to handle Backspace key press of a user. I have 2 handlers bound to one input element. Since it is not possible to detect key press in the onChange event handler, I have to do it in the onKeyDown. I want to stop the propagation of onChange event when backspace is pressed (and handled in the onKeyDown event handler). Any ideas how to achieve this? Thank you!

Is there a loaded event or something for img element when using the loading="lazy" attribute

Posted: 22 Mar 2021 08:06 AM PDT

I'm trying to set a CSS effect to images when using loading="lazy" attribute, is there any event so I can handle when the image is loaded?

<img laoding="lazy" src="someurl"/>  

Trying to get user input (asking for an integer) and making it loop until the user inputs an integer. Trying to use While true, try and except

Posted: 22 Mar 2021 08:07 AM PDT

tries = 0  while True:      try:        imput = int(input("Input An Integer: "))        if imput != 0:        print(imput)      except ZeroDivisionError:          print("Bro what you doin?")      except TypeError:          print("Bruh What you doin?")  

Validation of the dataset in GCN

Posted: 22 Mar 2021 08:07 AM PDT

I am using PyTorch I am trying to do the validation on my dataset to obtain optimal number of channels in my neural network. I have the following code:

def train_during_validation():      for epoch in range (1, 201):          model.train()          optimizer.zero_grad()          out = model(data.x, data.edge_index)          loss = criterion(out[data.val_mask], data.y[data.val_mask])          loss.backward()          optimizer.step()      return loss    def validation():      loss_val = np.zeros(50, dtype = float)      model = GCN(hidden_channels = 1)      loss_val = train_during_validation()      print(loss_val)            validation()  

In the code above I train previously defined model with 16 channels and I obtain a loss of 0.33. But as soon as I start doing validation on hidden_channel (see code below), my loss does not go down (it remains on 1.95). I do not understand why. Can somebody explain?

def train_during_validation(model):      print(f'Model:{model}')      for epoch in range (1, 201):            model.train()          optimizer.zero_grad()          out = model(data.x, data.edge_index)          loss = criterion(out[data.val_mask], data.y[data.val_mask])          loss.backward()          optimizer.step()      return loss    def validation():      loss_val = np.zeros(50, dtype = float)      model = GCN(hidden_channels = 1)      for i in range (50):          model = GCN(hidden_channels = i)          #print(model)          loss_val[i] = train_during_validation(model)          print(loss_val[i])            validation()  

Fill a 1 min Dateframe column from another 1 day Dateframe column

Posted: 22 Mar 2021 08:06 AM PDT

I'm new to pandas and time series analysis. So bear with me if I'm missing something very obvious.

I have 2 data frames. df1 is in 1 day time frame and df2 is in 1 min time frame. I want to insert new column in df2 and fill same data for all rows for a given day from df1.

df 1 :

    Date         Range    0   2020-03-01   50  1   2020-03-02   5  2   2020-03-03   20  3   2020-03-04   15  

df 2 :

    Date            0   2020-03-01 09:55:00   1   2020-03-01 09:56:00  2   2020-03-01 09:57:00    3   2020-03-01 09:58:00      .......      .......      .......  n   2020-03-04 03:15:00  

Expected Result :

df 2 :

    Date                   Range    0   2020-03-01 09:55:00    50  1   2020-03-01 09:56:00    50  2   2020-03-01 09:57:00    50  3   2020-03-01 09:58:00    50      .......      .......      .......  n   2020-03-04 03:15:00    15  

EDIT 1 :

1 min data frame have other column data too and I just wanna merge this particular Range data from 1 day df to 1 min df.

Option Strict On disallows implicit conversions between String and Object {String}

Posted: 22 Mar 2021 08:06 AM PDT

I am trying to clean my ways as a beginner programmer by using Option Strict On. I managed to clean all errors except this one.
I am using the parameter Tag of a tool strip for some text information. Clicking on the tool strip, I need to remember the value of the tag in a string and change the value of that tag.

How can I convert the Object {String} sender.tag to a String and the String myString and an Object {String}?

Private Sub ToolStrip_ItemClicked(sender As Object, e As ToolStripItemClickedEventArgs) Handles ToolStrip.ItemClicked      Dim myString As String = sender.tag      sender.tag = "It is selected"      'more code...  End Sub  

Thank you.

Edit: see here a screenshot of the relevant part of the code: enter image description here

How do i use multiple paths and endpoints in Express Gateway with my RESTAPI?

Posted: 22 Mar 2021 08:07 AM PDT

Currently working on an Express Gateway that handles call for an RESTAPI and a GraphQL microservices. The GraphQL pipeline works fine, but the pipeline for the RESTAPI is what I'm struggling with.

I made a simple CRUD functionality RESTAPI that can create, read, update and delelete books and authors. They have multiple routes to do this, like: http://localhost:4001/books/add.

The problem is that I dont really understand how to translate these routes or paths in tho the express gateway so I can reach them via the gateway.

This is my current code, config.yml:

http:    port: 8080  admin:    port: 9876    host: localhost  apiEndpoints:    restapi:      host: localhost      paths: '/rp'    graphql:      host: localhost      paths: '/gql'  serviceEndpoints:    restapi:      url: 'http://localhost:4001/'        graphql:        url: 'http://localhost:4000'  policies:    - proxy  pipelines:    restapi:      apiEndpoints:        - restapi      policies:        - proxy:            - action:                 serviceEndpoint: restapi                changeOrigin: true                ignorePath: false                prependPath: true                stripPath: true                    graphql:      apiEndpoints:        - graphql      policies:        - proxy:            - action:                serviceEndpoint: graphql                changeOrigin: true  

This is the restapi book code:

const express = require('express');  const mongoose = require('mongoose');  const book = require('../models/book');  const { findById } = require('../models/book');  const router = express.Router();  const Book = require('../models/book');    //read all books  router.get('/', async (req, res) =>{      try{          const AllBooks = await Book.find();          res.json(AllBooks);      }catch(err){          res.json({message:err});      }        })    //create book  router.post('/add', async (req, res) => {      var NewBook = new Book({          title: req.body.title,          pages: req.body.pages      })      try{          const SavedBook = await NewBook.save();          res.json(SavedBook);      }catch(err){          res.json({message: err})      }  })    //read book  router.get('/:BookId', async (req, res) => {      try{          const ReadBook = await Book.findById(req.params.BookId);          res.json(ReadBook);      }catch(err){          res.json({message: err});      }      })    //update book  router.patch('/update/:BookId', async (req, res) => {      try{          const updatedBook = await Book.updateOne({_id: req.params.BookId},              {$set: {title: req.body.title, pages: req.body.pages}});          res.json(updatedBook);      }catch(err){          res.json({message: err});      }      })    //delete book  router.delete('/delete/:BookId', async (req, res) => {      try{           const DelBook = await Book.findById(req.params.BookId);           DelBook.delete();           res.send(DelBook + " Deleted");      }catch(err){          res.json({message: err});      }  })        module.exports = router;  

Now when I call: http://localhost:4001/rp, it return "restapi" just like i told to do it so. But when I call: http://localhost:4001/rp/books, it returns a "CANNOT GET", which is logical cause I didnt define this path. First I thought the express gateway would understand this automaticly.

Do i have to hardcode all the paths?

I hope somebody can explain this to me, since express gateway does not have an example like my case. :)

Python conditional assignment where "condition" using compound statements and inline variable? [duplicate]

Posted: 22 Mar 2021 08:06 AM PDT

Using languages like java, c and csharp you are able to perform conditional assignment using an inline variable to avoid unnecessary function calls in the process.

As an example below, if Tree.find() finds an element the statement will extract just the text part of the element otherwise null.

strvar = (element = Tree.find(".//xpath/str")) ? element.text : null  

Question: why doesn't this work in Python and is there an alternative one liner?

strvar = None if not (element = Tree.find(".//xpath/str")) else element.text  

EDIT / ANSWER

  1. The very simple answer you need to utilize the recently added Walrus operator (:=) that enables comparison during assignment. The Walrus operator that was introduced in version 8.3. The solution is just to add := instead of =
strvar = None if not (element := Tree.find(".//xpath/str")) else element.text  
  1. Please note that the evaluated direction does matter when it comes to type casting and conditional assignment using :=

a) Ok

strvar = None if not (element := Tree.find(".//xpath/str")) else element.text  

b) Warning regarding implicit type casting

strvar = element.text if (element := Tree.find(".//xpath/str")) else element else None  

Warning: <input>:1: FutureWarning: The behavior of this method will change in future versions. Use specific 'len(elem)' or 'elem is not None' test instead.

In this case you need to check the assignment using "is not None" ie:

strvar = element.text if (element := Tree.find(".//xpath/str")) is not None else element else None  

Modbus registers can be only read and cannot be written

Posted: 22 Mar 2021 08:06 AM PDT

I am trying communicate via Modbus protocol to a uC2 SE controller for a air-water chiller. A serial RS485 to USB port COM is connected with the controller and I was able to read registers, but it is not possible to change their values by using write_register function. I have also tried with tester. exe and Modscan64 softwares and the result was the same, they only can read but not write. I have introduced here the piece of code is being run and debug responses can be checked. Thank you for your help in advance!

Change temperature setpoint

COOLING_SETPOINT_REG = 41

try: print(instrument.read_register(COOLING_SETPOINT_REG,1)) except IOError: print('Failed to read from instrument')

NEW_TEMPERATURE = 20.1

return_flag = instrument.write_register(COOLING_SETPOINT_REG, NEW_TEMPERATURE,1,functioncode = 6, signed = True) # Registernumber, value, number of decimals for storage output_flag = 'SUCCESS' if return_flag else 'FAILURE' print('writing single register status ' + output_flag + '\n' )

try: print(instrument.read_register(COOLING_SETPOINT_REG,1)) except IOError: print('Failed to read from instrument')

Respuesta debug:

MinimalModbus debug mode. Will write to instrument (expecting 7 bytes back): '\x01\x03\x00)\x00\x01UÂ' (01 03 00 29 00 01 55 C2) MinimalModbus debug mode. Opening port COM8 MinimalModbus debug mode. Clearing serial buffers for port COM8 MinimalModbus debug mode. No sleep required before write. Time since previous read: 334030.00 ms, minimum silent period: 4.01 ms. MinimalModbus debug mode. Closing port COM8 MinimalModbus debug mode. Response from instrument: '\x01\x03\x02\x00ȹÒ' (01 03 02 00 C8 B9 D2) (7 bytes), roundtrip time: 62.0 ms. Timeout for reading: 1000.0 ms.

20.0 MinimalModbus debug mode. Will write to instrument (expecting 8 bytes back): '\x01\x06\x00)\x00É\x98T' (01 06 00 29 00 C9 98 54) MinimalModbus debug mode. Opening port COM8 MinimalModbus debug mode. Clearing serial buffers for port COM8 MinimalModbus debug mode. No sleep required before write. Time since previous read: 47.00 ms, minimum silent period: 4.01 ms. MinimalModbus debug mode. Closing port COM8 MinimalModbus debug mode. Response from instrument: '\x01\x06\x00)\x00É\x98T' (01 06 00 29 00 C9 98 54) (8 bytes), roundtrip time: 47.0 ms. Timeout for reading: 1000.0 ms.

writing single register status FAILURE

MinimalModbus debug mode. Will write to instrument (expecting 7 bytes back): '\x01\x03\x00)\x00\x01UÂ' (01 03 00 29 00 01 55 C2) MinimalModbus debug mode. Opening port COM8 MinimalModbus debug mode. Clearing serial buffers for port COM8 MinimalModbus debug mode. No sleep required before write. Time since previous read: 46.00 ms, minimum silent period: 4.01 ms. MinimalModbus debug mode. Closing port COM8 MinimalModbus debug mode. Response from instrument: '\x01\x03\x02\x00ȹÒ' (01 03 02 00 C8 B9 D2) (7 bytes), roundtrip time: 47.0 ms. Timeout for reading: 1000.0 ms.

API response is showing outdated data with PUT/PATCH requests

Posted: 22 Mar 2021 08:06 AM PDT

I am working on an API using Django REST framework. In my case, I am using nested serializers so I am required to overwrite the .update method.

Here's the required desc:

Serializers

Config Serializer

class DeviceConfigSerializer(serializers.ModelSerializer):      config = serializers.JSONField()      context = serializers.JSONField()        class Meta:          model = Config          fields = ['backend', 'status', 'templates', 'context', 'config']  

Device Detail Serializer

class DeviceDetailSerializer(serializers.ModelSerializer):      config = DeviceConfigSerializer()        class Meta(BaseMeta):          model = Device          fields = [              'id',              'name',              'organization',              'mac_address',              'key',              'last_ip',              'management_ip',              'model',              'os',              'system',              'notes',              'config',          ]        def update(self, instance, validated_data):          config_data = None            if self.data['config'] is None and validated_data.get('config'):              config_data_ = dict(validated_data.get('config'))              config_templates = config_data_.pop('templates')              config = Config.objects.create(device=instance, **config_data_)              for template in config_templates:                  config.templates.add(template.pk)            if validated_data.get('config'):              config_data = validated_data.pop('config')            # When config data is provided with PATCH requests          if config_data:              instance.config.backend = config_data.get(                  'backend', instance.config.backend              )              instance.config.status = config_data.get('status', instance.config.status)                config_templates = config_data.get('templates')              instance.config.templates.clear()              for template in config_templates:                  instance.config.templates.add(template.pk)                instance.config.context = json.loads(                  json.dumps(config_data.get('context')),                  object_pairs_hook=collections.OrderedDict,              )              instance.config.config = json.loads(                  json.dumps(config_data.get('config')),                  object_pairs_hook=collections.OrderedDict,              )              instance.config.save()            return super().update(instance, validated_data)  

Device Detail Views

class DeviceDetailView(RetrieveUpdateDestroyAPIView):      serializer_class = DeviceDetailSerializer      queryset = Device.objects.all()  

Now when I Send a PUT/PATCH request to its endpoint, It works fine and the fields in the database get updated, but since after the PUT/PATCH request gets completed successfully I should be returned with the updated instance fields in the response, But in my case, I am required to again send a GET request/ ore refresh the page to get the updated data in the Browsable API. Is there anything more I need to add, or am I missing something?

How to check mandatory fields are present in the CSV while data ingestion in marklogic mlcp

Posted: 22 Mar 2021 08:07 AM PDT

I want to check few mandatory fields are available in CSV while ingestion of data through MLCP in marklogic. If those fields are not available, I need to ignore those records has to be ingested in marklogic

vb.net Stringbuilder to create HTML file

Posted: 22 Mar 2021 08:06 AM PDT

I am using a StringBuilder to create a HTML file from my DataTable. The file is created but when I open it in the webbrowser I have to scroll all the way down to see the table. In other words there is a big blank page first with nothing at all.

Public Function ConvertToHtmlFile(ByVal myTable As DataTable) As String          Dim myBuilder As New StringBuilder          If myTable Is Nothing Then              Throw New System.ArgumentNullException("myTable")          Else                                'Open tags and write the top portion.               myBuilder.Append("<html xmlns='http://www.w3.org/1999/xhtml'>")              myBuilder.Append("<head>")              myBuilder.Append("<title>")              myBuilder.Append("Page-")              myBuilder.Append("CLAS Archive")              myBuilder.Append("</title>")              myBuilder.Append("</head>")              myBuilder.Append("<body>")              myBuilder.Append("<br /><table border='1px' cellpadding='5' cellspacing='0' ")              myBuilder.Append("style='border: solid 1px Silver; font-size: x-small;'>")                  myBuilder.Append("<br /><tr align='left' valign='top'>")                For Each myColumn As DataColumn In myTable.Columns                  myBuilder.Append("<br /><td align='left' valign='top' style='border: solid 1px blue;'>")                  myBuilder.Append(myColumn.ColumnName)                  myBuilder.Append("</td><p>")              Next                myBuilder.Append("</tr><p>")                'Add the data rows.              For Each myRow As DataRow In myTable.Rows                  myBuilder.Append("<br /><tr align='left' valign='top'>")                  For Each myColumn As DataColumn In myTable.Columns                      myBuilder.Append("<br /><td align='left' valign='top' style='border: solid 1px blue;'>")                      myBuilder.Append(myRow(myColumn.ColumnName).ToString())                      myBuilder.Append("</td><p>")                  Next              Next              myBuilder.Append("</tr><p>")          End If            'Close tags.           myBuilder.Append("</table><p>")          myBuilder.Append("</body>")          myBuilder.Append("</html>")            'Get the string for return. myHtmlFile = myBuilder.ToString();          Dim myHtmlFile As String = myBuilder.ToString()            Return myHtmlFile      End Function  

How to best use TaskCompletionSource with SemaphoreSlim

Posted: 22 Mar 2021 08:06 AM PDT

This is an evolution of my previous question. To recap, I have 3rd party WebSocket that I need to consume where the request is sent in one method and the response is given in another. I'm attempting to convert this to a Task.

I read this MSDN Magazine article which shows an example of using a SemaphoreSlim to control entry but my case isn't quite the same and I'm not sure what the best thing to do is.

I could put the SemaphoreSlim.Release() in the finally block of GetPositionsAsync() as shown in the article but if there were an error then the finally could get called before positionEnd() which would cause an error in GetPositionsAsync() if there was another thread waiting for the semaphore. On the other hand if I put the SemaphoreSlim.Release() in positionEnd() can I reliably assume that GetPositionsAsync() will return the proper result? I'm worried that if the release happens a thread waiting for the semaphore might call Positions.Clear() before the other thread saves the value of Positions to result. So really the same concern either way. Which is better or is there another way to protect this problem from happening all together?

This is what I have so far...

    private TaskCompletionSource<List<Position>> PositionsTaskSource { get; set; }      private readonly SemaphoreSlim PositionsMutex = new(1, 1);            public async Task<List<Position>> GetPositionsAsync()      {          try          {              await PositionsMutex.WaitAsync().ConfigureAwait(false);              Positions.Clear();              PositionsTaskSource = new();              IbWebSocket.reqPositions();              var result = await PositionsTaskSource.Task;              //Write to Trace Log here              return result;          }          finally          {              //I could put the Release here as shown in the article              //PositionsMutex.Release();           }      }            /// <summary>      ///        Provides a position to the reqPositions() method.  When the last position has been received positionEnd() is called.      /// </summary>      /// <param name="account"></param>      /// <param name="contract"></param>      /// <param name="value"></param>      public void position(string account, Contract contract, double value)      {          Positions.Add(new Position(account, contract, value));      }        /// <summary>      ///     Indicates all the positions have been transmitted.      /// </summary>      public void positionEnd()      {          PositionsTaskSource.TrySetResult(Positions))          PositionsMutex.Release();      }  

How to round values to your expectations

Posted: 22 Mar 2021 08:07 AM PDT

Input values to below Python program:

20 21 22

Expected Output:

32

import math  n_stu_grp1 = abs(int(input()))  n_stu_grp2 = abs(int(input()))  n_stu_grp3 = abs(int(input()))  n_desk = (n_stu_grp1 + n_stu_grp2 + n_stu_grp3) / 2  print(n_desk)  

My code as mentioned above generates output as 31.5, i tried also using math.ceil(n_desk) but it gives me the same result ? Pls advise how we can get result as 32

Hi Friends, pls refer the code which i tried using math.ciel:

import math  n_stu_grp1 = abs(int(input()))  n_stu_grp2 = abs(int(input()))  n_stu_grp3 = abs(int(input()))  n_desk = (n_stu_grp1 + n_stu_grp2 + n_stu_grp3) / 2  n_desk_l = math.ceil(n_desk)  print(n_desk_l)  

the above mentioned code is against a coding prolem as mentioned below :

A school has decided to create three new math groups and equip three classrooms for them with new desks. At most two students may sit at any desk. The number of students in each of the three groups is known. Output the smallest number of desks to be purchased. Each group will sit in its own classroom.

Input data format:

The program receives the input of three non-negative integers: the number of students in each of the three classes (the numbers do not exceed 1000).

For ex: 20 21 22

Problem : As per above problem statement and as per my understanding my code is right which i have written using math.ceil. What are your thoughts my friends? The issue is that my program is failing some random tests for ex when i give input 17,22 and 23 it fails the test of the coding platform ? pls advice

Is the following java code thread safe without volatile?

Posted: 22 Mar 2021 08:06 AM PDT

public static Singleton singleton;    public static Singleton get(){      synchronized (Singleton.class) {            if (singleton == null) {                singleton = new Singleton();            }        }       return singleton;  }  

Some one say that no volatile for singleton variable is wrong. But I think this is the right code for singleton object creation. I want to know whether this code has a thread safety or not?

Filter data without altering date format

Posted: 22 Mar 2021 08:06 AM PDT

I have a large dataframes with date column like this one:

import pandas as pd    cars = {'Date': ['2020-09-11','2020-10-11','2021-01-12','2020-01-03', '2021-02-01'],          'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4','Mercedes'],          'Price': [22000,25000,27000,35000,45000]          }    df = pd.DataFrame(cars, columns = ['Date','Brand', 'Price'])    print (df)    

Now the date column is an object and I want to filter out only 2021 data. Originally I am changing date column from object to datetime but this approach wont work if I try to convert that data to json format. This what I tried

 yest_date = date(2021, 1, 01) - timedelta(days=1)   yest_date = yest_date.strftime("%Y-%m-%d")    cur_date = date(2021, 2, 05)  cur_date = cur_date.strftime("%Y-%m-%d")    df['Date] = pd.to_datetime(df['Date'])    if yest_date is not None:     yest_data = df.loc[df['Date'] <= pd.to_datetime(yest_date), :]    if cur_date is not None:     cur_data = data2.loc[data2[project.date_var] <= pd.to_datetime(cur_date), :]    

My question not is, can I be able to filter out values between 2 dates without converting the date object date to datetime? If so How can filter date between 2 dates without changing date structure to datetime.

Android emulator - error while loading state for instance 0x0 of device 'goldfish_pipe'

Posted: 22 Mar 2021 08:07 AM PDT

I updated some android studio components 2 days ago and everything messed up. Now I cant use android emulator since it exits immediately the moment it gets lunched.

I already tried the following:

  1. Delete all my virtual devices and created new ones - didn't work.
  2. Wipe Emulator data - didn't work.
  3. Tried to lunch emulator manually in AVD - didn't work
  4. Launch emulator with the option Cold boot now. - Emulator displayed this message Cold boot: requested by the user and exit.
  5. Uninstall Android Studio and deleted whole SDK folder and downloaded everything new - didn't work may be bacause the problem is within latest release.
  6. Tried to downgrade Emulator manually! I asked it here - I downloaded the previous release and deleted everything in sdk\emulator and put files there, Deleted all virtual devices and create new ones. Pressed run. this message pops up when emulator start Cold boot different AVD Configuration and then it exits again. This is may be I didn't downgrade all emulator related tools, I don't know how!. And sometimes different message pops up saying Resetting for cold boot: emulation engine failed and exits.

None of these worked and I am out of ideas.

Here are logs get printed before emulator flash disappearance.

16:00 Emulator: C:\Users\Nux\AppData\Local\Android\Sdk\emulator\qemu\windows-x86_64\qemu-system-x86_64.exe: error while loading state for instance 0x0 of device 'goldfish_pipe'

16:00 Emulator: deleteSnapshot: for default_boot

16:00 Emulator: qemu: unsupported keyboard cmd=0x84

16:00 Emulator: Process finished with exit code 0

Screenshot of emulator before disappearance enter image description here

SDK Tools screenshot enter image description here

Edit Several issues have been submitted already:

  1. https://issuetracker.google.com/issues/132481542
  2. https://issuetracker.google.com/issues/132834989
  3. https://issuetracker.google.com/issues/131854864

Angular - How to combine multiple "valueChanges" observables into one

Posted: 22 Mar 2021 08:06 AM PDT

How can I combine the following subscriptions into one?

    this.form.get("type").valueChanges.subscribe(() => {          this.calcFinalTransports();      })      this.form.get("departure").valueChanges.subscribe(() => {          this.calcFinalTransports();      })      this.form.get("destination").valueChanges.subscribe(() => {          this.calcFinalTransports();      })      this.form.get("stations").valueChanges.subscribe(() => {          this.calcFinalTransports();      })  

Mount Android emulator images

Posted: 22 Mar 2021 08:07 AM PDT

I am trying to analyse Android malware on an emulator with Android 2.1. I want to analyze the files permissions and fingerprints after the execution of the suspicious app. I know, I can use the adb shell to get this information, but I think I can't trust the information after the execution of e.g. a rootkit.

I think the only way to prevent rootkits from hiding is by mounting the images directly or? I have the following files:

ramdisk.img  snapshots.img  userdata-qemu.img  cache.img  system.img  userdata.img  zImage  

How can they be mounted/extracted on Ubuntu (read access is enough)?

With unyaffs I can extract the system.img and userdata.img file. simg2img returns "bad magic" for all files.

Thanks Alex

Edit: userdata-qemu.img works unyaffs2

Why is __dirname not defined in node REPL?

Posted: 22 Mar 2021 08:06 AM PDT

From the node manual I see that I can get the directory of a file with __dirname, but from the REPL this seems to be undefined. Is this a misunderstanding on my side or where is the error?

$ node  > console.log(__dirname)  ReferenceError: __dirname is not defined      at repl:1:14      at REPLServer.eval (repl.js:80:21)      at Interface.<anonymous> (repl.js:182:12)      at Interface.emit (events.js:67:17)      at Interface._onLine (readline.js:162:10)      at Interface._line (readline.js:426:8)      at Interface._ttyWrite (readline.js:603:14)      at ReadStream.<anonymous> (readline.js:82:12)      at ReadStream.emit (events.js:88:20)      at ReadStream._emitKey (tty.js:320:10)  

No comments:

Post a Comment