text:
Q: Plotly: Sunburst diagram is not rendering properly I am following the tutorial example for sunburst diagram in plotly on python3 from the official documentation.
Based on this example, I have built my DataFrame in a manner exactly similar to the example and verified the sanity of the data.
Now, here is the issue. If I add branchvalues='total' like shown in the following code, I get a blank white diagram. Which means, nothing gets rendered.
fig.add_trace(go.Sunburst(
    labels=df_all_trees['id'],
    parents=df_all_trees['parent'],
    values=df_all_trees['value'],
    branchvalues='total',
    marker=dict(
        colors=df_all_trees['color'],
        colorscale='RdBu'),
    hovertemplate='%{label}

 Allocated: %{value}',
    name=''
))

If I remove branchvalues='total', like in the following code,
fig.add_trace(go.Sunburst(
    labels=df_all_trees['id'],
    parents=df_all_trees['parent'],
    values=df_all_trees['value'],
    marker=dict(
        colors=df_all_trees['color'],
        colorscale='RdBu'),
    hovertemplate='%{label}

 Allocated: %{value}',
    name=''
))

I get a rather distorted diagram.

What am I doing wrong?
EDIT - ADDED DATA AND CODE
Data

Same data in csv
,id,parent,value,color
0,Tax Planning,Astral Poly,1.54,1.54
1,Tax Planning,Avenue Super.,8.46,8.46
2,Tax Planning,Bajaj Fin.,8.75,8.75
3,Tax Planning,Bandhan Bank,2.75,2.75
4,Tax Planning,Bharti Airtel,1.74,1.74
5,Tax Planning,Cummins India,1.5,1.5
6,Tax Planning,Divi's Lab.,2.16,2.16
7,Tax Planning,Endurance Tech.,0.86,0.86
8,Tax Planning,H D F C,4.9,4.9
9,Tax Planning,HDFC Bank,6.35,6.35
10,Tax Planning,ICICI Bank,2.32,2.32
11,Tax Planning,Info Edg.(India),5.08,5.08
12,Tax Planning,Kotak Mah. Bank,8.454707583,8.454707583
13,Tax Planning,MAS FINANC SER,0.74,0.74
14,Tax Planning,Maruti Suzuki,4.71,4.71
15,Tax Planning,Motherson Sumi,1.19,1.19
16,Tax Planning,Multi Comm. Exc.,1.29,1.29
17,Tax Planning,Nestle India,4.53,4.53
18,Tax Planning,Net CA & Others,1.1,1.1
19,Tax Planning,Pidilite Inds.,5.72,5.72
20,Tax Planning,Shree Cement,1.17,1.17
21,Tax Planning,Sundaram Fin.Hol,0.04,0.04
22,Tax Planning,Sundaram Finance,1.58,1.58
23,Tax Planning,Symphony,1.76,1.76
24,Tax Planning,TCS,6.17,6.17
25,Tax Planning,TTK Healthcare,0.07,0.07
26,Tax Planning,TTK Prestige,2.07,2.07
27,Tax Planning,Tata Global,0.52,0.52
28,Tax Planning,Tech Mahindra,1.39,1.39
29,Tax Planning,Torrent Power,3.61,3.61
30,Tax Planning,V-Guard Inds.,0.55,0.55
31,Tax Planning,WABCO India,1.74,1.74
32,Astral Poly,Plastics Products,1.54,1.54
33,Avenue Super.,Trading,8.46,8.46
34,Bajaj Fin.,Finance & Investments,8.75,8.75
35,Bandhan Bank,Banks - Private Sector,2.75,2.75
36,Bharti Airtel,Telecommunications - Service Provider,1.74,1.74
37,Cummins India,Engines,1.5,1.5
38,Divi's Lab.,Pharmaceuticals - Indian - Bulk Drugs,2.16,2.16
39,Endurance Tech.,Auto Ancillaries,0.86,0.86
40,H D F C,Finance - Housing,4.9,4.9
41,HDFC Bank,Banks - Private Sector,6.35,6.35
42,ICICI Bank,Banks - Private Sector,2.32,2.32
43,Info Edg.(India),Miscellaneous,5.08,5.08
44,Kotak Mah. Bank,Banks - Private Sector,8.454707583,8.454707583
45,MAS FINANC SER,Finance & Investments,0.74,0.74
46,Maruti Suzuki,Automobiles - Passenger Cars,4.71,4.71
47,Motherson Sumi,Auto Ancillaries,1.19,1.19
48,Multi Comm. Exc.,Miscellaneous,1.29,1.29
49,Nestle India,Food - Processing - MNC,4.53,4.53
50,Net CA & Others,Net CA & Others,1.1,1.1
51,Pidilite Inds.,Chemicals,5.72,5.72
52,Shree Cement,Cement - North India,1.17,1.17
53,Sundaram Fin.Hol,Finance & Investments,0.04,0.04
54,Sundaram Finance,Finance & Investments,1.58,1.58
55,Symphony,Domestic Appliances,1.76,1.76
56,TCS,Computers - Software - Large,6.17,6.17
57,TTK Healthcare,Pharmaceuticals - Indian - Bulk Drugs & Formln,0.07,0.07
58,TTK Prestige,Domestic Appliances,2.07,2.07
59,Tata Global,Tea,0.52,0.52
60,Tech Mahindra,Computers - Software - Large,1.39,1.39
61,Torrent Power,Power Generation And Supply,3.61,3.61
62,V-Guard Inds.,Electric Equipment,0.55,0.55
63,WABCO India,Auto Ancillaries,1.74,1.74
64,Auto Ancillaries,Equity,3.7899999999999996,3.7899999999999996
65,Automobiles - Passenger Cars,Equity,4.71,4.71
66,Banks - Private Sector,Equity,19.874707583,19.874707583
67,Cement - North India,Equity,1.17,1.17
68,Chemicals,Equity,5.72,5.72
69,Computers - Software - Large,Equity,7.56,7.56
70,Domestic Appliances,Equity,3.83,3.83
71,Electric Equipment,Equity,0.55,0.55
72,Engines,Equity,1.5,1.5
73,Finance & Investments,Equity,11.11,11.11
74,Finance - Housing,Equity,4.9,4.9
75,Food - Processing - MNC,Equity,4.53,4.53
76,Miscellaneous,Equity,6.37,6.37
77,Net CA & Others,Net CA & Others,1.1,1.1
78,Pharmaceuticals - Indian - Bulk Drugs,Equity,2.16,2.16
79,Pharmaceuticals - Indian - Bulk Drugs & Formln,Equity,0.07,0.07
80,Plastics Products,Equity,1.54,1.54
81,Power Generation And Supply,Equity,3.61,3.61
82,Tea,Equity,0.52,0.52
83,Telecommunications - Service Provider,Equity,1.74,1.74
84,Trading,Equity,8.46,8.46
85,Equity,total,93.71470758299998,93.71470758299998
86,Net CA & Others,total,1.1,1.1
87,total,,94.814707583,94.814707583
The above data / csv needs to be imported in a dataframe knows as alloc
Code
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd

df = alloc

average_score = df['PERC_HOLD'].sum()

fig = go.Figure()

fig.add_trace(go.Sunburst(
    labels=df_all_trees['id'],
    parents=df_all_trees['parent'],
    values=df_all_trees['value'],
    branchvalues='total',
    marker=dict(
        colors=df_all_trees['color'],
        colorscale='RdBu',
        cmid=average_score),
    hovertemplate='%{label}
 Sales: %{value}
 Success rate: %{color:.2f}',
    name=''
    ))

fig.update_layout(margin=dict(t=10, b=10, r=10, l=10))
fig.write_html("fig2.html")

A: In this particular case it's nearly impossible to offer a complete solution without a proper data sample. The first thing I would test though would be to set
branchvalues="remainder"


text:
Q: How do I search my database and return results for a partial word? I'm doing a search query, and would like to find any rows that match a post code. In a table there is a full list of postcodes, the first half of these codes could be 'WF12', or 'DN7', etc..
I want to input a full postcode (e.g. 'dn11pq'), and retrieve rows that start with 'dn1'. I'm familiar with LIKE and wildcards, tried FULL TEXT, also LOCATE but to no avail.
 SELECT * FROM postcodeData WHERE MATCH(postcode) AGAINST ('dn11pq' IN BOOLEAN MODE) LIMIT 50

Any help would be greatly appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do duplicate registrations have bad consequences? Registering the same device with the same tags and template results in multiple identical registrations in the hub.
Will this cause a problem and will Azure eventually remove them?
It doesn't seem to result in duplicate messages sent to a device.

A: I figure I can limit duplicate registrations by checking to see if they exist first using GetRegistrationsByTagAsync.
Even that method only takes one tag, so it's then typically necessary to iterate over all the tags for each registration to complete a match. Plus, the device token needs to be added as a tag because the registration base class doesn't have a "token" property. (EDIT: Actually, that doesn't work because it says the token is an invalid tag. So I'm going for one installation per platform - perhaps I could switch on the installation's class type to get the token value.)
Honestly, this API seems somewhat half baked. Even the newer installation based part of the API doesn't even let you download all the installations so you have to have some way of keeping track of them if you want to update them. If you have to keep a copy of this data then you may as well skip Azure altogether.
You can get the installations from the Azure tab in Visual Studio but once deleted, it doesn't seem possible to reinstall a device.
What a mess.


text:
Q: Change server mail from postfix to sendmail virtualmin Hi I have already install an ubuntu server with postfix and sendmail mail servers.Although postfix runs perfectly when I go to Virtualmin panel>Virtual Configuration>And choose sendmail mail server to configure >save and rebuild configuration file I get this :
The Read User Mail module is not setup to use the Sendmail mail server. Either adjust its module configuration to match, or change the Virtualmin configuration.
I do not know what to do.Any suggestion?

A: At first Virtualmin runs perfectly with Postfix. So long you did not setup an external mail server, it is better to keep Postfix with all the other mail services SpamAssasin, Procmail and ClamAV.
To jump over the Read User Mail issue, you have to deactivate it following:
Virtualmin -> System Settings -> Server Template -> Default Template -> Administrators Webmin module and there you can deactivate this feature.
This is only appending for new mail users.
Now Sendmail jumps over this step, but probably you are facing new ones ;-).
Virtualmin is thought to run on every server the mail service. This is very well done together with Postfix. So long you don't have a good reason to change that, I recommend not to switch to Sendmail.
Good luck ;-)
Urs
Ps.
More about Read User Mail and already running mail users:
Solution to deactivate existing mail users


text:
Q: Specifying the rule address in Snort alert file I am working on a project, which deals with changing the order of the rules, to make the IDS process faster and more efficient.
I just have to find where the rule generating any alert in snort alert file, is located. (I mean the rule is located on which line, in which rule file?)
Can anyone help me find out?

A: To locate rules within the configuration file:
you can use signature ID of snort rules.
For example,
[**] [1:5000361:0] need-to-know - suspicious spammed domain [**]

here the signature ID is 5000361.
or, you can search in the configuration file for the referenece shown in the alert
[Xref => url www.spamhaus.org/query/dbl?domain=xxxxxxx.com]

In the above line, the reference is www.spamhaus.org/query/dbl?domain=xxxxxxx.com
Snort configuration file is specified using the -c option followed by the name of the configuration file, usually named as snort.conf. Since it is specified using the option, it could be located anywhere on the system. Usually it can be found at /usr/local/etc/snort.conf or in the directory where snort is installed.

