2021-03-31

How to export multiple parameters from JSON to AWS SSM Parameter store

I am trying to copy SSM Parameters from one account to a different account and different region. I have 100's of parameters which I have imported using get-parameters-by-path.

Now I want to export them to a and different region in a different account. When I add one after the other using :

aws ssm put-parameter --cli-input-json file:///../parameters.json --region us-east-2

With parameters.json as:

    {
      "Name": "/env/../../..",
      "Type": "String",
      "Value": "/env/../../.."
    }

it works without any issues, but I would like to know how I could export more than one at a time, I want them all to be loaded at once.

Here is the sample paramaters.json which does not work. It doesn't throw any error but prints the same again.

    {
      "Name": "/env/../../..",
      "Type": "String",
      "Value": "/env/../../.."
    },
    {
      "Name": "/env/../../..",
      "Type": "String",
      "Value": " "
    },
    {
      "Name": "/env/../../..",
      "Type": "String",
      "Value": " "
    }

I cannot use aws-ssm-copy because both are different regions in different accounts and I am also, modifying the imported values before exporting to the new account which is not possible with aws-ssm-copy.



from Recent Questions - Stack Overflow https://ift.tt/31zxfjS
https://ift.tt/eA8V8J

How to balance and format String in java swing

I know that there are many previous explanations, but similar to my problem I did not find !

Simply i have a code to drow a bill info using graphics2d !

My Full Code IS :

 public PageFormat getPageFormat(PrinterJob pj) {

    PageFormat pf = pj.defaultPage();
    Paper paper = pf.getPaper();

    double middleHeight = 99999;
    double headerHeight = 2.0;
    double footerHeight = 2.0;
    double width = convert_CM_To_PPI(8);      //printer know only point per inch.default value is 72ppi
    double height = convert_CM_To_PPI(headerHeight + middleHeight + footerHeight);
    paper.setSize(width, height);
    paper.setImageableArea(
            0,
            2,
            width,
            height - convert_CM_To_PPI(1)
    );   //define boarder size    after that print area width is about 180 points

    pf.setOrientation(PageFormat.PORTRAIT);           //select orientation portrait or landscape but for this time portrait
    pf.setPaper(paper);

    return pf;
}

protected static double convert_CM_To_PPI(double cm) {
    return toPPI(cm * 0.393600787);
}

protected static double toPPI(double inch) {
    return inch * 72d;
}

public class BillPrintable implements Printable {

    @Override
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
            throws PrinterException {

        int result = NO_SUCH_PAGE;
        if (pageIndex == 0) {

            Graphics2D g2d = (Graphics2D) graphics;

            double width = pageFormat.getImageableWidth();

            g2d.translate((int) pageFormat.getImageableX(), (int) pageFormat.getImageableY());

            FontMetrics metrics = g2d.getFontMetrics(new Font("TimesRoman", Font.BOLD, 7));

            int idLength = metrics.stringWidth("000");
            int amtLength = metrics.stringWidth("000000");
            int qtyLength = metrics.stringWidth("00000");
            int priceLength = metrics.stringWidth("000000");
            int prodLength = (int) width - idLength - amtLength - qtyLength - priceLength - 17;

            int productPosition = 0;
            int discountPosition = prodLength + 5;
            int pricePosition = discountPosition + idLength + 10;
            int qtyPosition = pricePosition + priceLength + 4;
            int amtPosition = qtyPosition + qtyLength;

            try {
                /*Draw Header*/
                int y = 20;
                int yShift = 10;
                int headerRectHeight = 15;
                int headerRectHeighta = 40;

                String itiname;
                String CatToGetID;
                double couniti;
                double iticounter;
                String proptoremove;
                nf.setMaximumFractionDigits(2);

                int v = modelUpper.getRowCount();
                int h = modelUpper.getRowCount();

                String[] strArray = new String[v];
                String[] strCount = new String[v];
                String[] strAmount = new String[v];

                for (int x = 0; x < v; x++) {

                    proptoremove = String.valueOf(modelUpper.getValueAt(x, 3));
                    proptoremove = proptoremove.replace("NOK", "");
                    proptoremove = proptoremove.replace(" ", "");
                    proptoremove = proptoremove.replace(",", "");

                    iticounter = Double.parseDouble(String.valueOf(modelUpper.getValueAt(x, 1)));

                    couniti = Double.valueOf(proptoremove);

                    itiname = String.valueOf(modelUpper.getValueAt(x, 0));

                    strArray[x] = itiname;
                    strCount[x] = Double.toString(iticounter);
                    strAmount[x] = Double.toString(couniti);

                }

                cpuntAll = Double.valueOf(pricetoset);

                g2d.setFont(new Font("TimesRoman", Font.CENTER_BASELINE, 14));
                g2d.drawString("    -::: " + DashBord.MineName.getText().replace("Restaurant -", "") + " :::-", 16, y);
                y += yShift;
                g2d.setFont(new Font("TimesRoman", Font.CENTER_BASELINE, 10));
                g2d.drawString("", 12, y);
                y += headerRectHeight;
                g2d.drawString("Iteam Name     | Quantity |   Total   ", 10, y);
                y += yShift;
                g2d.drawString("--------------------------------------------------------", 10, y);
                y += headerRectHeight;
                g2d.setFont(new Font("monospaced", Font.BOLD, 10));

                for (int q = 0; q < h; q++) {

                    String ss = String.format("%-3s %7s %10s", strArray[q], arformat.format(Double.valueOf(strCount[q])), arformat.format(Double.valueOf(strAmount[q])) + " NOK");

                    g2d.drawString(ss, 10, y);
                    y += yShift;

                }
                
                g2d.setFont(new Font("TimesRoman", Font.CENTER_BASELINE, 10));
                g2d.drawString("--------------------------------------------------------", 10, y);
                y += yShift;
                y += yShift;
                g2d.setFont(new Font("monospaced", Font.BOLD, 10));
                g2d.drawString((String.format("%-3s %s", "Totil: ", arformat.format(cpuntAll) + " NOK")), 10, y);
                y += yShift;
                y += yShift;
                g2d.setFont(new Font("TimesRoman", Font.CENTER_BASELINE, 10));
                g2d.drawString("--------------------------------------------------------", 10, y);
                y += yShift;
                y += yShift;
                g2d.setFont(new Font("monospaced", Font.BOLD, 12));
                g2d.drawString((String.format("%-3s %s", "Invoice Number :", arformat.format(Double.valueOf(InvNum)))), 10, y);
                y += yShift;
                y += yShift;
                g2d.drawString("CashOut By : " + DashBord.NameLogIn.getText(), 10, y);
                y += yShift;
                y += yShift;

                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-M-yyyy hh:mm:ss");
                LocalDateTime now = LocalDateTime.now();

                g2d.drawString("Time And Date : " + dtf.format(now), 10, y);
                y += yShift;
                y += yShift;
                g2d.setFont(new Font("TimesRoman", Font.CENTER_BASELINE, 10));
                g2d.drawString("--------------------------------------------------------", 10, y);

            } catch (NumberFormatException r) {
            }

            result = PAGE_EXISTS;
        }

        return result;
    }

}

the output is like this :

enter image description here

my problim is in this line :

        String ss = String.format("%-3s %7s %10s", strArray[q], arformat.format(Double.valueOf(strCount[q])), arformat.format(Double.valueOf(strAmount[q])) + " NOK");

After i used a String.format it is must do the center of the text so it will be like this !.

To clarify more, I want the Autobot to be as this example :

--------------------------------
|Iteam Name | Quantity | Total |
--------------------------------
|Test            3       15 NOK
|Shawerma        2     27.2 NOK
--------------------------------
Totil: 42.2 NOK
--------------------------------
Invoice Number : 16
CashOut By : IT
Time And Date : 31-3-2021 02:10:20
--------------------------------

Any Help ?



from Recent Questions - Stack Overflow https://ift.tt/3rCOWKb
https://ift.tt/3cDTqfj

Is there a non-UART python transfer protocol layer to work with 512byte packets or less for BLE?

I'm on a team working on a non-profit, open-source project and we're creating a web-based configuration tool to control a piece of custom hardware on a Raspberry Pi, using the "Web Bluetooth API".

Packets over the BLE connection are limited to 512 bytes, so we seem to need a transfer protocol layer to assist communication with the Pi.

We do not want a UART implementation, as we want transmission guarantees.

Does such a transfer protocol layer exist, ideally implemented in Python?

Or is there a simple way to generate a python implementation of a transfer protocol layer, that would work with 512byte packages?



from Recent Questions - Stack Overflow https://ift.tt/39tjhEE
https://ift.tt/eA8V8J

SolrCloud Time Routed Alias Architecture

This is a broader question around building the architecture for SolrCloud Time Routed Alias application. I'm using SolrCloud to ingest time-series data on a regular basis and have SolrCloud running in a Kubernetes Cluster. A Solr node gets attached every time we add a new Pod to our cluster.

Since I'm trying to use Time Routed Aliases, it creates a new collection with preemptive calculation and currently places them across the Solr pods based on how much free-disk space is available in a pod, so new pods will get selected for shard placements whenever a new pod is introduced.

However, I would like to design a solution where we can avoid hot-spotting Solr nodes by distributing the shards across older pods and yet still maintaining SolrCloud architecture that grows in size as data is ingested every day.

I'm unsure what the best configuration would be at a collection/cluster level based on the available policies in https://solr.apache.org/guide/8_6/solrcloud-autoscaling-policy-preferences.html

I'm currently creating collections at weekly-intervals and my use-cases involve searching across data at least 2 weeks old. Because ingested data will be placed in newer pods, my client side facing applications will be bombarding the newer pods every time.

What level of configuration on a collection/alias/cluster level should I use in order to avoid hot-spotting?



from Recent Questions - Stack Overflow https://ift.tt/31vC0uZ
https://ift.tt/eA8V8J

StandardRestrictedSSLContextService - TrustStore Password as a Parameter

Im trying to get Nifi StandardRestrictedSSLContextService working if I manually enter the values, I am able to enable the service.

TrustStore Filename: /usr/local/openjdk-8/lib/security/cacerts
TrustStore Password: ImBHi7TI9C_XGay3lyRw.....
TrustStore Type: JKS

Once I try to move the password into a Parameter I get an Invalid Password/Type message.



from Recent Questions - Stack Overflow https://ift.tt/2O7MQ7b
https://ift.tt/eA8V8J

Google Reverse Geocoding API doesn't work on mobile internet

