text:
Q: How to avoid accuracy loss while using jeval? I used jeval for some data computing tasks, and found a loss of accuracy.
Is there any way to avoid accuracy loss while using jeval?
I want to get the accurate result just like BigDecimal.
public class EvalTest {

    private static Evaluator eva = new Evaluator();

    public static void main(String[] args) {

        try {
            String formula = "780.0000000-259.9999998";
            String res = eva.evaluate(formula);

            BigDecimal a = BigDecimal.valueOf(780.0000000);
            BigDecimal b = BigDecimal.valueOf(259.9999998);
            BigDecimal c = a.subtract(b);

            System.out.println("a");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

If I use jeval, the formula "780.0000000-259.9999998" will get an result as "520.0000001999999", but if I use BigDecimal, I can get the accuracy result "520.0000002".

A: According to Jeval's Javadoc for the evaluate(String expression) method for Jeval 0.9.4, it says:

"The result of the evaluated. expression. Numbers are treated as
  doubles, so resulting numbers will contain at least one decimal
  place."

You can't avoid accuracy loss when using doubles. See this.
Floating point numbers have this limitations. For example, you can see it for simple expressions like 5.6 + 5.8, which yields 11.399999999999.


text:
Q: Resistor is always in parallel to a current source and is always in series with a voltage source, why? I have a basic question on electronics. Why is it that typically a resistor is always in parallel to a current source and is always in series with a voltage source?
As observed in Norton's and Thevenin's theorems.

A: A voltage source has zero internal impedance and, ideally could supply infinite current. To model a more practical realistic voltage source a resistor is added in series. That resistor will limit the short circuit current to (say) 1 amp.
To model this as a current source you can't put a resistor in series because the current source can still generate 1 amp and the open circuit voltage would be infinite. So, if the original voltage source was 10 volts and had a 10 ohm resistor in series, the equivalent current source would be 1 amp in parallel with 10 ohms.

A: You could always connect a resistor in series with a current source or a resistor in parallel with a voltage source, but here we are just trying to model one of the inherent non-idealistic characteristics of a voltage (or current) source. Namely, the output voltage (or current) changes with the load resistance due to physical limitations in our source. e.g. A 9V battery will decrease in output voltage when trying to provide too many amps.
If you consider a battery (a voltage source):

simulate this circuit – Schematic created using CircuitLab
We put a resistance in series with the source because the output voltage will vary with the load by a simple voltage divider equation. Whereas, if we modeled our source with a resistor in parallel, then the output voltage would always be our ideal voltage (1V below) - not a useful model.

simulate this circuit
It's the same for the current source. A series resistor won't lessen the current through the load, but a parallel resistor will leech current by the current divider equation.

A: Because a parrallel resistor would not change the behaviour of the (ideal) voltage source and otherwise.
The sources set the current/voltage and the resistors would not change that

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Selenium Webdriver: Drag and drop failing Drag and drop feature is not working in test framework. It is working for last 6 months and all of a sudden this feature alone of Selenium is not working.
Previously my selenium version 2.33 and upgraded to latest 2.41.0. Still it is not working
All other actions say double click, filling text box etc are working fine.
I am not getting any error from selenium that drag and drop is failing but the object is not seen in the target.
I increased implicit time, and also inserted explicit sleep but it is not working.
firefox version is 16.
Did anyone faced similar issue?

A: Is drag and drop working manually when you open page in firefox? It may happen page has changed.


text:
Q: Send Only Parameters from tabs to other page - Ionic2 I'm using framework ionic 2 and I need send parameters from my tabs to other page , that page is not on my tab...
I know the method " this.navCtrl.push(view,{parameters}) " but I only need send the parameters , don't want open other page , Only parameters. please help me.
In my code I need send parameter "rut".
tabs.html:

   <ion-menu [content]="content" >

    <ion-header>
    <ion-toolbar>

{{nombre}} {{apellido}}

{{rut}}

    </ion-toolbar>
  </ion-header>

   <ion-content >
      <ion-list>

          <ion-icon name="md-qr-scanner"></ion-icon>

Escanear Producto

       <ion-icon name="md-person"></ion-icon>

Perfil

      <ion-icon name="md-settings"></ion-icon>

Opciones

      <ion-icon name="md-information-circle"></ion-icon>

Acerca De

    <ion-icon name="md-log-out"></ion-icon>

Cerrar Sesion

     </ion-list>
   </ion-content>

   </ion-menu>
   <ion-nav [root]="rootPage" #content  swipeBackEnabled="true" ></ion-nav>

<ion-tabs color="primary">
  <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab2Root"  tabTitle="Carro" tabBadge="{{num}}" tabIcon="cart"  tabBadgeStyle="danger" ></ion-tab>
  <ion-tab tabTitle="Perfil" tabIcon="md-person" (ionSelect)="modificarPerfil()"></ion-tab>
</ion-tabs>

A: I am assuming you have 3 pages: tabsAll, tab1Root, tab2Root where tabsAll is the overall and whose code is shown.
You need to send parameters from the tabs to other page. I am assuming the other page is the other tabs? You can make use of rootParams to pass parameters from tabs to other tabs.
tabsAll html
<ion-tabs color="primary">
  <ion-tab [root]="tab1Root" [rootParams]="{rutValue: rut}"></ion-tab>
  <ion-tab [root]="tab2Root" [rootParams]="{rutValue: rut}" ></ion-tab>
</ion-tabs>

tab1Root js
constructor(..., private navParams : NavParams){
  var rut = navParams.get("rutValue");
}

More documentation about rootParams here: https://ionicframework.com/docs/api/components/tabs/Tab/
Let me know if this is what you wanted.

A: If you do not wish to go to the page you send your data to a shared service by creating a provider and get the data wherever you want
Create a provider using the cli command,
ionic g provider providerName

Store your value in your provider.ts like this,
import { Injectable } from '@angular/core';

@Injectable()
export class Provider {
  public addedItems:any;
  constructor() {
  }
  addedItems(data) {
    return this.addedItems=data;
  }
}

and import this provider in your component.ts to retrieve the added value. This way you can send data to other pages without opening any pages. Hope that helps


text:
Q: Python: Code string to shorter meaningless string in reversible way I'm sorry for the generic question (I don't have any past knowledge about compression and I don't know if it has a possible solution).
I have some codes of always 19 characters.
These characters can be only: A-Z, a-z, 0-9, ., :, -
An example can be something like 1995AbC...123..456Z
What I want to do is to find a way to convert in a reversible way that string to a shorter one that contains only ascii characters: something like gfSDd2H.

*

*Is it possible?

*Is there a way to do it in python?

Thanks!

A: You can try to compress the string and the encode the result to for example base64. This of course assumes that your original strings are compressible. For strings of 19 characters this seems unlikely.
If you are allowed to persist some data you can compress the first string to 1, the second to 2, etc... and you will need to store the mapping you made in for example a database so that you can reverse it. You can then encode the number as a base 64 (or some other base) string.
This is similar to how URL shortening services work.

A: You allow 65 different characters. Assuming all inputs have the same probability, every encoding would produce not less than 19*65/128 ≈ 10 characters. However, since you probably want to ignore unprintable characters, this is diminished to 19*65/95=13 characters with a perfect mapping. Therefore, any such mapping will not lead to a significant reduction in space.

A: Of course (?) it's possible in Python. All you would be doing is converting a base-65 number into a base-95 or base-94 number, and back again. It's just that it would be a bit slow, and as pointed out in another answer, you wouldn't be saving much space
Here (untested) are the basic building blocks:
def ttoi(text, base, letter_values):
    """converts a base-"base" string to an int"""
    n = 0
    for c in text:
        n = n * base + letter_values[c]
    return n

def itot(number, base, alphabet, padsize):
    """converts an int into a base-"base" string
       The result is left-padded to "padsize" using the zero-value character"""
    temp = []
    assert number >= 0
    while number:
        number, digit = divmod(number, base)
        temp.append(alphabet[digit])
    return max(0, padsize - len(temp)) * alphabet[0] + "".join(reversed(temp))

Definitions for e.g. your existing base-65 code:
b65_letter_values = {
    'A': 0, 'Z': 25, 'a': 26, 'z': 51, '0': 52, '9': 61,
    # etc
    }
b65_alphabet = "ABCetcXYZabcetcxyz0123456789.:-"
b65_padsize = 19


text:
Q: Pass objects to application from HttpModule Is there a way to create objects in HTTP module and pass those objects to applications.
I can use HTTPContext.Items.  But that means I will reference System.Web in any DLL in the application that will use those data.  Utility.dll is reading data generated by the http module, and I don't want to reference System.Web in that DLL because it is used by both web and desktop applications.
of course Desktop applications will not find the object, this is not a problem.

A: You can use the new and extensible cache API in System.Runtime.Caching, namely, the MemoryCache class. Just use a shared constant as the name and you're done.

A: I think your web module should communicate with Utility.dll and not the other way around. It should call a function inside Utility.dll with the data it needs. Since we don't know much about the nature of your application and that you didn't provide much information about how you want your different modules to communicate, it hard to give a definite answer.
The Utility.dll module could have a method accepting data like
public void QueueProcessingData(YourDataType[] data) {/* ... */}
If you really want your Utility.dll module to pull data from the web server, then you could use the builtin cache like @Ricardo Peres said. Example of using the builtin MemoryCache:
var data = "object your web module created and you want to pass to utility.dll";
ObjectCache cache = MemoryCache.Default;
cache.Add("The name you want", data, new CacheItemPolicy { AbsoluteExpiration = DateTime.MaxValue });

That way your other modules don't have to reference System.Web

A: HttpContext.Items is an IDictionary, so you can avoid a System.Web dependency in your common code by depending on that abstraction:
Utility.dll
class Util
{
    static void DoStuff(IDictionary environment) { ... }
}

App.dll
class App
{
    void DoStuff()
    {
        Util.DoStuff(new Hashtable { { "Foo", "Bar" } });
    }
}

Web.dll
class MyModule : IHttpModule
{
    void Init(HttpApplication context)
    {
        Util.DoStuff(context.Context.Items);
    }
}

A: Thanks to @user1429080.  it is kind of simple DI pattern.
Add an interface to Util.dll.
Add a reference to it in class Util add a property to access it.
The interface is implemented in WebUtil.dll.  WebUtil is referencing System.Web.
In HttpModule.Init() I assign the implementation to the interface.
Util class is using the interface to read data generated from HttpModule instead of accessing System.Web.
Now I can have another source of data by creating another implementation for the interface.


text:
Q: Cubism.JS threshold scale doesn't work I'm using cubism with data coming from graphite
The data's domain is continuos [0,100] and the range is continuos [0,100] but anything below 100 is nonsense so I modified the scale and used a threshold scale so that:
values < 100 will be 0 and 100 will be 100. I tested that with:
var scale = d3.scale.threshold().domain([100]).range([0,100])

console.log(scale(1)) //returns 0
console.log(scale(99.9)) //returns 0
console.log(scale(88.9)) //returns 0
console.log(scale(100)) //returns 100

When I apply it, it the whole chart becomes empty
.call(context.horizon().height(100)
    .colors(colors)
    .scale(d3.scale.threshold().domain([100]).range([0,100])) // range([0,1]) doesn't work either
);

without applying the scale (notice the small white area)
    .call(context.horizon().height(100)
    .colors(colors)
    // .scale(d3.scale.threshold().domain([100]).range([0,100])) // range([0,1]) doesn't work either
);

A: Scale didn't work so I used graphite's functions
specifically I used
removeAboveValue(keepLastValue(xxx),99.99999)


text:
Q: Degenerate typeclass instance declaration using constant value I've reduced everything down to the essentials, so bear with me if the example code below is contrived. Let's say we have:
class Foo a where
    foo :: a

data Type a = Type a

instance (Foo a) => Foo (Type a) where
    foo = Type foo

Now, suppose I want to make Type a an instance of, say, Show  whenever a is an instance of both Foo and Show (Show was chosen to avoid defining another typeclass). So how do we want Type a to be an instance of Show? Well, unless we're crazy, we'd of course want it to be something like
instance (Foo a, Show a) => Show (Type a) where
    show (Type x) = show x

or maybe
instance (Foo a, Show a) => Show (Type a) where
    show (Type x) = "Blabla " ++ (show x)

That's all great and works fine. For some inexplicable reason, we'd like show to output whatever foo :: a looks/shows like! In our contrived setting I cannot imagine why we'd want that, but let's say we do. Shouldn't
instance (Foo a, Show a) => Show (Type a) where
    show _ = show foo

do the trick?
Alas, GHC says

Ambiguous type variable 'a' in the
  constraints: 'Foo a' [...] 'Show a'

Maybe GHC can't figure out which foo I'm talking about. Do I mean foo :: Type a or foo :: a? Changing the previous snippet to
instance (Foo a, Show a) => Show (Type a) where
    show _ = show (foo :: a)

gives me

Could not deduce (Foo a1) from the
  context ()
        arising from a use of 'foo' at [...]
      Possible fix:
        add (Foo a1) to the context of an expression type signature
      In the first argument of 'show', namely '(foo :: a)'
      In the expression: show (foo :: a)

At this point I'm starting to think I've misunderstood something basic. Yet, I have the strange feeling that similar constructions have worked for me in the past.

A: I think the problem is that type variables aren't scoped to definitions. That is, in
instance (Foo a, Show a) => Show (Type a) where
    show _ = show (foo :: a)

a in the second line is different from a in the first line, which is why it's shown as a1 in the error message. See http://www.haskell.org/haskellwiki/Scoped_type_variables. If this is the problem, this should work (I don't have GHC on this machine):
asTypeOf :: a -> a -> a
asTypeOf a b = a

instance (Foo a, Show a) => Show (Type a) where
    show (Type x) = show (foo `asTypeOf` x)


text:
Q: CS50 Recover (Pset4)- Images not Recovered So I'm trying CS50 Recover exercise (where you need to search for jpg files in a memory card and whenever you find one- you open a new file and write the jpg found to the new file).
My code compiles but when I'm running the check50 command I'm receiving the following errors:
:( recovers 000.jpg correctly
    recovered image does not match
:( recovers middle images correctly
    recovered image does not match
:( recovers 049.jpg correctly
    recovered image does not match

Can somebody help me figure out what am I doing wrong?
This is my code:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
// Checking if the user entered a correct input:
    if (argc!=2)
    {
        printf("You're not using it correctly!\n");
        return 1;
    }

// Opening the file in argv[1]
    FILE *f=fopen(argv[1], "r");

// Validating that there's a file in argv[1]
    if(f==NULL)
    {
        printf("File hasn't found\n");
        return 1;
    }

    unsigned char bytes[512];
    int counter=0;
    FILE *img= NULL;

    while (fread(bytes, 512, 1, f)==1)
    {
        if (bytes[0]==0xff && bytes[1]==0xd8 && bytes[2]==0xff && (bytes[3]&0xf0)==0xe0)
        {
            // If it's the first jpg found:
            if (counter==0)
            {
                img=fopen("000.jpg", "w");
            }
            else
            {
                fclose(img);
                char filename[8];
                sprintf(filename,"%03i.jpg", counter);
                img= fopen(filename, "w");
                if (img==NULL)
                {
                    printf("Couldn't open file\n");
                    return 1;
                }
            }
            counter++;
            fwrite(bytes, 512, 1, img);
        }
    }
    fclose(img);
    fclose(f);
}

A: Your primary problem is that you are not handling multiblock files correctly.
You only do the fwrite if the current block has the header. Otherwise, you are throwing away the data.
That's because the fwrite is inside the if block that detects the header.
If you have encountered the first (i.e. any) header, you will have an open output stream. Therefore, after that, you have to do the fwrite on each loop iteration.

Since you set img to NULL before entering the outer loop, there is no need to special case the 000.jpg
And, if the input file did not have a header [ever], the final fclose would segfault because the img pointer would be NULL.

I've annotated the bugs [with fixes]. I've wrapped the old/new code if #if 0 blocks:
#if 0
// old/original code
#else
// new/refactored code
#endif

Here's the code:
#include <stdio.h>
#include <stdlib.h>

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

    // Checking if the user entered a correct input:
    if (argc != 2) {
        printf("You're not using it correctly!\n");
        return 1;
    }

    // Opening the file in argv[1]
    FILE *f = fopen(argv[1], "r");

    // Validating that there's a file in argv[1]
    if (f == NULL) {
        printf("File hasn't found\n");
        return 1;
    }

    unsigned char bytes[512];
    int counter = 0;
    FILE *img = NULL;

    while (fread(bytes, 512, 1, f) == 1) {
        if (bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff &&
            (bytes[3] & 0xf0) == 0xe0) {
// NOTE/BUG: no need to special case the first file
#if 0
            // If it's the first jpg found:
            if (counter == 0) {
                img = fopen("000.jpg", "w");
            }
            else {
                fclose(img);
#else
            if (img != NULL)
                fclose(img);
#endif
                char filename[8];

                sprintf(filename, "%03i.jpg", counter);
                img = fopen(filename, "w");
                if (img == NULL) {
                    printf("Couldn't open file\n");
                    return 1;
                }
#if 0
            }
#endif
            counter++;

// NOTE/BUG: this is only executed if the current block has a header string
#if 0
            fwrite(bytes, 512, 1, img);
#endif
        }

// NOTE/FIX: this is the correct placement for the write
#if 1
        if (img != NULL)
            fwrite(bytes, 512, 1, img);
#endif
    }

// NOTE/BUG: if the input file had _no_ header, img will be NULL
#if 0
    fclose(img);
#else
    if (img != NULL)
        fclose(img);
#endif
    fclose(f);
}

Here's the fully cleaned up and refactored code [without the #if 0]:
#include <stdio.h>
#include <stdlib.h>

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

    // Checking if the user entered a correct input:
    if (argc != 2) {
        printf("You're not using it correctly!\n");
        return 1;
    }

    // Opening the file in argv[1]
    FILE *f = fopen(argv[1], "r");

    // Validating that there's a file in argv[1]
    if (f == NULL) {
        printf("File hasn't found\n");
        return 1;
    }

    unsigned char bytes[512];
    int counter = 0;
    FILE *img = NULL;

    while (fread(bytes, 512, 1, f) == 1) {
        if (bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff &&
            (bytes[3] & 0xf0) == 0xe0) {
            if (img != NULL)
                fclose(img);
            char filename[8];

            sprintf(filename, "%03i.jpg", counter);
            img = fopen(filename, "w");
            if (img == NULL) {
                printf("Couldn't open file\n");
                return 1;
            }
            counter++;
        }

        if (img != NULL)
            fwrite(bytes, 512, 1, img);
    }

    if (img != NULL)
        fclose(img);
    fclose(f);
}


text:
Q: Open source column-oriented storage engine for PostgreSQL? Are there any open source projects in the works to create a column-oriented storage engine for PostgreSQL? I know Yahoo created one in-house, and that there are commercial products built on PostgreSQL that are column-oriented.

A: The lack of responses here and my own research seems to indicate that there are indeed no open source initiatives to add column storage to PostgreSQL.
There was some talk in 2008 about Yahoo possibly outsourcing Everest (their column store back end for PostgreSQL), so here's hoping that they'll release it.

A: Greenplum has created a column-oriented storage engine for PostgreSQL.

A: Citus Data has developed an open source columnar store extension for PostgreSQL. It is available under the Apache License v2.0. It supports PostgreSQL 9.3 and higher.
First, creation the extension and a foreign server:
CREATE EXTENSION cstore_fdw;

CREATE SERVER cstore_server FOREIGN DATA WRAPPER cstore_fdw;

Next, create some foreign tables:
CREATE FOREIGN TABLE customer_reviews
(
    customer_id TEXT,
    review_date DATE,
    review_rating INTEGER,
    review_votes INTEGER,
    review_helpful_votes INTEGER,
    product_id CHAR(10),
    product_title TEXT,
    product_sales_rank BIGINT,
    product_group TEXT,
    product_category TEXT,
    product_subcategory TEXT,
    similar_product_ids CHAR(10)[]
)
SERVER cstore_server
OPTIONS(filename '/opt/citusdb/3.0/cstore/customer_reviews.cstore',
        compression 'pglz');

Finally, COPY data into the table:
COPY customer_reviews FROM '/home/user/customer_reviews_1998.csv' WITH CSV;

Foreign tables can be queried like any other table. You can even join them with regular tables.
More examples and information are available in a related blog post and the project's home page.

A: I was looking for the same kind of extension/implementation while I was playing with monetDB.
After finding cstore_ftw from Citus Data I came into this post from monetDB: https://www.monetdb.org/content/citusdb-postgresql-column-store-vs-monetdb-tpc-h-shootout

Since cstore_ftw is using PostgreSQL's volcano-style query processor,
  we immediately suspected that this component would be the limiting
  factor to its performance.

I have not tested myself but (IMO) MonetDB are serious with their stuff.
I think it will be perfect if MonetDB creates an extension/implementation for PostgreSQL. Right now I still working with monetDB while looking for new features on PostgreSQL.


text:
Q: data range for pvlib forecast modules I am wondering if it is possible to specify the time range for past data in  GFS, NAM, RAP, HRRR, and the NDFD forecasting models! the current option is recalling data for the present daya as stated here
`start = pd.Timestamp(datetime.date.today(), tz=tz)`
    end = start + pd.Timedelta(days=7)

A: The source code for the model.get_data() function indicates yes. The only stipulation is that the start and end arguments  must be datetime or timestamp datatypes to be compatible with the netcdf2pandas library


text:
Q: Split contents of a directory into multiple sub directories I have a directory which contain more than thousand images. I want to split the files in to multiple sub directories, each containing 100 files. How do I do this?

A: the following worked well for me. Open the directory in terminal, and just copy & paste the following script, press enter. sub directories will be created inside having names dir_001, dir_002 and so on.
i=0;
for f in *;
do
    d=dir_$(printf %03d $((i/100+1)));
    mkdir -p $d;
    mv "$f" $d;
    let i++;
done

A: Move fixed number of files using array with range and offset.
#!/bin/bash

shopt -s nullglob

a=(./src/*)
for ((i=0; i<${#a[@]}; i+=100)); do
    printf -v b ./img_%03d $((++n))
    mkdir -p $b && mv -t $b "${a[@]:$i:100}"
done

A: This will prompt you with how many directories you want and the sub-directory prefix.
The ls command is just a reminder of how many files you've got.
ls -1 | wc -l

read -p 'How Many Directories: ' F;
read -p 'Sub-Directories Prefix: ' S;

PARRENT=${PWD}
# cd $PARRENT
n=0
for i in *
do
  if [ $((n+=1)) -gt $F ]; then
    n=1
  fi
  todir=$PARRENT/"$S"_$n
  [ -d "$todir" ] || mkdir "$todir"
  mv "$i" "$todir"
done

Source: https://www.unix.com/shell-programming-and-scripting/248539-split-folder-huge-number-files-n-folders.html


text:
Q: Spring boot jpa data using wrong database I have a spring boot app, it pulls in a jar which has two database configs, both mysql db's.  Both databases look to be starting up correctly in the logs, but are not uniquely identified.  It looks like default is registered and then reregistered so it appears to overwrite.
2017-07-19 10:24:16,817 INFO  DriverManagerDataSource - Loaded JDBC driver: com.mysql.jdbc.Driver [tx-id=]
2017-07-19 10:24:16,937 INFO  LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'default' [tx-id=]
2017-07-19 10:24:16,947 INFO  LogHelper - HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...] [tx-id=]
2017-07-19 10:24:16,991 INFO  Version - HHH000412: Hibernate Core {5.0.12.Final} [tx-id=]
2017-07-19 10:24:16,992 INFO  Environment - HHH000206: hibernate.properties not found [tx-id=]
2017-07-19 10:24:16,993 INFO  Environment - HHH000021: Bytecode provider name : javassist [tx-id=]
2017-07-19 10:24:17,021 INFO  Version - HCANN000001: Hibernate Commons Annotations {5.0.1.Final} [tx-id=]
2017-07-19 10:24:17,379 INFO  Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect [tx-id=]
2017-07-19 10:24:17,593 WARN  RootClass - HHH000038: Composite-id class does not override equals(): com.example.EmployeeGroupEntity$EmployeeGroupId [tx-id=]
2017-07-19 10:24:17,593 WARN  RootClass - HHH000039: Composite-id class does not override hashCode(): com.example.EmployeeGroupEntity$EmployeeGroupId [tx-id=]
2017-07-19 10:24:17,943 INFO  LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'default' [tx-id=]
2017-07-19 10:24:17,970 INFO  DriverManagerDataSource - Loaded JDBC driver: net.sourceforge.jtds.jdbc.Driver [tx-id=]
2017-07-19 10:24:17,972 INFO  LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'default' [tx-id=]
2017-07-19 10:24:17,972 INFO  LogHelper - HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...] [tx-id=]
2017-07-19 10:24:18,370 INFO  Dialect - HHH000400: Using dialect: org.hibernate.dialect.SQLServerDialect [tx-id=]
2017-07-19 10:24:18,389 INFO  LobCreatorBuilderImpl - HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4 [tx-id=]
2017-07-19 10:24:18,394 WARN  RootClass - HHH000038: Composite-id class does not override equals(): com.example.EmployeeGroupEntity$EmployeeGroupId [tx-id=]
2017-07-19 10:24:18,394 WARN  RootClass - HHH000039: Composite-id class does not override hashCode(): com.example.entity.EmployeeGroupEntity$EmployeeGroupId [tx-id=]
2017-07-19 10:24:18,405 WARN  EntityManagerFactoryRegistry - HHH000436: Entity manager factory name (default) is already registered.  If entity manager will be clustered or passivated, specify a unique value for property 'hibernate.ejb.entitymanager_factory_name' [tx-id=]

I have two classes for configuring the database connections, both of these are located in the imported jar, basically a common library.
@Configuration
@EnableTransactionManagement
@PropertySource(value = { "classpath:/${app.execution.environment}/application.properties" })
@EnableJpaRepositories(basePackages = "com.example", entityManagerFactoryRef = "mysqlEntityManager", transactionManagerRef = "mysqlTransactionManager")
@EntityScan(basePackages = { "com.example" })
public class MysqlHibernateConfig {
// beans configured here marked with @Primary
...
}

and
 @Configuration
    @EnableTransactionManagement
    @PropertySource(value = { "classpath:/${app.execution.environment}/application.properties" })
    @EnableJpaRepositories(basePackages = "com.example.another_package", entityManagerFactoryRef = "mysqlEntityManager2", transactionManagerRef = "mysqlTransactionManager2")
    @EntityScan(basePackages = { "com.example.another_package" })
    public class MysqlHibernateConfig2 {
    ...
    }

I try to get data from each database through classes like this:
@Transactional("mysqlTransactionManager") // workspace complains about not being able to find this bean
@Service
public class PriceService {
}

@Transactional("mysqlTransactionManager2") // workspace complains about not being able to find this bean
    @Service
    public class PriceService2 {
    }

PriceService gets data just fine, but PriceService2 tries to get data from mysqlTransactionManager instead of from mysqlTransactionManager2.
I also have the following classes to run my boot app:
@Configuration
@ComponentScan(basePackages = "com.example")
public class WebMvcConfig extends WebMvcConfigurerAdapter {
//config stuff
}

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

How can I force one class to use a specific transaction manager/data source?  I have been trying various configs and as far as I can tell this is set up correctly.  If I put both of these datasource config classes into my spring boot app, I can connect to the correct datasources no problem.  But when I move them to an outside library it does not work.  I have to keep these in a common library because of the structure of my projects, two separate apps use this database config.
I do have the freedom to move the non primary db into my spring boot app if necessary, but that is not working either. Ends up with the same result.


text:
Q: SQL combine rows and create columns Sometimes the hardest thing is to know how to ask the right question, but I'm going to make an attempt.
I'm trying to figure out a SQL statement (I'm in Azure SQL) that will retrieve multiple rows, combine some of the columns and create new aliased column from other columns, all for each row returned from a larger select statement.
Clear as mud? Let me try to draw it out.
    Employees
    ------------
    employeeID  |  managerID | fname
     1                 5        Bill
     2                 5        John
     3                 6        Mary

ClassRegistration
-----------------
employeeID   |  classID
  1               25
  2               25
  1               27
  1               28
  2               30
  1               45
  1               55
  2               35

Classes
----------
classID  |   classStartDate
   25           7/1/2014
   27           7/14/2014
   28           7/28/2014
   30           7/11/2014
   35           8/1/2014
   45           8/1/2014

What I need to return is a table like this:
Employee fname  |  Last Class |  Upcoming Class
 Bill                 27              28
 John                 30              35

So I would need something like:  Select * Employees WHERE managerID = 5.
Then using that result set of all employees with specified managerID, return the last class and the next class in one row for each employee returned.
Also an employee may or may not have a last class and/or upcoming class.
I've seen many different ways to iterate through rows using temp tables, or combining with GROUP BY, etc.  But I just can't seem to wrap my head around what combination I need.

A: Better solution... use the over clause...
SELECT DISTINCT E.empId, E.managerid, e.fname,
                Max(lastclass.classStartDate) over(partition by e.empId) as lastClass,
                Min(nextClass.classStartDate) over(partition by e.empId) as nextClass
FROM [T_employees] E
INNER JOIN T_ClassRegistration CR on E.empId = CR.empid
LEFT JOIN T_Classes lastclass on CR.classid = lastclass.classid
                             and lastclass.classStartDate <= getdate()
LEFT JOIN T_Classes nextClass on CR.classid = nextClass.classid
                             and nextClass.classStartDate> getdate()
WHERE managerId = 5

A: This isn't the only way to solve it, but it's what came to my mind.  It requires two inner queries, one to obtain the last class and one to obtain the next class.
-- For testing the query, lets set hardcoded date.  Normally one might use GETDATE()
DECLARE @today DATE = '2014-07-16'

SELECT
  e.FName,
  (
    -- Get the class with the highest ClassStartDate which started before today
    SELECT TOP 1 c.ClassID
    FROM ClassRegistration cr
      INNER JOIN Classes c on c.ClassID = cr.ClassId
    WHERE cr.EmployeeID = e.EmployeeID
      AND c.ClassStartDate < @today
    ORDER BY ClassStartDate DESC
  ) AS LastClass,
  (
    -- Get the class with the lowest ClassStartDate which started after, or including, today
    SELECT TOP 1 c.ClassID
    FROM ClassRegistration cr
      INNER JOIN Classes c on c.ClassID = cr.ClassId
    WHERE cr.EmployeeID = e.EmployeeID
      AND c.ClassStartDate >= @today
    ORDER BY ClassStartDate ASC
  ) AS NextClass
FROM Employees e
ORDER BY FName

If you want to filter by employees which were registered in a previous class, then something like:
SELECT * FROM (
  SELECT
    e.FName,
    (
      -- Get the class with the highest ClassStartDate which started before today
      SELECT TOP 1 c.ClassID
      FROM ClassRegistration cr
        INNER JOIN Classes c on c.ClassID = cr.ClassId
      WHERE cr.EmployeeID = e.EmployeeID
        AND c.ClassStartDate < @today
      ORDER BY ClassStartDate DESC
    ) AS LastClass,
    (
      -- Get the class with the lowest ClassStartDate which started after, or including, today
      SELECT TOP 1 c.ClassID
      FROM ClassRegistration cr
            INNER JOIN Classes c on c.ClassID = cr.ClassId
          WHERE cr.EmployeeID = e.EmployeeID
            AND c.ClassStartDate >= @today
          ORDER BY ClassStartDate ASC
        ) AS NextClass
  FROM Employees e
) t
WHERE NextClass IS NOT NULL
ORDER BY FName


text:
Q: Excel formula do not update automatically I have created a simple excel formula to know what is the color of the font of the cell A1
Function GetFontColorIndex(elrango As Range) As Integer
        Application.Volatile
       GetFontColorIndex = elrango.Cells(1, 1).Font.ColorIndex
End Function

In excel-2010:
File > Options > Formulas > Workbook Calculation > Automatic is checked
In cell A1 I have a number, and in cell A3 I have
=GetFontColorIndex(A1)
but when I change the font of cell A1, the formula does not update automatically on cell A3. I have to click shift+F9 and then it works.
Any idea why is not showing the number of the font automatically?

A: As simoco has mentioned.
If you are using your 'udf' in Sheet1 then in the module associated with that sheet add the following:

If you just change the colour the formula does not update but as soon as you press enter or select another cell in the sheet it updates


text:
Q: Where can I read hints again? While driving, the game gives us some hints about the game in upper left corner of the screen.
I'm not accustomed to the game yet. So, I need full concentration when I drive and I don't have time to read the hints. And English is my second language, I need a little bit more time :-)
Can I see the hints again somewhere ?

A: From Kotaku:

You can read all of the game's recent notifications in the pause menu. Just pause the game, select "Brief" and flip down to both "Help" and "Notifications." Note that the option to read recent dialogue truncates the script, so if you find yourself missing what people are saying, turn on subtitles.


text:
Q: jQuery autocomplete, pass data-property of field autocomplete is located in I have a page with multiple autocomplete-fields. I'd need to pass some additional data of each field that autocomplete is attached to (e.g. "data-field-id="X")
Autocomplete is initialized with class "autocomplete". These autocomplete fields are generated dynamically.
Currently my code looks like this:
var autocompleteFields = $(".dynamic-fields.autocomplete");

// autocomplete data getter for necessary fields
if (autocompleteFields.length > 0) {
    autocompleteFields.autocomplete({
        source: function (request, response) {
            request.module = 'shared';
            request.page = 'get_autofill_data.php';
            $.ajax({
                url: "ajax.php",
                data: request,
                dataType: "json",
                type: "POST",
                success: function (data) {
                    response(data);
                }
            });
        },
        select: function (event, ui) {
            $(this).val(ui.item.value);
        }
    });
}

I would need to pass e.g. "data-field-id" -property in request.x of currently used field. Is this possible some how? I couldn't find a clear way to do this in the documentation..

A: Try this. It will work.
var autocompleteFields = $(".dynamic-fields.autocomplete");
if (autocompleteFields.length > 0) {
autocompleteFields.autocomplete({
    source: function (request, response) {
        request.module = 'shared';
        request.page = 'get_autofill_data.php';
        request.x = $(this)[0].element.attr('data-field-id')
        $.ajax({
            url: "ajax.php",
            data: request,
            dataType: "json",
            type: "POST",
            success: function (data) {
                response(data);
            }
        });
    },
    select: function (event, ui) {
        $(this).val(ui.item.value);
    }
});
}


text:
Q: How to start co-op in Halo MCC? I seem to have searched the menus everywhere, but I can't find how to start a co-op mode in Halo Master Chief Collection.
I only know Halo Reach, where it was under multiplayer > matchmaking > coop, or something like that. Here, I can only find versus modes in the multiplayer menu.
Thanks !

A: All you need to do is invite the player to your party & game (or just game). and they will be added in your roster.
Alternatively, they could just open up their roster menu, select you, and then select join.
Split screen co-op is simply press A on controllers that are involved(they must be on and connected) once you select the game to play.


text:
Q: Programmers that need a lot of "outside help" - is this bad? Is it kind of tacky or poor practice when programmers use an unusual amount of libraries/frameworks to accomplish certain tasks? I'm working with someone on a relatively simple programming project involving geolocation queries. The guy seems like an amateur to me. For the server software, this guy used Python, Django, and a bunch of other crazy libraries ("PostGIS + gdal, geoip, and a few other spatial libraries" he writes) to create it. He wrote the entire program in one method (in views.py, nonetheless facepalm), and it's almost unreadable.
Is this bad? Is this really tacky and amateurish? Am I the only minimalist out there these days?

A: In general that is considered good if the programmer has exposure to a multitude of libraries . if you can  do the task using an efficiently written algorithm already available in the library does it not save time and effort?.
But it would depend on the situation if the libraries and dependencies are to obscure and do not fit the design requirements or if the task can be done with a simple routine. Time saving is definitely a factor.

A: I'd rather people used existing, tried and tested, tooling to create things than going out and write everything from scratch, with the inherent risks of doing so, the extra time needed to test things we can know are tested by our suppliers if we buy it, etc. etc.

A: Using existing tools is good and recommended (actually, not using external tools is often a problem with junior programmers)
However, using to many such tools for a relatively small project may indicate that each tool is an overkill for what it is used for, and may lead to high integration overhead

A: Writing a program in one method: definitely bad (unless it's a trivial program, but I don't think that's what you mean).
Using lots of libraries: it depends.
There's a balance to be struck between re-inventing the wheel and doing zero work. If the attitude is "unless there's a library for [x], I'm not implementing it", that's certainly bad. Just keep in mind that the other extreme is (for example) "I know jQuery can do this in three lines, but I'm going to roll my own [y] functions".
Basically:

*

*Use frameworks and other abstractions where they significantly reduce effort and errors

*Don't use frameworks as a way to avoid learning about the thing they implement

*Don't use the lack of a framework as an excuse to avoid tackling a task

Otherwise you're (IMO) doing it wrong.

A: I absolutely agree. While I definatley lean towards 'reinventing the wheel' too often, there is a point where you've got to be able to think for yourself.
Most projects need a handful, at most, of well written and fitting libraries. If your project turns out to be little more than a collection of widgets and other people's code, it usually isn't very good.
There are... a few exceptions, but I'd rather not accept that.
Being aware of libraries and frameworks is good, but relying on them almost entirely, not a good sign in my experience.

A: I highly endorse the use of libraries and frameworks.  However, there is a limit where they are used because they exist, rather than because they are needed.  Use of several geo-spatial libraries leads me to believe they are being overused.
Of more concern to me is the unreadable nature of the code.  A few features I look for in good code:

*

*Clear easy to read code.  (A manager with minimal understanding of the language should be able to understand the code.)

*Small modules which are have one clear purpose and limited dependencies. (high cohesion and low coupling).

*Well formatted code which is easy to scan.

*Comments explaining what is being done where necessary.

*Limited duplication of code, no duplication of functionality.

*Consistent use of the languages standard libraries.

*Appropriate use of frameworks and libraries. (These should be project/organization standards.)

Unfortunately, there are a lot of developers who haven't leaned to value of the above factors.  No matter how complex the problem, it should be broken down into simpler components that are assembled into a solution.  Any components which remain complex should have a documented reason why it is done the way it is. (There should be a valid reason.)
EDIT: If the entire solution is less than 60 lines long, then it may be appropriate to do it in one method.  The source file should have several methods all of which are of a reasonable size.  If there are longer methods, it likely they need re-factoring.  I am concerned with the number of geo-spatial libraries being used for a simple problem.  (However, I have seen some simple problems for which the solution is very complex.)

A: Writing an entire program in one method is probably bad. That being said, utilizing tools that already exist can definitely help speed up development times. I hope I misinterpreted your wording as it seems to imply that Python or Django should be looked down upon as outside help. Both are extremely useful tools for developers. I think we can agree that for most cases, a developer who implements a linked list to use instead of using a provided standard is a bad idea. This can apply to more complex things as well, like TCP sockets, and maybe even GeoIP.
Agreed, sometimes when people incorporate external modules/libraries in a product things can get messy, especially when there are multiple modules and you start getting into dependency nightmares. These need to be managed appropriately, and yes, sometimes it is better to code things yourself. I wouldn't judge a developer on if they use "outside help", as much as how they use outside help and integrate it with the rest of the system.

A: One more thing to consider: is your colleague using the tool as a crutch to compensate for the fact that they don't understand the problem domain as well as they should? This could be a good opportunity to sit down with him/her to go over what tools they use, why, and get an idea of how they're looking to tackle the problem. Either they really don't know what they're doing and just throwing tools at the problem. Or if they do then that toolbox might be something you'd be interested in adding to your own set of tools.

A: How long was the single method?  If it was ten lines, that's a whole lot better than what this guy must have been writing:

At my previous job, we were porting a
  UNIX system to Windows NT using
  Microsoft VC++.
      A colleague of mine, that was in the process of porting his portion of
  the code, came
      to me, looking really upset.
Colleague: "Hey! I hate these
  Microsoft guys! What a rotten
  compiler! It only
          accepts 16,384 local variables in a function!"

(See http://www.rinkworks.com/stupid/cs_programming.shtml)

A: What design guidelines were given to this programmer before he/she started?
If you didn't lay any down, you are just as guilty as the programmer of creating more junk.


text:
Q: Sylvester-like criterion for semidefiniteness In Zhou's A Practical Guide To Quantitative Finance Interviews I see the following:

A symmetric matrix is positive semidefinite  if and only if all its upper left (or lower right) submatrices have nonnegative determinants.

I know that looking only at upper left submatrices (i.e, leading principal minors) is not enough to guarantee semidefinitess (see, e.g., this question).
I'm confused by Zhou's wording. I think it should read "all its upper left and lower right submatrices have nonnegative determinants". Is this a correct statement for semidefiniteness ?
I'm not good enough at linear algebra to come up with a proof.

A: The statement is false. As a simple counterexample, consider the matrix
$$
\pmatrix{0&0&0\\0&-1&0\\0&0&0}.
$$
It should be clear that all "leading" and "trailing" principal minors are zero and therefore non-negative. However, this matrix fails to be positive semidefinite.
For an arguably more interesting example, you can consider
$$
\pmatrix{
1&1&1&2\\
1&1&1&1\\
1&1&1&1\\
2&1&1&1
}.
$$


text:
Q: How to get value of filtered spreadsheets using google sheets api? i need to showing data from sheet based on user keyword.
i try using setBasicFilter to filter data.
Here example requestbody.
$query = [
        'requests' => [
            [
                'setBasicFilter' => [
                    'filter' => [
                        'range' => [
                            'sheetId' => 0,
                            'startColumnIndex' => 0,
                            'endColumnIndex' => 14,
                            'startRowIndex' => 0
                        ],
                        'sortSpecs' => [
                            [
                                'dimensionIndex' => 0,
                                'sortOrder' => 'DESCENDING'
                            ],
                            [
                                'dimensionIndex' => 2,
                                'sortOrder' => 'ASCENDING'
                            ]
                        ],
                        'filterSpecs' => [
                            [
                                'columnIndex' => 2,
                                'filterCriteria' => [
                                    'condition' => [
                                        'type' => 'TEXT_CONTAINS',
                                        'values' => [
                                            [
                                                'userEnteredValue' => 'input'
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ];

but, its only change view data on the spreadsheets, and response only return empty.
Do you have a solution for this problem?

A: I got the solution after seeing this issue Google Sheets API, Read Values by Filter
you can use foreach() than use if() to get data that you need to filter.
example :
foreach ($data['values'] as $key => $value) {

    if($value[2] === 'input') {

        // $key . $value
    }
}


text:
Q: Tkinter matplotlib - clear canvas and load second figure I need plot only last image on the Tkinter canvas.
I did lot of research here and tried multiple things but I am not successful. Somehow my code add the images to the bottom of original image.
I have tried canvas.destroy(), canvas.clear(), fig.clf(), fig.clear(), ax1.cla() etc but nothing worked for me.
What I want is clear the first image of REGION = 'NORTH AMERICA' and replace it with image of REGION = 'LATAM' data.
Instead this code is adding them to the bottom
import pandas as pd
from datetime import datetime
import tkinter as tk
from tkinter import ttk
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
from matplotlib.dates import DateFormatter

root=tk.Tk()

# ----------- REGION 1 PLOT -------------
data = {'SALES_MONTH':['01-Jan-21','01-Jan-21','01-Feb-21','01-Feb-21','01-Mar-21','01-Mar-21','01-Apr-21','01-Apr-21','01-May-21','01-May-21','01-Jan-21','01-Jan-21','01-Jan-21','01-Feb-21','01-Feb-21','01-Feb-21','01-Mar-21','01-Mar-21','01-Mar-21','01-Apr-21','01-Apr-21','01-Apr-21','01-May-21','01-May-21','01-May-21'],
'REGION':['NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM'],
'COUNTRY':['USA','CANADA','USA','CANADA','USA','CANADA','USA','CANADA','USA','CANADA','MEXICO','COSTA RICA','COLOMBIA','MEXICO','COSTA RICA','COLOMBIA','MEXICO','COSTA RICA','COLOMBIA','MEXICO','COSTA RICA','COLOMBIA','MEXICO','COSTA RICA','COLOMBIA'],
'QUANTITY':['1000','400','1000','400','1000','400','1000','400','1000','400','700','450','150','700','450','150','700','450','150','700','450','150','700','450','150']
}
df = pd.DataFrame(data)
print(df.head())

df = df[df['REGION']== 'NORTH AMERICA']

df = df[['SALES_MONTH', 'QUANTITY']]
df = df.groupby(['SALES_MONTH'], as_index=False)['QUANTITY'].sum()

print(df.head())
df['SALES_MONTH'] = pd.to_datetime(df['SALES_MONTH'])
df = df.set_index('SALES_MONTH').asfreq('MS')
df.dropna(inplace=True)
df.sort_values('SALES_MONTH',ascending=True)
print(df.head())

from statsmodels.tsa.filters.hp_filter import hpfilter
qtycycle , qtytrend = hpfilter(df['QUANTITY'], lamb=129600)
df['SALES_TREND'] = qtytrend
df['SALES_CYCLE'] = qtycycle
print(df.head())

x = df.index.to_numpy()
y = df['QUANTITY'].to_numpy()
y1 = df['SALES_TREND'].to_numpy()
y2 = df['SALES_CYCLE'].to_numpy()

date_form = DateFormatter("%y-%m")

fig = Figure(figsize=(16,7),dpi=100)
fig.tight_layout()

fig, (ax1,ax2,ax3) = plt.subplots(3)
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.6)
ax1.plot(x,y)
ax2.plot(x,y1)
ax3.plot(x,y2)
ax1.xaxis.set_major_formatter(date_form)
ax1.set_title('Sales Quantity')
ax2.xaxis.set_major_formatter(date_form)
ax2.set_title('Sales Trend')
ax3.xaxis.set_major_formatter(date_form)
ax3.set_title('Sales Cycle')

canvas = FigureCanvasTkAgg(fig, master = root)
canvas.draw()
canvas.get_tk_widget().pack(side = tk.TOP,fill = tk.BOTH, expand=1)

# ----------- REGION 2 PLOT -------------
data = {'SALES_MONTH':['01-Jan-21','01-Jan-21','01-Feb-21','01-Feb-21','01-Mar-21','01-Mar-21','01-Apr-21','01-Apr-21','01-May-21','01-May-21','01-Jan-21','01-Jan-21','01-Jan-21','01-Feb-21','01-Feb-21','01-Feb-21','01-Mar-21','01-Mar-21','01-Mar-21','01-Apr-21','01-Apr-21','01-Apr-21','01-May-21','01-May-21','01-May-21'],
'REGION':['NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','NORTH AMERICA','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM','LATAM'],
'COUNTRY':['USA','CANADA','USA','CANADA','USA','CANADA','USA','CANADA','USA','CANADA','MEXICO','COSTA RICA','COLOMBIA','MEXICO','COSTA RICA','COLOMBIA','MEXICO','COSTA RICA','COLOMBIA','MEXICO','COSTA RICA','COLOMBIA','MEXICO','COSTA RICA','COLOMBIA'],
'QUANTITY':['1000','400','1000','400','1000','400','1000','400','1000','400','700','450','150','700','450','150','700','450','150','700','450','150','700','450','150']
}
df = pd.DataFrame(data)
print(df.head())

df = df[df['REGION']== 'LATAM']

df = df[['SALES_MONTH', 'QUANTITY']]
df = df.groupby(['SALES_MONTH'], as_index=False)['QUANTITY'].sum()

print(df.head())
df['SALES_MONTH'] = pd.to_datetime(df['SALES_MONTH'])
df = df.set_index('SALES_MONTH').asfreq('MS')
df.dropna(inplace=True)
df.sort_values('SALES_MONTH',ascending=True)
print(df.head())

from statsmodels.tsa.filters.hp_filter import hpfilter
qtycycle , qtytrend = hpfilter(df['QUANTITY'], lamb=129600)
df['SALES_TREND'] = qtytrend
df['SALES_CYCLE'] = qtycycle
print(df.head())

x = df.index.to_numpy()
y = df['QUANTITY'].to_numpy()
y1 = df['SALES_TREND'].to_numpy()
y2 = df['SALES_CYCLE'].to_numpy()

date_form = DateFormatter("%y-%m")

fig = Figure(figsize=(16,7),dpi=100)
fig.tight_layout()

fig, (ax1,ax2,ax3) = plt.subplots(3)
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.6)
ax1.plot(x,y)
ax2.plot(x,y1)
ax3.plot(x,y2)
ax1.xaxis.set_major_formatter(date_form)
ax1.set_title('Sales Quantity')
ax2.xaxis.set_major_formatter(date_form)
ax2.set_title('Sales Trend')
ax3.xaxis.set_major_formatter(date_form)
ax3.set_title('Sales Cycle')

canvas = FigureCanvasTkAgg(fig, master = root)
canvas.draw()
canvas.get_tk_widget().pack(side = tk.TOP,fill = tk.BOTH, expand=1)

root.mainloop()


text:
Q: Rspec tests fail in similar situations I have the following methods in my controller:
def create
  @user = User.new(params[:user])
    if @user.save
      redirect_to log_in_path, notice: 'Signed up!'
    else
      render "new"
    end
end

def destroy
  @user = User.find(params[:id])
  @user.destroy
    redirect_to users_path, notice: 'User was deleted.'
end

and specs:
describe "POST 'create'" do
  it "should allow create user" do
    @user = Factory(:user)
    post 'create', :id => @user
    response.should be_success
  end

describe "DELETE 'destroy'" do
  it "should delete the user" do
    @user = Factory(:user)
    delete "destroy", :id => @user
    response.should redirect_to users_path
  end
end

I don't understand why the test for create method is passing even if there is a redirect right after the object is saved. if i set:
  response.should redirect_to log_in_path

as expectation the test will fail, same for destroy method, if I switch expectation to:
response.should be_success

it will fail. Any suggestions?
Thanks

A: The actual response of your create action is 200 OK (even with your model being invalid and not saved) and that's what you are testing right now.
Other than that, your create test is no good. Create action takes user hash as param, not the user's id.
You probably want something like this:
  it "should allow create user" do
    @user = Factory.attributes_for(:user)
    post 'create', :user => @user
    @user.persisted?.should be_true
    response.should be_redirect
  end


text:
Q: Constant-Current for a 20W LED Can someone explain "constant-current" circuits?

*

*When are they necessary?

*What happens without one?

*What's the simplest version of such a circuit?

I bought some 20W LEDs off ebay intending to make a bike light.  "Simple," I thought, "The LED and my laptop battery are both 11Vdc, so I'll just connect them."
I haven't actually tried this, but an EE friend suggested that if I do so, it will draw too much current and burn out -- but he didn't know why; he doesn't do power electronics.

A: P = V * I.  In your case for the LED, P = 20 W, V = 11 V and therefor I = 1.82 A.
To drive the LED correctly you will need to limit the current to 1.82 A.  (you will also need to provide adequate heat sinking as 20 W is a lot of power to dissipate and most of it will be in the form of heat!!!! .... but that is another matter)
Diodes, using a PN junction have forward voltage drop, in your case that drop is 11 V.  When referring to the diode datasheet they will include a V I curve, this will relate how much current flows for a given voltage.  When you examine this curve you will notice that the current heads toward infinite for the given voltage drop.  If you allow this to happen, you diode will simply burn out.
The simplest method to limit the current is to use a resistor.  V = I * R.   For a given voltage drop, a fixed resistor will limit the current to a fixed amount.
Assuming you have a 18 V battery and an 11 V LED, the difference, 7 V will need to be dropped across the resistor.  This is fixed.  Also fixed is the desired current, of 1.82 A.   Rearranging the equation you get R = V / I => R = 3.8 ohm.  This resistor will need to be rated to a minimum of 12 W.  That is a large resistor that will get hot!!!!
The brings up the second issue - heat.  At a total of 32 W to dissipate, you will need some serious heatsinking.
You can probably do away with the resistor and replace it with a controlled current circuit based on transistor and or mosfets but I will leave that to someone else to answer.  The same issue of heat dissipation may still be present depending on the circuit design!!!
I know you mentioned you have an 11 V battery and an 11 V LED.  Unless the LED has built in current limiting circuit, or the battery has, it will be difficult to drive it at the same voltage (depending on the VI curve of the diode) without a boost converter.

A: *

*When you are using non-linear power device, like a LED. Other notable example are gas-discharge lamps & lasers.

*Something burns or explodes. LED or power supply. Or both :-)

*For 20W the only reasonable solution is constant-current DC-DC circuit, but it's not simple. Simplest solution is linear regulator with powerful BJT transistor, but this will dissipate at least 10W of heat. Simple resistor will not give you linear current, but acceptable in low-power cases (let's say for 0.1W).

A: Most LED control circuits just have a series resistor to control the LED current. This is OK if the supply voltage is more or less constant, but it the voltage varies so will the LED current and luminosity. If you want constant luminosity you also want constant current. This means that the series resistance must vary with supply voltage. This is about the simplest circuit for it:

This is a constant current source dimensioned for 1mA, which is too little for your application, but the principle remains the same. The base-emitter voltage of the transistor is 0.6V, so given that the zener creates a drop of 5.6V between \$V_+\$ and the transistor's base there remains 5V for the resistor. \$\dfrac{5V}{5k\Omega} = 1mA\$.
If your LED is 20W @ 11V then you need 1.8A of current, so I'll calculate the other components for this value. Replace the zener by 3 x 1N4148, this gives you a 0.6V drop over R1 (three diodes because we'll use a darlington, which has 2 x 0.6V between base and emitter). \$R1 = \dfrac{0.6V}{1.8A} = 0.33\Omega / 1W\$.
The TIP125 darlington transistor has an \$H_{FE}\$ of 1000, R2 should be \$\dfrac{10V}{1.8A / 1000} = 5k\Omega\$.
Since \$V_{CE(SAT)}\$ for the transistor is 2V, and you have an additional voltage drop over R1 of 0.6V, you'll need a 14V power supply to be sure that there's enough left for the LED!
The darlington will dissipate \$2V \times 1.8A = 3.6W\$, so you'll have to mount it on a heat sink.

a note on current sources:
  Current sources are the dual of voltage sources, which are more common; we use them all the time in power supplies. This duality means that certain parameters are each other's opposites.
  Whereas a voltage source will try to keep the voltage at its output constant regardless of the load, a current source will keep the output current constant regardless of the load. That means for a current source the output voltage will vary, like for a voltage source the current will be variable.
  An ideal voltage source will have zero output impedance, an ideal current source will have infinite output impedance. And while an ideal voltage source should never be short-circuited because the current will go to infinite, an ideal current source should never be left open, because the voltage which determines the set current will go to infinite.

A: If you want a simple constant current LED driver, on All About Circuits we've been designing one.
However, it's only rated to 1W. You'd probably need to upgrade the fet and driver to get it to run at 20W, the fet would also need heatsinking and you'd probably need a bigger inductor.

A: ad. 1)
Whenever you use power leds and don't want them to burn.
ad. 2)
The key is the heat-current interdependence. In short, when diodes heat up, their dynamic resistance decreases, which leads to further increase of current. Sort of a chain reaction. So if you fail to dissipate all the heat, your LED can easily burn.
Another thing, from end-user perspective, is that the amount of light emitted by LED is proportional to current and the current-voltage dependence is highly nonlinear. Thus, it is much harder to precisely control the brightness by controlling the voltage.
ad. 3)
The simplest, though inefficient way to do that is to connect a series resistor that will compensate some of the negative heat-current dependence of the LED. That is because for resistors, that dependence is opposite in direction (but not in shape). So you won't really have constant current, but your LED will be safer. For basic tests, you can also simply add a fuse to that to protect your LED.


text:
Q: User location details from azure-ad-b2c User Journey Context Provider We can can get the IPAddress of the user from User Journey Context Provider, but I need user location details. Is it possible to get the user location details ?

A: All claims resolvers are here:
https://learn.microsoft.com/en-us/azure/active-directory-b2c/claim-resolver-overview
You cannot resolve their location/city etc. You can ask the user for their location instead:
https://learn.microsoft.com/en-us/azure/active-directory-b2c/configure-user-input?pivots=b2c-custom-policy
Or resolve the IP to a location using your own REST API:
https://learn.microsoft.com/en-us/azure/active-directory-b2c/custom-policy-rest-api-claims-exchange?pivots=b2c-custom-policy


text:
Q: Convert Mac Address Generation from SQL to C# I am converting an app from using stored procedures to using Entity Framework 6. I ran across a stored procedure that is generating the next Mac Address in a sequence.
Here is the SQL:
SELECT
    @macAddress = SUBSTRING(CONVERT(CHAR(8), CONVERT(VARBINARY(3), 1234567), 1) + SUBSTRING(CONVERT(CHAR(8), CONVERT(VARBINARY(3), @nextMacAddressValue), 1), 3, 6), 3, 12)

@nextMacAddressValue is just an incrementing number, let's say it's 21 for this example.
I am looking for help in converting this over to C#

A: It can't be random.  It needs to start with the first six values and then increment sequence after that.  This did the trick.
var macAddress = String.Concat(1234567.ToString("X").PadLeft(6, '0'), int.Parse(nextMacAddressParameter.Value).ToString("X").PadLeft(6, '0'));

A: The key here is maybe to not focus on how they did it exactly
If you just want a random Mac address, you can apply the solution in
Generate a random mac address


text:
Q: Select Value by Max Date I have a table in a PostgreSQL database with data like:
id  customer_id   item       value     timestamp

 1  001           price       1000     11/1/2021
 2  001           price       1500     11/2/2021
 3  001           condition   good     11/3/2021
 4  002           condition   bad      11/4/2021
 5  002           condition   good     11/5/2021
 6  002           price       1000     11/6/2021
 7  001           condition   good     11/7/2021
 8  001           price       1400     11/8/2021
 9  002           price       1500     11/9/2021
10  001           condition    ok      11/10/2021
11  002           price       1600     11/11/2021
12  002           price       1550     11/12/2021

From this table, I want to query the latest value by date and convert it to a table as below.
customer_id   price   condition
   001        1400      ok
   002        1550     good

To get this kind of table I tried with this below query, but it did not work well when there are too much data. (Operation like Min and Max to text and number)
I tested this in pgAdmin 4:
SELECT customer_id,
MAX (Case WHEN item='price' THEN value END) price,
MAX (Case WHEN item='condition' THEN value END) condition

FROM table_name GROUP BY customer_id

I want to query the value by the latest date updated data.

A: Your relational design might be improved. It's an anti-pattern to mix different types of data in the same column.
While stuck with the given setup, two subqueries with DISTINCT ON and a FULL OUTER JOIN do the job:
SELECT customer_id, p.value AS price, c.value AS condition
FROM  (
   SELECT DISTINCT ON (customer_id)
          customer_id, value
   FROM   tbl
   WHERE  item = 'condition'
   ORDER  BY customer_id, timestamp DESC
   ) c
FULL JOIN (
   SELECT DISTINCT ON (customer_id)
          customer_id, value
   FROM   tbl
   WHERE  item = 'price'
   ORDER  BY customer_id, timestamp DESC
   ) p USING (customer_id)

db<>fiddle here
See:

*

*Select first row in each GROUP BY group?
This assumes timestamp to be defined NOT NULL, or you'll want NULLS LAST.
Depending on undisclosed cardinalities and value distribution, there may be (much) faster query variants.
If there is a customer table with distinct customer_id, (much) faster query styles become possible.
These partial, multicolumn indexes would be perfect to make it fast in any case:
CREATE INDEX tbl_condition_special_idx ON tbl (customer_id, timestamp DESC, value) WHERE item = 'condition';
CREATE INDEX tbl_price_special_idx     ON tbl (customer_id, timestamp DESC, value) WHERE item = 'price';

See:

*

*Optimize GROUP BY query to retrieve latest row per user

A:  SELECT X.CUSTOMER_ID,X.PRICE,X.CONDITION
 FROM
 (
      SELECT A.CUSTOMER_ID,A.PRICE,A.CONDITION,
       ROW_NUMBER()OVER(PARTITION BY A.CUSTOMER_ID ORDER BY A.TIMESTAMP DESC)XCOL
  FROM YOUR_TABLE A
 )X WHERE X.XCOL=1

Could you please try if the above is suitable for you


text:
Q: Multiple hypothesis testing of same hypothesis I read an interesting statement: running the same data through multiple tests no longer counts as multiple comparisons.
I am fairly confident this is incorrect if you are testing different hypotheses e.g. testing for hundreds of different lags on the same data will yield some false significant results (if you have enough data to test for large lags).
However, if you are testing exactly the same hypothesis, but with two different tests, is this still a multiple comparison?
My thinking so far is that firstly it is rarely if ever true that two tests have exactly the same null hypothesis. e.g. the Shapiro-wilk test and Jarque–Bera test, while both ostensibly "normality tests" are testing slightly different null hypotheses, that the data came from a normal distribution and that the data cam from a distribution with skew and kurtosis equal to a normal distribution. Are there any tests with exactly the same null hypothesis?
If there are tests that against exactly the same null hypothesis, would this count as a multiple comparison? And if the tests have exactly the same null hypothesis, is it possible for them to yield different results given the same data?


text:
Q: Display api json data as ionic accordion I have to display the api json data(nested object response) as an ion-accordion. How can I achieve it?
Below is the code of the component.ts and service file
component.ts code:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
  selector: 'app-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.scss']
})
export class ViewComponent implements OnInit {

  users: any = [];
  constructor(private userdata: DataService) { }

  ngOnInit() {
    this.userdata.get().subscribe(data =>{
      this.users = [data];
      console.log(this.users);
    });
  }

}

service code:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private http: HttpClient) { }

  get():Observable<any>{
    return this.http.get<any>(' ');
  }
}

A: It will depend on how "this.users" is formated. But you can use *ngFor to create your accordion.
For example if in your TS file you have users data :
users = [{name: 'Michel', isPremium: true}, {name: 'Jean', isPremium: true}, {name: 'John', isPremium: false}];

In your HTML file :
<ion-accordion-group>
 <ion-accordion *ngFor="let user of users">
   <ion-item slot="header">
     <ion-icon slot="start" name="star-outline" *ngIf="user.isPremium === true"></ion-icon>
    <ion-label>{{user.name}}</ion-label>
   </ion-item>

{{user.name}} is one of your user

 </ion-accordion>
</ion-accordion-group>


text:
Q: Is prefixing each field name in a table with abbreviated table name a good practice? Do you prefix each field in a table with abbreviated table name?
Example:
Table: User

Fields:
user_id
user_name
user_password

Or do you do you name your fields minimally?
Fields:
id
name
password

If you have used both, then which format you feel helped you most in the long run?
Edit: This question doesn't seem to have a definite answer and both side presents good points. But I have kept the question open for too long time and maybe it's time to mark one answer as accepted. I am therefore marking the highest voted one as accepted.

A: I wouldn't do it. If you want the information which table a field belongs to, you can always write your queries as
select user.id, user.name from user where ...

But imagine you decide for whatever reason to rename one of your tables (maybe  from 'user' to 'customer'). You would have to rename all fields as well, to remain consistent.
My opinion: There is no good reason why you should do it, and several good reasons not to do it.

A: Putting the prefix on column names can be a good practice. If you're working on a formal (and probably large) database and you're paying any attention to ISO 11179 (particularly the concept of data element names), then it's good to put the full three (or four) part name in: Object - Property - Representation Term. (The fourth optional part is a qualifier.) For example, "user_first_name". That way you have consistency between your data dictionary and the database schema. I wouldn't do this for smaller databases for the reasons already commented on, but in a complex schema this reduces some risk for error.

A: Don't do that. It's redundant and leads to frustration in the long run.
The only field, where you could apply this might be id, because user_id would obviously be the id of the user and it would simplify writing joins in SQL. But I wouldn't even do that.

A: We also don't use abbreviated table prefixes normally and I wouldn't advice it either.
There's however one situation where we do: reserve fields.
 e.g. OH_Reserve_Field_Alpha3 in table ORDER_HEADER

Short background: Our database has 250+ tables and we put in most of them reserve columns to use them for future feature implementations. As you can imagine, without prefixing you would end up having 50 Reserve_Field_Alpha3's with totally different meaning but same name throughout your code. It's already hard as it's now, but without prefixes it would be worse.

A: I'd recommend sticking with table aliases, like:
SELECT
    user.id,
    user.email,
    user.firstname,
    user.secondname,
    avatar.filename
FROM
    pain_in_the_butt_table_name user
LEFT JOIN
    table_with_the_avatars avatar
ON avatar.user_id = user.id

The advantages:

*

*maintaining an easily comprehendable list of fields you select, and which tables you take them from

*avoid typing long or hard to comprehend table names and replace them with a short and understandable name (which you should have done when creating the table)

*perform joins that are readable (your example would read:

LEFT JOIN table_with_the_avatars.user_id ON user.user_id = table_with_the_avatars.avatars_user_i

*

*create even shorter aliases, in my example that would mean u instead of user, and a instead of avatar, shortening your query

A: if you do it you will end up writing queries like:
SELECT user.user_name, user.user_password, user.user_firstname ...

instead of
SELECT user.name, user.password, user.firstname

so IMO the answer to your question is quite clear.

A: When I add the field "ordinal" to a table I like to add in a prefix so I don't have to alias ordinal fields from other tables in JOINS.
It's handy for JOINS sometimes... not sure I have seen other benefits.
MediaWiki (the Wikipiedia software) uses that convention. Download the source.
They limit themselves to a two character prefix.
I don't recommend the practice though. For most databases its not necessary.

A: It's ok to name fields that way(minimally), but for primary key and captions/name.  If you consistently name all your primary key as ID, and name as Name, constructing query will degenerate into superfluous aliases:
select i.id as invoice_id

v.id as vendor_id, p.id as product_id,
v.name as vendor, p.name as product, b.name as branch, c.name as parcel,

i.total_amount,
i.discount,
i.invoice_date

from invoice i
join product p on i.product_id = p.id
join vendor v on i.vendor_id = v.id
join branch b on i.branch_id = b.id
join parcel c on i.parcel_id = c.id

As joining tables and displaying the entity's caption/name is the norm rather than exception, I name my primary key in full form, and for caption/name field, the same name as table name.
create table product
(
product_id uuid not null, -- primary key
product text not null,
bar_code text not null default '',
rfid_code text  not null default '',
current_qty int default 0
);

create table vendor
(
vendor_id uuid not null, -- primary key
vendor text not null,
is_active boolean not null default true
);

create table branch
(
branch_id uuid not null, -- primary key
branch text not null,
sub_branch_of_id uuid,
current_sales money not null default 0,
);

create table user
(
user_id uuid not null, -- primary key
user text not null,
password text not null default ''
);

So your query won't have superfluous aliases:
select i.invoice_id, p.product_id, v.vendor, p.product, b.branch, c.parcel,

i.total_amount,
i.discount,
i.invoice_date

from invoice i
join product p on o.product_code = p.product_code
join vendor v on o.vendor_code = v.vendor_code
join branch b on o.branch_code = b.branch_code
join parcel c on o.parcel_code = c.parcel_code

A: Personally, on the 'user' table, my column would just be 'id'.
But any foriegn key columns on different tables pointing to that column, I'd call the column 'user_id'.
so you might end up with something like this :
select  *
from    order
        inner join user
            on user.id=order.user_id

A: You do not need to do it anymore, and you really should not. The only exception as saua pointed out could be the ID field for the seek of clarity of joins.
The concept of prefixing field names with the table name comes from the old time of legacy systems when each field across the whole database needed to be unique.
So unless you are dealing with legacy systems which require that each field across the whole database has unique name; do not do it.

A: For all the reasons given, I don't think this is a good idea. Besides, you don't prefix all the methods in your classes with the class names, do you? So why do it for database objects?

A: The prefix variant just takes longer to write and makes it harder to read sql statements with many fields.
Even when you are selecting from several tables, this gives you only the benefit of not having to prefix ambiguous fields with the table name. But
SELECT user.name, image.name FROM user, image

is not very different from
SELECT user_name, image_name FROM user, image

The benefit of havong no ambiguous fields in your queries is quickly eaten up by the overhead of having to type the table name each time you are using a column name.

A: It's an awesome practise:

*

*You see what every field means, at
least at what domain it is. You
can't figure out what amount means
(transactions, incomes) — unless
they are xac_amount and
inc_amount. Most query tools do
not output alias along with the
field name.

*You may use tables aliases, for
sure. But SQL does not require them,
and by Murphy's law, if it's not
required, it won't be used. There is
no standard, so one developer will
use x as an alias for
transaction, another one will use
tran and so on.

In fact, prefixes are just forced tables aliases, so you can easily see what field belongs to what table.

A: If you are using a UNIQUE PREFIX for each table, then

*

*No need to use an alias for joins (except self join)

*All the columns in the database should be unique in name

*You can easily identity the table from column name itself(from a
output or select query)


text:
Q: How do I make a mongoose schema with a set of more than one type? So I have a schema with people and groups. I want to make it possible for a person to be related to one or more people or groups. So far I have this:
var PersonSchema = new Schema({
    name    : String,
});
var PersonModel = mongoose.model('Person', PersonSchema);

var GroupSchema = new Schema({
    name    : String,
    members : [PersonSchema]
});
var GroupModel = mongoose.model('Group', GroupSchema);

How to add to PersonSchema a set of one or more groups and/or other people?

A: Assuming you have both Persons and Groups collections in your database based on this, you could add arrays of ObjectId refs to PersonSchema to capture a person's relationships with other people or groups.  As in:
var PersonSchema = new Schema({
    name    : String,
    people: [{ type: Schema.ObjectId, ref: 'Person' }],
    groups: [{ type: Schema.ObjectId, ref: 'Group' }]
});

Then you can use mongoose's populate support to follow those refs whenever you need their full details.

A: You can define like:
var Relation = new mongoose.Schema({
RelationType:String, RefObjId: String //You can also take Schema.ObjectId
});

var PersonObj = new mongoose.Schema({
name: String,
OtherDetails: String,
RefObjDetails:[Relation]
});

Example:
A (_id:100) Person is related to B (_id:200) Person and to group MyGroup (_id:333).
JSON will look like:
{
 '_id':'100',
 'name': 'A',
 'OtherDetails': '',
 'RefObjDetails':[{'RelationType':'P', RefObjId:'200'},{'RelationType':'G', RefObjId:'333'}]
}


text:
Q: Ошибка сегментирования Не могу понять, почему падает.
struct Z {int x; int y;};

void calc(void)
{
   // ...

   struct Z **z;
   struct Z z0 = {0, 0};

   *z = &z0;

   // ...
}

Вроде все ок?
A: Ты пишешь по адресу, хранящемуся в z адрес указателя на z0. Так как z не инициализирована, он пишет в какую-то случайную область памяти


text:
Q: Java: Alternative to passing "this" as constructor argument in order to reference creating object I've spent a while thinking about different solutions that the one I went for as I've read around (I am not really experienced with Java yet) that using this for a constructor argument isn't usually a good practice.
What I am trying to do is to instantiate several objects of class JobGroupMod and for every JobGroupMod I have to create a certain number of JobMod objects that must be able to reference back the JobGroupMod objects in which they've been spawned from.
In order to accomplish that I am passing "this" to the JobMod constructor but, even if working, it didn't feel like proper designing.
public class JobGroupMod implements JobGroup {

    public JobGroupMod(Node n,Set<Job> clusterJobs){
        JobMod j=new JobMod(n,this);
    }
}

And now the JobMod class:
public class JobMod implements Job {
     public JobMod(Node n, JobGroup jg){
         setJobGroup(jg);
     }
}

My question is, is there a better way of solving this, or is my solution the suggested way?

A: You should try using a static factory method (Effective Java link).
This way you avoid passing this in a constructor call, which is highly ill-advised to say the least.
example code:
public class JobGroupMod implements JobGroup {

    public static JobGroupMod createModeMod(Node n, Set<Job> clusterJobs) {
        JobGroup jg = new JobGroupMod();
        JobMod j = new JobMod(n, jg);
        return jg;
    }
}

A: As long as it remains the only thing you do in the JobGroupMod constructor is is fairly safe as long as you understand the ramifications. There's a lot of Java code in the real world that does this. It's still not something you really want to do, especially when you start talking about multithreading and concurrency.
The danger is passing this to something else before an object is fully constructed. If the constructor were to throw an exception after you did this and not fully construct, you could have a nasty problem. If another thread were to access the object you passed this to before it was fully constructed, you'd have a nasty problem.
What you'll often find in Java is people using a factory pattern to avoid this, an "init" type method, or dependency injection.

A: Generally there is no magic. You can either pass parameter via constructor or initalize it later using setter/init method etc.
If your class JobMod needs reference to JobGroupMod and has nothing to do without it pass it using constructor. If sometimes it can stand without it create init() method or setter that can initialize this reference.
BTW sometimes you have to create both parameterized and default constructor: first for regular programmatic usage, second if you are using XML, JSON or other serialization that is going easier for bean-like classes. In this case at least create javadoc that explains that default constructor should not be used directly.


text:
Q: How to disprove an equality involving a double integral I want to show that the following equality does not hold:
\begin{equation}\label{at3}
    \frac{\lambda^2-1}{2}x^2-\int_{-\infty}^{\infty}\!\!\int_{-\infty}^{\infty}K(y_1,y_2,x)\ln g(y_1,y_2)dy_2dy_1=\mbox{constant}\ \ ,\ \ \forall x\in\mathbb{R},
\end{equation}
where $\lambda>1$, and
\begin{equation}\label{at2}
    g(y_1,y_2)=\int_{-1}^{1}e^{-\frac{(\lambda^2-1)u^2}{2}+\lambda y_1u}\cosh\left(y_2\sqrt{1-u^2}\right)dF(u),
\end{equation}
in which $F(u)$ is an unknown cumulative distribution function (CDF) for $U$ with the support $[-1,1]$. It could be discrete or continuous or a mixture. Finally,
\begin{align}
    K(y_1,y_2,x)=e^{-\frac{(\lambda^2-1)}{2}x^2}e^{\frac{-y_1^2-y_2^2+2\lambda y_1x}{2}}\cos \left(y_2\sqrt{x^2-1}\right).
\end{align}
In order to show that the first equality is not valid, I tried to see the scaling behaviour of the double integral term in $x$. I think that the double integral term is at most $O(x)$, so that it cannot cancel the effect of the first term $\frac{\lambda^2-1}{2}x^2$. However, I was not successful.
I highly appreciate your help about this problem.


text:
Q: Using required_unless for array I do have 3 select ..
<select name="roles" id="roles" class="form-control" ng-model="newUserFormData.roles" multiple required>
    <option ng-repeat="role in roleList" value="<% role.id %>"><% role.name %></option>
</select>

<select name="sites" id="sites" class="form-control" ng-model="newUserFormData.sites" multiple>
    <option ng-repeat="site in siteList" value="<% site.id %>"><% site.name %></option>
</select>

<select name="projects" id="projects" class="form-control" ng-model="newUserFormData.projects" multiple>
    <option ng-repeat="project in projectList" value="<% project.id %>"><% project.name %></option>
</select>

Note:

*

*the Roles can be multiple .. is front-end required ..

*

*(1) - Admin (not included in the options)

*(2) - Lead

*(3) - Analyst

*(4) - Key Entry

*the Sites can be multiple .. not front-end required ..

*

*(1) - Loc 1

*(2) - Loc 2

*(3) - Loc 3

*the Projects can be multiple .. not front-end required ..

*

*(1) - Project 1

*(2) - Project 2

*(3) - Project 3

now my validator ..
protected function validatorName(array $data)
{
    return Validator::make($data, [
        'roles' =>  'required|array|min:1',
        'sites'  => 'required_unless:roles.*,in:2|required_unless:roles.*,in:3',
        'projects'  => 'required_unless:roles.*,in:2|required_unless:roles.*,in:3',
    ],[
        'sites.required_unless' => 'Site is required unless Lead or Analyst is selected as role.',
        'projects.required_unless' => 'Project is required unless Lead or Analyst is selected as role.',
    ]);
}

Problem:

*

*When I select either Lead/Analyst as the role, it is still requiring sites and projects when supposedly should not.

Request Payload:
  roles: ["3"],

*When I select Key Entry as the role, it is still requiring sites and projects even there are values.

Request Payload:
  projects: ["1"], roles: ["4"], sites: ["2"],

What am I missing ?


text:
Q: Identification as a substructure - injective homomorphism Quite often in mathematical literature the following type of statement is made, and the following is only an example:
Let $f\in K[X]$ be a separable polynomial of degree $n>0$ with splitting field $L$ over $K$. If $\alpha_1,...,\alpha_n\in L$ are roots of $f$, then
$\varphi\colon \mathrm{Gal}(L/K)\longrightarrow S(\{\alpha_1,...,\alpha_n\})\simeq\mathfrak{S}_n,\\
\sigma\mapsto\sigma|_{\{\alpha_1,...,\alpha_n\}}$
defines an injective group homomorphism from the galois group of $L/K$ into the group of permutations of $\alpha_1,...,\alpha_n$, such that we can identify $\mathrm{Gal}(L/K)$ as a subgroup of $\mathfrak{S}_n$.
(Excerpt of Siegfried Bosch - "Algebra" 8.ed. p.158)
We shall not worry about the proof here.
The important thing here is the injective homomorphism. More generally, if we have two algebraic structures $A,B$ and we have a structure conserving map $\varphi$ which is injective from $A$ to $B$, we can consider $A$ as a substructure of $B$, whatever this might be (field, group, ring,...).
I don't really know why we can identify $A$ as a substructure of $B$ nor what this even means, since it is not a real substructure. (Note, that I have written 'identify' in bold to emphasize that it is not a subgroup per definition)
Could somebody elaborate on this concept of identification as a substructure by having an injective homomorphism? What is it used for and what exactly is its meaning? It is not a substructure by definition, is it?

A: If we are given two structures $A$ and $B$ and an injective homomorphism $f: A \to B$, then, as a notational convenience, we can pretend that $A$ is actually a substructure of $B$, by agreeing that $x$ really means $f(x)$ if $x$ is an element of $A$ and we want an element of $B$. I.e., we use $f$ to identify elements of $A$ with their images in $B$.
A standard example is in the constructions of the number systems $\Bbb{N}$, $\Bbb{Z}$, $\Bbb{Q}$, $\Bbb{R}$ and $\Bbb{C}$. We pretend that the natural number $1$ is an integer and a rational and a real number and a complex number despite the fact that the multiplicative units in the standard constructions of $\Bbb{Z}$, $\Bbb{Q}$, $\Bbb{R}$ and $\Bbb{C}$ are all different.


text:
Q: Having one class using objects from another I have a class that I want to contain an object from another class CRandomSFMT (that I haven't written myself). This is test.h:
using namespace std;
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include "sfmt.h"

class Something {

    public:
    Something();

    private:
    int seed;
    CRandomSFMT rangen();
    void seed_generator(int, CRandomSFMT&);
};

and this is test.cpp:
#include "test.h"

Something::Something() {
    seed=1;
    seed_generator(seed, rangen);

}

void Something::seed_generator(int seed, CRandomSFMT& rangen) {
    rangen.RandomInit(seed);
}

When I try to compile this with g++ -c sfmt.o -msse2 -std=c++11 -O2 test.cpp I get
test.cpp: In constructor 'Something::Something()':
test.cpp:5:30: error: invalid use of non-static member function
   seed_generator(seed, rangen);

I tried to declare seed_generator() static but that didn't help. Here's the declaration of the class CRandomSFMT:
class CRandomSFMT {
public:
   CRandomSFMT(int seed, int IncludeMother = 0) {
      UseMother = IncludeMother;
      LastInterval = 0;
      RandomInit(seed);}
   void RandomInit(int seed);
   void RandomInitByArray(int const seeds[], int NumSeeds);
   int  IRandom  (int min, int max);
   int  IRandomX (int min, int max);
   double Random();
   uint32_t BRandom();
private:
   void Init2();
   void Generate();
   uint32_t MotherBits();
   uint32_t ix;
   uint32_t LastInterval;
   uint32_t RLimit;
   uint32_t UseMother;
   __m128i  mask;
   __m128i  state[SFMT_N];
   uint32_t MotherState[5];
};

Any ideas?

A: You're declaring a function, not an object:
CRandomSFMT rangen();

Since you're trying to use it as an object is should be like this:
CRandomSFMT rangen;

A: You've declared rangen to be a function; the error is because you try to use it like an object.
From your desription, "I want to contain an object", it should be an object not a function:
CRandomSFMT rangen;  // no ()

This will have to be initialised using its constructor:
Something::Something() : seed(1), rangen(seed) {}


text:
Q: I am making a multi level networking referral system and want some suggestions I am going to make multi level referral system which is not a binary system. If A is the parent of B and B is the parent of C.
If C do any action, some percentage will be distributed between B and A. I will use for loop for giving certain commission. But this chain be of 75 levels.
I think running for loop for 75 times will hang the PHP script. Should I break loop into 3 pieces or 1 loop can handle this?
I know this is not related to coding but related to logic.
Looking for some useful suggestions. I am working on CodeIgniter framework.


text:
Q: why my text-overflow: ellipsis; did't work? i was trying to make the text wont be too long i have used overflow:hidden but how i use text-overflow: ellipsis;? i have used but it wont work.
here is the JSfillder of my code
i no sure why it didn't work?
this is my html code

Post

Post

            <a href="chatroom.php?chatroomID=<?php echo $row['id'];?>">

                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

            <a href="chatroom.php?chatroomID=<?php echo $row['id'];?>">

                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

            <a href="chatroom.php?chatroomID=<?php echo $row['id'];?>">

                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

      <button class="btn content-btn see-all-button">
        see all
      </button>

this is css code
.profile-post-container {
  width: 80%;
  height: auto;
  margin: 2.5% auto;
  padding: 2.5% 1% 2.5% 1%;
  background-color: #ffffff;
  display: block;
  vertical-align: top;
  border-radius: 25px;
}

.profile-post-answer-container {
  width: 100%;
  height: auto;
  display: block;
  vertical-align: top;
  text-align: left;
  background-color: red;
}

.profile-seeall-container {
  width: 100%;
  height: auto;
  display: block;
  vertical-align: top;
  text-align: right;
  padding-right: 2.5%;
  background-color: blue;
}

.table-list {
  display: block;
  width: 100%;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

h3 {
  margin-left: .5%;
}

A: You have to add this cssto the profile-post-setting element:
.profile-post-setting {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    width: 450px;
}

This way the element knows how much space it has to show the text and when to show the ellipses. In your example you have added the text-ellipsis to the table and it is not responsible to show the ellipsis for a dom element deeoply nested on it. Here is the updated jsfiddle

A: you should give a specific width to the div (.list-block).  and remove the p tag.

.profile-post-container {
  width: 80%;
  height: auto;
  margin: 2.5% auto;
  padding: 2.5% 1% 2.5% 1%;
  background-color: #ffffff;
  display: block;
  vertical-align: top;
  border-radius: 25px;
}

.profile-post-answer-container {
  width: 100%;
  height: auto;
  display: block;
  vertical-align: top;
  text-align: left;
  background-color: red;
}

.profile-seeall-container {
  width: 100%;
  height: auto;
  display: block;
  vertical-align: top;
  text-align: right;
  padding-right: 2.5%;
  background-color: blue;
}

.list-block {
  display: block;
  width:100px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

h3 {
  margin-left: .5%;
}

Post

Post

            <a href="chatroom.php?chatroomID=<?php echo $row['id'];?>">

                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

            <a href="chatroom.php?chatroomID=<?php echo $row['id'];?>">

                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

            <a href="chatroom.php?chatroomID=<?php echo $row['id'];?>">

                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

A: Please Mention the width of that element on which you want to put it.
.profile-post-setting {
    width: 350px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;

}


text:
Q: How to check if a string is in a list of strings I am trying to get my script to output an error when someone enters an incorrect hostname from a CSV file.
Here is the script I have
#get content from file
$data= import-csv ".\Earliest Date Template.csv"

#which Hostname do you want to look up
$hostid=Read-Host "Please enter Hostname"

#Error Conditions
$spellingerror=$hostid -notmatch "Hostname"

if ($spellingerror)
  {Write-Host -foregroundcolor Green "Hostname does not exist"}
else
  {$data | Sort-Object {[DateTime]$_."Last Modified"} |
  Where-Object   {$_."Hostname" -eq $hostid} |  Select -First 1 -
  ExpandProperty "Last Modified"
  }
Break

The script is designed to ask the user for which host they want to know about and when it was first modified and if the hostname does not exist spit out it does not exist.
No matter what I do it keeps spitting out Hostname does not exist.
Here is a sample from the contents of my CSV file.
Hostname    Last Modified
HD          9/8/2012
LOG         9/15/2004
NETMAN     12/25/2004
NETMAN      5/5/2015
LOG        2/14/2013
LOG        6/6/2011

A: Try using this error condition:
$spellingerror = $hostid -notin $data.hostname


text:
Q: Element-wise multiplication between vector and scalar with two matrices I have run a classification experiment with 2 classifiers on a dataset with 2 classes and 150 samples. Classifiers are scikit-learn objects with predict_proba() method. This method returns an array of shape (samples, classes) with the probability distribution for each sample. I also computed another matrix G with shape (samples, 2)  which contains the "importance" of each classifier for each sample.
The final output must be a linear combination of each predict_proba() row and the scalar in G. Example with one single sample:
G = np.array([0.3, 0.7])

classifier_1_proba = np.array([0.6, 0.4])
classifier_2_proba = np.array([0.2, 0.8])

Y = classifier_1_proba * G[0] + classifier_2_proba * G[1]

This is easy with just one sample/output, but i don't know how could it be done with multiple samples (e.g. an entire test set).

A: I think this would work for you:
Y = c1_proba * G[:, 0, None] + c2_proba * G[:, 1, None]

Assuming the classifier proba matrices c1_proba, c2_proba and the weights G are all 2D numpy arrays as you mentioned.