text:
Q: Can't Error Copying SQLite Database in Android I keep getting this error when I run my App. Can you help me please

Process: com.abdallahmurad.quoter001, PID: 6218
                                                   java.lang.Error: ErrorCopyingDataBase
                                                       at com.abdallahmurad.quoter001.DBHelper.createDataBase(DBHelper.java:123)
                                                       at com.abdallahmurad.quoter001.DBHelper.(DBHelper.java:65)
                                                       at com.abdallahmurad.quoter001.QuoterActivity.onCreate(QuoterActivity.java:77)

and here is the class:
public class DBHelper extends SQLiteOpenHelper{

SQLiteDatabase db = null;
Context context = null;

static String packageName = "com.easwareapps.quoter";
private static String DB_PATH = "/data/data/" + packageName + "/databases/";
private static String DB_NAME ="quoter.db";
private static final int VERSION = 1;

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public DBHelper(Context context) {
    super(context, DB_NAME, null, VERSION);
    try{
        this.context = context;
        createDataBase();
    }catch(Exception e){
        e.printStackTrace();
    }

}

public Cursor getQuotes(int tag, int author){

    db = this.getReadableDatabase();
    String authorFilter = (author == 0)?"":" and author._id=" + author;
    String tagFilter = (tag == 0)?"":" INNER JOIN quotes_tags tag ON tag.quote=quote._id AND tag.tag=" + tag + " ";
    String sql = "SELECT quote.quote, author.author, author._id, quote._id from quotes quote, authors author " +  tagFilter + "where quote.author=author._id and quote.status=1 " + authorFilter;// + " ORDER BY RANDOM()";
    return db.rawQuery(sql, null);

}

public String[] getRandomQuote(){

    db = this.getReadableDatabase();
    String sql = "SELECT quote.quote, author.author, author._id, quote._id from quotes quote, authors author where quote.author=author._id and quote.status=1 ORDER BY RANDOM() LIMIT 1";
    Cursor c = db.rawQuery(sql, null);
    if(c.moveToFirst()) {
        return new String[]{c.getString(1), c.getString(0), c.getString(2), c.getString(3)};
    }else{
        return new String[]{"", "", "", ""};
    }

}

public String[] getQuote(int id){

    db = this.getReadableDatabase();
    String sql = "SELECT quote.quote, author.author, author._id, quote._id from quotes quote, authors author where quote.author=author._id and quote.status=1 and quote._id=" + id;
    Cursor c = db.rawQuery(sql, null);
    if(c.moveToFirst()) {
        return new String[]{c.getString(1), c.getString(0), c.getString(2), c.getString(3)};
    }else{
        return new String[]{"", "", "", ""};
    }

}

public void createDataBase() throws IOException {

    boolean mDataBaseExist = checkDataBase();
    if(!mDataBaseExist) {
        try  {
            copyDataBase();
            Log.e("DB", "createDatabase database created");
        }
        catch (IOException mIOException)  {
            Log.d("Error", Log.getStackTraceString(mIOException));
            throw new Error("ErrorCopyingDataBase");
        }
    }
}

private boolean checkDataBase() {
    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();
}

private void copyDataBase() throws IOException {
    InputStream mInput = context.getAssets().open(DB_NAME);
    String outFileName = DB_PATH + DB_NAME;
    File dir = new File(DB_PATH);
    if(!dir.exists()){
        dir.mkdir();
    }
    OutputStream mOutput = new FileOutputStream(outFileName);
    byte[] mBuffer = new byte[1024];
    int mLength;
    while ((mLength = mInput.read(mBuffer))>0)
    {
        mOutput.write(mBuffer, 0, mLength);
    }
    mOutput.flush();
    mOutput.close();
    mInput.close();
}

public Cursor getTags() {
    db = this.getReadableDatabase();
    String sql = "SELECT _id, tag from tags where status > 0";
    return db.rawQuery(sql, null);

}

}
public class DBHelper extends SQLiteOpenHelper{

SQLiteDatabase db = null;
Context context = null;

static String packageName = "com.easwareapps.quoter";
private static String DB_PATH = "/data/data/" + packageName + "/databases/";
private static String DB_NAME ="quoter.db";
private static final int VERSION = 1;

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public DBHelper(Context context) {
    super(context, DB_NAME, null, VERSION);
    try{
        this.context = context;
        createDataBase();
    }catch(Exception e){
        e.printStackTrace();
    }

}

public Cursor getQuotes(int tag, int author){

    db = this.getReadableDatabase();
    String authorFilter = (author == 0)?"":" and author._id=" + author;
    String tagFilter = (tag == 0)?"":" INNER JOIN quotes_tags tag ON tag.quote=quote._id AND tag.tag=" + tag + " ";
    String sql = "SELECT quote.quote, author.author, author._id, quote._id from quotes quote, authors author " +  tagFilter + "where quote.author=author._id and quote.status=1 " + authorFilter;// + " ORDER BY RANDOM()";
    return db.rawQuery(sql, null);

}

public String[] getRandomQuote(){

    db = this.getReadableDatabase();
    String sql = "SELECT quote.quote, author.author, author._id, quote._id from quotes quote, authors author where quote.author=author._id and quote.status=1 ORDER BY RANDOM() LIMIT 1";
    Cursor c = db.rawQuery(sql, null);
    if(c.moveToFirst()) {
        return new String[]{c.getString(1), c.getString(0), c.getString(2), c.getString(3)};
    }else{
        return new String[]{"", "", "", ""};
    }

}

public String[] getQuote(int id){

    db = this.getReadableDatabase();
    String sql = "SELECT quote.quote, author.author, author._id, quote._id from quotes quote, authors author where quote.author=author._id and quote.status=1 and quote._id=" + id;
    Cursor c = db.rawQuery(sql, null);
    if(c.moveToFirst()) {
        return new String[]{c.getString(1), c.getString(0), c.getString(2), c.getString(3)};
    }else{
        return new String[]{"", "", "", ""};
    }

}

public void createDataBase() throws IOException {

    boolean mDataBaseExist = checkDataBase();
    if(!mDataBaseExist) {
        try  {
            copyDataBase();
            Log.e("DB", "createDatabase database created");
        }
        catch (IOException mIOException)  {
            Log.d("Error", Log.getStackTraceString(mIOException));
            throw new Error("ErrorCopyingDataBase");
        }
    }
}

private boolean checkDataBase() {
    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();
}

private void copyDataBase() throws IOException {
    InputStream mInput = context.getAssets().open(DB_NAME);
    String outFileName = DB_PATH + DB_NAME;
    File dir = new File(DB_PATH);
    if(!dir.exists()){
        dir.mkdir();
    }
    OutputStream mOutput = new FileOutputStream(outFileName);
    byte[] mBuffer = new byte[1024];
    int mLength;
    while ((mLength = mInput.read(mBuffer))>0)
    {
        mOutput.write(mBuffer, 0, mLength);
    }
    mOutput.flush();
    mOutput.close();
    mInput.close();
}

public Cursor getTags() {
    db = this.getReadableDatabase();
    String sql = "SELECT _id, tag from tags where status > 0";
    return db.rawQuery(sql, null);

}

}
public class QuoterActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private static String BANERID ="ca-app-pub-5013563814074355/3472037827";
QuotesAdapter qa;
RecyclerView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quoter);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    //navigationView.addView();

    lv = (RecyclerView)findViewById(R.id.quotesList);
    lv.setLayoutManager(new LinearLayoutManager(this));

    DBHelper dbh = new DBHelper(getApplicationContext());
    Cursor tags = dbh.getTags();

    int i = 0;
    final Menu menu = navigationView.getMenu();
    menu.add(R.id.tags, i, i, "All");

    if(tags.moveToFirst()) {
        do {
            i++;
            menu.add(R.id.tags, tags.getInt(0), i, tags.getString(1));
        }while (tags.moveToNext());
    }

    qa = new QuotesAdapter(getApplicationContext(),
            new DBHelper(getApplicationContext()).getQuotes(0, 0), this);
    lv.setAdapter(qa);

    menu.setGroupCheckable(R.id.tags, true, true);
    int count = 0;
    for (i = 0, count = navigationView.getChildCount(); i < count; i++) {
        final View child = navigationView.getChildAt(i);
        if (child != null && child instanceof ListView) {
            final ListView menuView = (ListView) child;
            final HeaderViewListAdapter adapter = (HeaderViewListAdapter) menuView.getAdapter();
            final BaseAdapter wrapped = (BaseAdapter) adapter.getWrappedAdapter();
            wrapped.notifyDataSetChanged();
        }
    }

    new EANotificationManager().setAlarmIfNeeded(getApplicationContext());

}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        saveScrollPositon();
        super.onBackPressed();
    }
}

@Override
public void onPause() {
    saveScrollPositon();
    super.onPause();
}

@Override
public void onResume() {

    super.onResume();
    scrollToLastPosition();

}

private void scrollToLastPosition(){
    SharedPreferences pref = getSharedPreferences(getPackageName(), MODE_PRIVATE);
    int y = pref.getInt("scroll-y", 0);
    if(lv != null ){
        //lv.smoothScrollToPosition(y);
        lv.scrollToPosition(y);
    }
}

private void saveScrollPositon(){
    if(lv != null ){
        int y = ((LinearLayoutManager)lv.getLayoutManager()).
                findFirstCompletelyVisibleItemPosition();
        SharedPreferences pref = getSharedPreferences(getPackageName(), MODE_PRIVATE);
        SharedPreferences.Editor edit = pref.edit();
        edit.putInt("scroll-y", y);
        edit.commit();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.quoter, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        Intent settings = new Intent(this, SettingsActivity.class);
        startActivity(settings);
        return true;
    }if (id == R.id.random) {
        Intent random = new Intent(this, DailyQuoteActivity.class);
        random.putExtra("from_quote", true);
        startActivity(random);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    lv.setAdapter(null);
    qa = new QuotesAdapter(getApplicationContext(),
            new DBHelper(getApplicationContext()).getQuotes(id, 0), this);
    lv.setAdapter(qa);
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.getMenu().getItem(id+1).setChecked(true);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

public void gotoWebsite(View v){
    String url = "http://quoter.easwareapps.com";
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);
}

}


text:
Q: hex string to SHA256 digest in python I have a string that contain a SHA256 digest in hexadecimal like blow:
"257612236efae809c23330ab67cf61f73aec938503f3ce126c34c6a32059f5f0"

and I want to convert it to hash.digest() that can be  like  below:
b'%v\x12#n\xfa\xe8\t\xc230\xabg\xcfa\xf7:\xec\x93\x85\x03\xf3\xce\x12l4\xc6\xa3 Y\xf5\xf0'

how can I achive this?
 I use Crypto.Hash and python 3.3.2