So i was able to get Google Geolocations and Geocoder API to work via desktop and on my phone when its connected to wifi, but when I disconnect from the wifi, geocoder doesn't display the results.

just to explain a bit more about what my code does, i use the geolocation APi to get lat/long values and then i use that output that is stored in a variable and i use it to get the city information using the reverse geocoding google API.

my code below is as follows

jQuery(function() {
      var GOOGLE_API_KEY = 'MY_KEY_HERE';
     var outlatlong = null;
      jQuery.ajax({
        url: 'https://www.googleapis.com/geolocation/v1/geolocate?key='+GOOGLE_API_KEY,
        data: JSON.stringify({ "considerIp": "true" }),
        type: 'POST',
        contentType: 'application/json',
        success: function(data) {
            
    outlatlong = [data.location.lat, data.location.lng].join(', ');
            
         
          if(data.location) {
            var out = [data.location.lat, data.location.lng].join(', ');
            jQuery('#gresponse').html(out);
           
    var urlTwo = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+out+"&key=MY_KEY_HERE";
    jQuery.get(urlTwo).success(function(data) {
       var loc1 = data.results[0];
       var county, city;
         jQuery.each(loc1, function(k1,v1) {
            if (k1 == "address_components") {
               for (var i = 0; i < v1.length; i++) {
                  for (k2 in v1[i]) {
                     if (k2 == "types") {
                        var types = v1[i][k2];
                        if (types[0] =="sublocality_level_1") {
                            county = v1[i].long_name;
                            //alert ("county: " + county);
                        } 
                        if (types[0] =="locality") {
                           city = v1[i].long_name;
                           alert ("city: " + city);
                       } 
                     }
                  }          
               }
            }

         });
         jQuery('#lattie').html(city); 
        
        
    });
              
          } else {
            jQuery('#lattie').html('didnt work');
          }
        },
        error: function(e) {
          console.log('error!', JSON.parse(e.responseText));
        }
      });
        return outlatlong
    });

Any help or solution will help! thank you all! <3



from Recent Questions - Stack Overflow https://ift.tt/3dqHlcC
https://ift.tt/eA8V8J

exitBeforeEnter is not working as intended - Trouble w/ Page Transitions

I'm trying to create a smooth page transition using a combination of react-router-dom and framer-motion, and I'm trying to have my pages fade out on exit and fade in on enter. But exitBeforeEnter is not working how it's supposed to. The page will not fade out on exit but the next page will fade in every time. Below is my code, and I'll attach one of the page files (all of the pages have pretty much the same code).

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter as Router } from "react-router-dom";

ReactDOM.render(<Router><App /></Router>, document.getElementById('root'));

App.js

import React from 'react';
import About from "./pages/About.js"
import Home from "./pages/Home.js"
import Projects from "./pages/Projects.js"
import { AnimatePresence } from 'framer-motion'
import { BrowserRouter as Switch, Route, useLocation } from "react-router-dom";

function App() {

  const location = useLocation();

  return (
    <div className="App">
      <AnimatePresence exitBeforeEnter>
        <Switch location={location} key={location.pathname}>
          <Route path="/about" component={About} />
          <Route path="/projects" component={Projects} />
          <Route path="/" exact component={Home} />
        </Switch>
      </AnimatePresence>
    </div>
  );
}

export default App;

Home.js (Page File)

import React from 'react';
import '../css/main.css';
import '../css/index.css';
import particleText from '../components/ParticleText.js'
import { Link } from 'react-router-dom';
import { motion } from 'framer-motion'

const pageVariants = {
  in: { 
    opacity: 1,
    transition: {
      duration: 1
    } 
  },
  out: { 
    opacity: 0,
    transition: {
      duration: 1
    } 
  }
}

class Home extends React.Component {

  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    try { particleText(true) } catch { /* Error */ }
    return (
      <motion.div className="main" initial="out" animate="in" exit="out" variants={pageVariants}>
        <div className="introOverlay"></div>
        <Link to="/about" className="homeButtonContainer">
            <p className="homeButtonText">About Me</p>
        </Link>
        <Link to="/projects" className="homeButtonContainer">
            <p className="homeButtonText">My Projects</p>
        </Link>
      </motion.div>
    );
  }
}

export default Home;


from Recent Questions - Stack Overflow https://ift.tt/3cDWo3s
https://ift.tt/eA8V8J

Python web scraping: websites from google search result

A newbie to Python here. I want to extract info from multiple websites (e.g. 100+) from a google search page. I just want to extract the key info, e.g. those with <h1>, <h2> or <b> or <li> HTML tags etc. But I don't want to extract the entire paragraph <p>.

I know how to gather a list of website URLs from that google search; and I know how to web scrape individual website after looking at the page's HTML. I use the Request and BeautifulSoup for these tasks.

However, I want to know how can I extract key info from all these (100+ !) websites without having to look at their html one by one. Is there a way to automatically find out the HTML tags the website used to emphasize key messages? e.g. some websites may use <h1>, while some may use <b> , or something else...

All I can think of is to come up with a list of possible "emphasis-typed" HTML tags and then just use BeautifulSoup.find_all() to do a wide-scale extraction. But surely there must be an easier way?



from Recent Questions - Stack Overflow https://ift.tt/2PGeuIT
https://ift.tt/eA8V8J

I got no output using echo $SLURM_NTASKS

I create this batch file myfirst_slurm_job.sh that contain the following code:

#!/bin/bash
#SBATCH --output="slurm1.txt"
cd $HOME/..
echo $PWD
echo $SLURMD_NODENAME
echo $SLURM_NTASKS

and then I run this command line:

sbatch myfirst_slurm_job.sh

note: it's my first post



from Recent Questions - Stack Overflow https://ift.tt/3rDqN5W
https://ift.tt/eA8V8J

How to merge data frame with different length in R by group?

data frame A1
Type  Worker
A  SHARON
B  RUN
C  JACK
D  NICK
K  EMILY

data frame A2
Type  Rate
A     0.39
A     0.78
A     0.22
A     -1.09

...

K     0.56
K     0.73
K     0.88
K     0.04
K     0.69

This is my coding.

K = merge(A1, A2,all.x=T)
Type  Rate
A     0.39
B     0.78
C     0.22
D     -1.09
K     -1.28
A     0.93
B     0.39
...

A     0.56
B     0.73
C     0.88
D     0.04
K     0.69

But my desired output is sorted by worker and type then show the corresponding value. Any ideas on different length of data frame merge?



from Recent Questions - Stack Overflow https://ift.tt/3czw4Hp
https://ift.tt/eA8V8J

Is there a way to specify that a template parameter type must be derived from a particular base class?

Is there a way to specify that a template parameter type must be derived from a particular base class? This is how I wish it would work:

class  foo
{
    a_foo_function();
}
//.......
//.......
//.......
template  < class F : public foo >  // <<<=== my deceptively creative syntax
class bar
{
    F * pfd;
    bar(F* food){ pfd = food; }
    void f() const {  pfd->a_foo_function();  }  //guaranteed to work in my book
}
//.......
class foo                         just_a_plain_foo;
//.......
class foodish : public foo {}     a_foodish;
//.......
class foolish : public not_foo {} a_foolish;
//.......
typedef bar<foodish> barf;
barf b(a_foodish); //ok
barf c(a_foolish); //NOT ok
barf d(just_a_plain_foo); //NOT ok ... pdf pointer is to a derived

Ain't that beautiful? But my beautiful syntax won't compile, though; and I can't seem to find how to do this. Note that using the base class as template parameter won't work for me, as I may have distinct and mutually incompatible classes deriving from foo. TIA.



from Recent Questions - Stack Overflow https://ift.tt/2PGemsT
https://ift.tt/eA8V8J

Is a mutex capable of performing this

I have a situation where I have multiple threads accessing the clipboard and performing an action with some sleeps. Basically I don't want to copy the wrong thing to the clipboard and perform something in an incorrect fashion.

Currently, I have an idea of using a mutex to lock a std::string variable and store the required data in it, then to the clipboard. After I finish the action, I unlock it. Then the other thread accesses the variable, then clipboard, and action.

As I have never used a mutex, my question is - will it work by just doing the above?

I'm using the following library to manage the clipboard: https://github.com/dacap/clip



from Recent Questions - Stack Overflow https://ift.tt/31va4aq
https://ift.tt/eA8V8J

Python Pandas Dataframe - Nothing being returned from my function

I have two dataframes:

energy_calculated (the time_stamp columns were just formatted using 3 decimal values to make sure there weren't any hidden values disrupting the simple math):

    fl_key min_time_stamp   max_time_stamp      energy
0    10051 1614556800019.000 1614556807979.000   0.352
1    10051 1614556808019.000 1614556815979.000   0.275
2    10051 1614556816019.000 1614556823979.000   0.429
3    10051 1614556824019.000 1614556831979.000   0.406
4    10051 1614556832019.000 1614556839979.000   0.444
5    10051 1614556840019.000 1614556847979.000   0.348
6    10051 1614556848019.000 1614556855979.000   0.381
7    10051 1614556856019.000 1614556863979.000   0.456
8    10051 1614556864019.000 1614556871979.000   0.362
9    10051 1614556872019.000 1614556879979.000   0.465
10   10051 1614556880019.000 1614556887979.000   0.577
11   10051 1614556888019.000 1614556895979.000   0.305
12   10051 1614556896019.000 1614556903979.000   0.347
13   10051 1614556904019.000 1614556911979.000   0.246
14   10051 1614556912019.000 1614556919939.000   0.340

df_test:

      fl_Key  time_stamp        energy       install_prediction
1007   10051  1614556840299      -1                  -1
491    10051  1614556819659      -1                  -1
1944   10051  1614556877779      -1                  -1
2227   10051  1614556889099      -1                  -1
677    10051  1614556827099      -1                  -1
2944   10051  1614556917779      -1                  -1
799    10051  1614556831979      -1                  -1
2378   10051  1614556895139      -1                  -1
1877   10051  1614556875099      -1                  -1
487    10051  1614556819499      -1                  -1

I am trying to do a lookup on the fl_Key and time_stamp from the df_test dataframe using them to find the "energy" value from the energy_calculated dataframe. The fl_Key to fl_key column should be exact match. The time_stamp column should be in between the min and max time_stamp columns.

The fl_Key and fl_key names are different so I can track which column is coming from where.

I have a simple method (I put in the raise exceptions just to make sure it was always finding a match):

def integrateEnergyCalculationData(row, energy_calculations):
  energy_calculations = energy_calculations[(energy_calculations['fl_key'] == row.fl_Key) & (energy_calculations['min_time_stamp'] <= row.time_stamp) & (energy_calculations['max_time_stamp'] >= row.time_stamp)]

  if (len(energy_calculations) == 0):
    raise Exception("No energy data for: " + str(row.fl_Key) + ", " + str(row.time_stamp))
  elif (len(energy_calculations) >= 2):
    raise Exception("Too much energy data for: " + str(row.fl_Key) + ", " + str(row.time_stamp))

  return energy_calculations['energy']

I tie it all together using apply():

df_test['energy'] = df_test[['time_stamp','fl_Key']].apply(integrateEnergyCalculationData, 1, args=(energy_calculated, ))

What ends up happening is that the mapping is made for some of the rows, but not all of them:

My resulting df_test dataframe looks like (I have a much bigger version of df_test, but I have shortened it to 10 rows to demonstrate the issue). I randomly selected 10 rows from the bigger version - that is why the index numbers are out of whack:

       fl_Key    time_stamp            energy     install_prediction
1007    10051    1614556840299                          -1
491     10051    1614556819659    0.4291915384067029    -1
1944    10051    1614556877779                          -1
2227    10051    1614556889099                          -1
677     10051    1614556827099                          -1
2944    10051    1614556917779                          -1
799     10051    1614556831979                          -1
2378    10051    1614556895139                          -1
1877    10051    1614556875099                          -1
487     10051    1614556819499    0.4291915384067029    -1

What am I missing? Thanks.



from Recent Questions - Stack Overflow https://ift.tt/3frBZAa
https://ift.tt/eA8V8J

How to filter the Chrome console so you only see messages/errors from one content script/Chrome Extension?

I'm running a content script on a page for an extension I'm building. I simply want to see only errors and messages from that one extension in the Google Chrome console. I need to be able to make this happen without:

  • without blocking messages/errors from other extensions [like this post explains], since I have a ton of extensions and I might need to know about their errors in future and don't want to forget to unhide their messages/errors

  • without installing a fresh install of Chrome on a VM, using Chrome incognito, or something similar

What I've tried

  • filtering in the console using "chrome-extension://myChromeExtensionIDHere" showed my extension's errors, but that didn't show any console.log messages I was sending in my script in my extension.
  • url:chrome-extension://myChromeExtensionIDHere showed my extension's console.log messages, but didn't show the errors
  • clicking my "content_script.js" on the side, but that didn't capture all the errors resulting from my content_script (there were some listed under a different script)

This seems simple but am struggling to find a way to do it. How can I do this?



from Recent Questions - Stack Overflow https://ift.tt/31wuXCj
https://ift.tt/eA8V8J

How to create a "hard-coded" small SQL join table in code?

Context: I do not have the ability to create/update/edit the tables in question.

I have two tables that I am trying to join via a manual SQL query in Tableau. There exists a column in each table I can use to link the tables together, but I need a third table (that does not exist) to link them.

There are only 6 values I'd like to link, I was hoping there is some way to declare an "in-memory" table or similar in SQL to join these tables.

For example - I'd like to join these two tables together:

Table 1

name value
place 1 14
place 2 10
place 3 100

Table 2

identifier property
superstore awesome
hospital bad
port great

Can I somehow hard-code the following "table" into SQL code to join them?

hard coded table

name identifier
place 1 hospital
place 2 port
place 3 superstore

Should yield the following:

name identifier value property
place 1 hospital 14 bad
place 2 port 10 great
place 3 superstore 100 awesome

If I could create a new table with the linkage above I would, but I can't.

If it's relevant - this is using an Oracle database.

Thank you for your help!



from Recent Questions - Stack Overflow https://ift.tt/3cBvk4y
https://ift.tt/eA8V8J

An XPath expression in Java for getting xml elements

I want to get nodes from an api which contains xml elements.

https://www.w3schools.com/xml/cd_catalog.xml Here is the link for the api.

So my Java code is like this:

    package in.automationtesting.neh;
    
    import java.io.IOException;
    import java.io.Reader;
    import java.io.StringReader;
    import java.net.URI;
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathExpression;
    import javax.xml.xpath.XPathExpressionException;
    import javax.xml.xpath.XPathFactory;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    public class Test1 {
        
        
    
            public static final String GET_API_URL = "https://www.w3schools.com/xml/cd_catalog.xml";        
            
            public static void main(String[] args) throws IOException, InterruptedException {
                HttpClient client = HttpClient.newHttpClient();
                HttpRequest request = HttpRequest.newBuilder()
                        .GET()
                        .header("accept", "application/xml")
                        .uri(URI.create(GET_API_URL))
                        .build();
                HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
                 
        
                 XPathFactory xpathfactory = XPathFactory.newInstance();
                 XPath xpath = xpathfactory.newXPath();
                 
                try {
    
                    Reader reader = new StringReader(response.body());
                    InputSource inputSource = new InputSource(reader);
                    XPath xpath1 = XPathFactory.newInstance().newXPath();
                    System.out.println(xpath1.evaluate("//CATALOG/CD", inputSource));
                    
                } catch (XPathExpressionException e) {
                    
                    e.printStackTrace();
                }

            }
}

The output on the console should be like this:

<CATALOG>
<CD>
<TITLE>1999 Grammy Nominees</TITLE>
<ARTIST>Many</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Grammy</COMPANY>
<PRICE>10.20</PRICE>
<YEAR>1999</YEAR>
</CD>


<CD>
<TITLE>Big Willie style</TITLE>
<ARTIST>Will Smith</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1997</YEAR>
</CD>
</CATALOG>

With the xpath expression i want to get the cd's which are released from 1995 and later ,plus they should be only from USA. And when i only match the root in the xpath expression which is CATALOG it shows all the elements which is good, but when i add cd next to it, on the console it only shows one album and not all of them, idk why i tried something like this in the expression and other varieties of it but no luck "//CATALOG/CD[@year>1995 and country='USA']



from Recent Questions - Stack Overflow https://ift.tt/3sPq7w1
https://ift.tt/eA8V8J

Should and Filter combination in ElasticSearch

I have this query which return the correct result

GET /person/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "fuzzy": {
            "nameDetails.name.nameValue.surname": {
              "value": "Pibba",
              "fuzziness": "AUTO"
            }
          }
        },
        {
          "fuzzy": {
            "nameDetails.nameValue.firstName": {
              "value": "Fawsu",
              "fuzziness": "AUTO"
            }
          }
        }
      ]
    }
  }
}

and the result is below:

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 3.6012557,
    "hits" : [
      {
        "_index" : "person",
        "_type" : "_doc",
        "_id" : "70002",
        "_score" : 3.6012557,
        "_source" : {
          "gender" : "Male",
          "activeStatus" : "Inactive",
          "deceased" : "No",
          "nameDetails" : {
            "name" : [
              {
                "nameValue" : {
                  "firstName" : "Fawsu",
                  "middleName" : "L.",
                  "surname" : "Pibba"
                },
                "nameType" : "Primary Name"
              },
              {
                "nameValue" : {
                  "firstName" : "Fausu",
                  "middleName" : "L.",
                  "surname" : "Pibba"
                },
                "nameType" : "Spelling Variation"
              }
            ]
          }              
        }
      }
    ]
  }

But when I add the filter for Gender, it returns no result

GET /person/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "fuzzy": {
            "nameDetails.name.nameValue.surname": {
              "value": "Pibba",
              "fuzziness": "AUTO"
            }
          }
        },
        {
          "fuzzy": {
            "nameDetails.nameValue.firstName": {
              "value": "Fawsu",
              "fuzziness": "AUTO"
            }
          }
        }
      ],
      "filter": [
        {
          "term": {
            "gender": "Male"
          }
        }
      ]
    }
  }
}

Even I just use filter, it return no result

GET /person/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "gender": "Male"
          }
        }
      ]
    }
  }
}


from Recent Questions - Stack Overflow https://ift.tt/2OarJRO
https://ift.tt/eA8V8J

How does the serverless datadog forwarder encrypt/encode their logs?

I am having trouble figuring out how the datadog forward encodes/encrypts its messages from the datadog forwarder. We are utilizing the forwarder on datadog using the following documentation: https://docs.datadoghq.com/serverless/forwarder/ . On that page there, Datadog has an option to send the same event to another lambda that it invokes via the AdditionalTargetLambdaARNs flag. We are doing this and having the other lambda invoke but the event input that we are getting is long string that looks like it is base64 encoded but when I put it into a base64 decoder, I get gibberish back. I was wondering if anyone knew how datadog is compressing/encoding/encrypting their data/logs that they send so that I can read the logs in my lambda and be able to preform actions off of the data being forwarded? I have been searching google and the datadog site for documentation on this but I can't find any.



from Recent Questions - Stack Overflow https://ift.tt/3sHEKkM
https://ift.tt/eA8V8J

Phaser 3 collider fires endless

I try to make a bouncing bullet for a game that should disappear after bouncing 3 times. I thought it's simple, I gave my bullet a variable with the value of 3 and decreased it in my bullet-platform collider by one.

After it didn't work and checked the variable with console.log(), I found out that the variable gets decreased continuously. I tested my other colliders and found out that only the bullet-platform collider do that, while the player-platform, enemy-platform, bullet-player and bullet-enemy collider don't. In addition my function for destroying bullets, when they hit a platform, oddly work fine. My bullets only get destroyed when hitting a platform.

Does anyone have an Idea how to fix that?

