Monday, January 17, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Python Selenium, Firefox driver. Dismiss Open/Save file popup

Posted: 17 Jan 2022 02:54 AM PST

this is my setup for the driver:

from selenium.webdriver import DesiredCapabilities  from selenium.webdriver.firefox.options import Options    #binary = FirefoxBinary(r'C:\Program Files (x86)\Mozilla Firefox\Firefox.exe')  fp = (r'C:\Users\user\AppData\Roaming\Mozilla\Firefox\Profiles\fdjhsjfhd.default')    opts = Options()  opts.profile = fp    fp = webdriver.FirefoxProfile()  fp.set_preference("browser.download.folderList", 2) # 0 means to download to the desktop, 1 means to download to the default "Downloads" directory, 2 means to use the directory   fp.set_preference("browser.helperApps.alwaysAsk.force", False)  fp.set_preference("browser.download.manager.showWhenStarting",False)  fp.set_preference("browser.download.dir", download_directory)   fp.set_preference('browser.helperApps.neverAsk.saveToDisk','image/jpeg,image/png,excel,text/plain,csv/text,application/octet-stream')    firefox_capabilities = DesiredCapabilities.FIREFOX  firefox_capabilities['marionette'] = True  

But still I get the pop, as per attached. enter image description here

What is wrong?

Thanks

Playing Background Music on Objective-C

Posted: 17 Jan 2022 02:54 AM PST

I want to do is playing audio in the background of the app in objective c langauge. I implemented some of code but don't know why it's not working, review below code and guide me if you have any solution or idea.

  • (void) remoteControl {

    theAppDelegate.currentSong = theSong.name; double CurrentDuration = (double) self.globalPlayer.currentTime.value / (double) self.globalPlayer.currentTime.timescale; theAppDelegate.currentSongSubtitle = theSong.album_name; MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage: [UIImage imageNamed:@"album_civil_procedure.png"]];

    double delayInSeconds = 2.0; // set the time dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

      NSMutableDictionary *audioObjectInfo = [[NSMutableDictionary alloc] init];    audioObjectInfo[MPMediaItemPropertyTitle] = self->theAppDelegate.currentSong;    audioObjectInfo[MPMediaItemPropertyArtist] = @"AAA";    audioObjectInfo[MPMediaItemPropertyArtwork] = albumArt;    audioObjectInfo[MPMediaItemPropertyAlbumTitle] = self->theAppDelegate.currentSongSubtitle;    audioObjectInfo[MPMediaItemPropertyPlaybackDuration] = [NSNumber numberWithDouble:self->theAppDelegate.totalDuration];    audioObjectInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = [NSNumber numberWithDouble:CurrentDuration];    audioObjectInfo[MPNowPlayingInfoPropertyPlaybackRate] = [NSNumber numberWithDouble:self.globalPlayer.rate];    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:audioObjectInfo];  

    }); }

Run PHP script after Azure Web app deployment

Posted: 17 Jan 2022 02:54 AM PST

I am having an Azure app Service and I want to upload/deploy an .php file to it an run it right after the upload.

I managed to upload it via curl and also start a post deployment script. Unfortunately I can not use the command "php ..." in it because I get an error like: "/opt/Kudu/Scripts/starter.sh: line 2: exec: php: not found\n" in the logs. The same occurs if I use the "/api/command" endpoint with the same command. I get the same kind of error in the response.

It seems like the php executable is not known in that environment. Is there any way to run a php script via the command API or in a post deployment script?

Thanks in advance

Presto SQL category counter

Posted: 17 Jan 2022 02:54 AM PST

I have the following table

cust_id | category | counts  1       | food     |   2  1       | pets     |   5  3       | pets     |   3  

I would like to get this output

cust_id | food_count | pets_count  1       |    2       |  5  3       |    0       |  3  

Where the number of columns map all unique values in the category column. Do you know how that can be done in Presto SQL? If I were doing this in pySpark I would use CountVectorizer but I'm a bit struggling with SQL.

Can't click on a button, need a solution (userscript for Greasemonkey/Tampermonkey)

Posted: 17 Jan 2022 02:53 AM PST

I'm trying to click the "Visit" button here:

<a name="claim" href="#" onmousedown="$(this).attr('href', '/sdf/view.php?dsg=45368');"  class="btn-small larg-btn">Visit<i class="fas fa-eye" aria-hidden="true"></i></a>  

There many other buttons (same but with different links) on the page, but I need to click only 1 (first link in a row) each time I visit/load the page.

Tried to combine those two solutions (1 and 2) but unfortunately I'm absolutely dumb in it:-)).

Also tried the simpliest thing which works in most cases