A: Use binascii.unhexlify:
>>> import binascii
>>> binascii.unhexlify("257612236efae809c23330ab67cf61f73aec938503f3ce126c34c6a32059f5f0")
b'%v\x12#n\xfa\xe8\t\xc230\xabg\xcfa\xf7:\xec\x93\x85\x03\xf3\xce\x12l4\xc6\xa3 Y\xf5\xf0'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prove that $B \setminus (\bigcup_{i\in I} A_i) = \bigcap_{i\in I} (B \setminus A_i)$ Help prove it by first proving that $\Rightarrow$ and later $\Leftarrow$ . I'm confused, if I let $x$ be arbitrary and later want to prove that $x \in B$ , and I've got $∀i ∈ I\,(x ∈ B\; \text{ and }\;x ∉ A_i)$. If I suppose $i ∈ I$, and obtain $x ∈ B$, still I've only proven $∀i ∈ I\,(x ∈ B)$ instead of $x ∈ B$. Thank you very much!! Yes, I've already seen that there's a question about infinite DeMorgan's law question. But what I'm confused of here if about the second identity of Infinite Demorgan's law. And I'm hoping someone would help me understand, if I let $x$ be arbitrary and later want to prove that $x \in B$.

A: \begin{align}
x\in B\setminus\Big(\bigcup_{i\in I}A_i\Big) &\iff x\in B \wedge \neg \Big(x \in \bigcup_{i\in I} A_i\Big)\iff x\in B \wedge \neg (\exists i\in I: x\in A_i)\\
&\iff x\in B \wedge \forall i\in I: x\notin A_i\iff \forall i\in I: x\in B \wedge x\notin A_i\\
&\iff \forall i \in I: x\in B\setminus A_i\iff x\in \bigcap_{i\in I} \,(B\setminus A_i)\end{align}


text:
Q: Trouble Isolating A Variable I ran across the following predicament in the course of solving a calculus problem. I'm embarrassed to admit I'm not sure how to proceed in order to solve for $x$.
$$e^x=6-x$$
I've tried taking the logarithm of each side yielding $x=\ln(6-x)$ where $x<6$. But this still leaves me in a position where I have trouble isolating $x$. Any help would be appreciated. Thanks!

A: The good news is it's not you-- it's the problem.  You can't isolate the variable. The bad news is you can't isolate the variable.
But note $e^x$ is increasing.  And $x-6$ is decreasing. So (in this case at least) the graphs cross and there will be exactly one $x$ where it is true.
So good news: You know there is one solution.  Bad news: there is no algebraic way to express it.
But there are a lot of functions we can not express algebraically so we make up a function as a list of values to describe it.  Example $\sin x$ is "the $y$ value of a point on a unit circle that has an interior angle of $x$".  There's no way to algebraically solve that but we know it makes sense.
Likewise we know that for any $x$ there is a unique $y$ so that $ye^y = x$.  We can't solve that algebraically but we know that $ye^y$ is increasing and has negative infinity and positive infinity as limits so we know $ye^y$ goes through every point exactly once so there is a unique $y$ so that $ye^y = x$.
So call this function the Lambert function $W(x)=y \iff ye^y = x$.
With this function in our arsenal:
We wont to get $\text{something about x}e^{\text{something about x}}= k$ so
$\text{something about x} = W(k)$. and then we can undo $\text{something about x}$.
$e^x = 6-x$
$\frac {e^x}{6-x} = 1$
$\frac 1{e^{-x}(6-x)} = 1$
$e^{-x}(6-x) = 1$
$e^{6-x-6}(6-x) = 1$
$e^{-6}*(6-x)e^{6-x}= 1$
$(6-x)e^{6-x} = e^{6}$
$6-x = W(e^{6})$
$x = 6-W(e^{-6})$
....
So $W(e^{6})$ is the value $y$ where $ye^y = e^{6}$  which we can only approximate.  We can't solve algebraically.

A: You can write the equation in Lambert form: $xe^x = c$ with substitution and get an answer in terms of $W_0(c)$ where ${\displaystyle W_{0}(x)=\sum _{n=1}^{\infty }{\frac {(-n)^{n-1}}{n!}}x^{n}=x-x^{2}+{\tfrac {3}{2}}x^{3}-{\tfrac {8}{3}}x^{4}+{\tfrac {125}{24}}x^{5}-\cdots .}$
Here's the process of substitution and getting the answer:
$$e^x = 6-x$$
$$1= e^{-x}(6-x)$$
Now let $u = 6-x$ and $x = 6-u$.
$$1=e^{u-6}u$$
$$e^uu = e^6$$
$\therefore u = W_0(e^6)$
$x= 6-W_0(e^6)$
According to Wolfram Alpha, the sum does not converge and therefore, the solution does not exist.

A: For sure, the solution in terms of Lambert function is the only way to get an explicit formula.
If you do not use it, only numerical methods would work. Graphing the function, you see that the root is close to $\frac 32$. So, you could use Newton method and get the following iterates
$$\left(
\begin{array}{cc}
 n & x_n \\
 0 & 1.500000000 \\
 1 & 1.503340381 \\
 2 & 1.503335827
\end{array}
\right)$$
Another way to do it is to Taylor expand
$$e^x+x-6=\left(e^{3/2}-\frac{9}{2}\right)+\left(1+e^{3/2}\right)
   \left(x-\frac{3}{2}\right)+\frac{1}{2} e^{3/2}
   \left(x-\frac{3}{2}\right)^2+\frac{1}{6} e^{3/2}
   \left(x-\frac{3}{2}\right)^3+\frac{1}{24} e^{3/2}
   \left(x-\frac{3}{2}\right)^4+O\left(\left(x-\frac{3}{2}\right)^5\right)$$ and use series reversion to get
$$x=\frac{3}{2}+\frac{t}{1+e^{3/2}}-\frac{e^{3/2} t^2}{2
   \left(1+e^{3/2}\right)^3}+\frac{\left(2 e^3-e^{3/2}\right) t^3}{6
   \left(1+e^{3/2}\right)^5}+\frac{\left(-e^{3/2}+8 e^3-6 e^{9/2}\right) t^4}{24
   \left(1+e^{3/2}\right)^7}+O\left(t^5\right)$$ where $t=y-e^{3/2}+\frac{9}{2}$.
Now, make $y=0$ and get the same result (at least for ten significant figures).


text:
Q: Why do I keep getting the nosuchelementexception error? I'm new to programming. I'm trying to get multiple inputs from the user by using Scanner class. I'm using net beans and trying to run and compile my code within the net beans IDE. The program runs and compiles whenever I do not close the scanner after asking for input. But when I attempt to close the scanner after every time I asked for input I get an the nosuchelementexception scanner closed error. In class, we were taught to close scanner after every time we ask for input from the user. My professor does this, also while using NetBeans and his program compiles and runs every time. Like me, he also only declares scanner once and uses the same variable multiple times while asking for input from the user.
    import java.util.Scanner; // This allows us to use Scanner

public class GettingInput {
public static void main(String[] args) {
// ALWAYS give the user instructions. System.out.println("Enter an integer: ");

    // Create a new scanner
    Scanner keysIn = new Scanner(System.in);
    // Specify the type of data/variable you are scanning in
    int num = keysIn.nextInt();
    // Close your scanner when you are done.
    keysIn.close();
    // ALWAYS confirm that you scanned in what you thought you did.
    System.out.println("Your int: " + num);

    // Repeat the process for a different data type
    System.out.println("---------");
    System.out.println("Enter a floating-point value:");
    keysIn = new Scanner(System.in);
    double num2 = keysIn.nextDouble(); // note the different method
    keysIn.close();
    System.out.println("Your floating-point: " + num2);

    // Repeat it yet again
    System.out.println("---------");
    System.out.println("Now enter a string.");
    keysIn = new Scanner(System.in);
    String str = keysIn.nextLine(); // again, a different method
    keysIn.close();
    System.out.println(str);
 }
}

This is code he had written, compiled and ran in class. When I try to run the same code it does not work.
I'm also using a Mac Book Pro and the latest version of Mac OS.

A: it happens because you closed the scanner and initiating the scanner object again. so it is better that you don't close the scanner where you know you are going to use it later again in your code, but you should do it once you are done with it.
Another thing is that, for different type of inputs you even don't need to create an entire scanner object again, you can just call appropriate methods of that scanner for your corresponding inputs type. Such that
import java.util.Scanner;

public class GettingInput {
    public static void main(String[] args) {
        Scanner keysIn = new Scanner(System.in);
        int num = keysIn.nextInt();
        System.out.println("Your int: " + num);

        System.out.println("---------");
        System.out.println("Enter a floating-point value:");
        double num2 = keysIn.nextDouble();
        System.out.println("Your floating-point: " + num2);

        System.out.println("---------");
        System.out.println("Now enter a string.");
        String str = keysIn.next();
        keysIn.close();
        System.out.println(str);
    }
}


text:
Q: Compiling VS 2012 project programmatically? I have this class library project sitting in a solution.
My need is to be able to embed resources (all files from 'Resources' folder) into DatabaseResources.resx and compile it all into an assembly, on the fly.

I tried CSC and was able to compile it
csc /target:library /out:MyClassLibrary.dll  /res:ContentChangeLog.gz /res:CountryBillingRules.gz /res:Finance.gz /res:Instructions.xml /res:Language.gz /res:Masters.gz /res:wbs.gz /res:wbsList.gz

But, MyClassLibrary.dll should be exposing these resources thru DatabaseResources.resx so that others can find it- MyClassLibrary.DatabaseResources.(resource name)

I couldn't find a way to do the same with CSC.
Any help appreciated.

A: I guess what you are looking for is MsBuild.
a good explanation here - Some confusions about Command Line Compiler and MSBuild


text:
Q: Why does sysvinit force the console to be its controlling terminal for any wait-type subprocess? I'm reading the source code init.c of sysvinit(now replaced by Systemd), in the function
spawn()(where init creates subprocesses), there is a comment at line 1165:
    /*
     *  In sysinit, boot, bootwait or single user mode:
     *  for any wait-type subprocess we _force_ the console
     *  to be its controlling tty.
     */

But I'm still not understand it. Could anyone explains the reason in more detail?


text:
Q: Remove join date How do I remove the Joined on MM DD, YYYY from my PyPI public profile?
Clicking on "Edit profile" does not give me the option to hide it.
Most accounts have the Joined on MM DD, YYYY. New accounts show it by default.

Examples:
tusharmakkar08 (4 projects) has Joined on May 22, 2016
but
alecthomas (12 projects) does not have Joined on MM DD, YYYY.
From this I thought that if there are greater than 10 projects then the date is not shown.

Counterexample:
iotile (30 projects) does not have Joined on MM DD, YYYY.

A: It looks like very old accounts don't have join date


text:
Q: How to access maven property from Jenkins? I have a maven project in which I have a property. I want to access it from Jenkins.
POM snippet:
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <timestamp>${build.time}</timestamp>
    <outputFolder>C:/AutomationTestReports/${project.name}/ExecutionReport${timestamp}</outputFolder>
</properties>

This output folder property gets evaluated at runtime. I want to access this property in Jenkins to navigate to the output folder which gets generated as per the time stamp. For this to happen I need to capture this output folder property in Jenkins, which I am not able to do.
Using this output folder only I will be able to navigate to the folder to access the result file.
Question: How to access Maven properties from Jenkins job?