Edit: I made a Github repository of my game for better insight. (At least I hope I did, I haven't used Github before.) https://github.com/Kiroho/Game

Edit2: After testing around, I found out that it must have something to do with how I use my ammoGroup class.

I found out that, if I create bullets via ammoGroup (via createMultiple), the collider starts firing for each bullet until I shot them at least once. After all existing bullets are fired once, everything works normally and the collider fires as intended -> only on collision.

My bullet-platform collider

this.scene.physics.add.collider(this.scene.platforms, this.scene.playerProjectiles_Bounce, function (platform, projectile) {
        //destoryProjectile(projectile);
        console.log("hit");
    });

The Ammo Groups. I use them as a "magazine" for each weapon

class AmmoGroup extends Phaser.Physics.Arcade.Group {
constructor(scene) {
    super(scene.physics.world, scene);

}

fire(x, y, direction) {
    const projectile = this.getFirstDead(false);
    if (projectile) {
        projectile.fire(x, y, direction);
    }
}



loadAmmo(ammoIndex) {
    this.clear();
    if (ammoIndex == 1) {
        this.classtype = Blaster;
    }
    else if (ammoIndex == 2) {
        this.classtype = BlasterBig;
    }
    else if (ammoIndex == 3) {
        this.classtype = Granade;
    }
    else if (ammoIndex == 4) {
        this.classtype = Granade;
    }
    else if (ammoIndex == 0) {
        this.classtype = Laser;
    }
    this.createMultiple({
        classType: this.classtype,
        frameQuantity: 20,
        active: false,
        visible: false,
        key: ['ballAnim', 'kugel']
    })
}

}

The bullet class

class Granade extends Phaser.Physics.Arcade.Sprite {
constructor(scene, x, y) {
    super(scene, x, y, 'kugel');
    this.dmg = 20;
    this.enemyHit = [];
    this.bounceCounter = 3;
    
}

fire(x, y, direction) {
    this.body.reset(x, y);
    this.body.setGravityY(-1000);
    this.setBounce(1);
    this.setActive(true);
    this.setVisible(true);

    this.setVelocityY(WeaponConst.VELOCITY_Y_GRENADE);
    if (direction == "left") {
        this.setVelocityX(WeaponConst.VELOCITY_X_GRENADE * -1);
    }
    else if (direction == "up") {
        this.setVelocityY(WeaponConst.VELOCITY_Y_GRENADE * 2);
        this.setVelocityX(0);
    }
    else {
        this.setVelocityX(WeaponConst.VELOCITY_X_GRENADE);
    }

}

preUpdate(time, delta) {
    super.preUpdate(time, delta);

    if (!this.scene.cameras.main.worldView.contains(this.x, this.y)) {
        this.enemyHit = [];
        this.setActive(false);
        this.setVisible(false);
    }
}

}

Additional: The player (and the enemies) has a weapon object. This weapon object has a ammoGroup object and set it's projectile, the velocity when shooting, assigning it to groups and so on.

class Weapon {
constructor(scene) {
    this.scene = scene;
    this.type = null;
    this.attackRate = null;
    this.attackRange = null;
    this.ammoGroup = new AmmoGroup(this.scene.scene, 1)
    this.direction = null;
}


chooseWeapon(type) {
    if (type == 'Blaster') {
        this.setUpWeapon(
            WeaponConst.TYPE_BLASTER,
            WeaponConst.ATK_RATE_BLASTER,
            WeaponConst.VELOCITY_X_BLASTER,
            WeaponConst.VELOCITY_Y_BLASTER,
            WeaponConst.AMMO_GROUP_BLASTER
        );
        console.log("Blaster choosen");
        this.assignToGroup(this.scene.scene.playerProjectiles_Normal);

    }
    else if (type == 'BlasterBig') {
        this.setUpWeapon(
            WeaponConst.TYPE_BLASTER_BIG,
            WeaponConst.ATK_RATE_BLASTER_BIG,
            WeaponConst.VELOCITY_X_BLASTER_BIG,
            WeaponConst.VELOCITY_Y_BLASTER_BIG,
            WeaponConst.AMMO_GROUP_BLASTER_BIG
        );
        console.log("BlasterBig choosen");
        this.assignToGroup(this.scene.scene.playerProjectiles_PierceEnemies);

    }
    else if (type == 'Grenade') {
        this.setUpWeapon(
            WeaponConst.TYPE_GRENADE,
            WeaponConst.ATK_RATE_GRENADE,
            WeaponConst.VELOCITY_X_GRENADE,
            WeaponConst.VELOCITY_Y_GRENADE,
            WeaponConst.AMMO_GROUP_GRENADE
        );
        console.log("Grenade choosen");
        this.assignToGroup(this.scene.scene.playerProjectiles_Bounce);

    }
    else if (type == 'GrenadeBig') {
        this.setUpWeapon(
            WeaponConst.TYPE_GRENADE_BIG,
            WeaponConst.ATK_RATE_GRENADE_BIG,
            WeaponConst.VELOCITY_X_GRENADE_BIG,
            WeaponConst.VELOCITY_Y_GRENADE_BIG,
            WeaponConst.AMMO_GROUP_GRENADE_BIG
        );
        console.log("GrenadeBig choosen");
        this.assignToGroup(this.scene.scene.playerProjectiles_PierceEnemies);

    }
    else if (type == 'Laser') {
        this.setUpWeapon(
            WeaponConst.TYPE_LASER,
            WeaponConst.ATK_RATE_LASER,
            WeaponConst.VELOCITY_X_LASER,
            WeaponConst.VELOCITY_Y_LASER,
            WeaponConst.AMMO_GROUP_LASER
        );
        console.log("Laser choosen");
        this.scene.scene.enemyProjectiles_Normal.add(this.ammoGroup);
        this.scene.scene.enemyProjectiles_PiercePlayer.remove(this.ammoGroup);
        this.scene.scene.enemyProjectiles_PierceAll.remove(this.ammoGroup);
    }

}


setUpWeapon(type, attackRate, velocityX, velocityY, ammoGroup ) {
    this.type = type;
    this.attackRate = attackRate;
    this.velocityX = velocityX;
    this.velocityY = velocityY;
    this.ammoGroup.loadAmmo(ammoGroup);
    //this.scene.scene.enemyProjectiles_Normal.add(this.ammoGroup);
}


fire(x, y, direction) {
    this.ammoGroup.fire(x, y, direction);

}


assignToGroup(group) {

    this.scene.scene.playerProjectiles_Normal.remove(this.ammoGroup);
    this.scene.scene.playerProjectiles_PierceEnemies.remove(this.ammoGroup);
    this.scene.scene.playerProjectiles_PierceAll.remove(this.ammoGroup);
    this.scene.scene.playerProjectiles_Bounce.remove(this.ammoGroup);

    group.add(this.ammoGroup)
}

}



from Recent Questions - Stack Overflow https://ift.tt/3wo4EfM
https://ift.tt/eA8V8J

confusion_matrix() | ValueError: Classification metrics can't handle a mix of multiclass and multiclass-multioutput targets

Definitely has been asked before, but I've not been successful at analysing other posts' solutions for my own instance of this problem.

I have many classification models I want to compare using confusion_matrix()

matrix = confusion_matrix(y_test, y_pred) # ERROR
>>> y_pred
[[2 2 2 ... 2 2 2]
 [2 2 2 ... 2 2 2]
 [2 2 2 ... 2 2 2]
 ...
 [3 3 2 ... 3 2 3]
 [2 2 2 ... 2 2 2]
 [3 3 3 ... 3 3 3]]
>>> y_pred.shape
(500, 256)
>>> y_test
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3
 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3]
>>> y_test.shape
(500, )

Error:

ValueError: Classification metrics can't handle a mix of multiclass and multiclass-multioutput targets

When .flatten() is performed on y_pred - i.e. 1D array (500 * 256 = 128000):

ValueError: Found input variables with inconsistent numbers of samples: [500, 128000]


from Recent Questions - Stack Overflow https://ift.tt/3rwwanB
https://ift.tt/eA8V8J

Use fillna() and lambda function in Pandas to replace NaN values

I'm trying to write fillna() or a lambda function in Pandas that checks if 'user_score' column is a NaN and if so, uses column's data from another DataFrame. I tried two options:

games_data['user_score'].fillna(
    genre_score[games_data['genre']]['user_score']
    if np.isnan(games_data['user_score'])
    else games_data['user_score'],
    inplace = True
)

# but here is 'ValueError: The truth value of a Series is ambiguous'

and

games_data['user_score'] = games_data.apply(
    lambda row: 
    genre_score[row['genre']]['user_score'] 
    if np.isnan(row['user_score'])
    else row['user_score'],
    axis=1
)

# but here is 'KeyError' with another column from games_data

My dataframes:

games_data

enter image description here

genre_score

enter image description here

I will be glad for any help!



from Recent Questions - Stack Overflow https://ift.tt/3w9t9wQ
https://ift.tt/3u8TSYN

How to configure Hangfire with Autofac in a dotnet core console app

I'm trying to port a working Hangfire setup embedded in a Kestrel webserver to a console app. I've modified the web app so it still provides the Hangfire dashboard but doesn't start its own Hangfire server.

The code I must port uses Autofac. I've added the Hangfire.Autofac package to the console app and have already performed all the steps detailed in the answer to Hangfire Autofac .net core 3.1

When I create a job (using the web app) the console app Hangfire server tries to execute the job but I get this failure message:

The requested service 'AED.ServicesLayer.JobProcessing.ProcessManager' has not been registered.

Investigating this we examine the setup of Autofac in the console app. This is how I set up my container.

IConfiguration config = new ConfigurationBuilder()
  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  .Build();
var containerBuilder = new Autofac.ContainerBuilder();
containerBuilder.RegisterInstance(Log.Logger).AsImplementedInterfaces();
containerBuilder.RegisterModule(new RepositoryModule(config));
containerBuilder.RegisterType<UserService>().As<IUserService>();
containerBuilder.RegisterInstance(config).As<IConfiguration>();
containerBuilder.RegisterModule(new JobProcessingModule(config));
var container = containerBuilder.Build();

When the app is executed, hitting a breakpoint in JobProcessingModule proves the following line of code is executed.

builder.RegisterType<ProcessManager>().As<IProcessManager>();

It is very curious that the containerBuilder instance passed to JobProcessingModule.Load(containerBuilder) is not the same containerBuilder object on which RegisterModule is invoked.

However, experiments with simplified injectables suggest that this is normal, and the injected items are nevertheless visible in the registrations for the container that is returned.

Re-examining the logged failure we note that the class is mentioned by class name and not by interface. Changing the registration by removing the interface registration, like so

builder.RegisterType<ProcessManager>();//.As<IProcessManager>();

caused the ProcessManager to be found in the Hangfire console host but caused run-time errors in the web application when creating the job.

Registering it both ways caused ProcessManager to be found by both, with a new problem surfacing: cannot resolve dependencies. This, however, is merely a new case of the same problem.

While this allows me to move forward with getting a console host working, I do not like code I do not understand. Why should the console host require registration by class name when the web app does not?

Whatever is causing this has also caused Hangfire.IBackgroundJobClient to fail to resolve to the background job client. This is a hangfire class so it really does seem like there is a fundamental problem.



from Recent Questions - Stack Overflow https://ift.tt/3stqiwK
https://ift.tt/eA8V8J

curl https time_appconnect is zero

my company has a web project, named projectA, is deployed in a cloud server(similar as AWS). projectA is in tomcat.

we have ssl certificate, e.g. mycompany.com, users are able to access projectA by typing https://mycompany.com/projectA which will be redirected to https://mycompany.com/projectA/loginPage.action page if user has not login(only type https://mycompany.com will show 404 page), the browsers shows this website is secured.