A: This question doesn't really make any sense. "I am working on a project, which deals with changing the order of the rules, to make the IDS process faster and more efficient."
This implies that if you change the order that the snort rules are in in a file then it will change the order in which they are evaluated, and that is completely wrong. The way snort works in terms of rule evaluation is much more complicated and to be more efficient you must make your rules more efficient. For snort the most important part of a rule is the fast_pattern keyword. Even if you do not specify a fast_pattern in a rule snort will automatically choose the longest content match in the rule that is at least 3 characters and use this as the fast_pattern. For every packet that comes in snort will build a rule evaluation tree for that packet and the order of these rules is completely unrelated to the order that they are stored in the config files. Snort will just read all rules in the configs and the order they are evaluated is determined when it receives the packet at during run time.


text:
Q: PowerShell: Parse Specific Item from Output Formatted as List I need to programmatically determine if a specific certificate is involved, which is trivial. However, I'd like the output to only contain the subject line of said certificate.
Using the following, I can get a list of installed certificates:

Get-ChildItem -Recurse Cert:

========================================================================

Subject      : CN=VeriSign Class 3 Public Primary Certification Authority - G5
Issuer       : CN=VeriSign Class 3 Public Primary Certification Authority - G5
Thumbprint   : 4EB6D578499B1CCF5F581EAD56BE3D9B6744A5E5
FriendlyName : VeriSign
NotBefore    : 11/7/2006 6:00:00 PM
NotAfter     : 7/16/2036 6:59:59 PM
Extensions   : {System.Security.Cryptography.Oid, System.Security.Cryptography.Oid}

Subject      : CN=Go Daddy Root Certificate Authority - G2, O="GoDaddy.com, Inc.", L=Scottsdale, S=Arizona, C=US
Issuer       : CN=Go Daddy Root Certificate Authority - G2, O="GoDaddy.com, Inc.", L=Scottsdale, S=Arizona, C=US
Thumbprint   : 47BEABC922EAE80E78783462A79F45C254FDE68B
FriendlyName : Go Daddy Root Certificate Authority – G2
NotBefore    : 8/31/2009 7:00:00 PM
NotAfter     : 12/31/2037 5:59:59 PM
Extensions   : {System.Security.Cryptography.Oid, System.Security.Cryptography.Oid, System.Security.Cryptography.Oid}

Subject      : CN=StartCom Certification Authority, OU=Secure Digital     Certificate Signing, O=StartCom Ltd., C=IL
Issuer       : CN=StartCom Certification Authority, OU=Secure Digital    Certificate Signing, O=StartCom Ltd., C=IL
Thumbprint   : 3E2BF7F2031B96F38CE6C4D8A85D3E2D58476A0F
FriendlyName : StartCom Certification Authority
NotBefore    : 9/17/2006 2:46:36 PM
NotAfter     : 9/17/2036 2:46:36 PM
Extensions   : {System.Security.Cryptography.Oid, System.Security.Cryptography.Oid.}

Using this one I can find only the sections with a specific string:

Get-ChildItem -Recurse Cert: | select-string "CN=Go Daddy Root Certificate Authority"

========================================================================

Subject      : CN=Go Daddy Root Certificate Authority - G2, O="GoDaddy.com, Inc.", L=Scottsdale, S=Arizona, C=US
Issuer       : CN=Go Daddy Root Certificate Authority - G2, O="GoDaddy.com, Inc.", L=Scottsdale, S=Arizona, C=US
Thumbprint   : 47BEABC922EAE80E78783462A79F45C254FDE68B
FriendlyName : Go Daddy Root Certificate Authority – G2
NotBefore    : 8/31/2009 7:00:00 PM
NotAfter     : 12/31/2037 5:59:59 PM
Extensions   : {System.Security.Cryptography.Oid, System.Security.Cryptography.Oid, System.Security.Cryptography.Oid}

However, I'd like to get only the "Subject" line so that my output is a single line. Ideally, the output looks like
CN=Go Daddy Root Certificate Authority - G2, O="GoDaddy.com, Inc.", L=Scottsdale, S=Arizona, C=US

but as long as the single-line output contains only the certificate in question the result is fine.

A: You could do something like:
Get-ChildItem -Recurse Cert: | Where-Object { $_.Subject -like 'CN=Go Daddy Root Certificate Authority*' } | Select Subject

Using Select-String makes you lose the objects that you are interested in, and then you are left to dealing with strings.
Note that you can find the particular certificate you are looking for by using a different property in the like comparison, such as FriendlyName. Example:
Get-ChildItem -Recurse Cert: | Where-Object { $_.FriendlyName -like 'Go Daddy Root Certificate Authority*' } | Select Subject


text:
Q: How to get the elapsed time in milliseconds in a bash script? I tried using t1=$(date +%s%N) to get the time in nanoseconds, but I kept in getting this error:
./script.sh: line 10: 1292460931N: value too great for base (error token is "1292460931N")

I looked up online and it seems that you can use the "time" command, however I can't find a good example of using the time command. Any help would be appreciated :)

A: The date command you're using doesn't support %N so your output is literally 1292460931N.  I tried it on Linux and it worked, but on FreeBSD I see the results you got.  Run that date command in a shell and see what comes out.  Is it possible you're using busybox?  Its cut-down date command also omits %N but the version I just tried gave me 1292463535%N.

A: Okay, a couple of things here.
First, not a lot of systems can give you a time that actually accurate to nanoseconds anyway.
Now, using time, either as /usr/bin/time or the shell builtin (bash: help time) is very easy.  If the command you want to time is foo1, then
$ time foo

will return the elapsed time as three lines on stderr
real 0m0.001s
user 0m0.000s
sys  0m0.000s

which you can use any way you like.
If you want to get a better, more accurate timing, execute the command many times.  This can be as simple as writing a short loop
time for i in 0 1 2 3 4; do foo; done

will do foo five times and give you the total time.  You probably want to do more than 5 iterations, so you'd probably want a counter and a while loop or the like.


text:
Q: Can't run GAE Shiro demo source code out of the box Downloaded and unzipped the GAE Shiro demo from https://github.com/cilogi/gaeshiro but couldn't get it to work.
Running mvn appengine:devserver causes errors because of :
[WARNING] Error injecting: com.google.appengine.devappserver.DevAppServerRunner
java.lang.NoClassDefFoundError: Lorg/sonatype/aether/RepositorySystem;
        at java.lang.Class.getDeclaredFields0(Native Method)
        at java.lang.Class.privateGetDeclaredFields(Class.java:2397)
        at java.lang.Class.getDeclaredFields(Class.java:1806)
        at com.google.inject.spi.InjectionPoint.getInjectionPoints(InjectionPoint.java:661)
        at com.google.inject.spi.InjectionPoint.forInstanceMethodsAndFields(InjectionPoint.java:366)

This is right out of the box, with no modifications. Ideas?
Details:

*

*Mac OS X 10.9

*Java 1.7.0_45

*Maven 3.1.1


text:
Q: Initialize an object from multiple input file data I have 2 fixed-length flat files F1 and F2 containing data (id, A, B) and (id, C, D) respectively.
I am trying to instantiate an object Foo f = new Foo (id, A, B, C, D).
How can I achieve this feat with spring batch. I don't have access to any DB so I can't insert Foo(id, A, B) into a staging table and then update the missing values.
Thank you so much :)

A: Thank you Mahmoud Ben Hassine, using an awk script solved my issue, here's my script
awk 'NR==FNR
{dossier[$3] = $0;next}
 {
    printf("<client>\n");
    printf "<rev>%s</rev>\n<pdd>%s</pdd>\n",$0,dossier[$9];
    print("</client>")
  }' pdddos.txt revass.txt > output.txt
sed -i '1s/^/<clients>\n/' output.txt
sed -i -e '$a</clients>' output.txt


text:
Q: How do i stop my tcp echo server to work the right way? // A simple echo server
// ./server port_no

#include<stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<error.h>
#include<strings.h>
#include<unistd.h>
#include<arpa/inet.h>

#define ERROR -1
#define MAX_CLIENTS 2
#define MAX_DATA 1024

main(int argc, char **argv)
{
  struct sockaddr_in server;
  struct sockaddr_in client;
  int sock;
  int new;
  int sockaddr_len = sizeof(struct sockaddr_in);
  int data_len;
  char data[MAX_DATA];

  if((sock = socket(AF_INET , SOCK_STREAM, 0)) == ERROR)
  {
       perror("server socket: ");
       exit(-1);
  }

  server.sin_family = AF_INET;
  server.sin_port = htons(atoi(argv[1]));
  server.sin_addr.s_addr = INADDR_ANY;
  bzero(&server.sin_zero,8);

  if((bind(sock , (struct sockaddr *)&server, sockaddr_len)) == ERROR)
  {
          perror("bind : ");
          exit(-1);
  }

  if((listen(sock, MAX_CLIENTS)) == ERROR)
  {
         perror("listen");
         exit(-1);
  }

  while(1) //Better signal handling required
  {
      if((new == accept(sock, ( struct sockaddr *)&client , &sockaddr_len)) == ERROR)
      {
         perror("accept");
         exit(-1);
      }

 printf("New Client connected from port no %d and IP %s\n",ntohs(client.sin_port),inet_ntoa(client.sin_addr));
 data_len = 1;

 while(data_len)
    {
       data_len = recv(new,data , MAX_DATA, 0);

             if(data_len)
               {
                    send(new, data, data_len, 0);
                    data[data_len] = '\0' ; // null the last byte to detect string
                    printf("Sent mesg: %s", data);
               }
    }

 printf("Client disconnected\n");

 close(new);
}

close(sock);

}

HI i have been learning socket programming in C . And recently i had written a code for tcp echo server. Server does shows connected when i use netstat command but as soon as i run the code using telnet it starts printing infinite messages instead of waiting for me to write a message in other terminal. Please help me figure out where i am i going wrong.

A: The reason for the infinite loop is the code
f((new == accept(sock, ( struct sockaddr *)&client , &sockaddr_len)) == ERROR)

It should instead be
f((new = accept(sock, ( struct sockaddr *)&client , &sockaddr_len)) == ERROR)

It's == vs =.  With ==, the socket returned by accept() is never assigned to new, so calling recv() on it returns -1 (error in this case), and because the code doesn't check for the error, as pointed out Alan Au, the result is an infinite loop.
BTW, if you watch the compiler warnings or enable more warnings by using a switch, e.g. -Wall with gcc, you can usually get some good insight into possible issues with the code.


text:
Q: How to override css of other components from App I need to make fonts for some of my components bigger when my app is in full screen mode. In my App.jsx I have variable that triggers me adding "fullscreen" class to the root DIV of the whole app. I can go brute force and override it like * { font-szie: 18px; } but thats too simple. I want to override certain classes only (like .some-class * { font-size: 18px; }). Of course React hash stands in my way so here is question: how do I apply my font size to all components in the app?

A: If you have hashed classes (i.e some-class-[hash]), you can use CSS selector to deal with it.
Like this:
[class^="some-class-"]

The above CSS selector will select all classes which start with "some-class-".
You can read more about CSS selectors here: https://www.w3schools.com/cssref/css_selectors.asp