(function (){  document.querySelector('selector').click();  

But obviously didn't help at all.

Thank you.

Largest number formed from some or all elements in an array divisible by 3

Posted: 17 Jan 2022 02:53 AM PST

I am trying solve the following question:

Given an array of digits, what is the largest number divisble by 3 that can be formed using some / all the elements in the array?

The question only accepts Java and Python, and I chose Python despite being completely inexperienced with it.

I looked around and it seems like the general idea was to kick off the smallest element to get the digits total divisible by 3, and wrote the following "subtractive" approach:

def maxdiv3(l):      l.sort()        tot = 0      for i in l:          tot += i        if tot % 3 == 0:          l.sort(reverse=True)          return int(''.join(str(e) for e in l))      elif tot % 3 == 1:          cl = []          acl = []          for i in l:              if i % 3 == 0:                  acl.append(i)              else:                  cl.append(i)            removed = False          nl = []          for i in cl:              if not removed:                  if i % 3 == 1:                      removed = True                  else:                      nl.append(i)              else:                  nl.append(i)            if removed:              nl.extend(acl)              nl.sort(reverse=True)              if len(nl) > 0:                  return int(''.join(str(e) for e in nl))              else:                  return 0          else:              if len(acl) > 0:                  acl.sort(reverse=True)                  return int(''.join(str(e) for e in acl))            return 0      elif tot % 3 == 2:          cl = []          acl = []          for i in l:              if i % 3 == 0:                  acl.append(i)              else:                  cl.append(i)            removed2 = False          nl = []          for i in cl:              if not removed2:                  if i % 3 == 2:                      removed2 = True                  else:                      nl.append(i)              else:                  nl.append(i)            if removed2:              nl.extend(acl)              nl.sort(reverse=True)              if len(nl) > 0:                  return int(''.join(str(e) for e in nl))            removed1 = 0          nl = []          for i in cl:              if removed1 < 2:                  if i % 3 == 1:                      removed1 += 1                  else:                      nl.append(i)              else:                  nl.append(i)            if removed1 == 2:              nl.extend(acl)              nl.sort(reverse=True)              if len(nl) > 0:                  return int(''.join(str(e) for e in nl))            if len(acl) > 0:              acl.sort(reverse=True)              return int(''.join(str(e) for e in acl))          else:              return 0  

This approach kept gets stuck on a hidden test case, which means I can't work out what or why.

Based on this, I wrote up a new one:

def maxdiv3(l):      l.sort()        l0 = []      l1 = []      l2 = []      for i in l:          if i % 3 == 0:              l0.append(i)          elif i % 3 == 1:              l1.append(i)          elif i % 3 == 2:              l2.append(i)        tot = sum(l)        nl = []        if tot % 3 == 0:          nl = l            nl.sort(reverse=True)            if len(nl) > 0:              return int(''.join(str(e) for e in nl))                    return 0      elif tot % 3 == 1:          if len(l1) > 0:              l1.remove(l1[0])                nl.extend(l0)              nl.extend(l1)              nl.extend(l2)                nl.sort(reverse=True)                if len(nl) > 0:                  return int(''.join(str(e) for e in nl))                return 0          elif len(l2) > 1:              l2.remove(l2[0])              l2.remove(l2[0])                nl.extend(l0)              nl.extend(l1)              nl.extend(l2)                nl.sort(reverse=True)                if len(nl) > 0:                  return int(''.join(str(e) for e in nl))                return 0          else:              return 0      elif tot % 3 == 2:          if len(l2) > 0:              l2.remove(l2[0])                nl.extend(l0)              nl.extend(l1)              nl.extend(l2)                nl.sort(reverse=True)                if len(nl) > 0:                  return int(''.join(str(e) for e in nl))                return 0          elif len(l1) > 1:              l1.remove(l1[0])              l1.remove(l1[0])                nl.extend(l0)              nl.extend(l1)              nl.extend(l2)                nl.sort(reverse=True)                if len(nl) > 0:                  return int(''.join(str(e) for e in nl))                return 0          else:              return 0  

And this one does pass all the test cases, including the hidden ones.

Here are some of the test cases that I ran my attempt through:

[3, 9, 5, 2] -> 93  [1, 5, 0, 6, 3, 5, 6] -> 665310  [5, 2] -> 0  [1] -> 0  [2] -> 0  [1, 1] -> 0  [9, 5, 5] -> 9  

It seems to me that my attempt and the SO solution had the same idea in mind, so what did I neglect to consider? How is the SO solution different from mine and how does that catch whatever it is that my attempt didn't?

Thank you for your time.


A slightly off topic additional question: How do I find edge cases when dealing with blind test cases? I built a random input generator for this question but that didn't help anywhere near I wished it would and is likely not a good general solution.

Chrome Extension doesn't work with MV3, getting "Insecure CSP value "'unsafe-eval'" in directive 'script-src'."

Posted: 17 Jan 2022 02:53 AM PST

I'm trying to make a simple Chrome extension that replaces all images with another one (img.jpg).

Main folder

  • clrimgs.js
  • img.jpg
  • manifest.json
  • window.html

window.html:

<!DOCTYPE html>  <html lang="en">  <head>      <meta charset="UTF-8">      <meta http-equiv="X-UA-Compatible" content="IE=edge">      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <title>ClrImgs</title>      <script type="text/javascript" src="clrimgs.js"></script>  </head>  <body>      <button onclick="clrimgs()"></button>  </body>  </html>  

clrimgs.js:

function clrimgs(){      images = document.getElementsByTagName("img")      for(image in images){          image.src = "img.jpg";      }  }  

manifest.json:

{      "manifest_version": 3,      "name": "ClrImgs",      "description": "Description",      "version": "1.0",      "minimum_chrome_version": "46",      "content_security_policy": {          "extension_pages": "script-src 'self' 'unsafe-eval'; object-src 'self'",          "sandbox": "..."         },      "action": {      "default_icon": "img.jpg",      "default_popup": "window.html"      }      }  

When I try to reload the extension, I get this error:

'content_security_policy.extension_pages': Insecure CSP value "'unsafe-eval'" in directive 'script-src'. Could not load manifest.

Is there any way to use MV3 and still use such code? If yes, what am I doing wrong? I have tried doing numerous things, but I keep getting an error or the other.

No such module 'Firebase' in iOS

Posted: 17 Jan 2022 02:53 AM PST

Getting No such module 'Firebase' error . If commented this "import Firebase" and showing the same error other modules, tried almost all solutions available in google. The project implemented in both Objective C and Swift and this error occurring in Xcode 11.6. Any help would be highly appreciated.

Xamarin swap single ResourceDictionary programmatically

Posted: 17 Jan 2022 02:53 AM PST

I'm currently trying to get custom themes working with a Xamarin App and I've found a way I can make this work the way I want it to, but it seems terribly inefficient, so figured I'd ask to see if you lot had better answers.

So here's the issue, I want to build a screen where users can change themes (there will be many, not just light/dark), and I want to swap out the current theme ResourceDictionary and replace it with the new chosen theme's ResourceDictionary. The problem is I also want the App to have other global ResourceDictionaries, and every tutorial I find recommends calling Resources.MergedDictionaries.Clear(), but that then gets rid of my other ResourceDictionaries.

Here is my Xaml, I don't want to replace DefaultButton.xaml or LinkButton.xaml, I only want to replace LightTheme.xaml.

<?xml version="1.0" encoding="utf-8" ?>  <Application xmlns="http://xamarin.com/schemas/2014/forms"               xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"               x:Class="myTestApp.App">      <Application.Resources>          <ResourceDictionary Source="Themes/ResourceDictionaries/LightTheme.xaml" />          <ResourceDictionary Source="Styles/DefaultButton.xaml" />          <ResourceDictionary Source="Styles/LinkButton.xaml" />      </Application.Resources>  </Application>  

Then in my App class I have

public void ChangeTheme(ThemeOptions theme)  {      ResourceDictionary newRes;      switch (theme)      {          case ThemeOptions.Light:              newRes = new LightTheme();              break;          case ThemeOptions.Dark:              newRes = new DarkTheme();              break;          default:              newRes = new LightTheme();              break;      }            Resources.MergedDictionaries.Clear();      Resources.Add(newRes);  }  

Now obviously the DefaultButton.xaml and LinkButton.xaml ResourceDictionaries have now been cleared. I can add them back, but it seems terribly inefficient over just finding and removing the Theme. Is there an easy way to simply identify the ResourceDictionary I want to overwrite and replace that?

Can anyone tell me about V8 engine?

Posted: 17 Jan 2022 02:53 AM PST

How v8 engine runs and where does it run? I found some resources where I got that it runs in the browser but what about in node js? please try to understand me. where does it run?

where to add javascriot in an existing rails project

Posted: 17 Jan 2022 02:53 AM PST

window.addEventListener("load", () => {  const element = document.querySelector("#new-article");  element.addEventListener("ajax:success", (event) => {  const [_data, _status, xhr] = event.detail;  element.insertAdjacentHTML("beforeend", xhr.responseText);  });  element.addEventListener("ajax:error", () => {  element.insertAdjacentHTML("beforeend", "<p>ERROR</p>");  });  });  

this is the code i wanted to add in my existing rails project . To use ajax in my forms

Blockquote

Is it possible to provide a constuctor with copy elision for member initialization?

Posted: 17 Jan 2022 02:53 AM PST

I'm testing different modes for initializing class members with following small code:

struct S {      S() { std::cout << "ctor\n"; }      S(const S&) { std::cout << "cc\n"; }      S(S&&) noexcept{ std::cout << "mc\n"; }      S& operator=(const S&) { std::cout << "ca\n"; return *this; }      S& operator=(S&&) noexcept{ std::cout << "ma\n"; return *this; }      ~S() { std::cout << "dtor\n"; }  };    struct P1 {      S s_;  };    struct P2 {      P2(const S& s) : s_(s) {}      S s_;  };    struct P3 {      P3(const S& s) : s_(s) {}      P3(S&& s) : s_(std::move(s)) {}      S s_;  };      int main() {      S s;      std::cout << "------\n";      {          P1 p{s}; // cc      }      std::cout << "---\n";      {          P1 p{S{}}; // ctor = copy elision      }      std::cout << "------\n";      {          P2 p{s}; // cc      }      std::cout << "---\n";      {          P2 p{S{}}; // ctor + cc      }      std::cout << "------\n";      {          P3 p{s}; // cc      }      std::cout << "---\n";      {          P3 p{S{}}; // ctor + mc      }      std::cout << "------\n";  }  

As you see in comments, only in case of aggregate-initialization of P1{S{}} copy elision happens and out class is initialized without any copy/move constructor calls. I wonder if it is possible to provide a constructor which initialize members directly like aggregate initializer. Any idea?

Hello Help me please, Unexpected child "uses-material -design" found under "flutter"

Posted: 17 Jan 2022 02:52 AM PST

Unexpected child "uses-material -design" found under "flutter". Please correct the pubspec.yaml file at C:...

Prediction with calculated coefficients without dataset

Posted: 17 Jan 2022 02:53 AM PST

Background: I have a DOE-output for 4 responses and 4 factors and I calculated new coefficients (substraction of two functions) to get a new function which I wanna use in the end for visualization and calculations.

I tried it with the following code:

a <- rep(1,20)  b <- rep(1,20)  c <- rep(1,20)  d <- rep(1,20)  y <- rep(1,20)      formula<- y~a+b+c+d+a:b+a:c+a:d+b:c+b:d+c:d+I(a^2)+I(b^2)+I(c^2)+I(d^2)  fit_predict <- lm(formula)  fit_predict$coefficients<-new_coefficients    new<-data.frame(a=rep(25,20),b=c(seq(0.1,0.5,length=20)),c=rep(3.5,20),d=c(seq(0.05,1.0,length=20)))    pred<-predict(fit_predict, newdata=new)    new_prediction <- cbind(new,pred)  

The output is always the same as the first coefficient. Order of the coefficients is the same and was not changed. Does anybody have a more robust way or a better way to get the prediction from the calculated formula?

Find specific column data with where condition in INNER Join

Posted: 17 Jan 2022 02:53 AM PST

I want to search posts and media from DB. my query works fine

But i want only application/pdf from post type attachment

I added my query AND result screenshot. I just want only application/pdf from this result if post type attachment

SELECT acms_posts.ID as postId, acms_posts.post_mime_type as mediaType,          acms_posts.post_type as postType   FROM acms_postmeta   INNER JOIN acms_posts ON acms_postmeta.post_id = acms_posts.ID   WHERE acms_postmeta.meta_value LIKE '%We%' AND acms_posts.post_type <> 'revision' OR acms_posts.post_mime_type = 'application/pdf' AND acms_posts.post_parent ='' AND (acms_posts.post_status = 'inherit' OR acms_posts.post_status = 'publish')   GROUP BY acms_posts.ID, acms_posts.post_parent;  

Query Result

predict matrix with machine learning models (classification)

Posted: 17 Jan 2022 02:52 AM PST

I have 2 dataset which is of shape :

X = 3114 x 627

y = 3114 x 1 (species)

Each 9 rows (spectras) from X corresponds to 1 strain, thus there is

3114/9 = 346 strains.

The goal is to predict the species of each strains.

I was wondering what is the best way to predict. Thus, is it possible to predict this way :

reshaping the dataset this way : having a matrix with 9 x 627 which predict the species of one strain, thus having 346 (each strains is a 9 x 627 matrix)

Or I can just let the dataset as it is and predict that way?

Matrix Values to Probabilities with Logistic Regression

Posted: 17 Jan 2022 02:53 AM PST

I have a Non Negative Matrix Factorization algorithm and I'm calculating the A-hat matrix from it. Rows of the matrix are customers, columns are my products and values are the occurrences of product views.

Fitting the data to the model and I calculate the R matrix as follow.

model = NMF( n_components=100 )  W  = model.fit_transform( input_matrix )  H = model.components_  R = np.dot( W, H )  

Then I want to calculate the probabilities to this matrix. Currently I can calculate them by normalizing the matrix with the following code

row_sums= R.sum(axis=1)  probabilities= R / row_sums[:, np.newaxis]  

But its not 100% correct way to calculate the probabilities. The correct way is to run a logistic regression algorithm to generate them.

How to do that?

After upgrading to react-scripts 5.0.0 gives error "RangeError: Array buffer allocation failed"

Posted: 17 Jan 2022 02:53 AM PST

After updating react app to react-scripts 5.0.0 it gives error RangeError: Array buffer allocation failed. enter image description here

id attribute not recognised in vs code ( HTML)

Posted: 17 Jan 2022 02:54 AM PST

Today I was learning HTML. it was about ids and classes. When I typed id in vs code it was supposed to show a suggestion box. I typed id = "mainBox" class ="redBg" but it did not change the color as it was shown in the video.( all my other suggestions like h1 ! script are working) Can some help ?

<!DOCTYPE html>  <html lang="en">  <head>  <meta charset="UTF-8">  <meta http-equiv="X-UA-Compatible" content="IE=edge">  <meta name="viewport" content="width=device-width, initial-scale=1.0">  <title>Document</title>  </head>  <body>  <div>   **id = "mainBox" class ="redBg"**         </div>   </body>  </html>  

NoOffsetForPartitionException when using Flink SQL with Kafka-backed table

Posted: 17 Jan 2022 02:52 AM PST

This is my table:

CREATE TABLE orders (    `id` STRING,    `currency_code` STRING,    `total` DECIMAL(10,2),    `order_time` TIMESTAMP(3),    WATERMARK FOR `order_time` AS order_time - INTERVAL '30' SECONDS  ) WITH (    'connector' = 'kafka',    'topic' = 'orders',    'properties.bootstrap.servers' = 'localhost:9092',    'properties.group.id' = 'groupgroup',    'value.format' = 'json'  );  

I can insert into the table:

INSERT into orders   VALUES ('001', 'EURO', 9.10, TO_TIMESTAMP('2022-01-12 12:50:00', 'yyyy-MM-dd HH:mm:ss'));  

And I can have verified that the data is there:

$ kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic orders --from-beginning  {"id":"001","currency_code":"EURO","total":9.1,"order_time":"2022-01-12 12:50:00"}  

But when I try to query the table I get an error:

Flink SQL> select * from orders;  [ERROR] Could not execute SQL statement. Reason:  org.apache.flink.kafka.shaded.org.apache.kafka.clients.consumer.NoOffsetForPartitionException: Undefined offset with no reset policy for partitions: [orders-0]  

How to resolve the circular import issue for type hint? [duplicate]

Posted: 17 Jan 2022 02:53 AM PST

I have two files with type hints. In file a.py, A.x has type of B. And in file b.py, B.y has type of A. (Python 3.6)

a.py

from b import B    @dataclass  class A:      x: B  

b.py

from a import A    @dataclass  class B:      y: Union[A, None] = None  

How to resolve the circular import issue for type hint?

Fit with convolution

Posted: 17 Jan 2022 02:54 AM PST

I want to fit experimental data of a time-dependent signal. The signal is the result of a concentration convolved with a pulse. But the question is more general, so I hope the picture below will help. As you see, the values of the convolution drop off at the start and end. This is correct since also the signal drops to zero. However, my experimental data would start on 1 (normalized background) and would rise to some unknown value. But of course, I can only take a finite amount of data. When I now use my fit function, it will also drop off at the start and end, but that is not how it should look like to have a good fit.

My solution would be to define the fit function so that it gives a zero where I don't have full overlap of the data and the pulse and modify my experimental data (which are basically lost then) accordingly, i.e. set them at those x-values to zero as well.

Since time-resolved measurements need this, I wonder what is the usual way to go about that? Or any other solutions?

Convolution of signal and pulse:
enter image description here

Spark Scala - I need nth row of the group

Posted: 17 Jan 2022 02:52 AM PST

I exploded a column and got the dataframe as below:

+------------+-----------+--------------------+  |serialnumber|   roomname|             devices|  +------------+-----------+--------------------+  |hello       |Living Room|             device1|  |hello       |Living Room|             device2|  |hello       |Living Room|             device3|  |hello       |Living Room|             device4|  |hello       |Living Room|             device5|  |hello       |    Kitchen|             device1|  |hello       |    Kitchen|             device2|  |hello       |    Kitchen|             device3|  |hello       |    Kitchen|             device4|  |hello       |    Kitchen|             device5|  |hello       |   Bedroom1|             device1|  |hello       |   Bedroom1|             device2|  |hello       |   Bedroom1|             device3|  |hello       |   Bedroom1|             device4|  |hello       |   Bedroom1|             device5|  |hello       |  Bedroom 2|             device1|  |hello       |  Bedroom 2|             device2|  |hello       |  Bedroom 2|             device3|  |hello       |  Bedroom 2|             device4|  |hello       |  Bedroom 2|             device5|  |hello       |   Bedroom3|             device1|  |hello       |   Bedroom3|             device2|  |hello       |   Bedroom3|             device3|  |hello       |   Bedroom3|             device4|  |hello       |   Bedroom3|             device5|  +------------+-----------+--------------------+  

Now I want a dataframe as below, that means 1st of Living room, 2nd of Kitchen, 3rd of Bedroom1 and so on....

   +------------+-----------+--------------------+      |serialnumber|   roomname|             devices|      +------------+-----------+--------------------+      |hello       |Living Room|             device1|      |hello       |    Kitchen|             device2|      |hello       |   Bedroom1|             device3|      |hello       |  Bedroom 2|             device4|      |hello       |  Bedroom 3|             device5|      +------------+-----------+--------------------+  

C# Finding the word that only appears once in an array

Posted: 17 Jan 2022 02:53 AM PST

I have this array full of colors and have to find the one that only appears once in the array.

string[] colors = {"red","green","white","green","red","red"}    string[] noDupcolors = szinek.Distinct().ToArray(); //the same array without duplicates                int num = 0;  int once = 0;  for (int i = 0; i < noDupcolors.Length; i++)  {      for (int j = 0; j < S; j++)      {          if (noDupcolors[i]==colors[j])          {              num++;          }          if (num == 1)          {              once = j;          }          else          {              nums = 0;          }      }  }  Console.WriteLine(colors[once]);  

I've tried this but for some reason it writes out green. Can someone help please. Thank you.

How to store a variable or object on desired memory location?

Posted: 17 Jan 2022 02:53 AM PST

Let's suppose I have an object of a class as shown in below.

Myclass obj;  

Now I want to store this object to my desired memory location. How can I do tgis . Is it possible or not. I'm using C++

GoogleMaps get center location of current view

Posted: 17 Jan 2022 02:54 AM PST

I'm using google maps js in my project.PRoject shows locations by marker in googlemaps. I can add marker with some butotn but marker needs lat and long values so i put the locations[0].lat,locations[0].lon,It works fine but not user friendly.

So, what i want to do is make a static marker into the center of the map, when user slides the map , it will still stay in the middle when the user scrolls the map then user clicks the add location button then it adds.

It can also done with add marker in current view center

Current add location code, map and title is global, index comes from document.ready foreach loop

function addLocation(){          var myLatlng = new google.maps.LatLng(allMarkers[0].position.lat()+0.20, allMarkers[0].position.lng()+0.20);                      var marker = new google.maps.Marker({              position: latlng,              map: map,              title: title,              draggable: true,              index:index          });                marker.addListener('dragend', handleEvent);            marker.addListener("click", () => {                                            allMarkers[index].isDeleted='1';              allMarkers[index].setMap(null);                               });          allMarkers.push(marker);  }  

Query with ElasticSearch body using GluonhqConnect.Provider.RestClient

Posted: 17 Jan 2022 02:52 AM PST

I am trying to use the com.gluonhq.connect.provider.RestClient to query an API that is Elastic Search enabled.

Maven:      <dependency>          <groupId>com.gluonhq</groupId>          <artifactId>connect</artifactId>          <version>2.0.1</version>      </dependency>  

I have attempted to make a request using the following:

private GluonObservableObject<Item> getData() {      RestClient myApiClient = RestClient.create()              .method("POST")              .host(applicationProperties.getAPIURL())              .path("search")              .header("accept", "application/json")              .header("Content-type", "application/json")              .queryParam("private_key", applicationProperties.getAPIKEY())              .dataString(ITEMREQUEST);        return DataProvider.retrieveObject(              myApiClient.createObjectDataReader(Item.class));  }  

...where the dataString is a json-formatted String representing the body of the request (I can assume the request is correctly formatted because I tested it in Postman and the request returned the expected data). If it helps, here is the request body:

 {    "indexes": "idx1, idx2",    "columns": "col1,col2,col3,col4,col5",    "body": {      "query": {        "bool": {          "must": [            {              "wildcard": {                "NameCombined_en": "*"              }            }          ],          "filter": [            {              "range": {                "ID": {                  "gte": "20000"                }              }            }          ]        }      },      "from": 0,      "size": 100    }  }  

The problem I have is that the (gluon) RestClient and, by extension, the DataProvider.retrieveObject method return exactly...nothing.

I'm pretty sure I'm doing something wrong and I'm fairly certain it is the .dataString() method (which requires an "entity"), but I have not found an alternative to use as a way of passing the body into the request.

The reasoning behind using the com.gluonhq.connect library is to avoid having to also create my own Observable lists (by hand) - the library automatically spits one out, providing the data is suitably formatted...and present. At least, that's my understanding of it.

Can someone point me in the right direction? I have found no indication or explanation of how to do POST requests with this library.

UPDATE 20220117

Main.java

public class Main extends Application {  ApplicationProperties applicationProperties = new ApplicationProperties();  private static final String RESTLIST_VIEW = HOME_VIEW;  private static final String RESTOBJECT_VIEW = "RestObjectView";      private final AppManager appManager = AppManager.initialize(this::postInit);    @Override  public void init() {      appManager.addViewFactory(RESTOBJECT_VIEW, () -> new RestObjectView(applicationProperties.APIURL, applicationProperties.APIKEY));        updateDrawer();  }    @Override  public void start(Stage stage) {      appManager.start(stage);  }    private void postInit(Scene scene) {      Swatch.BLUE.assignTo(scene);        ((Stage) scene.getWindow()).getIcons().add(new Image(Objects.requireNonNull(Main.class.getResourceAsStream("/icon.png"))));  }    private void updateDrawer() {      NavigationDrawer navigationDrawer = appManager.getDrawer();      NavigationDrawer.Header header = new NavigationDrawer.Header("Gluon Mobile", "Gluon Connect Rest Provider Sample",              new Avatar(21, new Image(getClass().getResourceAsStream("/icon.png"))));      navigationDrawer.setHeader(header);      NavigationDrawer.Item listItem = new NavigationDrawer.Item("List Viewer", MaterialDesignIcon.VIEW_LIST.graphic());      NavigationDrawer.Item objectItem = new NavigationDrawer.Item("Object Viewer", MaterialDesignIcon.INSERT_DRIVE_FILE.graphic());      navigationDrawer.getItems().addAll(listItem, objectItem);      navigationDrawer.selectedItemProperty().addListener((obs, oldItem, newItem) -> {          if (newItem.equals(listItem)) {              appManager.switchView(RESTLIST_VIEW);          } else if (newItem.equals(objectItem)) {              appManager.switchView(RESTOBJECT_VIEW);          }      });  }    public static void main(String[] args) {      System.setProperty("javafx.platform", "Desktop");        launch(args);  }  

RestObjectView.java

public class RestObjectView extends View {    public RestObjectView(String apiurl, String apikey) {        Label lbItemId = new Label();      Label lbName = new Label();      Label lbDescription = new Label();      Label lbLvlItem = new Label();      Label lbLvlEquip = new Label();        GridPane gridPane = new GridPane();      gridPane.setVgap(5.0);      gridPane.setHgap(5.0);      gridPane.setPadding(new Insets(5.0));      gridPane.addRow(0, new Label("Item ID:"), lbItemId);      gridPane.addRow(1, new Label("Name:"), lbName);      gridPane.addRow(2, new Label("Description:"), lbDescription);      gridPane.addRow(3, new Label("Item Level:"), lbLvlItem);      gridPane.addRow(4, new Label("Equip Level:"), lbLvlEquip);      gridPane.getColumnConstraints().add(new ColumnConstraints(75));        lbItemId.setWrapText(true);      lbName.setWrapText(true);      lbDescription.setWrapText(true);      lbLvlItem.setWrapText(false);      lbLvlEquip.setWrapText(false);        setCenter(gridPane);        // create a RestClient to the specific URL      RestClient restClient = RestClient.create()              .method("POST")              .host(apiurl)              .path("Item")              .queryParam("private_key", apikey);        // create a custom Converter that is able to parse the response into a single object      InputStreamInputConverter<Item> converter = new SingleItemInputConverter<>(Item.class);        // retrieve an object from the DataProvider      GluonObservableObject<Item> item = DataProvider.retrieveObject(restClient.createObjectDataReader(converter));        // when the object is initialized, bind its properties to the JavaFX UI controls      item.initializedProperty().addListener((obs, oldValue, newValue) -> {          if (newValue) {              lbItemId.textProperty().bind(item.get().itemIdProperty().asString());              lbName.textProperty().bind(item.get().nameProperty());              lbDescription.textProperty().bind(item.get().descriptionProperty());              lbLvlItem.textProperty().bind(item.get().levelItemProperty().asString());              lbLvlEquip.textProperty().bind(item.get().levelEquipProperty().asString());          }      });  }    @Override  protected void updateAppBar(AppBar appBar) {      appBar.setNavIcon(MaterialDesignIcon.MENU.button(e -> getAppManager().getDrawer().open()));      appBar.setTitleText("Rest Object Viewer");  }  

}

How to upsample a multi-index dataframe ensuring each grouping covers the same time range (provide custom starting and ending datetimes)

Posted: 17 Jan 2022 02:54 AM PST

Here is a dummy example to illustrate the problem.

I am interested in upsampling to the beginning of the each year (AS) and, for every country, I want to cover the period that goes from 1995 to the year 2000.

Imagine we had the following dataset:

df = pd.DataFrame({      'year': [          '1995-01-01', '1997-01-01',           '1997-01-01', '1998-01-01', '2000-01-01',          '1996-01-01', '1999-01-01',       ],      'country': [          'ES', 'ES',           'GB', 'GB', 'GB',          'DE', 'DE',      ],      'members': [          100, 101,           200, 201, 202,          300, 301,      ]  })  df['year']= pd.to_datetime(df['year'])  df = df.set_index(['country', 'year'])  print(df)  
                    members  country year                 ES      1995-01-01      100          1997-01-01      101    GB      1997-01-01      200          1998-01-01      201          2000-01-01      202    DE      1996-01-01      300          1999-01-01      301  

As you can see, no country has data available for all the years between 1995 to 2000. Notice that some countries are also missing the year 1995 and other are missing the year 2000.

I know how to upsample the dataframe so that, for each country, it fills the years missing in between (e.g. adds the year 1996 to Spain).

def my_upsample(df):      return (          df          .reset_index('country')               # upsampling multi-index wit the keyword level is not supported          .groupby('country', group_keys=False) # hence this little trick of single-indexing & grouping                                              # see this issue for details: https://github.com/pandas-dev/pandas/issues/28313          .resample('AS') # resample to the beggining of each year          .apply({              'country':'pad',    # pad the countries              'members':'asfreq', # but leave the number of members as NaN. Irrelevant in this dummy example, but                                   # the desired behaviour in my real-world problem          })      )    print(my_upsample(df))  
           country  members  year                         1996-01-01      DE    300.0  1997-01-01      DE      NaN  1998-01-01      DE      NaN  1999-01-01      DE    301.0    1995-01-01      ES    100.0  1996-01-01      ES      NaN  1997-01-01      ES    101.0    1997-01-01      GB    200.0  1998-01-01      GB    201.0  1999-01-01      GB      NaN  2000-01-01      GB    202.0  

But what I would like to do is make sure that all the countries cover the period from 1995 to 2000.

The desired output should look like this:

           country  members  year                         1995-01-01      DE      NaN  1996-01-01      DE    300.0  1997-01-01      DE      NaN  1998-01-01      DE      NaN  1999-01-01      DE    301.0  2000-01-01      DE      NaN    1995-01-01      ES    100.0  1996-01-01      ES      NaN  1997-01-01      ES    101.0  1998-01-01      ES      NaN  1999-01-01      ES      NaN  2000-01-01      ES      NaN    1995-01-01      GB      NaN  1996-01-01      GB      NaN  1997-01-01      GB    200.0  1998-01-01      GB    201.0  1999-01-01      GB      NaN  2000-01-01      GB    202.0  

I could use python loops iterating over each country and adding the missing rows (see code below), but I would like to know what is the pandas way of achieving this?

for country in df.index.levels[0]:      if not (country, '1995-01-01') in df.query(f"country == @country").index:          # if this country doesn't have the year 1995 create the row with NaN as value          df.loc[(country, '1995-01-01'),:] = np.nan         if not (country, '2000-01-01') in df.query(f"country == @country").index:          # if this country doesn't have the year 2000 create the row with NaN as value          df.loc[(country, '2000-01-01'),:] = np.nan  print(df.sort_index())  
                    members  country year                 DE      1995-01-01      NaN          1996-01-01    300.0          1999-01-01    301.0          2000-01-01      NaN  ES      1995-01-01    100.0          1997-01-01    101.0          2000-01-01      NaN  GB      1995-01-01      NaN          1997-01-01    200.0          1998-01-01    201.0          2000-01-01    202.0  

And then running my_upsample returns the desired output:

print(my_upsample(df.sort_index()))  
           country  members  year                         1995-01-01      DE      NaN  1996-01-01      DE    300.0  1997-01-01      DE      NaN  1998-01-01      DE      NaN  1999-01-01      DE    301.0  2000-01-01      DE      NaN    1995-01-01      ES    100.0  1996-01-01      ES      NaN  1997-01-01      ES    101.0  1998-01-01      ES      NaN  1999-01-01      ES      NaN  2000-01-01      ES      NaN    1995-01-01      GB      NaN  1996-01-01      GB      NaN  1997-01-01      GB    200.0  1998-01-01      GB    201.0  1999-01-01      GB      NaN  2000-01-01      GB    202.0  

Why has GitLab saved one folder of my project as a Subproject commit?

Posted: 17 Jan 2022 02:53 AM PST

I have started developing a website, saved in my local folders, and I am trying to save it to a GitLab repository. I created a new repository on GitLab and then did the following:

cd existing_folder  git init --initial-branch=main  git remote add origin https://gitlab.com/...  git add .  git commit -m "Initial commit"  git push -u origin main  

The project comprises two folders, Server and Client, the Client is a React App. However the Client folder is appearing as a red folder icon that can't be opened:

1

When I click on the initial commit it says that Client has been added as a Subproject commit:

2

I don't know what this means, I have built websites with a similar structure before and Gitlab has not done this. I just want the contents of both Client and Server folders to be saved in the repo.

Error "the JAVA_HOME environment variable is not defined correctly" on running "mvn clean javadoc:jar package"

Posted: 17 Jan 2022 02:53 AM PST

When I try to execute the command

mvn clean javadoc:jar package

it shows

the JAVA_HOME environment variable is not defined correctly. This environment variable is needed to run this program.

NB: JAVA_HOME should point to a JDK, not a JRE.

I checked out the already asked question Unable to find javadoc command - maven and the solution I tried above were taken from this solution only. I am new to Ubuntu. How can I fix this?

Whereas when I run echo $JAVA_HOME it prints:

/usr/lib/jvm/java-11-openjdk-amd64  

I also tried setting the JAVA_HOME to:

  1. /etc/launchd.conf/java-11-openjdk-amd64
  2. /usr/libexec/java-11-openjdk-amd64
  3. /usr/libexec/java-11-openjdk-amd64/

When I run mvn -v, it prints:

Apache Maven 3.6.3  Maven home: /usr/share/maven  Java version: 11.0.10, vendor: Ubuntu, runtime: /usr/lib/jvm/java-11-openjdk-amd64  Default locale: en_IN, platform encoding: UTF-8  OS name: "linux", version: "5.8.0-45-generic", arch: "amd64", family: "unix"  

And when I run echo $JAVA_HOME it prints:

/usr/lib/jvm/java-11-openjdk-amd64  

No comments:

Post a Comment