however, either curl -w "TCP handshake:%{time_connect}, SSL handshake: %{time_appconnect}\n" -so /dev/null https://mycompany.com or curl -w "TCP handshake:%{time_connect}, SSL handshake: %{time_appconnect}\n" -so /dev/null https://mycompany.com/projectA, or curl -w "TCP handshake:%{time_connect}, SSL handshake: %{time_appconnect}\n" -so /dev/null https://mycompany.com/projectA/loginPage.action their time_appconnect are zero, why? time_connect has value.

i run curl in a cloud server whose CentOS is 7.9.2009(Core), Linux version 3.10.0, curl version is 7.29.0



from Recent Questions - Stack Overflow https://ift.tt/3djKXgh
https://ift.tt/eA8V8J

2021-03-30

Making Regex combination of multiple chars and numbers combined

How to write a regex that will combine numbers and chars in a string in any order? For example, If I want to read some kind of invoice number, I have example like this:

example 1: 32ah3af
example 2: 32ahPP-A2ah3af
example 3: 3A63af-3HHx3B-APe5y5-9OPiis
example 4: 3A63af 3HHx3B APe5y5 9OPiis

So each 'block' have length between 3 and 7 chars (letters or numbers) that can be in any order (letters can be lowercase or uppercase). Each. 'block' can start with letter or with number. It can have one "block" or max 4 blocks that are separated with ' ' or -.

I know that I can make separators like: \s or \-, but I have no idea how to make these kind of blocks that have (or do not have) separator.

I tried with something like this:

([0-9]?[A-z]?){3,7}

But it does not work



from Recent Questions - Stack Overflow https://ift.tt/3cyQtwv
https://ift.tt/eA8V8J

Bootstrap 5 floating label for a textarea overlaps with input on scroll

Looking at the documentation for a floating label of a textarea, https://getbootstrap.com/docs/5.0/forms/floating-labels/, it appears that the label overlaps with the input if the content is scrollable:

Textarea label overlap

Is there a way to prevent this and make the scrollable area below the label?



from Recent Questions - Stack Overflow https://ift.tt/2P91Zpv
https://ift.tt/2Pg6kac

automatically updates the table without refreshing/reloading the page

I would like to ask if how do I get the latest update of my data that is displayed in my table without reloading or refreshing it. The insertion of the data is already good, it already inserts however I see that the page is still reloading. I am still new to ajax and sweetalert using the client-side.

addingUser.php

$(document).ready(function(){
    $('#addStudent').click(function(e){
        e.preventDefault();
        Swal.fire({
            title: "Are you sure?",
            text: "New student will be added added!",
            icon: "success",
            showCancelButton: true,
            allowEscapeKey : false,
            allowOutsideClick: false
        }).then((result) => {
            if (result.isConfirmed) {
                var valid = this.form.checkValidity();
                if(valid){
                    var studentNumberId = $('#studentNumberId').val();
                    var studentFullName = $('#studentFullName').val();
                    var studentPassword = $('#studentPassword').val();
                    var studentEmail = $('#studentEmail').val();
                    var studentYearBlock = $('#studentYearBlock').val();
                        e.preventDefault()
                        $.ajax({
                            type: 'POST',
                            url: 'includes/model_addStudent.php',
                            data: {studentNumberId: studentNumberId,studentFullName: studentFullName,studentPassword: studentPassword,studentEmail: studentEmail,
                                studentYearBlock: studentYearBlock},
                            success: function(data){
                                Swal.fire({
                                    title: "Successfully Added!",
                                    text: "New student has been added!",
                                    icon: "success"
                                }).then(function() {
                                    // update page without refreshing/reloading....
                                    location.href = "ManageStudent.php";
                                });
                            },
                            error: function(xhr, thrownError, ajaxOptions){
                                Swal.fire({
                                    title: "Successfully Added!",
                                    text: thrownError,
                                    icon: "info"
                                })
                            } 
                        });
                }
                else {
                    Swal.fire({
                        title: "Error!",
                        text: "Invalid Form",
                        icon: "warning"
                    });
                }
            }
            else {
                Swal.fire(
                'No Changes!',
                'No New Student has been added.',
                'info'
                )
            }
        });   
            });      
    });

Thank you so much.



from Recent Questions - Stack Overflow https://ift.tt/3u4FIb1
https://ift.tt/eA8V8J

The weighted means of group is not equal to the total mean in pandas groupby

I have a strange problem with calculating the weighted mean of a pandas dataframe. I want to do the following steps:

(1) calculate the weighted mean of all the data
(2) calculate the weighted mean of each group of data

The issue is when I do step 2, then the mean of groups means (weighted by the number of members in each group) is not the same as the weighted mean of all the data (step 1). Mathematically it should be (here). I even thought maybe the issue is the dtype, so I set everything on float64 but the problem still exists. Below I provided a simple example that illustrates this problem:

My dataframe has a data, a weight and group columns:

data = np.array([
    0.20651903, 0.52607571, 0.60558061, 0.97468593, 0.10253621, 0.23869854,
    0.82134792, 0.47035085, 0.19131938, 0.92288234
])
weights = np.array([
    4.06071562, 8.82792146, 1.14019687, 2.7500913, 0.70261312, 6.27280216,
    1.27908358, 7.80508994, 0.69771745, 4.15550846
])
groups = np.array([1, 1, 2, 2, 2, 2, 3, 3, 4, 4])
df = pd.DataFrame({"data": data, "weights": weights, "groups": groups})
print(df)
>>> print(df)
       data   weights  groups
0  0.206519  4.060716       1
1  0.526076  8.827921       1
2  0.605581  1.140197       2
3  0.974686  2.750091       2
4  0.102536  0.702613       2
5  0.238699  6.272802       2
6  0.821348  1.279084       3
7  0.470351  7.805090       3
8  0.191319  0.697717       4
9  0.922882  4.155508       4

# Define a weighted mean function to apply to each group
def my_fun(x, y):
    tmp = np.average(x, weights=y)
    return tmp

# Mean of the population
total_mean = np.average(np.array(df["data"], dtype="float64"),
                        weights= np.array(df["weights"], dtype="float64"))
# Group data 
group_means = df.groupby("groups").apply(myfunc, 'data', 'weights')

# number of members of each group
counts = np.array([2, 4, 2, 2],dtype="float64")

# Total mean calculated from mean of groups mean weighted by counts of each group
total_mean_from_group_means = np.average(np.array(group_means,
                                              dtype="float64"),
                                     weights=counts)

print(total_mean)
0.5070955626929458

print(total_mean_from_group_means)
0.5344436242465216

As you can see the total mean calculated from group means is not equal to the total mean. What I am doing wrong here?



from Recent Questions - Stack Overflow https://ift.tt/2PhrxAK
https://ift.tt/eA8V8J

Python 3: Code is looking for directories that don't exist when it isn't supposed to

I have been working on the following code:

#ZIPPYORACLE USB worm module.
import os, random, stat
#User chosen at random
picked = 0
userchoice = random.choice (os.listdir ("/media/"))
randomdir = random.choice (os.listdir ("/media/" + userchoice))
picked = "/media/" + userchoice + "/" + randomdir
os.chdir (picked)
os.chmod ("usb.txt", stat.S_IWRITE)
with open ("usb.txt", "w") as file:
    print (picked)
    file.write ("Create a new text file!")

It is supposed to upload a file to a random USB drive. The problem is it works only 10% of the time, but 90% of the time gives errors like these:

NotADirectoryError: [Errno 20] Not a directory: '/media/asher/Ubuntu-MATE 20.10 amd64usb.txtusb.txtusb.txtusb.txt'

I have no idea why this is happening, and have been debugging it for an hour now. Do any of you more experienced programmers know what's causing this issue?



from Recent Questions - Stack Overflow https://ift.tt/3cwelka
https://ift.tt/eA8V8J

Python plot two heat maps at once using squares divided in 2 halves

I am trying to generate a heatmap where each rectangle is split into two pieces and can be colored differently. Essentially, I have two 20x20 matrices that I want to be able to plot on one Heatmap, similar to what is done in this here except I want to divide into 2 rectangles rather than triangles.

Any suggestions on how to do this? It's not obvious there's an easy way to do this but I was thinking of using a hacky solution where I use pcolormesh to draw a 40x40 grid and then somehow plot my points onto that. I'd like to be able to color the outside of single rectangle in a dark line and then use a thinner line to divide the rectangle in 2.



from Recent Questions - Stack Overflow https://ift.tt/3sMuPut
https://ift.tt/eA8V8J

Split the date and time in data frame itself

I am working on 15 minutes historical OHLC stocks data and calculating few technical indicators like stochastic, VWAP and RSI etc. Followed is my code, and I need help on splitting the date and time right in the data frame itself then I can save it to CSV file.

import requests
import pandas as pd
import arrow
import datetime
window = 10
window20 = 20
window50 = 50
window100 = 100
window200 = 200

ema_time = 8
import numpy as np
import csv

def get_quote_data(symbol='GOOGL', data_range='10d', data_interval='60m'):
    res = requests.get('https://query1.finance.yahoo.com/v8/finance/chart/{symbol}?range={data_range}&interval={data_interval}'.format(**locals()))
    data = res.json()
    body = data['chart']['result'][0]    
    dt = datetime.datetime
    dt = pd.Series(map(lambda x: arrow.get(x).to('US/Central').datetime.replace(tzinfo=None), body['timestamp']), name='Datetime')
    df = pd.DataFrame(body['indicators']['quote'][0], index=dt)
    dg = pd.DataFrame(body['timestamp'])
    
    #calculation for VWAP
    volumeC = df['volume']
    priceC = df['close']
    df = df.assign(VWAP=((volumeC * priceC).cumsum() / volumeC.cumsum()).ffill())
    # calculate stochastic
    df['low5']= df['low'].rolling(5).min()
    df['high5']= df['high'].rolling(5).max()
    
    #k = 100 * (c - l) / (h - l) 
    df['K'] = (df['close']-df['low5'])/(df['high5']-df['low5'])
    
    #calculate RSI
    df['RSI'] = calculate_rsi(df)
    df = df.loc[:, ('open','high','low', 'close','volume','VWAP','RSI','K')]
    df.columns = ['OPEN','HIGH','LOW', 'CLOSE','volume','VWAP', 'RSI', 'K']
    df.dropna(inplace=True)    
       
       
    return df