A: You can use General Classes like Bootstrap or Tailwind, then you should use it in your public folder and use linkcss`
<head>
    <link rel="stylesheet" href="..." />
</ head>

.text-sm {
    font-size: 1rem !important;
}

import hashed_classes from "./file.css";

const Component = () => {
    return (
        <div className={`${hashed_classes.class} text-sm`} />
    )
}


text:
Q: Undefined Reference to class function issue I've scoured the internet and my own intellect to answer this basic question, however, much to my own dismay I've been unable to find a solution. I'm normally pretty good about multiple header files however I have hit a wall. The problem is a function that I've declared in a header and defined in its proper namespace in the source file. I'm developing on windows using Bloodshed.
///////////////////////////////
    //  class Matrix4x3.h
    ///////////////////////////////
#ifndef _MATRIX4X3_H
#define _MATRIX4X3_H

class Matrix4x3{
    public:

        //set to identity
        void identity();

};

#endif

///////////////////////////////
//  class Matrix4x3.cpp
///////////////////////////////
#include <assert.h>
#include <math.h>
#include "Matrix4x3.h"
.
.
.
void Matrix4x3::identity(){
    //calculations here...
}

////////////// Main ////////////////
#include <cstdlib>
#include <iostream>

#include "../Matrix4x3.h"

using namespace std;

int main(int argc, char *argv[])
{
    Matrix4x3 a;

    a.identity();

    cin.get();
    return EXIT_SUCCESS;
}

I use Bloodshed, and it displays a list of class members and methods when I use the constructed object, however it tells me that the method dipicted above hasn't been referenced come time to compile. If anyone has a response I would be very appreciative.

A: If you compile using the IDE, look for some button like "add file to project" or something like this, to add the Matrix4x3.cpp file to your project, so that when you build it, the IDE will put the translated result to the linker and all functions are resolved.
Currently, it looks like you don't tell the IDE about that cpp file, and so that function definition is never considered.

A: I think litb has it right.

On a totally unrelated note, you might want to look into templates so you can have this class:
template <size_t Rows, size_t Columns>
class Matrix
{
    ...
};

typedef Matrix<4, 3> Matrix4x3;

Instead of a new class for each matrix size. You might also throw the type into the mix:
template <size_t Rows, size_t Columns, typename T>
class Matrix
{
    ...
};

typedef Matrix<4, 3, float> Matrix4x3f;
typedef Matrix<4, 3, double> Matrix4x3d;

Or look into boost.


text:
Q: Error during subtraction of a variable in bytes in C# Subtraction of a variable in bytes in C# is pretty simple, but not worked for me in the loop. My code:
public static byte[] GetRandomArray(int size)
  {
     Random rnd = new Random();
     byte[] b = new byte[size];
     rnd.NextBytes(b);
     return b;
  }

private void button1_Click(object sender, EventArgs e)
{
byte[] a2 = GetRandomArray(8);
byte[] b2 = a2;
for (int x = 0; x < 8; x++)
    {
      a2[x]=(byte)(a2[x] - 1);
      MessageBox.Show(a2[x].ToString() + "  |  " + b2[x].ToString());
    }
}

Finally a2[x] is equal to b2[x]. No anything changes. What's the problem?

A: The subtraction is working, but is is changing b2[x] as wel.
I have used this code
using System;
public class Program
{
    public static void Main()
    {
        byte[] a2 = GetRandomArray(8);
        byte[] b2 = a2;
        Console.WriteLine(string.Join(",",a2));
        Console.WriteLine(string.Join(",",b2));
        for (int x = 0; x < 8; x++)
        {
            a2[x]=(byte)(a2[x] - 1);
        }
        Console.WriteLine(string.Join(",",a2));
        Console.WriteLine(string.Join(",",b2));
    }
    public static byte[] GetRandomArray(int size)
    {
        Random rnd = new Random();
        byte[] b = new byte[size];
        rnd.NextBytes(b);
        return b;
    }
}

This gives me a output of:
27,65,24,105,94,143,119,226
27,65,24,105,94,143,119,226
26,64,23,104,93,142,118,225
26,64,23,104,93,142,118,225

This is bequase array is a reference type by assigning b2 you make a reference to a2 not a copy

A: Thanks to all. I forget pointer.
   private void button22_Click(object sender, EventArgs e)
    {
        byte[] a2 = GetRandomArray(8);
        byte[] b2 = new byte[8];
        for (int x = 0; x < 8; x++)
        {
            b2[x] = a2[x];
            a2[x]=(byte)(a2[x] - 1);
            MessageBox.Show(a2[x].ToString() + "  |  " + b2[x].ToString());
        }

    }


text:
Q: Reading constants values from python file and using it in a shell PatchConstants.py:
class PatchConstants:

 PATCHHOME='/scratch/app/product/fmw/obpinstall/patching'
 FMWHOME='/scratch/app/product/fmw'
 DOMAINPATH=FMWHOME+'/user_projects/domains/'
 def __init__(self):
    pass

b.sh:
from PatchConstants import PatchConstants
path = PatchConstants.PATCHHOME

I want to extract python constant variable in a shell scripts.
Is it possible?

A: You can try the -c option of python to run python commands and deliver the result to the shell variable.
Just like:
path = $(python -c "from PatchConstants import PatchConstant ; print PatchConstants.PATCHHOME")


text:
Q: Unable to add data into database with foreign key constraints In reference to my earlier question at
Unable to add foreign keys to mysql database
I wanted to know, what is the best way to insert new data into the section, takes and teaches tables since the foreign key constraints are already present? I don't want to drop the table and rebuild the schema as there is too much data that needs to be re-entered.
Any suggestions?

A: You can insert the value in to table like
insert into table_name values("a", "b", "c");

This is the common syntax of insert statement. Coming to your tables
While inserting into other tables also make sure that you are not violating the primary and foreign key constraints.
Eg:
Student:
ID    name    Dept_name    tot_credit
1     abc     EE            3
2     def     CS            3

Department:

Deptname    building    budget
EE           1            200
CS           2            299
IS           3            900

course:
courseid    title    dept_name    credits
44       Algorithms   CS           3
899       OS          CS           3

Now if you are trying to insert into section it should go like this:
insert into section values(44, 199, 5, 2000, 500, 50, "Whatever format");

Since this is referring only to the course table
Ok try this:
insert into teaches values(instructor_id(existing in instructor table), course_id(match section table), secid(from section table), semester(from section table), year(from section table));

Good luck.


text:
Q: Transferring data through tcp sockets using nodejs I have a simple node application that sends data through tcp sockets. Essentially it's two node applications a sender and a receiver, or a client and server. I can open two terminal shells on my localhost and see data transferring though tcp sockets, so I know it works. I want to send data from my localhost to my server with these applications but I can't figure it out.. wether its the ip address routing or if I have to open tcp ports or disable firewalls, not sure. here's what the server and client apps look like when I can successfully send data on my localhost. I want to use this client app on my localhost and host the server app on my centos server and transfer data, is this possible?
  /*** TCP Client ***/
    /* Dependencies */
    var fs = require('fs');
    var hl7 = require('simple-hl7');
    /* Build TCP Server */
    var server = hl7.Server;
    var tcpClient = server.createTcpClient();
    /* Connection */
    tcpClient.connect('127.0.0.1', 6969);
    /* Get XML  */
    var msg = fs.readFileSync('./data/example.xml').toString();
    /* Send Message */
    setTimeout(function() {
        tcpClient.send(msg, function(ack) {
          console.log("ACK: ",ack.toString());
          console.log("\nsuccessful transfer");
          tcpClient.close();
        });
    }, 500);

the server can be found here. click here
but heres the config code..
/*
    Config class
    vars:
    baseFolder: Where to save the messages
    port      : What port to listen on
    ip        : what ip to listen on
*/
var Config = new function() {
    this.baseFolder = "data";
    this.port = 6969;
    this.ip = '127.0.0.1';
}

A: Ofcouce it is possible. Set server's IP and listening port in client. Then since client gonna connect to server, you will have to open this port on the server in both directions. And then just connect.
Basically here tcpClient.connect('127.0.0.1', 6969); Instead of 127... should be server's real external IP address.


text:
Q: Parse.com - substring search in tokenised array field I'm trying to implement complex full text search feature on multiple Parse classes at once (query1 on class1 OR query2 on class2, etc.). As per Parse's recommendation it's better to tokenise the strings and after filtering store it in an Array where one can take advantage of whereKey:containsAllObjectsInArray:.
My issue is that:

*

*it searches for ALL terms instead of ANY

*it doesn't search for substrings (e.g. Parse Array: ["David", "Peter", "Vivien"], searching for vi returns 0 objects)

As of now it seems that the only "decent" way is to concatenate all strings within the class into one big string and use whereKey:containsString:. I'm assuming this will be less efficient than the tokenised method.
Do you guys have any recommendation or suggestions how to develop both - efficient and scalable search over multiple Parse classes?
Thanks!

A: Full text search is a complex issue, many databases have special support for it that you can turn on after considering the costs... Parse doesn't support full text search.
In regards to doing what you want with parse, whereKey:equalTo: will work on an array finding where one of the items match the string supplied.
If you want to match on ANY you can use an OR query:
PFQuery *term1Query = [[PFQuery queryWithClassName:@"Class"] whereKey:@"terms" equalTo:@"David"];
PFQuery *term2Query = [[PFQuery queryWithClassName:@"Class"] whereKey:@"terms" equalTo:@"Peter"];

PFQuery *query = [PFQuery orQueryWithSubqueries:@[term1Query, term2Query]];

If you want to be able to match on partial strings, you'll need to change your schema a bit. Create a new Class called "SearchToken" or something, with a "token" column of type string.
Make sure this is always forced to lowercase when creating/updating this. You can then share tokens between related classes (e.g. don't create two "david" tokens, simply link to the existing one on new classes). Force your input to lowercase also, since all string matching is case-sensitive.
Your "terms" column would need to now contain pointers instead of just words.
You can now do a query against your "SearchToken" class and use a whereKey:matchesQuery: criteria on your parent class, e.g.:
PFQuery *tokenQuery = [PFQuery queryWithClassName:@"SearchToken"];
[tokenQuery whereKey:@"token" containsString:@"vi"];

PFQuery *mainQuery = [PFQuery queryWithClassName:@"MyClass"];
[mainQuery whereKey:@"terms" matchesQuery:tokenQuery];

You can even use an or query like above with a mixture of full matches and partial matches.
Be aware that the token query might match many rows, and is limited by the 100 row default, consider setting the limit higher if you think you'll need to, the max is 1000.
In regards to creating SearchToken rows, assuming you've already gathered tokens from a string and forced them to lowercase and now have tokens to link/create:
// these would be generated, manually creating for demonstration
NSArray *tokens = @[@"david", @"and", @"the", @"lion"];

PFQuery *existingTokens [PFQuery queryWithClassName:@"SearchToken"];
[existingTokens whereKey:@"token" containedIn:tokens];

// results of the above already exist, create new rows for the remainder

There is the issue of a possible race-condition where another device might create a "david" token after the query is run. You could have a job that looks for duplicates and removes duplicate rows, fixing all pointers as it goes... though even there you want to handle race conditions so the logic might be to tag the duplicates and have all other queries search [query whereKeyDoesNotExist: @"duplicateOf"]; then find all records that point to rows that do point to a duplicate and point them to the duplicateOf. All depends how important it is to you to avoid duplicates, perhaps it is a non-issue for you.

A: I've successfully implemented the search feature with few small modifications. Convincing Parse to perform full text search is quite expensive (saving: 2 API calls: fetch existing tokens + save new tokens, searching: 1 + (1 * N): fetching tokens matching search terms + N == no of searchable objects). I wonder if there's better way of achieving the same result, anybody has any suggestions on how to improve the cost?
While saving is quite the same as Timothy described, retrieving is as follows:
// 1)   check for sanitised terms in SearchToken class
//      _marrInputTokens - mutable array of sanitised search terms
NSMutableArray *_marrInnerQueries = [[NSMutableArray alloc] init];
for(NSString *_token in _marrInputTokens)
{
    PFQuery *_innerQuery = [PFQuery queryWithClassName:@"SearchToken"];
    [_innerQuery whereKey:@"token" containsString:_token];
    [_marrInnerQueries addObject:_innerQuery];
}

PFQuery *_pSearchTokenQuery = [PFQuery orQueryWithSubqueries:_marrInnerQueries];
[_pSearchTokenQuery setLimit:1000];
[_pSearchTokenQuery findObjectsInBackgroundWithBlock:^(NSArray *tokenObjects, NSError *error) {
    if(error)
    {
        QLog([error localizedDescription]);
    }
    else
    {
        // 2)   if not all search terms (even as substrings) were found in SearchToken, no need to search further
        //      as no object can meet the search criteria and we can save some calls
        if([tokenObjects count] >= [_marrInputTokens count])
        {

            // 3) all search terms were found in SearchToken
            // fetch all SearchableObject_1 corresponding objects
            PFQuery *_pResultQuery = [PFQuery queryWithClassName:@"SearchableObject_1"];

            // 4) need to make sure all tokens are conjugated with AND operator
            for(PFObject *_tokenObject in _marrSearchTokenResults)
            {
                [_pResultQuery whereKey:@"searchIndex" equalTo:_tokenObject];
            }

            // 5) pagination (adding setSkip: for real pagination)
            [_pResultQuery setLimit:PARSE_RESULT_LIMIT];
            [_pResultQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

                if(error)
                {
                    QLog([error localizedDescription]);
                }
                else
                {
                    // 6) objects contains all matching entries for SearchableObject_1

                    // 7) nested additional SearchableObject_x searches
                    // ....
                }
            }];
        }
    }
}];


text:
Q: What are the default transformation matrices set by ID3DXSprite::Begin? Unless the D3DXSPRITE_OBJECTSPACE flag is set, the ID3DXSprite::Begin method sets the world, view and projection transformations on the device.
These default transformations do not work well if sprites are rotated out of the X-Y plane so I would like to modify them, which will be a lot easier if I know what they are.
What transformations does ID3DXSprite::Begin set?

A: ID3DXSprite::Begin sets the world and view transformations to the identity.
The projection transformation is set to matProj:
// pdev is the IDirect3DDevice9 pointer
D3DVIEWPORT9 viewport;
pdev->GetViewport(&viewport);

// Short variable names to make the matrix readable
int w = viewport.Width; int h = viewport.Height;
int vx = viewport.X; int vy = viewport.Y;

// The scaling factors
float sx = 1.0f / w;
float sy = 1.0f / h;

// The projection matrix
D3DMATRIX matProj = {
                    sx * 2.0f,                  0.0f, 0.0f, 0.0f,
                         0.0f,            -sy * 2.0f, 0.0f, 0.0f,
                         0.0f,                  0.0f, 1.0f, 0.0f,
       -sx * (w + 2 * vx + 1), sy * (h + 2 * vy + 1), 0.0f, 1.0f
};


text:
Q: "Debugging" an android app after it has been deployed to the store I have deployed an Android app (that utilises maps) on the Google Play Store and all my friends who have got it say it works fine, except for one user, who is on a Samsung S9 running Android 9. He says that the app crashes as soon as the launcher icon is pressed. I'm at a loss as to how to proceed since the app works fine on my machine and on everyone elses, as far as I can determine. How can I proceed? Is there a way to run the app on his machine to generate a trace or some logs to determine when/how the crash occurs?

A: I used to use Fabric, It's free and doing awesome job. now Fabric joined forces with Firebase with the goal of giving developers one place to build and grow their apps. Now that we've brought over the Fabric tools you know and love to Firebase, Fabric will deprecating on March 31, 2020 and terminating all Fabric service agreements at that time. so you can check Firebase too.
And also from your Google Play Console -> Select you app -> Android Vitals -> ARNs & craches and here you can also find some useful informations about craches (The activity and the line number)

A: I use firebase crashlytics. Crashlytics creates a full report about any bug that your app suffers. It is very easy to implement and very useful.

A: An alternative to Crashlytics is ACRA. It's still actively maintained and you can host the stack by yourself or use one of the provided solutions.


text:
Q: Variable From Other Script Sometimes not Loading I have Two JavaScript scripts linked to my HTML File in this order:
<script src="first.js"></script>
<script src="second.js"></script>

first.js has a variable which is accessed by second.js. The Variable is Used by second.js at the end of the file and the variable is defined in first.js at the beginning. Whenever I reload the site, a console error occasionally comes up saying that the Variable in first.js is not defined.

Uncaught ReferenceError: dbis not defined
at second.js:80

Why is this? Thanks in Advance.
Full Example:
first.js:
var db = [{name: "Obj1", property: "property1"}, {name: "Obj2", property: "property2"}]; // At Line 8

second.js:
function loadDbItems() {
    for(i = 0; i < db.length; i++) {
        console.log(db[i].name); // Line is Near End of Script
    }
}

A: You can register the variable with window to make it global guaranteed.
See script example below.
You should not pollute the window object with every little variable you need, but this way the variable will exist across scripts, provided the first one executes first.

window.db = [{name: "Obj1", property: "property1"}, {name: "Obj2", property: "property2"}];
<html>
  <body onload="loadDbItems()">
    <script>
      function loadDbItems() {
        for(var i = 0; i < window.db.length; i++) {
            console.log(window.db[i].name);
        }
      }
    </script>
  </body>
</html>


text:
Q: How to ensure Spring `Resource::createRelative` returns relative file resource for directory resource without trailing slash? Hej,
in a Spring Boot application I need to use a base directory on the filesystem and access file resources relative to that.
Spring Boot allows to configure a directory via application.properties and a file:// URL as value.
When the property is missing its trailing slash, Resource::createRelative() fails to actually return a relative resource.
What kind of code or configuration do I need to make the createRelative() call work as intended, e.g. by ensuring that the Resource ends with a trailing slash?
The follwing test should illustrate my use case / problem:
@SpringBootTest
// NOTE: directory is missing trailing slash
@TestPropertySource(properties = "demo.directory=file://C:/Windows")
class RelativeFileUrlResourceTest {

    @ConfigurationProperties(prefix = "demo")
    static class TestProperties {

        Resource directory;

        public Resource getDirectory() {
            return directory;
        }

        public void setDirectory(Resource directory) {
            this.directory = directory;
        }
    }

    @TestConfiguration
    @EnableConfigurationProperties(TestProperties.class)
    static class Config {

    }

    @Autowired
    TestProperties testProperties;

    @Test
    void givenCreateRelative_thenResourceShouldBeRelative() throws IOException {
        Resource directoryResource = testProperties.getDirectory();
        File directoryFile = directoryResource.getFile();
        assertTrue(directoryFile.isDirectory());

        Resource relativeResource = directoryResource.createRelative("relative");
        File relativeFile = relativeResource.getFile();
        assertEquals(directoryFile, relativeFile.getParentFile());
    }
}

The test fails with:
org.opentest4j.AssertionFailedError:
Expected :C:\Windows
Actual   :C:\

The magic C:/Windows value is just an example of a folder that exists and does not have a trailing slash for test purposes. Once the trailing slash is added, i.e. C:/Windows/, the test passes.
Further note that both the canonical and absolute directory File do not contain a trailing slash either (at least tested on Windows).
The relative (file) resource is needed to pass it up all the way to a Spring MVC controller while using the Spring Resource abstraction to access it as a generic InputStream.
The actual application contains some logic to determine the relative file from the HTTP request instead of a hardcoded "relative" filename.
Is Resource::createRelative() unfit for this kind of use case? What other abstractions / solutions does Spring (Boot) offer?


text:
Q: Jasmine 2.0 async done() and angular-mocks inject() in same test it() My usual test case looks like
it("should send get request", inject(function(someServices) {
     //some test
}));

And Jasmine 2.0 async test should look like
it("should send get request", function(done) {
     someAsync.then(function(){
         done();
     });
});

How can I use both done and inject in one test?

A: This should work; I ran into the same problem when I updated to Jasmine 2.0
it("should send get request", function(done) {
    inject(function(someServices) {
        //some async test
        done();
    })(); // function returned by 'inject' has to be invoked
});

A: An IMPORTANT note is the brackets after the inject call. Eg.
inject(function(someServices) {
   //some async test
   done();
})();  <-- these brackets here important.

If you look at the type of inject:
export declare function inject(tokens: any[], fn: Function): () => any;

You can see it returns a function, so you were getting no output because you forgot to call the function!!
If you think about it, it makes sense that it returns a function, because it takes a function!
So the extra parentheses should solve all problem!
Working Example:
  it('should allow you to observe for changes', function(done) {
    inject([GlobalStateService], (globalStateService: GlobalStateService) => {
      globalStateService.observe("user", storageType.InMemoryStorage, (user: string) => {
        expect(user).toBe("bla");
        done();
      });

      globalStateService.write({ user: "bla"}, storageType.InMemoryStorage);
    })();
  });

A: You could write the test like that:
describe("Some service'", function () {
    var service;
    var data;

    beforeEach(function (done) {

        module('app');

        inject(function (someService) {
            service = someService;
        });

        service
            .getData()
            .then(function(result) {
                data = result;
                done();
            });
    });

    it('should return a result', function () {
        expect(data).toBeDefined();
    });
}

A: To add to the answer of @Scott Boring and to the comment of @WhiteAngel who mentionned that the code inside inject was never called.
This worked for me:
it("should send get request", function(done) {
    inject(function(someServices) {
       //some async test
       done();
    })();
});

A: For Angular 5.2.0: @scott-boring's approach did not work for me. What did work is using the TestBed.get() to get the services instead of inject(), as described in the docs:
describe('TooltipComponent', () => {
  let component: TooltipComponent;
  let fixture: ComponentFixture<TooltipComponent>;
  let myService: MyService;

  beforeEach(async(() => {
    const myServiceSpy = jasmine.createSpyObj('MyService', ['calc']);

    TestBed.configureTestingModule({
      declarations: [ MyComponent ],
      providers: [
        {provide: MyService, useValue: myServiceSpy}
      ]
    })
    .compileComponents();

    myService = TestBed.get(MyService);
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should render correctly', (done) => {
    component.render();

    setTimeout(() => {
      expect(myService.calc).toHaveBeenCalled();
      done();
    }, 1000);
  });


text:
Q: What permissions are needed for a user running Ola Hallengren's IndexOptimize stored procedure? I'm planning to orchestrate my index maintenance with other jobs in my Azure SQL Database (serverless) using Azure Data Factory. The job will be run by the Managed Identity of my ADF service, and the MI has been added to the "db_datareader", "db_datawriter" and "db_ddladmin" roles, as well as been granted EXECUTE rights.
The statistics update worked, but after that I got this error:

Sql error number: 50000. Error Message: Msg 297, The user does not have permission to perform this action.

What permission(s) is my MI missing? I would like to avoid making it "db_owner" if possible

A: Considering Ola Hallengren recommendations :

Which permissions are needed for the SQL Server Maintenance Solution
to work? If you are using SQL Server Agent, the jobs run under the SQL
Server Agent service account that is a member of the sysadmin server
role. If you are using a proxy account, I recommend that the account
be a member of the sysadmin server role.
If you are using another scheduler, I recommend that the scheduler run
under an account that is a member of the sysadmin server role.
If you need to have users execute the stored procedures ad hoc against
specific databases, these permissions are needed:
IndexOptimize: EXECUTE on dbo.IndexOptimize, VIEW DEFINITION on
dbo.CommandExecute, VIEW DEFINITION on dbo.CommandLog, VIEW SERVER
STATE, db_owner on all target databases

So short answer :
sysadmin user for a SQL Server Agent service Account

If you have to use a specific user :
EXECUTE on dbo.IndexOptimize
VIEW DEFINITION on dbo.CommandExecute
VIEW DEFINITION on dbo.CommandLog
VIEW SERVER STATE
db_owner on all target databases
References :
https://ola.hallengren.com/frequently-asked-questions.html


text:
Q: Cloudfront - why is this not being "browser cached"? Here's the curl -I response to my Javascript file:
    HTTP/1.1 200 OK
    Content-Type: text/javascript
    Content-Length: 72640
    Connection: keep-alive
    Date: Sat, 18 Feb 2017 16:12:06 GMT
    Cache-Control: 86400
    Last-Modified: Wed, 15 Feb 2017 15:09:28 GMT
    ETag: "a6ee06ff5e49a4290bb2aabe5e0f9029"
    Server: AmazonS3
    Vary: Accept-Encoding
    Age: 1173
    X-Cache: Hit from cloudfront
    Via: 1.1 3b17302562f1709d8b6c9f7be1.cloudfront.net (CloudFront)

I can see the Cache-Control tag there. Not sure what the Vary and the ETag are doing, but so be it. Does this somehow specify to a user's browser NOT to cache this file? Why are Pingdom or Goog PageSpeed not recognising this as a browser-cacheable file?

A: Your Cache-Control header is present, but the value is not actually valid.  The correct format looks like this:
Cache-Control: max-age=86400

The number, by itself, is meaningless.

ETag: is the entity tag -- an opaque value that uniquely identifies the current content of a given URL.  If the content changes, the ETag will also change.  A browser with a cached copy may use this value for subsequent requests to ask that the server only return the content if it differs, by sending an If-None-Match: request header, including the last-seen ETag.
Vary: tells the browser that certain changes to the request may generate a different response.  Unlike browsers, curl doesn't advertise its ability to support gzipped payload unless you specify the --compressed option.  Adding that option when invoking curl triggers the addition of Accept-Encoding: gzip to the request, which may trigger the response to be compressed if you have that option enabled in CloudFront.


text:
Q: In ReactJS, how to map object items coming in redux state In ReactJS, how to map object items coming in redux state?

const mapStateToProps = (state) => {
     console.log("state.donorReducer.donor" ,state.donorReducer.donor)
    return {
        donorReducer: state.donorReducer,
        donorslist: state.donorReducer.donor,
    }
}

How can I map donorslist items?
I tried it ,
{this.props.donorReducer.donor.map((m, i) => {
                    return(

                        <Paper style={style} zDepth={5} >
                        >Blood: {m.bloodgroup}

                        >Mobile: {m.mobile}

                        >Name: {m.fullname}

                        >Age: {m.age}

                        >Address: {m.address}

                        </Paper>

  )
                })

                }

A: You can simply map over the list like and remove the > signs before items
{this.props.donorslist && this.props.donorslist.map((m, i) => {
                    return(

                        <Paper style={style} zDepth={5} >
                        Blood: {m.bloodgroup}

                        Mobile: {m.mobile}

                        Name: {m.fullname}

                        Age: {m.age}

                        Address: {m.address}

                        </Paper>

                     )
            })

 }


text:
Q: CUDA in BulletPhysics / BulletSharp? Could BulletSharp (or BulletPhysics itself, if you don't know about BulletSharp) use CUDA? If so, where could I find appropriate settings? (like on/off CUDA, e.t.c.)
I found old info, that there was experiments with using CUDA in Bullet. But can't find info about actual state. (and didn't find any mention in BulletSharp or BulletPhysics code)
note: BulletSharp is C# wrapper for BulletPhysics.
Thank you for any information

A: I think, @Andres Traks answered this question also in his answer to this one
Namely:

Work on the GPU pipeline in Bullet 3 seems to have stopped, so there are currently no plans to support version 3 in BulletSharp.


text:
Q: Database Design Advice For Fees and Payments Below is the current design of school fees and payment I have created.
I'm just a little stuck right now because I can't model the payment/transaction table. Also, I would like to know your thoughts and comments with my current design. This is the first time I'll create a database for fees and payments.

Main tables of my concern are schoolyearfee_lt , student_fee_lt and Payment
I'm thinking of using the Payment table to store the sum of all fees on which will be divided to whatever payment term was chosen (monthly,quarterly,annual,cash).
Let's say for instance, Monthly was chosen as payment plan.
amountToPayPerMonth = (sumOfAllAssignedFees / paymentterm) - downpayment

Where 11 inserts of the amountToPayPerMonth to payment table will be executed and 1 downpayment. 11+1 = 12 months
How do I mark it as paid? Should I use another Transaction table?
Is this a good design? Any thoughts or advice?
Thank you.

A: some (personal) thoughts about your design and question.
1- schoolyearfee_lt. It seems 1-to-n with fee_mt. If i well understand the same fee can be applied for several shoolyears, category etc, but the amount for a fee does not change. It means, for example, that every year in which fee amounts change i should create -at least- a new fee and some shoolyearfee.  I believe something can be reviewed here. I could from example move some of its fields (schoolyear?) to the fee_mt table, and/or i could move the amount from fee_mt to schoolyearfee_lt. There are also some more possibilities, i.e. making a table fee_years_lt, where storing year and amount (and maybe other factors which change the fees) and so on. Maybe you could make some of these changes, maybe none, depends on your design and requirements.  The questions may be: is the amount changing by year (i believe yes), gradelevel, feetype, feecategory or not ? You want a master fee that you want applicable forever or your fees are recreated each year from scratch ?
2- Payment. I would call it exactly with its meaning: payment_plan. I would add a field paid, a field payment_date and a field schoolyear (in current design).
3- Student_fee_lt and schoolyear. In the current design you better add the year too. Depending on the mode the fee_mt is managed (see above) i would put it in the PK too. Moving the year to the fee_mt, you don't need. Is student_fee_lt really needed (it seems the result of a query + the field date_effective) ?
4- Payment Formula. The downpayment and consequently the formula is a little nclear to me. Is it a kind of discount for every payment you do or is it a fixed amount ? In the latter you should review your formula. Why 11 payments ?
5- Choosen Payment Plan storage. I would have a table where storing the chosen payment plan by the student (and some other data), this should not be student_fee_lt, because it stores the single fees assigned for each student.


text:
Q: Regex character find replace i am new to regex in PHP, and had a question
What i am trying to do (in PHP):

*

*Find whether a string contains special characters or non-alphabets in a name (e.g. if term contains -, *, ., &, etc)

*If string contains special characters - find and replace it using str_replace. Sample strings include 'e*trade', 'e-trade', 'Barnes&Noble', etc.

A: Replace Symbols only
<?php
$regex = "/[-*.&]/";
$subject = "Barnes&Noble";
$replacement = "-";
$result = preg_replace($regex, $replacement, $subject);
echo $result;

Output:

Barnes-Noble

Replace all parts of the string if it matches Symbols:
<?php
$regex = "/(.*)([-*.&])(.*)/";
$subject = "Barnes&Noble";
$replacement = "$1 is not so $3";
$result = preg_replace($regex, $replacement, $subject);
echo $result;

Output:

Barnes is not so Noble

http://ideone.com/ByXagy


text:
Q: Expression to string How can I get a string like
Namespace.IMyService.Do("1")

from the expression as demoed in this snip it:
IMyService myService = ...;
int param1 = 1;

myExpressionService.Get(c => myService.Do(param1));

I actually don't want to call Do unless a condition is met using the string that was generated.

A: You will have to traverse Expression trees. Here is some sample code:
internal static class myExpressionService
{
    public static string Get(Expression<Action> expression)
    {
        MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body;
        var method = methodCallExpression.Method;
        var argument = (ConstantExpression) methodCallExpression.Arguments.First();

        return string.Format("{0}.{1}({2})", method.DeclaringType.FullName, method.Name, argument.Value);
    }
}

It works if called in this way: string result = myExpressionService.Get(() => myService.Do(1));
The output is: Namespace.IMyService.Do(1)
You can extend/update it to handle your scenario.

A: This would also work (though it's not particularly elegant):
public static string MethodCallExpressionRepresentation(this LambdaExpression expr)
{
    var expression = (MethodCallExpression)expr.Body;

    var arguments = string.Join(", ", expression.Arguments.OfType<MemberExpression>().Select(x => {
        var tempInstance = ((ConstantExpression)x.Expression).Value;
        var fieldInfo = (FieldInfo)x.Member;
        return "\"" + fieldInfo.GetValue(tempInstance).ToString() + "\"";
    }).ToArray());

    return expression.Object.Type.FullName + "." + expression.Method.Name + "(" + arguments + ")";
}

You can call it like this:
Expression<Action> expr = c => myService.Do(param1));
var repr = expr.MethodCallExpressionRepresentation();    // Namespace.IMyService.Do("1")

A: You should be able to call .ToString() on the resulting expression. According to the MS documentation ToString() returns the textual representation of the expression. Have you tried that?


text:
Q: Hibernate Validation Error Having big problems with Hibernate Validator
Getting this error

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'company' available as request attribute

Here is my Controller
 import java.util.logging.Logger;

 import javax.validation.Valid;

 import org.springframework.stereotype.Controller;
 import org.springframework.ui.ModelMap;
 import org.springframework.validation.BindingResult;
 import org.springframework.web.bind.annotation.ModelAttribute;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.SessionAttributes;

 import com.muuves.reservosity.model.Business_Register;

 @Controller
 @SessionAttributes( {"company"})
 @RequestMapping("/business")
 public class BusinessController {
private final static Logger LOG = Logger.getLogger(BusinessController.class .getName());

@RequestMapping(method = RequestMethod.GET)
public String business(ModelMap model) {
    LOG.info("Entering Business Home");
    model.put("company", new Business_Register());
    return "business";
}
@RequestMapping(value="/register", method = RequestMethod.GET)
public String businessRegister() {
    LOG.info("Register Business Page");
    return "business_register";
}

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addBusiness(@Valid Business_Register company, BindingResult result, ModelMap model) {
    LOG.info("Registering Business"+result.getErrorCount());
    if (result.hasErrors()){
        System.out.println("I found errors now now");
        return "business_register";
    }
    //companyService.addCompany(company);
    return "business_add";
}

}
This is jsp
 <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

Register Your Business

Please register your business details below

    <form:form method="post" action="add" commandName="company">
        <form:errors path="Company"></form:errors>
        <form:input type="text" placeholder="Company Name" path="Company"/>

                <form:input type="text" placeholder="Address Line 1" path="Address_Line_1"/>
                <form:errors path="Address_Line_1"></form:errors>

                <form:input type="text" placeholder="Address Line 2" path="Address_Line_2"/>
                <form:errors path="Address_Line_2"></form:errors>

                <form:input type="text" placeholder="Postcode" path="Postcode"/>
                <form:errors path="Postcode"></form:errors>

                <form:input type="text" placeholder="County" path="County"/>
                <form:errors path="County"></form:errors>

                <form:input type="text" placeholder="Country" path="Country"/>
                <form:errors path="Country"></form:errors>

                <form:input type="text" placeholder="Mobile telephone" path="Mobile_Number"/>
                <form:errors path="Mobile_Number"></form:errors>

                <form:input type="text" placeholder="Home telephone" path="Telephone_Number"/>
                <form:errors path="Telephone_Number"></form:errors>

        <form:errors path="Username"></form:errors>
        <form:input type="text" placeholder="Username" path="Username"/>
        <form:errors path="Password"></form:errors>
        <form:input type="password" placeholder="Password" path="Password"/>

        <button class="radius button" type="submit">Register</button>
        <button class="radius button" type="reset">Cancel</button>
    </form:form>

   import org.hibernate.validator.constraints.NotBlank;

   public class Business_Register {

@NotBlank(message="Name field is mandatory.")
private String Company;
@NotBlank(message="Name field is mandatory.")
private String Address_Line_1;
@NotBlank(message="Name field is mandatory.")
private String Address_Line_2;
@NotBlank(message="Name field is mandatory.")
private String Postcode;
@NotBlank(message="Name field is mandatory.")
private String County;
@NotBlank(message="Name field is mandatory.")
private String Country;
@NotBlank(message="Name field is mandatory.")
private String Mobile_Number;
@NotBlank(message="Name field is mandatory.")
private String Telephone_Number;
@NotBlank(message="Name field is mandatory.")
private String Username;
@NotBlank(message="Name field is mandatory.")
private String Password;

public String getCompany() {
    return Company;
}
public void setCompany(String company) {
    Company = company;
}
public String getAddress_Line_1() {
    return Address_Line_1;
}
public void setAddress_Line_1(String address_Line_1) {
    Address_Line_1 = address_Line_1;
}
public String getAddress_Line_2() {
    return Address_Line_2;
}
public void setAddress_Line_2(String address_Line_2) {
    Address_Line_2 = address_Line_2;
}
public String getPostcode() {
    return Postcode;
}
public void setPostcode(String postcode) {
    Postcode = postcode;
}
public String getCounty() {
    return County;
}
public void setCounty(String county) {
    County = county;
}
public String getCountry() {
    return Country;
}
public void setCountry(String country) {
    Country = country;
}
public String getMobile_Number() {
    return Mobile_Number;
}
public void setMobile_Number(String mobile_Number) {
    Mobile_Number = mobile_Number;
}
public String getTelephone_Number() {
    return Telephone_Number;
}
public void setTelephone_Number(String telephone_Number) {
    Telephone_Number = telephone_Number;
}
public String getUsername() {
    return Username;
}
public void setUsername(String username) {
    Username = username;
}
public String getPassword() {
    return Password;
}
public void setPassword(String password) {
    Password = password;
}
  }

I have import this into my pom.xml
            <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>4.3.1.Final</version>
    </dependency>

A: Needed to  add @ModelAttribute("company") http://blog.nigelsim.org/2011/09/07/spring-mvc-validation-bindingresult/
And it works
Seems ridiculous that you needed to do this though


text:
Q: put_time() ignores conversion specifier 'z' for time zone offset The following code shall print the time with the time zone offset, the lowercase format specifier z is passed:
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;

int main() {
    time_t current_time = time(nullptr);
    tm* timeinfo = localtime(&current_time);
    cout << put_time(timeinfo, "%c %z") << "\n";
    return 0;
}

g++ -o time time.cpp -Wall -pedantic
The function put_time() (C++) is described on cppreference.com. The format specifiers are the ones from strftime() (C). You can also read about them in the C Standard, currently page 396 in chapter 7.27.3.5:

  %z

is replaced by the offset from UTC in the ISO 8601 format ''−0430'' (meaning 4
      hours 30 minutes behind UTC, west of Greenwich), or by no characters if no time
      zone is determinable. [tm_isdst]

This works well on Linux:

Fri Jul 26 12:30:02 2019 +0200

But on Windows it's returning:

07/26/19 12:03:53 Mitteleuropäisches Sommerzeit

That's wrong, my code doesn't ask for the name of the timezone, but for the offset to UTC. I'm using on both platforms GCC as compiler.
Question
Am I doing something wrong here? Or is either GCC or Microsoft Windows violating the standard? I read some "rumors" about that it could be influenced through some settings on Windows.
Caluclating the offset by hand is rather treacherous. The best helper would be  tm.gmt_offset, which is platform specific field. Therefore gmt_offset is not listed and only available on GNU based systems. I'm currently using a workaround based on GetTimeZoneInformation and the fields Bias and DaylightBias, which is a platform specific Windows-API. I appreciate more secure suggestions.
Thank you for help and insights!
Environments:
GNU/Linux with GCC 9.1.0 (Archlinux)
Windows with GCC 8.3.0 (MSYS2)

A: If you are willing to use a free, open-source (MIT license) 3rd party library, it will give portable results.
#include "date/tz.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std;
    using namespace std::chrono;
    zoned_seconds zt{current_zone(), floor<seconds>(system_clock::now())};
    cout << format("%c %z", zt) << '\n';
}

Though on Windows you will need to install curl and 7-zip, and on linux you'll need to link with -lcurl.  More detailed installation instructions are available here.
This is a preview of the draft C++20 <chrono> library, though admittedly the syntax for the format statement is going to change slightly due to votes being taken just last week in Cologne.  C++20 will incorporate the fmt library (which is great news).
This library still uses put_time for the %c part of the format, but formats the %z part itself (and gives the offset in [+/-]hhmm form as desired).


text:
Q: JUnit: is it possible to create a Test Suite that executes all test of classes that share a naming convention? I am aware that I can make a TestSuite enumerating all the classes that I want, for example:
@RunWith(Suite.class)
@SuiteClasses({SQLServerTests1.class, SQLServerTest2.class, ... })
public class AllSQLServerTests {}

However I have almost 100+ classes and I don't want to have to remember to include any new one in the @SuiteClasses annotation.
As my classes have a naming convention (starting with "SQLServer" for example) I am searching for a way to do something like this:
@RunWith(Suite.class)
@SuiteClasses(prefix="SQLServer")
public class AllSQLServerTests {}

is it possible with plain JUnit? with spring or any other framework?

A: Tag'em
You can add many tags to each test or test class:
@Test
@Tag("red")
@Tag("production")
public void testWithColour() {...}

@RunWith(JUnitPlatform.class)
@IncludeTags("red & !production")
public class JUnit5Example {
   //...
}

You can also use @ExcludeTags but it cannot co-exist with @IncludeTags
Run all in test package
@RunWith(JUnitPlatform.class)
@SelectPackages("com.acme.megaproduct.slowtests")
public class JUnit5Example {
   //...
}

Write custom Test Runner
Perhaps none of the above can acommodate your needs, in which case you can add custom filtering by writing your own runner.
See here for step by step how to do it.
Then you just use it like:
@RunWith(MyCustomRunner.class)
public class CustomTestSuite {
   //...
}


text:
Q: Replace full html anchor with another html anchor using jQuery I have an anchor tag
Locking

I have to replace this anchor tag with following
var TempHtml= "Lock"

I did this
htmlString=htmlString.replace("Locking",TempHtml);

The htmlString is containing a very large amount of string which is coming from the database.
This is my htmlString which is coming from the database

Settings

Details

Add Products

QuickSpec

Print Setup

Print

Export

Duplicate

Preview

Print Setup (Beta)

QuickSpec(Old)

Add Products(Old)

Details(Old)

Remove

**Locking**

As you can see the last anchor tag in htmlString is the same I want to replace.How to achieve this?Kindly help.

A: the last li element, that contains the anchor tag you want to replace, first empty that and then appens the anchor tag you want to add.
$("#ancLockProposal").empty();
$("$ancLockProposal").append("Lock");

hope this helps.

A: you need to make the following change:
htmlString=htmlString.replace(/Locking<\/a>/g,TempHtml);

A: I'd not use replace. Since you flagged this as jquery:
$('#ancLocProposal').next('a').text('Lock').click( function(){ LockProposal(PKProposalId, 1); } );

Possibly you'll need to use a closure, depending on scope/usage of PKProposalId:
(function(PKProposalId){$('#ancLocProposal').next('a').text('Lock').click( function(){ LockProposal(PKProposalId, 1); } );})(PKProposalId);

.. or you work with data-attributes.

A: Try this, it get last anchor tag object in your div tag
var totalACount= $('div a').length-1;
var lastAncher = $('div a:eq('+totalACount+')');
alert($(lastAncher).attr("href"));

you can access class,id,onclick any thing you want, if attribute is exist in anchor tag.
after accessing object you can replace object.


text:
Q: Flask app loads css changes only after compuster restarts Hello I follow an online course which will teach me flask/jinja2 etc.
I use for my coding a PyCharm Pro version.
My problem is that the css is not loaded correctly when I run the app. The css only refreshes when I restart my computer.... this does not make any sense to me. I even tried different connecting ways( Full path, relative path, let flask create the path...)
I need a hand to find the problem.
Here is my code:
Python:
Python:
import flask

app = flask.Flask(__name__)

def get_latest_packages():
    return [
        {'name': 'flask','version': '1.2.3'},
        {'name': 'sqlalchemy', 'version': '2.2.0'},
        {'name': 'passlib', 'version': '3.0.0'}
    ]

@app.route('/')
def index():
    test_packages = get_latest_packages()
    return flask.render_template('index.html', packages = test_packages)

@app.route('/about')
def about():
    return flask.render_template('about.html')

if __name__ == '__main__':
    app.run(debug=True)

HTML:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Python Package Index Demo</title>
      <link rel="stylesheet"
           href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
           integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
           crossorigin="anonymous">
          <link rel="stylesheet" type="text/css" href="/static/css/site.css"/>

         Home
         About

Python Packages Index

Packages

         {% for p in packages %}

                    {{ p.name.upper() }}

                    {{ p.version }}

            {% endfor %}

A: I had the same problem when I first started out with web development, are you sure you arent cashing the site in your browser ? The fact that a restart fixes it makes me think you do. In chrome you can open the DevTools and go to Settings to disable caching while they are open. Go to your site, press F12 and then refresh with open DevTools and see if it helps.


text:
Q: creating multiple .gitconfig I am new to Git.
I have gone through couple of on-line tutorials. I want to do some hands on to understand it better.
I am using eclipse EGit plug in(not installed git in the system).
I created a git remote repository and added 2 users for the project.
Now I want to try out things in eclipse, but I am facing a problem.
I have 2 eclipse instance in my system, I want to use it for each git user.
But the problem is both are pointing to same .gitconfig file.
So I can't use it for 2 users.
Could any one please help how to create multiple .gitconfig?
Thanks in advance.
Kitty.

A: Two ways to achieve this.

*

*Make it look like there are two users on the machine. Set $HOME to different values and launch each eclipse instance with a different setting.

*Don't use the $HOME/.gitconfig at all and configure everything per repository. To change settings, go to Preferences -> Team -> Git -> Configuration and then change settings in the Repository Settings tab.
For this section option, you may want to clone the same repository twice. To do that you need to give a new directory name on the last page of the clone wizard:


text:
Q: Newtonsoft.Json System.InvalidOperationException: Synchronous operations are disallowed I am getting the following exception and I am not sure how to resolve it. I do not want to set AllowSynchronousIO = true. MS has made the decision starting with 3.0 to no longer allow synchronous by default and for good reason. So how do I get around this issue?
System.InvalidOperationException: Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.StreamReader.ReadBuffer(Span`1 userBuffer, Boolean& readToUserBuffer)
   at System.IO.StreamReader.ReadSpan(Span`1 buffer)
   at System.IO.StreamReader.Read(Char[] buffer, Int32 index, Int32 count)
   at Newtonsoft.Json.JsonTextReader.ReadData(Boolean append, Int32 charsRequired)
   at Newtonsoft.Json.JsonTextReader.ParseValue()
   at Newtonsoft.Json.JsonReader.ReadAndMoveToContent()
   at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Deserialize[T](JsonReader reader)

A: Using the Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream class as a wrapper around the stream solves the issue. This allows you to access a stream asynchronously and then expose the stream to a synchronous tool like Newtonsoft.Json without enabling SynchronousIO for the entire solution. MVC is getting around this error by using the FileBufferingReadStream class as well so it's well tested.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.webutilities.filebufferingreadstream?view=aspnetcore-3.1


text:
Q: Create a floor plan in Compose I need to create a floor plan in Android, which is basically the same problem reported by Create floor plan in Android.
I'm currently using the Canvas component to draw it, but it's not scaling well when I got hundreds of rectangles.
This floor plan is also dynamic, and I need to change some styling as the server changes its representation.


text:
Q: how to make value required for items created with the help of apex_item API in oracle apex 5 how to set value required=yes for items created with APEX_ITEM in apex5.0
APEX_ITEM.TEXT (p_idx =>2 ,  p_item_id =>  ISSUED_TO) TO from ISSUED_INFO,

this item should be

A: have you tried p_attributes? It might be possible like this:
  APEX_ITEM.TEXT(p_idx =>2 ,  p_item_id =>  ISSUED_TO , p_attributes=> 'required="" aria-required="true"')


text:
Q: hasura multilevel nested mutations I try to upsert 2-level nested mutation:
department: { subdivisions: { users: { department, subdivision } } }

User was updated, but user.department=null.
And users returning was empty.
Full query:
mutation MyMutation($d: [department_insert_input!]!) {
  insert_department(objects: $d,
    on_conflict: {
      constraint: department_u_onec_id,
      update_columns: description
    }
  ) {
    returning {
      id
      subdivisions {
        id name
        users {
          id
          login
          subdivision
          department
      }}

    }
  }
}

Variables:
{
  "d": {
    "onec_id": "test1",
    "title": "test",
    "subdivisions": {
      "data": [
        {
          "description": "test1",
          "users": {
            "data": {
              "login": "test1",
              "role": 1,
              "onec_id": "test1"
            },
            "on_conflict": {
              "constraint": "user_login_uindex",
              "update_columns": [
                "role"
              ]
            }
          }
        }
      ],
      "on_conflict": {
        "constraint": "subdivision_u_onec_id",
        "update_columns": [
          "description",
        ]
      }
    },
  }
}

Result:
{
    "insert_department": {
        "returning": [
            {
                "id": 6,
                "subdivisions": [
                    {
                        "id": 10,
                        "name": "test1",
                        "users": [
                           {
                               "id": 35,
                                "login": "test1",
                                "subdivision": 10,
                                "department": null
                            }
                        ]
                    }
                ]
            }
        ]
    }
}

Can I set users.{department, subdivision} in one query, if I not know it in advance?

A: I duplicated the users section into departments and it works.
Variables:
{
  "department": {
     ...
     "users":{
       "data":[{"login":"test1","role":2}],
       "on_conflict":{"constraint":"user_login_uindex",
       "update_columns":[ "department"]}}
     ...
     "subdivisions": { users: { ... }}
  }
}


text:
Q: Partition function in the non-interacting limit Let's consider the partition function $$Z(\lambda)=Tr (e^{-\beta H})=Tr (e^{-\beta (H_1+\lambda H_2)})$$ for a quantum system with the Hamiltonian $H=H_1+\lambda H_2$ where $H_1$ is the free part of the hamiltonian and $\lambda H_2$ is the interacting part.
I'm wondering if it is true that
$$ \lim_{\lambda \rightarrow 0} Z(\lambda)=Z(0)=Tr(e^{-\beta H_1}) $$
 Can there be some subtilty which makes $Z$ discontinous at $\lambda=0$?


text:
Q: edit PATH variable using command line in widows 10 I was trying to edit %path% variable using command line in windows 10, following this tutorial, but pathman/au was not recognized. What should be the right approach to do that?

A: In order to use this tool you need to install Windows resource kit tools 'pathman.exe'
Alternatively you can use this directly on the command line:
setx path "%path%;c:\directoryPath"
To add a new path variable to the %path% script. (You can use the option /M for system PATH variable)
I found this reference useful to look through:
https://www.windows-commandline.com/set-path-command-line/


text:
Q: How to convert a large sparse matrix to an array(Details given below)? i have a sparse matrix of features formed as a result of following operations using sklearn:
from sklearn.feature_extraction.text import CountVectorizer

vectorizer = CountVectorizer(analyzer = "word",tokenizer = None,preprocessor = None,stop_words = None,max_features = 5000)

train_data_features = vectorizer.fit_transform(y)

Converting to the contiguous array representation would materialize all the zeros in memory and the resulting size would be:
train_data_features.shape[0] * train_data_features.shape[1] * train_data_features.dtype.itemsize / 1e6

which yields:`6242.4
That's 8GB, compared to less than 1MB for the original sparse representation.
So,how to tackle this problem so that I can efficiently fit the resulting array into a random forest classifier?
`

A: Try this:
m = np.memmap('train_data_features_dense.mmap', dtype=train_data_features.dtype, mode='w+', shape=train_data_features.shape)
train_data_features.todense(out=m)
# Some work with m here, if you want, reading, writing, etc
# Better to call delete when you've done all work with it, del will flush buffers automatically
del m
# If you want to load memmap in another script
m = np.memmap('train_data_features_dense.mmap', dtype=train_data_features.dtype, mode='r+', shape=train_data_features.shape)

But as @yangjie said above, you should operate on sparse matrices when you can.


text:
Q: Javascripts GTM Writing a small custom javascript macro in GTM to set Category value if an outbound link is clicked. Most internal links are relative urls.
function(){
var eventCat = "";
if({{element url}}.indexOf("redirect") < 0) {
    eventCat = "Outbound Link Clicked";
}
return eventCat;
}

Does the {{element url}}.indexOf("redirect") < 0) { search for "redirect" within the url and set the Category as "Outbound Link Clicked"?

A: yes, it searches for redirect and sets eventCat but only in the case when redirect is not found.
Just say >=0 if you need to set eventCat = "Outbound Link Clicked"; when the redirect is found.
That's because indexOf returns the numeric position of the first occurence of the searched string. If the returned value is smaller than zero the string is not contained in the examined string.


text:
Q: Sitecore SXA : Your site has been exported in Wireframe mode Sitecore SXA : Your site has been exported in Wireframe mode. This mode does not reflect your site's look and feel and may cause problems for importing and editing.
When i try to export, Site themes getting above error

A: This happens if you export when your View mode is set to wireframe. You need to select Experience Accelerator ribbon > View Mode > Selected Theme. You may need to set a theme first using Experience Accelerator ribbon > Theme.
See The View Modes for SXA 1.9 for the full background.


text:
Q: Convert string from datetime php
Possible Duplicate:
convert date string to mysql datetime field

I have a DateTime column in MySQL database. I would like to convert Form text field data on POST (string) to DateTime before inserting into the database. I appreciate any suggestions.

A: Depends entirely on what format your POST data is in. Quick/dirty/probably-will-blow-up-and-steal-your-belongings method is
$date = date('Y-m-d H:i:s', strtotime($_POST['yourfield']));

A: date() function.
You can find the function in php.net

A: It depends on format of MySQL date time field and the format of the form field. Normally db datetime is Year-Month-day Hour:min:sec for example, "2011-10-24 14:25:20". Now to convert form submitted date string to datetime, do the following:

$date = strtotime($_POST['form_date']);
$DatabaseDate = date("Y-m-d H:i:s", $date);

Now you can use the above $DatabaseDate to insert datetime into database:

@mysq_query("INSERT INTO TEST_TABLE (id, date_test) VALUES (2,
  '$DatabaseDate')");

Hope it helps.

A: instead of strtotime($_POST['yourfield'])
use the function mktime, in that way you dont need to worry about the string format


text:
Q: How can I access GitLab CI CD Environment variables in .net core 2.2 webapi I have some connection strings and confidential data in config which I want to move out of the code for security reasons and move it to Environment variables in Gitlab. But don't know how to use and implement that.
any help would be appreciated. Thanks.

A: After creating a variable in GitLab CI/CD under Settings -> CI/CD -> Variables, I am able to read the value in C# using this:
string gitLabVar = Environment.GetEnvironmentVariable("VARNAME", EnvironmentVariableTarget.Process);


text:
Q: multiple upload dynamic file My problem is when the list input file is dynamic, so here is the code :
<?php
if(!empty($_FILES)){
    $syarat = array('2','3','4','7');
    $path = "./uploadtest/";
    $jmlsyarat = count($syarat);
        for($y = 0; $y<$jmlsyarat; $y++) {
            foreach ($_FILES as $file){
                $namafile = $syarat[$y].".jpg";
                $tmpfile = $file['tmp_name'];
                $kefile = $path.$namafile;
                move_uploaded_file($tmpfile,$kefile);
            }
        }
}
?>
<form method="post" enctype="multipart/form-data" action="/uploadtest.php">
<input type="file" name="2" />
<input type="file" name="3" />
<input type="file" name="4" />
<input type="file" name="7" />
<input type="submit" />
</form>

Can it be done with dynamic handler that I create at above?
Thank you in advance

A: here is the work code (thx to @Federkun) :
<?php
    if(!empty($_FILES)){

        $path = "./uploadtest/";

                foreach ($_FILES as $y => $file){
                    $namafile = $y.".jpg";
                    $tmpfile = $file['tmp_name'];
                    $kefile = $path.$namafile;
                    move_uploaded_file($tmpfile,$kefile);
                }

    }
?>
<form method="post" enctype="multipart/form-data" action="/uploadtest.php">
<input type="file" name="2" />
<input type="file" name="3" />
<input type="file" name="4" />
<input type="file" name="7" />
<input type="submit" />
</form>

That code work perfectly!


text:
Q: How to evaluate quality of probability estimator for Bernoulli experiments? Given that I have a set of bernoulli experiments, each with a different and unkown probability $p_i$ and an outcome $x_i$, and an estimator that for each experiment gives a prediction of the probability of the event, I want to measure the prediction quality of the estimator.
Example: I have a stack of n "unfair" coins, each with a different probability $p_i$ for heads and $1-p_i$ for tails. The probabilities are unknown and I can flip each coin only once.
Assume that there is a "coin flipping expert" which can have a close look at each coin before flipping them and make an estimate for the probabilities, based on form, size, width, regularity and so on. After the expert makes his prediction, the coin is flipped and the result is noted.
After all coins are flipped, I want to measure how good the expert was, for example on a scale between 0 and 1, where 1 means perfect prediction and 0 means pure randomness. I would also be interested in bias / variance of the predictor.

A: You can quantify the quality of the estimator by calculating the total surprisal of all of the coin flips.
Suppose that your expert makes predictions $q_i$ for each coin.  Then, given indicator variables for the coins coming up heads $x_i$, the total surprisal is:
\begin{align}
\sum_i\left[ -x_i\log q_i - (1-x_i)\log (1-q_i)\right].
\end{align}
The expected value of the surprisal given the true values $\{p_i\}$ is the cross-entropy:
\begin{align}
\sum_i \left[-p_i\log q_i  -(1-p_i)\log (1-q_i)\right].
\end{align}
It is nonnegative, and achieves its minimum value (the entropy of $\{p_i\}$) if and only if $p_i = q_i \forall i$.
If you subtract the entropy from the cross-entropy, you get the relative entropy (whose minimum value is zero).  If you take $e^{-x}$ of that, you have a number in $[0, 1]$ as you wanted with a reasonable probabilistic interpretation.

A: If I understand your question correctly, you might want to check out this question.  As I explained there, one way of assessing the calibration of probability predictions is with a scoring rule.  A common example of a scoring rule is the Brier score: $$BS = \frac{1}{N}\sum\limits _{t=1}^{N}(f_t-o_t)^2$$ where $f_t$ is the forecasted probability of the event happening and $o_t$ is 1 if the event did happen and 0 if it did not.
Of course the type of scoring rule you choose might depend on what type of event you are trying to predict.  However, this should give you some ideas to research further.
Perfect prediction with the Brier score would actually be 0 though, so you could take $1 - BS$ if that quality is important to you.  Note though that the other extreme score (0 or 1 depending upon whether you decide to flip the Brier score) actually would not be pure randomness but rather would represent getting the wrong answer every time.

A: The above answer may be useful but is complicated and I am not sure how to apply it. Thinking in simple terms this is a special case of testing whether or not a person has psychic powers (really no different from a scientific evaluation of the mechanics and physics of the coin flip).  Obviously have psychic capability would have to be defined as doing something much better than by random chance.  I would first want to define what is enough.  The difficulty is to decide how much better than random guessing is and what random guessing will do.  If all the coins were fair random choice would be 0.5 and so maybe saying anything over 0.75 is  Then testing the hypothesis that the person has psychic powers is doing a one-sided hypothesis that a binomial parameter p is <= to 0.75 versus the alternative that it is greater.  As an estimator I have chosen the binomial parameter for successfullu calling heads or tails and the variance of my estimator is p(1-p)/n. The added difficulty is that the coins are not fair and the individual pis are unknown. I would still define chance as random guessing of heads or tails and 0.5 is what I would test against.  However with unfair coins there may be statistical strategies that would lead to a better than chance success rate but neither indicate skill with the individual coin flips or psychic powers.  To illustrate suppose the average for the pis is 0.80.  Then after seing heads come up much more frequently than tails we could switch to an all heads strategy and tend to be correct close to 80% of the time.  This assumes randomguessing until we are convinced that head occurs much more often than tails and at that point we switch to all heads.  So without knowing the pis or at least their averages I cannot tell what success rate would indicate skill.  Comparing against random guessing is not the standard to beat in this case. Note that my argument only makes sense if the stack of coins is very large.

A: Another way to evaluate the quality is to look at the Reliability Diagram.
This does not immediately yield a value between 0 and 1, but can be used for a first visual evaluation.


text:
Q: exception when sending message to android using cordova I follow the tutorial in this link. I could successfully get the reg id back from Google.
I am using server side script from here
But when I send message from server the app crashes and please find my log here
—–
02-14 17:36:13.684: E/AndroidRuntime(377): FATAL EXCEPTION: IntentService[GCMIntentService-GCMIntentService-2]
02-14 17:36:13.684: E/AndroidRuntime(377): java.lang.NullPointerException: println needs a message
02-14 17:36:13.684: E/AndroidRuntime(377): at android.util.Log.println_native(Native Method)
02-14 17:36:13.684: E/AndroidRuntime(377): at android.util.Log.v(Log.java:116)
02-14 17:36:13.684: E/AndroidRuntime(377): at com.cordova2.gcm.GCMIntentService.onMessage(GCMIntentService.java:63)
02-14 17:36:13.684: E/AndroidRuntime(377): at com.google.android.gcm.GCMBaseIntentService.onHandleIntent(GCMBaseIntentService.java:179)
02-14 17:36:13.684: E/AndroidRuntime(377): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:59)
02-14 17:36:13.684: E/AndroidRuntime(377): at android.os.Handler.dispatchMessage(Handler.java:99)
02-14 17:36:13.684: E/AndroidRuntime(377): at android.os.Looper.loop(Looper.java:130)
02-14 17:36:13.684: E/AndroidRuntime(377): at android.os.HandlerThread.run(HandlerThread.java:60)
02-14 17:36:13.757: D/DroidGap(377): Paused the application!
——-

what may be the reasons for this issue?

A: It was a mistake with me. the issue was with the variable name of the server script.
if (isset($_GET["regId"]) && isset($_GET["message"])) {
    $regId = $_GET["regId"];
    $message = $_GET["message"];

    include_once './GCM.php';

    $gcm = new GCM();

    $registatoin_ids = array($regId);
    $message = array("price" => $message);

    $result = $gcm->send_notification($registatoin_ids, $message);

    echo $result;
}     . The line $message = array("price" => $message); changed to   $message = array("message" => $message); Now I could get the push message on my android phone.


text:
Q: How to convert delete+insert SQL into DBT module I'm learning DBT and would like to rewrite following Snowflake procedure with DBT model.
Unfortunately I don't know how to express SQL delete/inserts in DBT.
Here is my procedure:
create or replace procedure staging.ingest_google_campaigns_into_master()
    returns varchar
    language sql
as
$$
    begin
    DELETE FROM GOOGLE_ADWORD_CAMPAIGN
           WHERE DT IN (SELECT DISTINCT ORIGINALDATE AS DT FROM GOOGLEADWORDS_CAMPAIGN);
    INSERT INTO GOOGLE_ADWORD_CAMPAIGN
        SELECT DISTINCT *
        FROM
            (
               SELECT  g.* ,
                       YEAR(TO_TIMESTAMP(DATE_PART(EPOCH_SECOND, ORIGINALDATE::TIMESTAMP)::VARCHAR)) AS YEAR,
                       LPAD(MONTH(TO_TIMESTAMP(DATE_PART(EPOCH_SECOND, ORIGINALDATE::TIMESTAMP)::VARCHAR)),2,0) AS MONTH,
                       LPAD(DAY(TO_TIMESTAMP(DATE_PART(EPOCH_SECOND, ORIGINALDATE::TIMESTAMP)::VARCHAR)),2,0) AS DAY,
                       TO_DATE(DATE_PART(EPOCH_SECOND, ORIGINALDATE::TIMESTAMP)::VARCHAR) AS DT

               FROM GOOGLEADWORDS_CAMPAIGN g
            ) t;
    end;
$$
;

The procedure first remove old rows from table GOOGLE_ADWORD_CAMPAIGN and later replace them with the fresh one.

A: This pattern is called an "incremental" materialization in dbt. See the docs for more background.
On Snowflake, there are a few different "strategies" you can use for incremental materializations. One strategy is called delete+insert, which does exactly what your stored procedure does. Another option is merge, which may perform better.
Adapting your code to dbt would look like this:
{{
    config(
        materialized='incremental',
        unique_key='ORIGINALDATE',
        incremental_strategy='delete+insert',
    )
}}

SELECT DISTINCT
    g.* ,
    YEAR(TO_TIMESTAMP(DATE_PART(EPOCH_SECOND, ORIGINALDATE::TIMESTAMP)::VARCHAR)) AS YEAR,
    LPAD(MONTH(TO_TIMESTAMP(DATE_PART(EPOCH_SECOND, ORIGINALDATE::TIMESTAMP)::VARCHAR)),2,0) AS MONTH,
    LPAD(DAY(TO_TIMESTAMP(DATE_PART(EPOCH_SECOND, ORIGINALDATE::TIMESTAMP)::VARCHAR)),2,0) AS DAY,
    TO_DATE(DATE_PART(EPOCH_SECOND, ORIGINALDATE::TIMESTAMP)::VARCHAR) AS DT
FROM GOOGLEADWORDS_CAMPAIGN g

Note that this assumes there is just a single record in GOOGLEADWORDS_CAMPAIGN for each ORIGINALDATE -- if that is not true, you will want to substitute your own unique_key in the config block.
This also assumes that GOOGLEADWORDS_CAMPAIGN contains a sliding date window already. If that isn't the case, and you want to filter the dates contained in that table (and only update a subset of the data), you want to add a conditional WHERE statement when the model is built in incremental mode:
...
FROM GOOGLEADWORDS_CAMPAIGN g
{% if is_incremental() %}
WHERE
    DT >= (SELECT MAX(DT) FROM {{ this }}) - INTERVAL '7 DAYS'
{% endif %}


text:
Q: Couldn't get quotation marks out from string, Python Hello this is the code that I try to remove the quotation marks, but it seems doesn't work
text = "the "anatomical sex:"Local school boards shall develop and implement policies that "
print text

remove_quotation_marks = text.replace('"', '')
print remove_quotation_marks

A: Looks like you have some smart quotes in your text. Smart quotes are a different character than straight quotes.
http://smartquotesforsmartpeople.com/
http://hashtag-labs.com/eliminating-smart-quotes

A: text = "the "anatomical sex:"Local school boards shall develop and implement policies that "
print text

remove_quotation_marks = text.replace(text.replace('"', ''), '"', '')
print remove_quotation_marks

Works in my python prompt. Probably you also need an encoding set.


text:
Q: What is the best way to send emails from PHP script? [2] I hope this question wont be too specific. But I really need to ask. We all know that we cannot fully prevent our emails to go to spam box right? But I guess we can decrease the #of emails that goes there.
Till now, I use PHP's built-in function mail() but I guess there are other methods right? What are they and what is your best practice for this problem?
Taken from: What is the best practice to send emails from PHP script?
That's over a year old, hence the new question.

A: Swiftmailer
It's awesome! I've used it in all my projects with great results!
About the mail going to spam, I suggest this article

A: I love PHPMailer and it is now maintained at github. If you want then you could check then go to the page at: https://github.com/Synchro/PHPMailer