A: In the current version of Jenkins there is a nice and simple way to achieve this using "readMavenPom()".
For example, I want to read the version of the pom.xml file. But if it is using the newer maven "revision" practice, I need to read that "revision" value from the properties defined in the pom.xml.
      def pomVersion = readMavenPom().version   // read version
      if (pomVersion.equals("\${revision}"))    // using revision strategy, read revision property
      {
        pomVersion = readMavenPom().properties['revision']
      }

So the best way is to use
readMavenPom().properties['PROPETY_NAME']

A: Jenkins Maven jobs provide by default some maven properties to be used during job configuration, however it doesn't provide any easy access to further properties defined into the pom file.
Hence, a custom approach is required. Here is a working solution which makes use of a groovy script and could be used to transform any defined Maven property into a new Jenkins variable at build time, to be then further used in additional post build steps.
Pre-requirements to this solution are:

*

*Groovy is installed in the Jenkins server (easy step, just download it, unzip, set it to the path

*The Jenkins Groovy Plugin is installed in Jenkins (easy step, Manage Jenkins > Manage Plugins, Available Plugins, install it, then configure it under Manage Jenkins > Configure System > Groovy, to make it point to the installation of step above

You can then add to the project pom the following to is build/plugins section:
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>properties-maven-plugin</artifactId>
    <version>1.0.0</version>
    <executions>
        <execution>
            <phase>initialize</phase>
            <goals>
                <goal>write-project-properties</goal>
            </goals>
            <configuration>
                <outputFile>${project.build.directory}/build.properties</outputFile>
            </configuration>
        </execution>
    </executions>
</plugin>

What are we doing? Simply using the properties-maven-plugin and its write-project-properties goal to write the project properties into a new file under the target folder (target\build.properties). Note: properties in this file will already be interpolated.
This new file will be harmless for your build and project, ignored by any other build step, removed as part of a mvn clean invocation, but yet really helpful for Jenkins.
Then, in the concerned Jenkins job you can add a new Post Steps > Execute system Groovy script (and not an Execute Groovy script, bear the difference) pointing to a new groovy file you can store where desired or type into the console the following groovy code:
import hudson.model.*;
import hudson.util.*;

def thr = Thread.currentThread();
def currentBuild = thr?.executable;

def props = new Properties();
new File(currentBuild.workspace.toString()+"\\target\\build.properties").withInputStream {
  stream -> props.load(stream);
}

println "detected from properties: "+props.get("outputFolder");

def newParamAction = new ParametersAction(new StringParameterValue("outputFolder", props.get("outputFolder")));
currentBuild.addAction(newParamAction);

What is this script doing? Simply reading the property file, printing to the console the outputFolder property as a log (to be removed, optionally) and then set it as a new Jenkins job variable with the same name (to be changed if required).
You can then use in further post build steps the ${outputFolder} new variable (or the %outputFolder% in Windows commands) and it will be correctly present.
As an example, you can debug it via a new Post Steps > Execute Windows Batch command and simply echo it. Here is a screenshot:

As output of a sample Jenkins job you would then have:
detected from properties: C:/AutomationTestReports/sample-project/Execution_(2016-04-24_12-11-13UTC)
[workspace] $ cmd /c call C:\dev\tomcat-7\temp\hudson6024790907972070905.bat

C:\Users\user-name\.jenkins\jobs\sample-maven\workspace>echo C:/AutomationTestReports/sample-project/Execution_(2016-04-24_12-11-13UTC)
C:/AutomationTestReports/sample-project/Execution_(2016-04-24_12-11-13UTC)

C:\Users\user-name\.jenkins\jobs\sample-maven\workspace>exit 0
Finished: SUCCESS

A: A quick and dirty solution.
Add an 'Execute Shell' step, and assign the property's value into a variable:
outputFolderVar=$(awk -F '[<>]' '/outputFolder/{print $3}' pom.xml)

A: environment {
       OUTPUT_FOLDER = "${sh(script: 'mvn help:evaluate -Dexpression=outputFolder -q -DforceStdout', returnStdout: true)}"
    }

pipeline-utility-steps


text:
Q: How to: javascript fade in fade out text First of all: I looked through other posts on stackoverflow and none of them had the information I was looking for.
Second: I'm new to programming ;)
I want to have a div on my website that fades in and fades out text. I've seen this on a few web sites and am pretty sure it is javaScript using the jQuery library.
Does anyone know of a good tutorial, or can tell me how to accomplish this?

A: Here you go :)
http://api.jquery.com/category/effects/
Click on the effects you want, there are demos you can click around and copy the code from.
Another good one is Scriptaculous. There are bunch of demos there too.

A: i just gave an answer on another question:
Using CSS for fade-in effect on page load
does this answer your question?


text:
Q: Custom RetryPolicy in Spring doesn't retry I have the following configuration class:
@Configuration
public class MyAppConfig {
@Value("${retry.backoff}")
private String retryBackoff;

@Bean
public RetryTemplate retryTemplate() {
    RetryTemplate retryTemplate = new RetryTemplate();

    FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
    fixedBackOffPolicy.setBackOffPeriod(Long.parseLong(retryBackoff));
    retryTemplate.setBackOffPolicy(fixedBackOffPolicy);

    retryTemplate.setRetryPolicy(new CustomRetryPolicy());

    return retryTemplate;
  }
}

Below is the component I created for my custom retry policy. Purpose of this policy is to improve it to retry only when certain HttpClientErrorExceptions happen.
@Component
public class CustomRetryPolicy extends ExceptionClassifierRetryPolicy {

public void CustomRetryPolicy() {
    final SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();

    simpleRetryPolicy.setMaxAttempts(5);

    this.setExceptionClassifier(new Classifier<Throwable, RetryPolicy>() {
        @Override
        public RetryPolicy classify(Throwable classifiable) {
            if (classifiable instanceof HttpClientErrorException) {

                return simpleRetryPolicy;
            }
            return simpleRetryPolicy;
        }
    });
  }
}

This issue has no error log and retry does not happen. How can I fix this?


text:
Q: When opening a plain text file with Chrome, how can I know how many lines the text contains? I'd prefer not having to copy the text to another program, as it may be very large (example).

A: CTRL + U (or Right Click, then View page source) will display the source with line numbers:

Thanks to Reddit user ThatFreeSpirit for the trick.


text:
Q: Is 'this this' correct? The ability to echo words and still make a meaningful statement has always bugged me. Take this example sentence:
"Thank you for bringing this issue to my attention. We will take care of this this afternoon."
Is this sentence grammatically correct? Also, is there a technical term for the echoed 'this'?

A: Sure it's grammatically correct. There are many cases where a word can occur twice in a row and make complete sense, especially when the word is being used with two different definitions. "After fixing twenty mistakes, Sally had had enough." "Bob saw that that was not the right answer." "I got lost because I turned right too soon, but then I circled around and made the right right turn." And of course if you try hard you can come up with crazy examples, like the ever-popular "Buffalo" sentence. (I know that was quoted on here somewhere.)
In most cases where a word is used twice in a row people read it without noticing. If you think in a given case it might be confusing, then sure, find a way to re-word it.

A: You could avoid the echo by saying we will take care of it this afternoon as you have established the it in the previous sentence.
I believe the term is doubled words.

A: In general, I recommend avoiding use of non-determinate "this" as a pronoun and instead replace it with a determiner, "this what". In your example, replace the potentially ambiguous "this" with "this issue":
"Thank you for bringing this issue to my attention. We will take care of this issue this afternoon."
Doing so eliminates the double "this" and avoids the potential for "this" to refer to anything, including the potential interpretation, "We will take care of my attention this afternoon."
See this article for a more in-depth explanation on why an ambiguous "this" pronoun can be dangerous and should be avoided.


text:
Q: _unAnswered_ Turn on android hotspot by button click in my application then see the connected devices MAC address I want to turn on the hotspot of my android mobile as i click on button in my hello world application.
After that I also want below that the list of all connected devices MAC address must be seen.
And there will be option of giving the custom name to those MAC address(alias).
This question is asked way before stack overflow and never answered properly. So please try to give ANS

A: We will not give you the code to do this. But this is a way you can explore.
To control the wifi of your android device you have to add this line to your manifest :
<manifest ...>
 <uses-feature android:name="android.hardware.wifi" />
 <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
 <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
...
</manifest>

After you have to use the class : WifiManager to manage the hotspot


text:
Q: How do I switch my Wordpress URL correctly I would like to switch my testing website url from www.hello.com/testing to www.hello.com
After I changed the url the website display non-safety.
What should I need to do?

A: Scenario 1: leave the wordpress files in /testing directory and just change the index file to achieve target.
Scenario 2: move all the wordpress files to root directory and replace all URLs inside your database to remove /testing
Solution for Scenario 1:
Copy index.php and .htaccess files to your root directory. Open this new index.php to edit and search for /testing and remove it. Go to Admin panel -> settings -> General and change Site URL and remove /testing from here also.
Solutionfor Scenario 2:
Go to Admin panel -> settings -> General and change Site URL and remove /testing. Then move all your files to new location and run interconnectit script (available here)


text:
Q: BCP a table with multiple line in single column I need to BCP a table which contains three lines in a single column. For example:
ID  Name    Comments
---------------------
 1 | Sample |   "Hai.
             Hello.
         How."

But the final BCP output file is having three lines instead of one line:
1^|^Sample^|^Hai
Hello^|^
How^|^

BCP Query:
bcp table out table_one.bcp -c -t "^|^" -Q -User -Password.

A: Try the command a little different
bcp "select * from db..table" queryout "C:\dir\file.bcp" -n -T -SServer

A: If you have Windows line separators ({CR}{LF}) in your source text and don't want those in the output file, you can replace them in a query with something of your liking (eg a space).
Consider the following snippet. The source data contains Windows line separators. In the query these are replaced with a space. You will see in the output file that there are no longer multiple lines for a source text. You should be able to run this snippet from SSMS.
CREATE TABLE ##t(header INT IDENTITY(1,1) PRIMARY KEY,txt VARCHAR(1024));
INSERT INTO ##t(txt)VALUES
('This is the first line.
This is the second line.
This is the third line'),
('Again the first line.
Again the second line.
Again the third line.');

DECLARE @cmd NVARCHAR(4000)='BCP "SELECT header,REPLACE(txt,CHAR(13)+CHAR(10),'' '') FROM ##t" QUERYOUT "C:\Temp\test_txt.txt" -c -T -S ' + @@SERVERNAME + ' -d ' + DB_NAME();
EXECUTE master.sys.xp_cmdshell @cmd;

DROP TABLE ##t;

The output file C:\Temp\test_txt.txt:
1   This is the first line. This is the second line. This is the third line
2   Again the first line. Again the second line. Again the third line.


text:
Q: Saving complex form data in zend framework using doctrine 2 Doctrine 2 integration into ZF seems to make simple things very hard and time consuming(At least for me).
I cant just give a submitted form array to doctrine to automatically map key/value pairs to doctrine entities and it gets very complicated if i have a many-to-many entity and submitted form has nested array.
In symfony, submitted form keys/values are easily and AUTOMATICALLY mapped and saved to doctrine tables. I don't know how to do that in ZF especially if I have "Many to Many" and/or "Many to One" doctrine entities and I have **nested form elements which need multi-level iteration.
I don't want to Set every entity explicitly and create every entity object manually**.
Pain would be alot less if i used ZF`s native database architecture.
I have done some coding and now its done half-automatically but is not very useful.

A: You should program this sort of logic into your models.
I usually add this sort of logic into my form, for example
class Application_Form_SomeModel extends Zend_Form
{
    // the usual stuff

    public function populateModel(\Entity\Model $model)
    {
        $model->setSomething($this->getValue('something'));

        $subForm = $this->getSubForm('name');

        $relatedModel = new \Entity\RelatedModel;
        $relatedModel->setSomething($subForm->getValue('something'));

        $model->getRelatedModels()->add($relatedModel);

        // assuming the related model collection has cascade persist
        // otherwise you'll need to pass in the entity manager to persist
        // the new model
    }
}

I do it this way due to the fact the form's elements are really only known to the form. This allows you to encapsulate everything to do with the form and its element names within the form without having to assume anything else knows this information.

A: I think the best solution is to use PHP's Reflection API to inject/retrieve values from your entities (using smart get/set detection as well). I started a little library called ObjectSerializer to help with the process but never finished. That said, if you look at the logic contained in these two classes you might get a good idea where to start.


text:
Q: why react user input type text make number get NaN I am learning and try to make use of user input (textbox) type text to type in number and which will auto add commas and fixed to 2 decimal places using regex. It's work at first, but when I click the same textbox again (to edit the input) then I click other textbox or outside of the same textbox, the value change to NaN. Can anyone help me on this? Below is my code:
<InputForm
  inputtype="text"
  name="initialBalance"
  placeholder=""
  value={props.values.initialBalance}
  onChange={async (name,value) => {
  props.setFieldValue(name, value);

  }}
  onBlur={event => {

  const formatted = props.values['initialBalance'];

  var deciFormatted = Number(formatted).toFixed(2);

  props.setFieldValue('initialBalance',deciFormatted?deciFormatted.replace(/\B(?=(\d{3})+(?!\d))/g, ',') :Number.parseFloat(0).toFixed(2));

  props.handleBlur(event);

  }}
  onKeyPress={(event) => {
      if (/[^0-9.]|(?<=\..*)\./.test(event.key)) {
      event.preventDefault();
      }
    }}
  className={props.errors.initialBalance && props.touched.initialBalance && "is-invalid"}
  disabled={props.disabledForm}
  isInvalid={!!props.errors.initialBalance}

A: Actually, I have found the solution to the problem. I just add below method:
Number.isNaN(value)

which will change NaN to previous input that user type in. So, the code will be like this:
onBlur={event => {
  const formatted = props.values['initialBalance'];

  var deciFormatted = Number(formatted).toFixed(2);

  var newValue = (isNaN(deciFormatted) ? formatted : deciFormatted);

  props.setFieldValue('initialBalance',deciFormatted?deciFormatted.replace(/\B(?=(\d{3})+(?!\d))/g, ',') :Number.parseFloat(0).toFixed(2));

  props.handleBlur(event);


text:
Q: Questions regarding Apple's in-app purchases I can't find the answer on the following questions in Apple's documentation, so perhaps someone around here can tell me.
My questions are the following:

*

*When someone buys an in-app purchase, in how much time am I able to see this transaction on iTunes Connect? Immediately? After a day? After a week?

*Is a customer able to recall a transaction and if so, on what grounds?

A: *

*You will see the transaction the next day of the transaction.

*A customer is able to recall a transaction to Apple, or to you, if his purchase does not suit him, or if the in-app functionnality have not been enabled correctly.


text:
Q: Need Hints Prove "$((\neg \alpha \to \alpha) \to \alpha) $" Using Axiom 1,2,3 and MP and deduction theorem $((\neg \alpha \to \alpha) \to \alpha) $
Hi, I am trying to prove this.
Can someone gives me some hints to start the question...
My friend told me I might need to use deduction theorem here, but I have no clue to approach it..
Axiom 1: A→(B→A).
Axiom 2: (A→(B→C))→((A→B)→(A→C)).
Axiom 3: (¬B→¬A)→((¬B→A)→B).
To clarify: A, B, C, α, and β are propositions (i.e. assigned True or False). → and ¬ have the standard logical meanings.

A: here's a proof without using the deduction theorem. I will use the Mendelson Axioms, which I think are the basic ones (or at least they are taught on a first course of logic). Hope it helps.
$1.- ¬a \implies ((¬a \implies ¬a) \implies ¬a )$   (Ax1)
$2.- (¬a \implies ((¬a \implies ¬a) \implies ¬a )) \implies ((¬a \implies (¬a \implies ¬a)) \implies (¬a \implies ¬a ))$  (Ax2)
$3.- (¬a \implies (¬a \implies ¬a)) \implies (¬a \implies ¬a ) $  (MP (1,2))
$4.- ¬a \implies (¬a \implies ¬a )$   (Ax1)
$5.-  ¬a \implies ¬a $   (MP(3,4))
$6.- ( ¬a \implies ¬a) \implies (( ¬a \implies  a) \implies a)$ (Ax3)
$7.-  (¬a \implies a) \implies a $ (MP(5,6))

A: I don't know what Axioms 1, 2, and 3 are. They are not standardized to that extent. But the following may help:

*

*Suppose $\neg\alpha \implies \alpha$.

*Suppose to the contrary that $\neg\alpha$.

*$\alpha$ (from 1 and 2).

*$\alpha \land \neg\alpha$ (from 3 and 2)

*$\neg\neg\alpha$ (from 2 and 4)

*$\alpha$ (from 5)

*$[\neg\alpha \implies \alpha]\implies \alpha$ (from 1 and 6)

A: Since I don't know your basis, I'll pick a three-axiom basis that I sometimes like which Elliot Mendelsohn uses (there is a suggestion that in some sense the basis can at least get said to have hinted at by Jaskowski in his original paper on Natural Deduction, "On the Rules Of Supposition in Formal Logic", if not earlier).  I use Polish/Lukasiewicz notation, and condensed detachment.
axiom 1 C p Cqp.
axiom 2 C CpCqr C Cpq Cpr.
axiom 3 C CNpNq C CNpq p.
D2.1  4 C Cpq Cpp.
D4.1  5 Cpp.
D3.5  6 CCNppp.

A: We can start with the "standard" proof of :

$\vdash \alpha \rightarrow \alpha$.

(1) $\alpha → ((\alpha \rightarrow \alpha) → \alpha)$ --- from Ax 1
(2) $(\alpha → ((\alpha \rightarrow \alpha) → \alpha)) → ((\alpha → (\alpha \rightarrow \alpha)) → (\alpha \rightarrow \alpha))$ --- from Ax 2
(3) $(\alpha → (\alpha \rightarrow \alpha)) → (\alpha \rightarrow \alpha)$ --- from (1) and (2) by MP
(4) $\alpha → (\alpha \rightarrow \alpha)$ --- from Ax 1

(5) $\alpha \rightarrow \alpha$ --- from (3) and (4) by MP

With it, Ax 1 and Ax 2, we can prove the Deduction Theorem.

Now for the proof of :

$\vdash (¬α→α)→α$

(1) $\vdash \lnot \alpha \rightarrow \lnot \alpha$ --- see above
(2) $\lnot \alpha \rightarrow \alpha$ --- assumed [a]
(3) $\vdash (\lnot \alpha \rightarrow \lnot \alpha) \rightarrow ((\lnot \alpha \rightarrow \alpha) \rightarrow \alpha)$ --- from Ax 3
(4) $\alpha$ --- from (1), (2) and (3) by MP twice

(5) $(\lnot \alpha \rightarrow \alpha) \rightarrow \alpha$ --- from (1) and (4) by Deduction Theorem


text:
Q: JPA Query gets error InvalidDataAccessResourceUsageException I've written a query
public interface TeabagRepository extends CrudRepository<Teabag, Long> {

    @Query(value = "SELECT t.post, t.status, t.expires FROM teabags t WHERE t.status = 'hot' AND t.user_id = ?1", nativeQuery = true)
    Teabag findTea(Long id);
}

I set spring.jpa.show-sql=true in application.properties
So the query is shown in the console, I ran this query in database and it works:
SELECT
    t.post,
    t.status,
    t.expires
FROM
    teabags t
WHERE
    t.status = 'hot'
    AND t.user_id = ?

The error:

2018-05-08 19:22:27.675 ERROR 1259 --- [nio-8080-exec-4]
  o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for
  servlet [dispatcherServlet] in context with path [] threw exception
  [Request processing failed; nested exception is
  org.springframework.dao.InvalidDataAccessResourceUsageException: could
  not execute query; SQL [SELECT t.post, t.status, t.expires
  FROM teabags t WHERE t.status = 'hot' AND t.user_id = ?]; nested
  exception is org.hibernate.exception.SQLGrammarException: could not
  execute query] ****with root cause
org.postgresql.util.PSQLException: The column name id was not found in
  this ResultSet.****
org.springframework.dao.InvalidDataAccessResourceUsageException: could
  not execute query; SQL [SELECT t.post, t.status, t.expires FROM
  teabags t WHERE t.status = 'hot' AND t.user_id = ?];

update: more error text

nested exception is org.hibernate.exception.SQLGrammarException: could not execute query

root error

with root cause

org.postgresql.util.PSQLException: The column name id was not found in
    this ResultSet.

Why isn't this query working in the spring boot application?

A: The result was expecting every column of the Teabag so I had to select t.*
@Query(value = "SELECT t.* FROM teabags t WHERE t.status = 'hot' AND t.user_id = ?1", nativeQuery = true)
    Teabag findTea(Long id);


text:
Q: VS2010 - one pinned icon where all opened solutions will stack to and will display recent projects I have the following exe pinned in the start menu:
"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe"

however, it does not display any recent projects, even though I have many.
I pinned this to the task bar and all solutions opened get stack over it - which is desired and expected. However, when I right click it, it does not display the recent projects. Somewhere I read that I need to pin
"C:\Program Files (x86)\Common Files\microsoft shared\MSEnv\VSLauncher.exe"

in order to have recent projects, which I did and indeed it shows them, however, the opened solutions are still on the other icon (devenv.exe)
So, how can I just have one icon pinned in the task bar where the opened solutions will stack to and will display recent projects upon right click.


text:
Q: Is it possible to have half baked extents? Is it possible to have half baked extents if we have high volume data load and lets say query fails in between while the data load to the table is going on ? So lets say we have a high volume data load going on as part of a single ingest from table query (.set-or-append) and since the data is huge , it's creating several extents for the table (which the cluster may later try to merge as per the merge policy applicable for the table , but that is much later , not during the data load mostly). So in a way it's a single ADX command causing data load against individual extents separately -- so what if some of the extent loads succeed and some of them fail -- will we be left with a failed command with the table partially loaded ? I am trying to make sure that if a command fails as a whole , the data does not appear in the table.

A: Ingestion command is atomic regardless of the number of extents it creates, either it completely fails or completely succeeds, it cannot provide partial results.
The transactional guarantees also span update policies, where the policy can be transactional or non-transactional. In the non-transactional case, the ingestion can succeed on the source table and fail on the target table, in the transactional case all the relevant ingestions across all tables that participate in the update policy chain either succeed or fail.


text:
Q: How to make a calendar view with horizontal scrolling week view I am trying to make a calendar view similar to this one. One with horizontal scrolling week view, and list of events below the selected date.
I have tried using this library https://github.com/prolificinteractive/material-calendarview but the appearance is not the same. The calendar consumes a lot of screen space since the day name and dates are so wide apart. How can I make similar like this one below?
Thank you

A: use this library,,,
compile 'devs.mulham.horizontalcalendar:horizontalcalendar:1.1.7'

and this in xml
  <devs.mulham.horizontalcalendar.HorizontalCalendarView
                            android:id="@+id/calendarView"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:background="#FAFAFA"
                            app:selectedDateBackground="#00ffffff"
                            app:selectorColor="#c62828"
                            app:textColorNormal="#bababa"
                            app:textColorSelected="@color/blue_color"
                            app:textSizeDayName="20sp"
                            app:textSizeDayNumber="20sp" />

and here Java
private HorizontalCalendar horizontalCalendar;

   Calendar endDate = Calendar.getInstance();
        endDate.add(Calendar.MONTH, 1);
        Calendar startDate = Calendar.getInstance();
        startDate.add(Calendar.MONTH, -1);

        horizontalCalendar = new HorizontalCalendar.Builder(root, R.id.calendarView)
                .startDate(startDate.getTime())
                .endDate(endDate.getTime())
                .datesNumberOnScreen(5)
                .dayNameFormat("EEE")
                .dayNumberFormat("dd")
                .monthFormat("MMM")
                .textSize(14f, 24f, 14f)
                .showDayName(true)
                .showMonthName(true)

                .build();

        horizontalCalendar.setCalendarListener(new HorizontalCalendarListener() {
            @Override
            public void onDateSelected(Date date, int position) {
//                Toast.makeText(getContext(), DateFormat.getDateInstance().format(date) + " is selected!", Toast.LENGTH_SHORT).show();
            }

        });


text:
Q: FXML files don't seem to be transfered in the JAR I am trying to export a JavaFX program that I wrote with Intellij into a JAR so that I can send it to my classmates so they can run it during an oral presentation.
My files are structured this way :
src

*

*main

*

*java

*

*plop

*

*main

*others classes and controllers

*resources

*

*plop

*

*the three FXML files

To access the FMXL I use this :
53        FXMLLoader fxmlLoader = new FXMLLoader(main.class.getResource("SceneOuverture.fxml"));
54        Parent root =fxmlLoader.load();
55        Scene scene = new Scene(root);

When I run it from Intellij, it works, however when I export it with this artifact it stops working :
<component name="ArtifactManager">
  <artifact type="jar" name="modified-boids:jar">
    <output-path>$PROJECT_DIR$/out/artifacts/modified_boids_jar</output-path>
    <root id="archive" name="modified-boids.jar">
      <element id="directory" name="META-INF">
        <element id="file-copy" path="$PROJECT_DIR$/src/META-INF/MANIFEST.MF" />
      </element>
      <element id="module-output" name="modified-boids.main" />
      <element id="extracted-dir" path="$PROJECT_DIR$/../../../../../../Program Files/Java/jdk-18.0.1.1/lib/src.zip" path-in-jar="/" />
      <element id="extracted-dir" path="$PROJECT_DIR$/../../../../../../Program Files/Java/jdk-18.0.1.1/lib/jrt-fs.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.openjfx/javafx-base/18.0.1/3285f1855bf294dd4eba57ba84f96c555c819260/javafx-base-18.0.1-win.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.openjfx/javafx-graphics/18.0.1/79b7b4ecf6a90692e4accdbf9e4e68714d235844/javafx-graphics-18.0.1-win.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.openjfx/javafx-base/18.0.1/be9bf95be2716c11b88594eeaf4b832874265cc9/javafx-base-18.0.1.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.openjfx/javafx-controls/18.0.1/22cf4d2bbb80d0d0430fcf71cdf0dfe3475ebd93/javafx-controls-18.0.1-win.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.kordamp.bootstrapfx/bootstrapfx-core/0.4.0/8d019b30266c00770cf29921d1008ad7feed0ed6/bootstrapfx-core-0.4.0.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.openjfx/javafx-graphics/18.0.1/4180a4bfda9692cbb444fb70b2506546e03f961b/javafx-graphics-18.0.1.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.openjfx/javafx-fxml/18.0.1/c38102123668cca2a7dea83a7567fbebbe93f148/javafx-fxml-18.0.1-win.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.controlsfx/controlsfx/11.1.1/d303c563c23d5176346e8d05932afbec421060ae/controlsfx-11.1.1.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.openjfx/javafx-controls/18.0.1/c292e8fcec3ffd843216a29c3b00b2d320efe83d/javafx-controls-18.0.1.jar" path-in-jar="/" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-console-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-console-l1-2-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-datetime-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-debug-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-errorhandling-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-file-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-file-l1-2-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-file-l2-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-handle-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-heap-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-interlocked-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-libraryloader-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-localization-l1-2-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-memory-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-namedpipe-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-processenvironment-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-processthreads-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-processthreads-l1-1-1.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-profile-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-rtlsupport-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-string-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-synch-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-synch-l1-2-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-sysinfo-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-timezone-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-core-util-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-crt-conio-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-crt-convert-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-crt-environment-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-crt-filesystem-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-crt-heap-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-crt-locale-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-crt-math-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-crt-multibyte-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-crt-private-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-crt-process-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-crt-runtime-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-crt-stdio-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-crt-string-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-crt-time-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/api-ms-win-crt-utility-l1-1-0.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/decora_sse.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/fxplugins.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/glass.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/glib-lite.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/gstreamer-lite.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/javafx_font.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/javafx_iio.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/jfxmedia.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/jfxwebkit.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/msvcp140.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/msvcp140_1.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/msvcp140_2.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/prism_common.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/prism_d3d.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/prism_sw.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/ucrtbase.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/vcruntime140.dll" />
      <element id="file-copy" path="$PROJECT_DIR$/../../javafx-sdk-19/bin/vcruntime140_1.dll" />
    </root>
  </artifact>
</component>

This is the error message I have when I launch the JAR :
Exception in Application start method
(...)
Caused by: java.lang.IllegalStateException: Location is not set.
(...)
at plop.main.start(main.java:54)

I have tried to replace the three lines with these two :
53        Parent root =FXMLLoader.load(Objects.requireNonNull(getClass().getResource("SceneOuverture.fxml")));
54        Scene scene = new Scene(root);

However it still doesn't work so I have opened the JAR with 7-Zip and I can't find the FXML files in the ones that are extracted from the JAR, so I don't really know if the FXML cannot be extracted with 7-Zip or if they are not exported at all.
Do you have an idea of what I should do?

A: To put the fxml files in the jar, the solution is to add the resources folder in the artifact as "directory content".
Then, I had to replace
Parent root=FXMLLoader.load(Objects.requireNonNull(getClass().getResource("SceneOuverture.fxml"))) with Parent root =FXMLLoader.load(Objects.requireNonNull(getClass().getResource("/plop/SceneOuverture.fxml"))) for every FXML loader.


text:
Q: AngularJS controller with factroy reference not being called I cannot seem to get a simple controller working when I add a factory reference (homeFactory) to the controller's function constructor. If I remove the factory reference, the controller works. Also, with the reference in the controller, the controller never even gets called when I breakpoint it, so it doesn't appear to be something wrong with the factory. The value on the view shows up as {{ account }}, curly braces and all. Basically, the factory is calling a webapi controller to get the current user's active directory name.
Controller (doesn't work):
app.controller('HomeController', function ($scope, homeFactory) {
    $scope.message = 'This is a test Angular JS App';

    // get the account info from a webapi controller
    $scope.getAccount = function () {
        homeFactory.getAccount()
        .success(function (data) {
            $scope.status = '';
            $scope.account = data;
        })
        .error(function (error) {
            $scope.status = 'Unable to get user account: ' + error;
        });
    };
});

Controller (works):
app.controller('HomeController', function ($scope) {
    $scope.message = 'This is a test Angular JS App';
    // pass a test value
    $scope.account = 'Bob Jones'
});

Factory:
app.factory('homeFactory', function ($http) {
    var baseAddress = "../api/";
    var factory = {};
    // baseAddress and url are based on the

    // call the webapi controller
    factory.getAccount = function () {
        url = baseAddress + "home/account";
        return $http.get(url);
    };

    return factory;
});

Routing mod:
var app = angular.module('myApp', ['ngRoute']);

app.config(function ($routeProvider) {
    $routeProvider
    .when('/', {
        controller: 'HomeController',
        templateUrl: 'Partials/ViewStart.html'
    })
    .when('/view-start', {
        controller: 'HomeController',
        templateUrl: 'Partials/ViewStart.html'
    })
    .otherwise({ redirectTo: '/' });
});

ViewStart view:

This is the start view

{{ account }}

    <input type="text" data-ng-model="account" />

A: Stupid mistake on my part. I didn't include the script reference to my factory's javascript file in the main page. I was going to delete this post but figured I leave it in case someone else is having a similar issue.


text:
Q: How to create a 2D array of repeated lower triangular arrays I have a rectangular 2D array on which I want to apply a 2D indexing array (e.g. arr[indexing_array]).
import numpy as np
import pandas as pd
np.random.seed(1234)
arr = np.random.rand(4,9)

[[0.19 0.62 0.44 0.79 0.78 0.27 0.28 0.8  0.96]
 [0.88 0.36 0.5  0.68 0.71 0.37 0.56 0.5  0.01]
 [0.77 0.88 0.36 0.62 0.08 0.37 0.93 0.65 0.4 ]
 [0.79 0.32 0.57 0.87 0.44 0.8  0.14 0.7  0.7 ]]

I want the 2D indexing array to be a repeated lower triangular, something similar to this for the array arr:
[[False False False False False False False False False]
 [ True False False  True False False  True False False]
 [ True  True False  True  True False  True  True False]
 [ True  True  True  True  True  True  True  True  True]]

Right now I'm creating this index with the following command:
nb_rep = 3 # The number of times the lower triangular array is repeated
k = 0 # An offset for the diagonal
np.arange(arr.shape[0])[:, None] + k > np.tile(np.arange(arr.shape[1]-6), nb_rep)

I tried a solution with np.tril and np.tril_indices functions, but it was quite slower than this solution. Is there a way to simplify this (I'm really not sure about my implementation on the right side of the >)? I used np.tile, but from what I found it might not be the fastest for replicating arrays.

A: I don't know if my method is the most efficient but it seems to run faster than your code.
Your code:
import numpy as np
import pandas as pd
np.random.seed(1234)
arr = np.random.rand(4,9)

nb_rep = 3 # The number of times the lower triangular array is repeated
k = 0 # An offset for the diagonal
%timeit np.arange(arr.shape[0])[:, None] + k > np.tile(np.arange((arr.shape[1]-6)), nb_rep)

output:
The slowest run took 10.90 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 5: 12.9 µs per loop

My method:
%timeit np.arange(arr.shape[0])[:, None] + k > ((np.arange(6*nb_rep) % arr.shape[0])[None, :])

output:
The slowest run took 15.11 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 5: 6.02 µs per loop

using a much larger array the size of (4000, 9000), the difference is even more significant.
Output of testing your code:
100 loops, best of 5: 46.8 ms per loop

Output of testing my code:
100 loops, best of 5: 133 µs per loop


text:
Q: Is it possible to obtain the same legendary item from the same boss on successive kills? When farming an enemy and you get a legendary from an enemy (Killed Rakkman and you get a Gunerang out of him) when you kill that specific enemy again straight after you save and quit, is it certain that you'll get the legendary again?

A: There is definitely not a guaranteed chance at the same legendary weapon; the pseudorandom number generator isn't nearly that easy to fool. I have farmed many many bosses for less than many many legendary weapons and I'm not sure I've ever seen the same weapon spawn successively, and it certainly doesn't happen every time.
You can still get the same legendary a second/third/nth time around, but whether you do or not is completely random based on the boss' drop rate.

A: Are you asking if you are guaranteed to get a legendary every time you fight a boss after getting it the first time? Because that is a resounding no. You are not guaranteed any loot based on previous loot. Even if you were able to restart fights instantaneously.
But on that same note, getting a legendary from a boss does not remove that legendary from the loot table. You can get the same legendary from a boss as many as times as you can fight the boss. I don't know if the odds change at all* but there is always a chance for a legendary to drop despite how many times you have killed a boss. So yes it is possible to get a legendary several fights in a row. The odds are not in your favor but statistically it is possible.
*: The Warrior is unique if I recall correctly, where the first kill has something like a 90% chance of dropping a legendary. After that, it goes back down to a 'normal' boss loot table with legendaries being dropped only rarely.

A: AFAIK no, it's not certain. If I'm not mistaken, the algorithm processes the drop the moment you kill it, there is no predetermined fixed value regarding drops.
Say that you kill a Psycho and it drops a green weapon, exiting, reloading and killing the same Psycho again won't result in the same drop.


text:
Q: Calculating simple and their syzygies in group algebras with GAP Let $KG$ be a a group algebra for a finite field $K$ and a finite group $G$.

Question 1: How to obtain using GAP a finite field extension $L$ such that $L$ is a splitting field for $KG$ and all the simple $LG$-modules?

Question 2: Is there an easy way to calculate the n-th syzygies of the simple $LG$-modules using GAP?

Question 3: Can one calculate the $Hom$-spaces for two given $LG$-modules using GAP?

Those are all very elementary questions but looking at the GAP manual there seems to be no easy commands that answer one of those questions.
Thanks for any help


text:
Q: How one can use 'Wide-angle lense' or 'Telephoto lense' using camera2 api? As per my understanding manager.getCameraIdList() returns the possible number of logical camera id's we can use.Is there any way to determine which camera Id is an Id for 'Wide-angle lense' or 'Telephoto-lense' using manager.getCameraCharacteristics()?

A: Try using LENS_INFO_AVAILABLE_FOCAL_LENGTHS. If the cameras don't have optical zoom, then the numbers they will provide can straightforwardly  be used to tell the difference between a wide-angle lens(low number) and a telephoto lens(high number).


text:
Q: One Entity Have A Reference To Two Similar Entities A pair of domain entity classes, B1 and B2, which one of them mirrors the other mostly and shares its counterpart's id. Due to the system requirement, they need to be mapped to two DB tables. Both B1 and B2 has a one-to-many bi-directional relationship with another entity C. On the "many" side of the relationship, the entity C knows a relationship with both B1 and B2. Because of the similarity between B1 and B2, including the entity ID, I am wondering whether I could create an abstract entity class and let the entity C have a reference to only one entity. After looking into JPA mapping inheritance, I feel there isn't a suitable solution. And an embedded class likely isn't a suitable one either. If I really want to go with one entity reference route in C, I might need to add an entity ID attribute which refers either B1 or B2 to the entity C, but not defines any relationship between B1 or B2 and C. Any better approaches?

A: If you are willing to place a @OneToOne mapping between B1 & B2, you can easily give C and link to B1 or B2.  A @OneToOne seems most appropriate given the fact that B1 & B2 share the same identifier.


text:
Q: разный ответ mySQL на одинаковые команды С помощью терминала установил связь с удаленным сервером MySQL через SSH, авторизовался.
Ввожу команды и получаю разные ответы:
mysql> show databases // результат - перевод на новую пустую строку
    -> show databases;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'show databases' at line 2
mysql> show databases;
+-------------------------------------------------+
| Database                                        |
+-------------------------------------------------+
| information_schema                              |
+-------------------------------------------------+

почему, что не так и как надо? заранее спасибо

A: Команда заканчивается точкой с запятой. В первом случае вы ввели:
show databases
show databases;

Т.е. с точки зрения mysql вы ввели команду show databases show databases, которую он естественно не знает.
Во втором случае команда show databases; - т.е. все правильно.


text:
Q: CorePlot - CPTAnnotation.h not found I'm trying to use CorePlot to draw a simple plot.
I'm working from this tutorial, but when I type this in my ViewController.h:
<CPPlotDataSource>
{
   CPXYGraph *graph;
}

I encounter an error: CPTAnnotation.h file not found
What might be the cause?

A: The Core Plot class prefix has changed from "CP" to "CPT" since that tutorial was written. If you're using anything later than Core Plot 0.3, you'll need to make the change in your code, too. There are several other needed changes that are discussed in the comments on that post.


text:
Q: Generate large .csv file (1 Million rows+) within .NET Framework web application We have a .NET Framework (4.8) web application deployed in Azure and it has a feature where the user can export raw data to a .csv file. Dataset is large and could be millions of rows with around 20 columns.
Previously, the export feature used OpenXML SDK to generate a .xslx file but that process was way too long (could take up to 2 hours). Also, usually users click on export and then they close the browser and some times the app domain would get recycled by the application pool lifecycle and that leads to the fact that the file generation would never finish as the process gets killed.
We changed the file format to .csv and now the process takes around 15 minutes for a million rows. Reducing the execution time = reducing the chance that the app domain gets recycled before file generation ends.
BUT, we are still never sure that the file will always be generated and we are scared that in the future (as DB is constantly growing) the process will get killed easily again.
We're currently thinking about another approach, i've been investigating in Azure Web Jobs, Windows service, etc. but I did not find anything that would cover our needs : generate a large file at user request from web interface and then send download link by email. The process needs to be fast and we need to be sure that it will always finish execution.
I was wondering if any of you would have any ideas on how to solve that.
We are wondering on how to extract that file generation from the web application and how to trigger that at user request (meaning that we would need to pass parameters to that file generation).
Thanks!


text:
Q: Sort and manipulate array in javascript I have the following array:
var curr =     [{
      "Year": 2019,
      "Title": "Asset Management Sample",
      "Sum": 1020000.0,
      "Budget":0
}, {
  "Year": 2019,
  "Title": "Monday test 2",
  "Sum": 2546658.0,
  "Budget":100
}, {
  "Year": 2020,
  "Title": "Asset Management Sample",
  "Sum": 1020000.0,
  "Budget":1000
}, {
  "Year": 2020,
  "Title": "Monday test 2",
  "Sum": 3472000.0,
  "Budget":100
}, {
  "Year": 2021,
  "Title": "Asset Management Sample",
  "Sum": 1020000.0,
  "Budget":100
}, {
  "Year": 2021,
  "Title": "Monday test 2",
  "Sum": 2452000.0,
  "Budget":100
}]

That I need to change to:
[{
  "Year": 2019,
  "Asset Management Sample": 1020000.0,
  "Monday test": 2546658.0
}, {
  "Year": 2020,
  "Asset Management Sample": 1020000.0,
  "Monday test 2": 3472000.0
}, {
  "Year": 2021,
  "Asset Management Sample": 1020000.0,
  "Monday test 2": 2452000.0
}]

With help from earlier posters I have used .reduce (slightly modified from below) to generate this:
      var res = arr.reduce(function(acc, curr) {
      acc[curr.Year] = acc[curr.Year];
      acc[curr.Year] = acc[curr.Year] || { Year: curr.Year } ;
      acc[curr.Year][curr.Title] = curr.Sum;

      return acc;

I need to expand this to include a sum of all the budget values for each year (there should be a single budget value per year). I added the following line in before the return:
acc[curr.Year][curr.Budget] = curr[curr.Budget] || { Budget: curr.Budget } ;

It is adding individual entries for each Budget value. How do I sum the Budget values and return it without affecting the other returned array?

A: Use reduce like so:

const arr = [{"Year":2019,"Title":"Asset Management Sample","Sum":1020000},{"Year":2019,"Title":"Monday test 2","Sum":2546658},{"Year":2020,"Title":"Asset Management Sample","Sum":1020000},{"Year":2020,"Title":"Monday test 2","Sum":3472000},{"Year":2021,"Title":"Asset Management Sample","Sum":1020000},{"Year":2021,"Title":"Monday test 2","Sum":2452000}];
const res = Object.values(arr.reduce((acc, { Year, Title, Sum }) => (acc[Year] = acc[Year] || { Year }, acc[Year][Title] = Sum, acc), {}));
console.log(res);

More verbose version:

const arr = [{"Year":2019,"Title":"Asset Management Sample","Sum":1020000},{"Year":2019,"Title":"Monday test 2","Sum":2546658},{"Year":2020,"Title":"Asset Management Sample","Sum":1020000},{"Year":2020,"Title":"Monday test 2","Sum":3472000},{"Year":2021,"Title":"Asset Management Sample","Sum":1020000},{"Year":2021,"Title":"Monday test 2","Sum":2452000}];
const res = Object.values(arr.reduce((acc, { Year, Title, Sum }) => {
  acc[Year] = acc[Year] || { Year };
  acc[Year][Title] = Sum;
  return acc;
}, {}));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

ES5 syntax:

var arr = [{"Year":2019,"Title":"Asset Management Sample","Sum":1020000},{"Year":2019,"Title":"Monday test 2","Sum":2546658},{"Year":2020,"Title":"Asset Management Sample","Sum":1020000},{"Year":2020,"Title":"Monday test 2","Sum":3472000},{"Year":2021,"Title":"Asset Management Sample","Sum":1020000},{"Year":2021,"Title":"Monday test 2","Sum":2452000}];
var res = arr.reduce(function(acc, curr) {
  acc[curr.Year] = acc[curr.Year] || { Year: curr.Year };
  acc[curr.Year][curr.Title] = curr.Sum;
  return acc;
}, {});
res = Object.keys(res).map(function(key) {
  return res[key];
});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }


text:
Q: l'Hopital's rule in context with CDF and its density Consider, that the following $\lim_{x\to \infty} \frac{G(x)}{x} $ exists with $G(x) =-ln(1-F(x))$.
F is an arbitrary CDF with its density f.
I want to proof:
$$m(s)= s\int_0^{\infty} e^{st} (1-F(x))dx +1 = \infty \Leftrightarrow \lim_{x\to \infty} G'(x)=0 $$
From  $\lim_{x\to \infty} \frac{G(x)}{x} $ I can conlude using l'Hopital's rule  $\lim_{x\to \infty} \frac{G(x)}{x}= \lim_{x\to \infty} G'(x)$
How can I go on from that?


text:
Q: How can I reinterpret a byte as an integer in java? I have a problem with conversions of different types.
In my code I am trying to use bytes and then convert them to an integer to be able to write x amount of bits from the integer to a storage of a kind.
The problem is that when I have a negative number as byte and I convert it to an integer, the bit representation as an integer has all the leading bits set as 1.
So when I try to save for example 10 bits from the integer, I get the leading bits as 1 instead of 0 as I expected.
Is there a way to reinterpret the byte as an integer while keeping the bit representation the same? I do not need to care about the actual numerical value of the integer.
From C++ I am used to having unsigned values which would prevent this issue, but now I am at loss with how to deal with this in java being limited to signed integers.
Example:
/*
    decimal: -28
    as byte: 11100100
    as integer: 11111111111111111111111111100100
    needed/expected integer: 00000000000000000000000011100100
*/
import java.util.*;
import java.lang.*;
import java.io.*;

class MyClass
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(Integer.toBinaryString((byte)-28));
    }
}

https://ideone.com/VE960u

A: yourInt = yourByte & 255;

Just mask out the undesired bits.


text:
Q: Criteria with TempVars - but prompt user if tempvars is null I'm trying to create a query in Access that uses TempVars such that when the query runs and the tempvars has been populated it uses that value, but that if it has not been populated it prompts the user for a date.
Here is what I'm trying as my query criteria at present and it's not working.
IIF(IsNull([TempVars]![Role_DT]), [TempVars]![Role_DT],[please enter the date to report])

Everytime I run the query even though TempVars is populated a dialog is presented to enter the date.
Is there away to do this?

A: It's the other way 'round for IIf:
IIf([TempVars]![Role_DT] Is Not Null, [TempVars]![Role_DT], [Please enter the date to report])


text:
Q: Offloading PPPoE from an OPNsense router I'm running opnSense, a FreeBSD-based firewall and router similar to pfSense, in a virtual machine under VMware ESXi 7 on a Dell PowerEdge R230, as a router for my home network. No other VMs are running or even set up on the host, just this one.
My ISP uses symmetrical gigabit fiber. You connect to it via PPPoE with VLAN tagging. The IP is dynamically assigned, although it's unclear if it's DHCP or not. Either way, I get assigned a single IP not of my choosing. I don't have any static IPs nor a static block, something for which my ISP charges a non-trivial amount. Reconnecting often does give me a new IP, so I can't assume it would stay the same all the time.
I set up a gateway for the ISP in opnSense. opnSense does the PPPoE connection and for simplicity ESXi itself does the VLAN tagging so it's transparent to the underlying switch. The topology ends up looking like this:
       Internet
           ↓
      Fiber line
           ↓
       Fiber ONT
           ↓
    Ethernet cable
           ↓
     Physical NIC
           ↓
Virtual switch/port group
           ↓
      Virtual NIC
           ↓
      opnSense VM

The NICs in ESXi look like this. The first two are the onboard LAN. The last four are the PCI-E card: Dell Intel I350-T4 Quad Port 1GbE PCI-E card. The ISP's connection is using vmnic2, the first port on the PCI-E card.

But, the problem is I'm not getting the full speed. This is because FreeBSD has a bug with some NICs where PPPoE does not use all the CPU cores. The VM has what I'd consider overkill assigned to it: 4 vCPUs from a Xeon E3-1240 v5 (3.5 GHz) and 8 GB RAM, but apparently the single core performance isn't fast enough to do gigabit due to PPPoE. When I do a speed test, the CPU usage within the VM predictably goes to 25% (one of four cores) and I only get about 600 Mbps peak download, and for some reason upload is much worse than that too. When I use other hardware, like a Ubiquiti UniFi USG-3P or the ISP's provided modem/router, I get the nearly the full speed both directions. I've tried making the virtual NIC both vmxnet3 and e1000e with no difference in performance.
So with this setup, how can I get full speed with a PPPoE connection? I see several options but I don't know which is the best or the most likely chance of success:

*

*Use some other network driver in opnSense, although I have no idea how to do that or if an applicable one even exists. Is this even an option?

*Offload the PPPoE unwrapping in a Linux VM which doesn't have the PPPoE bug, and then have opnSense use that VM as the gateway and not the ISP directly. With this option there are two approaches I can think of:

*

*Use a Linux VM to act as a very simple router with NAT and treat opnSense as a DMZ, so all the port forwarding, etc. applies only to opnSense and I don't have to do it two places. This does directly expose the Linux VM to the internet without the opnSense firewall to protect it. Is this safe?

*Use a Linux VM to only unwrap the PPPoE aspect of the connection and send the unwrapped Ethernet frames straight to another interface; i.e., opnSense still gets the assigned the external IP and there's no NAT. I saw a tutorial on that but I don't think it works in my case because I don't have a static IP or static IP block. This sounds like the cheapest option with no new hardware or service charges if it works, but is it a good idea and is it safe?

*Use a hardware device of some kind to do the PPPoE-to-Ethernet conversion. My ISP-provided modem/router, which I'm not using right now, is a Zyxel C1100Z. It has an option for "transparent bridging", but best I can tell, the PPPoE handling would still happen on opnSense in this scenario which doesn't help. I'm not using the UniFi USG-3P because it is very buggy with software updates and also doesn't do the WAN failover reliably at all.

*Replace the PCI-E NIC with something else, or passthrough the physical PCI-E card to the VM instead of virtualizing it. From what I've seen so far, other vendors' cards like Realtek are even more unreliable in opnSense. Is there a NIC that's known to work for this scenario? Would the onboard LAN work any better?

*Install opnSense directly on the host or run it directly off a USB stick to eliminate the VMware side. I'm really hoping I can do a VM-based setup for snapshots and whatnot for safety. Would this be any improvement at all given the underlying hardware won't change?

*Replace opnSense with some other virtual appliance not based on FreeBSD, although I haven't yet found something as comparatively easy to use or feature-rich, or they're expensive or require subscription pricing. I prefer UIs over text configuration and want to use open source self-hosted software. Does such a product exist?

A: Here's a few suggestions:

*

*Use a bridge interface from ESXi for your WAN interface as opposed to PCI passthrough

*Use a Broadcom NIC, or an older Intel NIC using the em(4) driver. It may sound weird, but Broadcom NICs may be better for PPPoE.

A: Have you tried this.
There is another way. By default, FreeBSD kernel performs all processing of received PPPoE frame within driver interrupt context: decapsulation, optional decompression/decryption, network address translation, routing lookups, packet filtering and so on. This can result in overloaded single CPU core in default configuration when sysctl net.isr.dispatch=direct. Since FreeBSD 8 we have netisr(8) network dispatch service allowing any NIC driver just enqueue received ethernet frame and cease its following processing freeing this CPU core. Other kernel threads using other CPU cores will then dequeue received frames to complete decapsilation etc. loading all CPU cores evenly.
So, one just should make sure it has "net.isr.maxthreads" and "net.isr.numthreads" greater than 1 and switch net.isr.dispatch to "deferred" value that permits NIC drivers to use netisr(9) queues to distribute load between CPU core
From
https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=203856#c11


text:
Q: Not sure of my use of foreign keys I'm building a system whereby students can view their results once they are out. The system is supposed to keep record of the student's marks over the course period when they progress to the next year. I'm not sure about my use of foreign keys in the Module_tests table though. I have two foreign keys in this table to identify a test's mark for a specific student and specific module. I guess this pair of foreign keys are the primary key of Module_tests table. Is this a sensible design? Is there a more efficient one?
Thanks in advance
Student table has three columns: StudentID, first name, surname.
Module table has three columns: ModuleID, ModuleName, Year.
Module_tests table has five columns: StudentID, ModuleID, Assignment, PracticalTest, FinalExam.
(hope it's clear as text as I can't attach images in my posts)

A: I think you should add an additional column to Module_tests that can be primary and auto-increment.
In the situation whereby the students have to retake a module, the integrity of your database might get compromised. Other than that, your tables seem fine.

A: A junction table that uniquely identifies rows by two foreign keys has been asked in this question, and the answers pretty much apply here.


text:
Q: In aiohttp or httpx do I need to close session/client on application shutdown I am using httpx library but I think the principle for aiohttp is the same.
If I create and reuse AsyncClient for multiple requests throughout the lifetime of the application do I need to call aclose() (or close if use Client) at the application shutdown event? Or will those connections die themselves.
What if I run application in Docker container? Will that be a factor as well?
I don't understand what's going on underneath AsyncClient or Client (or ClientSession in aoihttp) objects.
Thanks for help.

A: I suggest you to use the triggers on startup and shutdown. They are described in the docs https://fastapi.tiangolo.com/advanced/events/#events-startup-shutdown.
Below an adaptation of the example taken from the docs:
from fastapi import FastAPI
import httpx

app = FastAPI()

items = {}
client = None

@app.on_event("startup")
async def startup_event():
    items["foo"] = {"name": "Fighters"}
    items["bar"] = {"name": "Tenders"}
    client = httpx.AsyncClient()

@app.on_event("shutdown")
async def shutdown_event():
    items["foo"] = {"name": "Fighters"}
    items["bar"] = {"name": "Tenders"}
    await client.aclose()

EDIT
Sorry, misunderstood the question.
Anyway, as @Klaus D commented, the system should kill the child process(es if many are spawned) that keep open ports.
In my experience, this may not always be the case, as I remember when programming with php, I had to manually kill all the database connections, otherwise on application restart I got "The process is already using that port".
Although it was the case of a database connection and not an HTTP connection, it is always good practice to close all unused connections, since the OS may have a delay in noticing the running process with the open port and killing it. So your app (or whatever you have) would be stopped, but the process still running after a while.
Updates to the OS may change the behavior of the process watcher and depend on the OS itself. So, take what I say with a grain of salt.


text:
Q: Laravel 5.4: Error with migrations and foreign keys Having used the appropriate artisan commands:
php artisan make:model VenuesGeoNations --migration
... and:
php artisan make:model VenuesGeoRegions --migration
I created the schema:
Schema::create('venues_geo_nations', function (Blueprint $table) {
    $table->increments('id');
    $table->string('nation');
    $table->string('iso');
    $table->timestamps();
});

... and:
Schema::create('venues_geo_regions', function (Blueprint $table) {
    $table->increments('id');
    $table->string('towns_cities');
    $table->string('regions');
    $table->string('nations');
    $table->mediumInteger('venues_geo_nation_id')->unsigned();
    $table->foreign('venues_geo_nation_id')->references('id')->on('venues_geo_nations');
    $table->timestamps();
});

However, when I run the migration command, I get the error:

[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error:
  1215 Cannot add foreign key constraint...

... on the venues_geo_regions table, in spite of the correct execution order.
I've also tried executing in the reverse order and I get the same error.
Compounding things is the fact that each rollback wipes out the tables for Voyager, and if it wasn't for snapshots on the EC2 instance I'm using, I'd have gone mad before now.
At this stage I'm a bit lost, and have to assume I'm doing something wrong.


text:
Q: Find the limit of the following problem Can someone please help me understand this problem
Does the limit exist in the part (a) and part (b)
A) $$\lim_{(x,y) \to (0,0)} x \sin (\frac{1}{y})$$
B) $$\lim_{(x,y) \to (0,0)} \left( x \sin (\frac{1}{y})+y \sin (\frac{1}{x}) \right)$$

A: Hints:
For first: Squeeze theorem and $|\sin u| \leq 1$. So that:
$$|x \sin (\frac{1}{y})| \leq |x|$$
For second: Triangle inequality that $$|a+b| \leq |a| +|b|$$ and similar reasoning as in the first hint.

A: If you mean that
a) $f(x,y) = x \sin (\frac{1}{y})$, and the question is if $\lim_{(x,y) \to 0} f(x,y)$ exists, then yes, it exists and is equal to $0$.

A: $ |x\sin{1/y}| \leqslant|x|$ etc


text:
Q: Jquery image overlay gallery parameter issue I'm using the mosaic sliding boxes and captions plugin. It's pretty smooth but I'd love to fix two problems, visible on this jfiddle. Some CSS/jQuery wiz here will know:
http://jsfiddle.net/9ZPrf/2
1) The overlay box doesn't cover the bottom of the image. I've fiddled with many of the obvious parameters in the CSS and jQuery. This problem has emerged because I add the hover_y parameter in my inline script. That is designed to raise the overlay higher so more text becomes visible.
2) The opacity only changes when you hover on the overlay, but it would be good if it changed wherever you are over the image, which is what the slide responds to.
I've already tried many of the obvious parameters, I'm hoping someone here can help.
Thanks

A: Here, I've fixed it for you http://jsfiddle.net/9ZPrf/4/
I'd like to give you some explanations, but this is general HTML/CSS, so it is difficult to do it briefly. Good luck learning!


text:
Q: Finding a limit without using L'Hospital's rule I encountered an issue for finding the limit for a function, one small step I just can't get.
I know that this is classic case for L'Hospital's however our calculus course didn't reach it and I can not use it for this one.
$
2.3 .m,n\in\mathbb{N}\quad\underset{x\rightarrow1}{\lim}\frac{x^{m}-1}{x^{n}-1}$
$x\neq1$
\begin{aligned}\underset{x\rightarrow1}{\lim}\frac{x^{m}-1}{x^{n}-1}=\underset{x\rightarrow1}{\lim}\frac{x^{m}-1^{m}}{x^{n}-1^{n}}=\underset{x\rightarrow1}{\lim}\frac{\left(x-1\right)\sum_{i=0}^{m-1}x^{i}\cdot1^{m-i-1}}{\left(x-1\right)\sum_{i=0}^{m-1}x^{j}\cdot1^{n-j-1}}=\\
\underset{x\rightarrow1}{\lim}\frac{\left(m-1\right)x^{m-1}}{\left(n-1\right)x^{n-1}}=\underset{x\rightarrow1}{\lim}\frac{mx^{m-1}-x^{m-1}}{nx^{n-1}-x^{n-1}}
\end{aligned}
And here I stuck...
know I need to reach $\frac{m}{n}$ but how can I proceed...?!!? nothing to cancel out here...

A: It seems you are aware that the numerator and denominator factor. Check the upper limit on the sigma in the denominator, and also check the conclusion that $$\underset{x\rightarrow1}{\lim}\frac{\left(x-1\right)\sum_{i=0}^{m-1}x^{i}\cdot1^{m-i-1}}{\left(x-1\right)\sum_{i=0}^{m-1}x^{j}\cdot1^{n-j-1}}=
\underset{x\rightarrow1}{\lim}\frac{\left(m-1\right)x^{m-1}}{\left(n-1\right)x^{n-1}}.$$
The left hand side is correct (apart from the upper limit in the denominator), but the right is not. It should read $$\underset{x\rightarrow1}{\lim}\frac{\sum_{i=0}^{m-1}x^{i}\cdot1^{m-i-1}}{\sum_{i=0}^{n-1}x^{j}\cdot1^{n-j-1}}=\frac{m}{n}.$$

A: You can factor
$$x^m-1 = (x-1)(x^{m-1} + x^{m-2} + \dots + x + 1)$$.

A: $$\frac{x^m-1}{x^n-1}=\frac{(x-1)(1+x+x^2+\cdots +x^{m-1})}{(x-1)(1+x+x^2+\cdots +x^{n-1})}$$
The numerator has $m$ terms and the denominator has $n$.
Applying the limit, we get
$$\lim_{x \to 1}\frac{x^m-1}{x^n-1}=\frac{m}{n}$$

A: Another approach is along the lines of
\begin{align}
L & = \lim_{x \to 1} \frac{x^m-1}{x^n-1} \\
  & = \lim_{h \to 0} \frac{(1+h)^m-1}{(1+h)^n-1} \\
  & = \lim_{h \to 0} \frac{1+mh+O(h^2)-1}{1+nh+O(h^2)-1} \\
  & = \lim_{h \to 0} \frac{mh+O(h^2)}{nh+O(h^2)} \\
  & = \frac{m}{n}
\end{align}

A: Once you factor $x-1$ from the numerator and denominator, simply cancel them out, then substitute $1$.  This yields
$$\dfrac{\sum_{i=0}^{m-1}1}{\sum_{i=0}^{n-1}1}$$
Since each term in the sum is now constant, this reduces to simple multiplication.  There are $m$ $1$'s in the numerator and $n$ $1$'s in the denominator.  So the result is simply $\frac{m(1)}{n(1)}=\frac mn$.

A: $\lim_{x\to 1} \dfrac{x^m - 1}{x^n - 1} =
\lim_{x\to 1} \dfrac{(x-1)(x^{m - 1} + x^{m - 2} + x^{m - 3} + ... + 1)}{(x-1)(x^{n - 1} + x^{n - 2} + x^{n - 3} + ... + 1)} =
\lim_{x\to 1} \dfrac{(x-1)\sum_{i=1}^{m} x^{m-i}}{(x-1)\sum_{j=1}^{n} x^{n-j}} =
\lim_{x\to 1} \dfrac{\sum_{i=1}^{m} x^{m-i}}{\sum_{j=1}^{n} x^{n-j}} =
\dfrac{\sum_{i=1}^{m} 1^{m-i}}{\sum_{j=1}^{n} 1^{n-j}} =
\dfrac{\sum_{i=1}^{m} 1}{\sum_{j=1}^{n} 1} =
\dfrac{m}{n}$

A: \begin{aligned}\underset{x\rightarrow1}{\lim}\frac{x^{m}-1}{x^{n}-1}
&=\underset{x\rightarrow1}{\lim}\frac{x^{m}-1^{m}}{x^{n}-1^{n}}\\
&=\underset{x\rightarrow1}{\lim}\frac{\left(x-1\right)\sum_{i=0}^{m-1}x^{i}\cdot1^{m-i-1}}{\left(x-1\right)\sum_{i=0}^{m-1}x^{j}\cdot1^{n-j-1}}\\
&=\underset{x\rightarrow1}{\lim}\frac{\sum_{i=0}^{m-1}x^{i}\cdot1^{m-i-1}}{\sum_h{i=0}^{m-1}x^{j}\cdot1^{n-j-1}}\\
&=\dfrac mn
\end{aligned}

A: Define $\displaystyle L(m,n) = \underset{x\rightarrow1}{\lim}\frac{x^{m}-1}{x^{n}-1}.$ You wish to find the value of $L(m,n)$ for $m,n\in\mathbb N$.
It's easy to see that $L(k,k)=1$, and if $L(m,n)$ exists and is nonzero, then $L(m,n)=\dfrac{1}{L(n,m)}$. Now notice that
$$L(m+1,n)=\underset{x\rightarrow1}{\lim}\frac{x^{m+1}-1}{x^{n}-1}=\underset{x\rightarrow1}{\lim}\frac{x\left(x^{m}-1\right)+(x-1)}{x^{n}-1}=L(m,n)+L(1,n),$$
so $L[m,n]$ satisfies the recurrence relation
$L[m,n]={\Big\{}
\begin{array}{cc}
  \ &
    \begin{array}{cc}
      1 & m=n \\
      \dfrac{1}{L[n,m]} & m<n \\
      L(m-1,n)+L(1,n) & m>n
    \end{array}
\end{array}
$
This recurrence relation has a unique solution $L[m,n]=\dfrac{m}{n}$.


text:
Q: Resource Optimization: which one to use Knapsack, brute-force or any other approach? In a resource allocation problem i have n bucket sizes and m resources. Resources should be allocated to buckets in such a way that there will be max utilization. I need to write algorithm in Node js
Here's the problem: Let's say i have 2 buckets of sizes 50 and 60 respectively. Resource sizes are 20, 25, 40.  Following is the more proper representation with possible solutions:
Solution 1:
| Bucket Size | Resource(s) allocated | Utilization |
|             50             |                       20, 25                   |    45/50 = 0.9    |
|             60             |                          40                      |  40/60 = 0.667  |
Total Utilization in this case is  >1.5
Solution 2:
| Bucket Size | Resource(s) allocated | Utilization |
|             50             |                          25                      |    25/50 = 0.5    |
|             60             |                       20, 40                   |    60/60 = 1.0    |
Total Utilization in this case is  1.5
Inference:
-- Knapsack approach will return Solution 2 because it will do optimization based on higher bucket size.
-- Brute-Force approach will return both the solutions. One concern with this approach i have is; given that i have to use Node js and it is single threaded, i am little skeptic about performance when n (buckets) and m (resources) will be very large.
Will Brute-Force would do just fine or is there a better way/algorithm with which i can solve this problem? Also, is the concern which I've cited above is valid in any sense?

A: Knapsack problem (and this is knapsack problem) is NPC, which means, you can find solution only by brute-force or with alghoritms which  have O-complexity same as bruteforce, but can be better in average case...

it is single threaded, i am little skeptic about performance when n
  (buckets) and m (resources) will be very large.

I am not sure, if you know how thing works. If you do not create child threads and handle them (which is not that easy), every standard language will work in one thread, therefore in one processor. And if you want more processors that much, you can create child threads even in Node.Js.
Also in complexity problems, it does not matter, if solution takes multiple-time more, if the "multiple" is constant. In your case, I suppose the "multiple" means 4, if you have quad-core.
There are two good solutions :
1)Backtracking - it is basically advanced brute-force mechanism, which can in same cases return solution much faster.
2)Dynamic programming - If you have items with relatively low-values, then while classic brute-force is not able to find solution for 200 items in the expected time of universe itself, the dynamic approach can give you solution in (mili)seconds.