def calculate_rsi(df):
    delta = df.close.diff()
    window_rsi = 14
    up_days = delta.copy()
    up_days[delta<=0]=0.0
    down_days = abs(delta.copy())
    down_days[delta>0]=0.0
    RS_up = up_days.rolling(window_rsi).mean()
    RS_down = down_days.rolling(window_rsi).mean()
    rsi= 100-100/(1+RS_up/RS_down)
    return rsi



data = get_quote_data('AMZN', '30d', '15m')
print(data)

It prints data like followed. OPEN HIGH LOW CLOSE
Datetime
2021-02-16 12:00:00 3271.580078 3276.655029 3267.879883 3271.580078
2021-02-16 12:15:00 3273.000000 3277.874023 3269.949951 3275.500000
2021-02-16 12:30:00 3273.860107 3278.290039 3272.000000 3273.619873
2021-02-16 12:45:00 3273.149902 3274.327393 3265.510010 3268.120117
2021-02-16 13:00:00 3269.500000 3272.229980 3267.850098 3271.943604
... ... ... ... ...
2021-03-29 13:45:00 3063.350098 3073.989990 3063.350098 3069.439941
2021-03-29 14:00:00 3068.635010 3083.368896 3068.635010 3078.189941
2021-03-29 14:15:00 3079.534912 3082.459961 3075.130127 3080.810059
2021-03-29 14:30:00 3081.500000 3083.021973 3075.939941 3076.739990
2021-03-29 14:45:00 3076.280029 3081.235107 3067.639893 3076.760010

                 volume         VWAP        RSI         K  

Datetime
2021-02-16 12:00:00 67712 3282.279987 38.809164 0.779962
2021-02-16 12:15:00 52424 3282.080086 34.602731 0.887348
2021-02-16 12:30:00 42972 3281.880445 44.879847 0.741838
2021-02-16 12:45:00 34363 3281.625596 38.436315 0.405271
2021-02-16 13:00:00 34606 3281.448318 36.041982 0.503410
... ... ... ... ...
2021-03-29 13:45:00 62228 3105.228131 55.439824 0.294534
2021-03-29 14:00:00 75404 3105.206534 59.610208 0.757640
2021-03-29 14:15:00 53411 3105.192739 56.776731 0.880254
2021-03-29 14:30:00 77107 3105.169530 58.732036 0.689787
2021-03-29 14:45:00 195762 3105.110819 53.152839 0.669866

[766 rows x 8 columns]

I would like to have columns like DATE TIME OPEN HIGH LOW CLOSE VOLUME VWAP RSI K in the data frame itself. I am new to python and struggling to split the date and time RIGHT INTO Dataframe itself.

Please help.

Thanks, DR



from Recent Questions - Stack Overflow https://ift.tt/31scqqy
https://ift.tt/eA8V8J

How to specify repc's output path in qmake?

in qmake I have

REPC_SOURCE = rpc/SomeRPC.rep

and it generates rep_SomeRPC_source.h in the root of the project. I would like to store it somewhere else to keep root as clean as possible.
Documentation says repc creates the rep_SimpleSwitch_source.h header in the build directory that you specify. But how to specify build directory?
The only option I see is to change OUT_PWD, but documentation says Do not attempt to overwrite the value of this variable.



from Recent Questions - Stack Overflow https://ift.tt/3m7qcbB
https://ift.tt/eA8V8J

Java :: Generics :: Capture Wildcards

I have a couple of classes having identical methods, except with respect to certain parameter types:

interface ICls<T> {
    void doSomething(String key, T value);
    Map<String, T> getSomething();
}
class ClsA implements ICls<Boolean> {
    void doSomething(String key, boolean value) {}
    Map<String, boolean> getSomething() {}
}

class ClsB implements ICls<String> {
    void doSomething(String key, String value) {}
    Map<String, String> getSomething() {}
}

Now I'm trying to have a main class that stores a mixed list of these class objects and for each of these instances, passes info between its two methods:

class Main {
    List<ICls<?>> list = List.of(
        new ClsA(),
        new ClsB()
    );
    void run() {
        list.forEach(cls -> {
            Map<String, ?> data = cls.getSomething();
            data.keySet().forEach(key -> cls.doSomething(key, map.get(key));
        });
    }

The List<ICls<?>> and Map<String, ?> statements are OK. However, the map.get(key) throws an IDE error:

'doSomething(<String, capture<?>>) in '...ICls' cannot be applied to 'String, capture<?>'

Hovering the mouse cursor over the offending statement shows:

Required type: capture of ?
Provided: capture of ?

Assuming that I can't/don't want to change the generic type T to Object, and don't want to change the architecture either, what can I do to make the code here compile?

I've tried changing the signature of doSomething so that it accepts the entire Map<String, T> and call it like so, with no luck either:

cls.doSomething(cls.getSomething());


from Recent Questions - Stack Overflow https://ift.tt/2QPE8LX
https://ift.tt/eA8V8J

Show an image based on date

I'm trying to show a check mark image based on date, the date format is March 28, 2021 for an event list

For example:

if the event date is on March 29, 2021 then it will show the following image (green checkbox)

<img src="https://i.imgur.com/iw9fm7A.jpg">

but if today date was March 28, 2021, and the event has not happened yet then it will not show any images, just blank.

Code:

<table width="80%" border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td>Event Name</td>
    <td>Event Date</td>
    <td>Completed? </td>
  </tr>
  <tr>
    <td>E-Bike meet up at <strong>Los Angeles, Griffith Park</strong></td>
    <td>March 29, 2021</td>
    <td>Show Checkbox Here</td>
  </tr>
  <tr>
    <td>E-Bike meet up at <strong>Los Angeles, State Historic Park</strong></td>
    <td>April 5, 2021</td>
    <td>Leave empty</td>
  </tr>
</table>


from Recent Questions - Stack Overflow https://ift.tt/3sBM2X8
https://ift.tt/eA8V8J

How to get result back as JSON in looped query?

I am looping and getting results from multiple tables, and forming a result. How do I get the result back? All I am doing right now is logging it. Also, when I use array_append, it is converting the json into string.

This is the code I am running to get the data.

do
$$
    DECLARE
        sampleproductId   varchar;
        productIds        text[] := array [
            'abc1',
            'abc2'
            ];
        tId              varchar;
        DECLARE result  jsonb;
        DECLARE resultS jsonb[];
    begin
        FOREACH sampleproductId IN ARRAY productIds
            LOOP
                tId := (select id
                        from product.product
                        where uid = sampleproductId);
                result = (select row_to_json(row)
                           from (select accountid as "accountid", tId as "productUID", sampleproductId as "sampleproductId"
                                 from product.accountproductmap
                                 where productId = cast(tId as int)) row);
                if (result is not null) then
                    resultS = array_append(resultS, result);
                end if;
            END LOOP;
        RAISE NOTICE 'Result: %', resultS;
    end ;
$$;

And the result I am getting is

{"{\"accountid\": 8133, \"productUID\": \"1685\", \"sampleproductId\": \"abc1\"}","{\"accountid\": 9034, \"productUID\": \"2114\", \"sampleproductId\": \"abc2\"}"}

I am not sure why array_append is converting it into string before adding it, and not just keeping it as json.

I am looking to get it formatted like this

[
  { "accountid": 8133, "productUID": 1685, "sampleproductId": "abc1" },
  { "accountid": 9034, "productUID": 2114, "sampleproductId": "abc2" }
]


from Recent Questions - Stack Overflow https://ift.tt/2PH06Ag
https://ift.tt/eA8V8J

Thunk Fetch is Undefined When Called from React Component

I was playing around with a Thunk function called from a form submit, but had to stop because the fetch returns undefined inside the component and won't trigger .then(). I can't figure out why, I simplified the Thunk to its core, but still no luck. I have the same pattern with another form in the same app and it works smoothly. The backend answers correctly.

// actions/users.actions.js
export const login = (formData) => {
  return (dispatch) => {
    return fetch("http://localhost:3001/login", {
      method: "POST",
      headers: {"Content-Type": "application/json"},
      body: JSON.stringify(formData)
    }).then(res => res.json())
  }
}
// containers/LoginForm.js
import React, { Component } from 'react'
import { connect } from "react-redux";
import { Link } from 'react-router-dom'
import { login } from '../actions/users.actions'

class LoginForm extends Component {

    state = {
      username: '',
      password: ''
    }

    handleChange = (e) => {
      this.setState({
        ...this.state,
        [e.target.name]: e.target.value
      })
    }

    fetchOnSubmit = (e) => {
      e.preventDefault()
      this.props.login(this.state) 
//=> at this point it says TypeError: Cannot read property 'then' of undefined
        .then(res => this.props.errors ? null : this.props.history.push(`/`))
    }

    render() {
        return (
          <form onSubmit={this.fetchOnSubmit}>
            { this.props.alert.message &&
              <div className={`alert ${this.props.alert.type}`}>
                {this.props.alert.message.split('<b>').splice(0,1)}
                <b>{this.props.alert.message.split('<b>').splice(1,1)}</b>
              </div>
            }
            <h2 className='text-dark mb-4'>Login{'  '}
              {this.props.submitting && 
                <img alt="spinner" src="data:image/gif;...." />
              }
            </h2>
            <div>
              <fieldset className='ml-auto mr-auto w-100'>
                <label htmlFor="username" className="block">
                  Username*
                  <span className="text-red-400"></span>
                </label>
                <input
                  type="text"
                  name="username"
                  className='w-100 border border-primary shadow p-2 mb-4 rounded'
                  onChange={this.handleChange}>
                </input>
              </fieldset>
            </div>
            <div>
              <fieldset className='ml-auto mr-auto w-100'>
                <label htmlFor="password" className="block">
                  Password*
                  <span className="text-red-400"></span>
                </label>
                <input
                  type="password"
                  name="password"
                  className='w-100 border border-primary shadow p-2 mb-4 rounded-3 rounded'
                  onChange={this.handleChange}>
                </input>
              </fieldset>
            </div>
            <div class="row mb-5 ml-2 mr-2 mt-3">
                <div class="col-8 d-flex"><button className='h-1 border-0 rounded-pill ml-auto mr-auto' 
                  style= type='Submit'>Login</button></div>
                <div class="col-4 d-flex">
                  <Link to="/Signup" className='ml-auto mr-auto mt-auto mb-auto text-primary hardlink'>Register</Link>
                </div>
            </div>
          </form>
        )
    }
}

const mapStateToProps = state => {
  return {
    submitting: state.sessions.submitting,
    alert: state.alert,
    errors: state.sessions.errors
  }
}

const mapDispatchToProps = dispatch => {
  return {
    login: (credentials) => {
      dispatch(login(credentials))
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);

How can I avoid to get the error TypeError: Cannot read property 'then' of undefined. I even tried to return a Promise from the action creator, but it doesn't work.



from Recent Questions - Stack Overflow https://ift.tt/39pb0BJ
https://ift.tt/eA8V8J

Button color is not changed.Android Studio

Every time when I want to change color of button through xml, color is not changed and stays in default color. When I change color through java code, color changes but totally to another color which i don't want. Now I am changing colors of buttons by changing default color in themes.xml file.

I tried a lot of ways on Youtube , searched old answers on stackoverflow but could not solve the issue. How can I fix this problem in my Android Studio?



from Recent Questions - Stack Overflow https://ift.tt/3dfJzLL
https://ift.tt/eA8V8J

Uncaught ReferenceError: sapper is not defined, in main.js Svelte file

I have done the following:

  • installed
    • node.js
    • Svelte
    • Sapper
  • created
    • client.js
    • server.js

This is my main.js:

import App from './App.svelte';

const app = new App({
    target: document.body,
    props: {
        name: 'Acme Limited'
    }
});

export default app;

client.js:

import * as sapper from '@sapper/app';

sapper.start({
    target: document.querySelector('#sapper')
});

Top of App.svelte:

<script>
  import { writable } from 'svelte/store';
  import * as sapper from '@sapper/app';

My app was working until I added Sapper.

I tried adding this line to main.js:

import * as sapper from '@sapper/app';

The only code of mine that references is Sapper is in the index file:

<!-- src/routes/index.svelte -->
<svelte:head>
    <title>Welcome</title>
</svelte:head>

<h1>Hello, and welcome!</h1>

<nav>
    <a href=".">Home</a>
    <a href="about">About</a>
</nav>

Screenshot:

enter image description here

If you down vote me fine, but then at least leave a comment explaining/hinting what information is missing from my question. Otherwise I don't know what to add. "You don't know about what you don't know", as the old adage goes.



from Recent Questions - Stack Overflow https://ift.tt/3fqn35m
https://ift.tt/3fritUn

Save a Google Form as PDF on a Drive's folder using Google Scripts

This is my first approach using Google Scripts so apologize if the question is too easy.

All the steps are explained here: Hacking it: Generate PDFs from Google Forms. I took the following image from there:

What I have

The code is posted on the link but I post it here anyways:

function onSubmit(e) { // From https://medium.com/swlh/hacking-it-generate-pdfs-from-google-forms-3ca4fcc5a0aa
  const rg = e.range;
  const sh = rg.getSheet();
  
  //Get all the form submitted data
  //Note: This data is dependent on the headers. If headers, are changed update these as well.
  const cName = e.namedValues['Client Name'][0];
  const cEmail = e.namedValues['Client Email'][0];
  const cAddress = e.namedValues['Client Address'][0];
  const cMobile = e.namedValues['Client Mobile'][0];
  const sendCopy = e.namedValues['Send client a copy?'][0];
  const paymentType = e.namedValues['What is your agreed upon payment schedule?'][0];
  const fixedCost = e.namedValues['What was your agreed upon cost for the project?'][0];
  const hourlyRate = e.namedValues['Hourly Rate'][0];
  const manHours = e.namedValues['Total man hours'][0];
  const services = e.namedValues['Select the services'][0];
  
  //Consequential Data
  const tax = 18.5
  var subtotal = 0;
  var taxAmt = 0;
  var payableAmt = 0;
      
  //if the user has selected hourly payment model
  //Note: Be careful that the responses match the elements on the actual form
  switch (paymentType ){
    case 'Hourly Rate':
      subtotal = hourlyRate*manHours;
      taxAmt = subtotal * (tax/100);
      payableAmt = +subtotal + +taxAmt;
      break;
    case 'Fixed Cost':
      subtotal = fixedCost;
      taxAmt = fixedCost * (tax/100)
      payableAmt = +fixedCost + +taxAmt;
      break;            
  }
  
  const invoiceID = 'IN' + Math.random().toString().substr(2, 9);
  var formattedDate = Utilities.formatDate(new Date(), "IST", "dd-MMM-yyyy");
  
  //Set the consequential data in the columns of the spreadsheet for record keeping
  //Note: These variable are dependent on the sheet's columns so if that changes, please update.
  const row = rg.getRow();
  
  const payableAmtCol = 2; //B
  const invoiceIDCol = 3; //C
  
  sh.getRange(row,payableAmtCol).setValue(payableAmt);
  sh.getRange(row,invoiceIDCol).setValue(invoiceID); 
  
  
  //Build a new invoice from the file
  //Folder and file IDs
  const invoiceFolderID = '<invoice-folder-id>';
  const invoiceFolder = DriveApp.getFolderById(invoiceFolderID);
  
  const templateFileID = '<template-id>';
  const newFilename = 'Invoice_' + invoiceID;
  
  //Make a copy of the template file
  const newInvoiceFileID = DriveApp.getFileById(templateFileID).makeCopy(newFilename, invoiceFolder).getId();;
  
  //Get the invoice body into a variable
  var document = DocumentApp.openById(newInvoiceFileID);
  var body = document.getBody();
  
  //Replace all the  text in the invoice body
  body.replaceText('', invoiceID);
  body.replaceText('', formattedDate);
  body.replaceText('', cName);
  body.replaceText('', cAddress);
  body.replaceText('', cMobile);
  body.replaceText('', cEmail);
  body.replaceText('', services.split(', ').join('\n'));
  
  body.replaceText('', subtotal);
  body.replaceText('', taxAmt);
  body.replaceText('', payableAmt);
  
  //In the case of hourly rate payment type, let's add an additional message giving the rate and the man hours.
  if(paymentType.includes('Hourly Rate')){
     //It should look something like this on the invoice
     //Hourly Rate
     //Rate of Rs.1200/hour
     //Completed 50 man hours
     const message = paymentType + '\nRate of Rs.' + hourlyRate + '/hour\nCompleted ' + manHours + ' man hours';
     body.replaceText('', message);
  } else {
    body.replaceText('', paymentType);
  }
  
  document.saveAndClose();
  }
  
}

All the generated documents are saved in Invoices folder as .docx.

Is there any way to edit the above code to save them as PDF? Of course the PDF already had to be filled with the data provided in the Google Form, like the code does but they have to be saved as PDF, not .docx.



from Recent Questions - Stack Overflow https://ift.tt/3u3lO06
https://ift.tt/2PD9KUy

Google Sheets slicers don't work until I refresh the page on a large project

I have a very big project and have set up my project and slicers carefully following Google's documentation. I have 3 tabs with a chart on each tab and 4 slicers for each chart. The slicers will not respond to the slicers unless I refresh the page first. Is this normal behavior? I can only find two other posts related to this issue, and they are both unanswered. I can't share a dummy project because when I set up smaller projects the slicers work as expected.

I know this question is not very specific, but does anyone have a suggestion on what would be a good way to handle this or even where I might be able to look in order to fix it? How can I make the page refresh automatically when it is open, for example on an on_open trigger in Google Apps Script? I don't want to spend too much time scrutinizing everything to see what is wrong if there could be a general fix.

Thank you.



from Recent Questions - Stack Overflow https://ift.tt/3tXmnZo
https://ift.tt/eA8V8J

R web scraping function getPageNumber error

I am building a webscraper and trying to understand why my getPage Number Function does not work. The function worked last night and tonight I have been having an error getting the right output

library(rvest)
library(RCurl)
library(XML)
library(stringr)

    getPageNumber <- function(URL) {
      parsedDocument <- read_html(URL)
      results_per_page <- length(parsedDocument %>% html_nodes(".sr-list"))
      total_results <- parsedDocument %>%
        toString() %>%
        str_match(., 'num_results":"(.*?)"') %>% 
        .[,2] %>%
        as.integer()
      pageNumber <- tryCatch(ceiling(total_results / results_per_page), error = function(e) {1})
      return(pageNumber)
    }
    getPageNumber("https://academic.oup.com/dnaresearch/search-results?rg_IssuePublicationDate=01%2F01%2F2010%20TO%2012%2F31%2F2010&fl_SiteID=5275&page=")

The output I am getting is NA, when it should be numeric number



from Recent Questions - Stack Overflow https://ift.tt/3u2Csgo
https://ift.tt/eA8V8J

How to keep track of old versions of objects in .net core?

I was working on a project on ASP.NET Core where I had to keep track of edits to Contracts here is where I've come so far, Models -

  //Contract Model
  public class Contract
    {
        [Key]
        public int Id { get; set; }
        public string ContractId { get; set; }
    }




//Contrat History Model
   public class ContratEditHistory
    {
        [Key]
        public int Id { get; set; }
        [DisplayName("Edited By")]
        public string EditorId { get; set; }

        [ForeignKey("EditorId")]
        public virtual ApplicationUser User { get; set; }

        public int ContratId { get; set; }

        [ForeignKey("ContractId")]
        public virtual Contract Contrat { get; set; }

        [StringLength(2, MinimumLength = 255)]
        public string ChangeReason { get; set; }

        [Required]
        [DataType(DataType.Date)]
        public DateTime DateEdited { get; set; }

    }

This seems to work fine in logging who made changes to a contract but I want to "store" the previous version of the contract when the contract is updated so users will be able to look up what changes were made. How can I achieve that?



from Recent Questions - Stack Overflow https://ift.tt/2O5A6y3
https://ift.tt/eA8V8J

how can insert multiple record using

I'm working on a small project Django Rest Framework, I already create add contact function as you can see in my create function. now I'm working on bulk import, but when I submit my data as a list not as a dict I get an error message :

{"non_field_errors":["Invalid data. Expected a dictionary, but got list."]}

this is my code to add a contact,

class ContactView(ListModelMixin, viewsets.GenericViewSet):
    queryset = Contact.objects.all()
    serializer_class = ContactSerializer

    def create(self, request):
        serializeObject = ContactSerializer(data = request.data)
        if serializeObject.is_valid():
            serializeObject.save()
            contactObject = Contact.objects.all()
            contactSerializer = ContactSerializer(contactObject, many=True)
            return Response(contactSerializer.data, status = status.HTTP_201_CREATED)
        return Response(serializeObject.errors, status.HTTP_400_BAD_REQUEST)

Now i would like to create another function, for bulk create, since i have a list

This is my header data structure :

[{"Greeting":"amine","first_name":"alain","last_name":"amine","title":"ricardo","language":"ab@xyz.com","email":43822510594,"phone_1":43822510594,"phone_2":"not yet","mobile":43822510594,"fax":"not yet","internal_id":"xname"},{"Greeting":"bill","first_name":"microsoft","last_name":"bill","title":"microsoft","language":"bill@microsoft.com","email":652565455,"phone_1":652565455,"phone_2":"new york","mobile":652565455,"fax":"new york","internal_id":"microsoft"},{"Greeting":"john","first_name":"Yoyo","last_name":"Ruth","title":"xnameagain","language":"rh@xyz.com","email":5465559852,"phone_1":5465559852,"phone_2":"Vancouver","mobile":5465559852,"fax":"Vancouver","internal_id":"yname"}]

This is my serializer:

class ContactSerializer(serializers.ModelSerializer):
    class Meta:
        model = Contact
        fields = "__all__"


from Recent Questions - Stack Overflow https://ift.tt/3uiEWrh
https://ift.tt/eA8V8J

How to get the length of every column in a kdb database?

We've seen issues where a kdb database is corrupted and are looking for a way to implement a check that every kdb column is the same length in a particular table. Any recommendation on how to do this?

i.e., would like to get a return value of each column in a table and it's length.

These tables have upwards of 200 columns. Any way to go about this efficiently?

Any help is appreciated. Thank you.



from Recent Questions - Stack Overflow https://ift.tt/3rzT51t
https://ift.tt/eA8V8J

awk pattern matching one file to another then save the difference in new file

$ cat File1
781789
989778
898989

$ cat File2
AA^ABB^ACC^A781789^B781782^AEE^AFF^A781789^B781782AA^ABB^ACC^A7817891^B7817821^AEE^AFF^A7817891^B781782AA^ABB^ACC^A781789^B898989^AEE^AFF^A781789^B898989^B898923
  • Field Separator: "^A" or "\x01"
  • Record Separator: "^B" or "\x02"

I would like to create a resultant file "File3" where records from "File1" DOES NOT match any of the records for Column number 4 and 7 in "File2". If the record matches then DO NOT consider.

Expected output:

$ cat File3
AA^ABB^ACC^A7817891^B7817821^AEE^AFF^A7817891^B781782

Tried with the below awk code, where I am able to parse "File2" with field separators, but not able to match records from "File1" to "File2".

awk 'BEGIN { FS="\x01"} NR==FNR{A[$4]~/$0/;next}{print A[$0]} File1 File2 > File3'

awk 'BEGIN { FS="\x01"} NR==FNR{A[$7]~/$0/;next}{print A[$0]} File1 File2 > File3'

Requesting help.



from Recent Questions - Stack Overflow https://ift.tt/3dlsi3w
https://ift.tt/eA8V8J

How can I plot several series in groups in Julia?

I am trying to plot a large number of line series in Julia, and I want to use two colors to differentiate between two groups.

With the code below, which uses a small dataset, I get the following:

using Plots
toy = rand(10, 5)
color = rand(0:1, 5)
full = vcat(toy, color')

plot(full, label = color)

enter image description here

What I am trying to do is to have only two colours, corresponding to the value in "color" {0, 1}. How can I do that?

PS: I have seen a similar question for matplotlib: How do I plot multiple time series grouped by different colours?



from Recent Questions - Stack Overflow https://ift.tt/3w9SIxZ
https://ift.tt/3tXmnIS

How to transfer data from multiple websites to Excel with MSXML2.XMLHTTP

I am trying to transfer data from multiple Websites to Excel. It is meant that the homepage creates a query page after data input.

In main-site:

http://www.zvg-portal.de/index.php?button=Termine%20suchen

with MSXML2.XMLHTTP I choose for example "Berlin" in dropdown LAND, it changes to a query-site:

http://www.zvg-portal.de/index.php?button=Suchen

and there I try to access this content:

(HTML part:)

<td valign="top" align="left">Objekt/Lage</td>
<td colspan="2" valign="center" align="left">
<b>
Eigentumswohnung (3 bis 4 Zimmer)
<!--Lage--->
:
</b> 
Schützenstraße  41, 10117 Berlin, Mitte
</td>

with my code:

Sub GetDataInformation()
  Dim xml    As Object
  Dim html   As Object
  Dim elements As Object
Set xml = CreateObject("MSXML2.XMLHTTP")
Set html = CreateObject("htmlFile")
   With xml
      .Open "POST", "http://www.zvg-portal.de/index.php?button=Termine%20suchen", False
      .setRequestHeader "Content-type", "application/x-www-form-urlencoded"
      .send "updateAmtsgericht=be"  ' OR .send "land_abk=be"
      .Open "GET", "http://www.zvg-portal.de/index.php?button=Suchen", False
      .setRequestHeader "Content-type", "text/xml"
      .send
   End With
html.body.innerHTML = xml.responseText
Set elements = html.querySelectorAll("td")   ' OR ("b")
   For y = 0 To elements.Length - 1
      ActiveSheet.Cells(y + 2, 2) = elements.Item(y).innerText
   Next
End Sub

but I just get an ERROR: queryselectorall can't be used for this element: html.querySelectorAll("form_sucheZvg")

how can this problem be solved?



from Recent Questions - Stack Overflow https://ift.tt/3m4cRRs
https://ift.tt/eA8V8J

2021-03-29

MongoDB async save parallel desync

I'm using mongoose to save an communicate with my mongo database. The question I have is: what happens if I load a document from a database, make changes to it, then asynchronously load the same document in another instance and change it there too before the first change has been saved? For example i might have a user with email and a name. In this case the first operation would change the name and the second would change the email. Will the name not be changed in the end as a result of this occurence?

Will the first operation be saved to the database and then be erased by the second or how does it work? And if it turns out to be a problem how does one manage it? I know the chance of this occurence is very slime but it's not non-existent right?

What's the best practice here?



from Recent Questions - Stack Overflow https://ift.tt/3u1CNjh
https://ift.tt/eA8V8J

Combining PiHole stats from Prometheus in Grafana

I have two PiHole instances, and I am trying to display their stats in a single Grafana display. Prometheus is being used to store the PiHole data.

I have a Prometheus metric called "pihole_top_ads" that I can successfully call from Grafana, and display each domain and count returned in a bar graph format for each PiHole instance. I can combine two of them using the 'Mixed' option in Grafana, but this does not merge the two results, it only lists the first set then the second set. Duplicate domains are not combined, which is what I'm trying to achieve.

What I get:

Domain "A - as seen by PiHole 1"    count
Domain "B - as seen by PiHole 1"    count
Domain "C - as seen by PiHole 1"    count
Domain "D - as seen by PiHole 1"    count
Domain "B - as seen by PiHole 2"    count
Domain "D - as seen by PiHole 2"    count
Domain "E - as seen by PiHole 2"    count    
Domain "F - as seen by PiHole 2"    count    

What I want:

Domain "A - as seen by PiHole 1"    count
Domain "B - as seen by PiHole 1 and 2"    total count
Domain "C - as seen by PiHole 1"    count
Domain "D - as seen by PiHole 1 and 2"    total count
Domain "E - as seen by PiHole 2"    count
Domain "F - as seen by PiHole 2"    count 

This is an example of the return from the Prometheus function:

pihole_top_ads{domain="api.mixpanel.com", hostname="192.168.11.87", instance="localhost:9617", job="pihole"}
    3
pihole_top_ads{domain="brahe.apptimize.com", hostname="192.168.11.87", instance="localhost:9617", job="pihole"}
    1
pihole_top_ads{domain="fls-na.amazon.com", hostname="192.168.11.87", instance="localhost:9617", job="pihole"}
    1
pihole_top_ads{domain="g.live.com", hostname="192.168.11.87", instance="localhost:9617", job="pihole"}
    10
pihole_top_ads{domain="g.msn.com", hostname="192.168.11.87", instance="localhost:9617", job="pihole"}
    22
pihole_top_ads{domain="go.redirectingat.com", hostname="192.168.11.87", instance="localhost:9617", job="pihole"}
    1
pihole_top_ads{domain="graph.accountkit.com", hostname="192.168.11.87", instance="localhost:9617", job="pihole"}
    2
pihole_top_ads{domain="self.events.data.microsoft.com", hostname="192.168.11.87", instance="localhost:9617", job="pihole"}
    4
pihole_top_ads{domain="ssl.google-analytics.com", hostname="192.168.11.87", instance="localhost:9617", job="pihole"}
    1
pihole_top_ads{domain="trace.svc.ui.com", hostname="192.168.11.87", instance="localhost:9617", job="pihole"}
    4

I'm doing this in a bar graph Grafana panel, which looks like this: Grafana panel

Notice (self.events.data.microsoft.com) appears twice. I'd like entries like that to be merged, and all the entries sorted together.

Any assistance would be greatly appreciated.



from Recent Questions - Stack Overflow https://ift.tt/31rYzAx
https://ift.tt/eA8V8J

Discord Python Reaction Role

I want that my bot add the role "User" to a user who react with a heart. But it doesn't work.
My code:

@client.event
async def on_reaction_add(reaction, user):
    if reaction.emoji == "❤️":
        user = discord.utils.get(user.server.roles, name="User")
        await user.add_roles(user)

I hope you can help me :)



from Recent Questions - Stack Overflow https://ift.tt/31vc8zj
https://ift.tt/eA8V8J

Laravel streaming platform

I am currently working on a streaming platform especially music. The API with Laravel and the front with REACT.JS. My question is how I can set up a streaming server with Laravel or if someone has ever had to work on something similar he could help me with some leads. Thank you



from Recent Questions - Stack Overflow https://ift.tt/2O0aNgD
https://ift.tt/eA8V8J

GROUP BY and get the columns values into single row column

i was thinking if possible to get all the values of using GROUP BY room. example i have a tables named subject , room and classroom

table subject

   subject_id | subject_name
    -------------------
        1     | math
        2     | science
        3     | english

table room

    room_id | room_name
   -------------------
       1    | sunflower
       2    | cornflower
       3    | redflower

table classroom

    id | room_id | subject_id 
   -------------------
    1  | 1       | 1          
    2  | 1       | 2
    3  | 1       | 3

now the query. not sure if the query im used was correct or enough querying.. but the outputed query show expecting not that

SELECT * FROM classroom 
LEFT JOIN subject ON classroom.subject_id = subject.subject_id
LEFT JOIN room ON classroom.room_id = room.room_id 
GROUP BY room_name

now the output i want to expecting like this

classroom

room_name | subject_name 
------------------------
sunflower | math
          | science
          | english

it should grouping by sunflower into one row column



from Recent Questions - Stack Overflow https://ift.tt/3u2QaQp
https://ift.tt/eA8V8J