text:
Q: Executing an external program in Java returns "Access denied" or stops execution Update 3
Progress! I wrote a CMD script which takes three parameters:

*

*the absolute path to sqlite3cipher.exe

*the absolute path to testdb

*the absolute path to statements.sql
All the script does is execute the command
path\to\sqlite3cipher.exe path\to\testdb < path\to\statements.sql

This script is being called from within my Java code. And it works like a charm! At least with all the files residing in a folder in my home directory. Having the files in a subfolder of C:\Program Files doesn't work so there might be an issue with privileges which I have to work out with the administrator.

Update 2
I've created a dummy SQL file in my home directory. The code should now read the SQL file from and write the database file to my home directory.
Again omitting cmd /c in the command reads and writes the first line from the SQL file but stops after that (execution of the whole program comes to a halt).
Executing the command including cmd /c reads and writes every single line of the SQL file but once EOF is reached (in which case nothing will be written of course) I again get the Access denied message.

Update 1
Taking skarist's comment into account the following command (omitting cmd /c as it isn't mandatory for executing exe-files after all)
String cmdForRuntime = "\"" + prog.getAbsolutePath() + "\" \"" + fDb.getAbsolutePath() + "\"";

which spelled out looks like
"C:\Program Files\Apache Software Foundation\bin\sqlite3cipher.exe" "C:\Program Files\Apache Software Foundation\pages\dbdir\testdb"

doesn't produce any output. Also the code stops executing, so I assume there's something wrong with the I/O?

Problem
In order to encode a database I want to execute sqlite3cipher.exe on the command line in Java.
I ran into quite some diverging results for various approaches. At first the setup (notice that this is a testing environment where right now nothing can be changed regarding where files are located):

*

*sqlite3cipher.exeresides in C:\Program Files\Apache Software Foundation\bin\

*an empty file testdbresides in C:\Program Files\Apache Software Foundation\pages\dbdir\

*a file containing SQL statements statements.sql resides in the same folder as testdb does
Executing sqlite3cipher.exe -help on the command line prints the usage. Here is an exerpt:
C:\Program Files\Apache Software Foundation\bin\sqlite3cipher.exe [OPTIONS] FILENAME [SQL]
FILENAME is the name of an SQLite database. A new database is created if the file does not previously exist.

Executing "C:\Program Files\Apache Software Foundation\bin\sqlite3cipher.exe" "C:\Program Files\Apache Software Foundation\pages\dbdir\testdb" < "C:\Program Files\Apache Software Foundation\pages\dbdir\statements.sql" on the command line has the desired effect: testdb now is an encrypted database according to the SQL statements that were put in through the statements.sql.
Now in Java my code looks like this:
String cmdForRuntime = "cmd /C \"" + prog.getAbsolutePath() + "\" \"" + fDb.getAbsolutePath() + "\" < \"" + fSqlScript.getAbsolutePath() + "\"";
Process process = Runtime.getRuntime().exec( cmdForRuntime );

BufferedReader stdIn = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s;

while ((s = stdIn.readLine()) != null) {
    logger.info("OUTPUT FROM PROG: " + s);
}

if (process.waitFor() == 0) {
    logger.info("Process finished");
}
else {
    logger.error("Error!");

    // Get input streams
    BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    System.out.println("Standard error: ");
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
    }
}

where prog , fDb and fSqlScript are of type File and represent sqlite3cipher.exe, testdb and statements.sql respectively.
I'm not well versed with Process.execute() but what I gathered from reading about it is that cmd /c as part of the command is required on Windows (the test server is running Windows 8) in order to start the command interpreter.
On execution this code returns Access denied on the command line (via the process's streams). Executing this exact command (including cmd /c) on the command line directly returns the same result: Access denied. Even if I start the command line as administrator.
Leaving cmd /c out of the command (because it had worked without on the command line before), I get the message that there are too many options.
On further investigation, I learned that this problem is caused by the < operator, used in the command to redirect the input. The exec() method won't recognize < as an operator and it was suggested to use the process's OutputStream. So I changed my code to look like this:
String cmdForRuntime = "cmd /c \"" + prog.getAbsolutePath() + "\" \"" + fDb.getAbsolutePath() + "\"";
Process process = Runtime.getRuntime().exec( cmdForRuntime );

BufferedWriter bufferedwriter = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
BufferedReader br = new BufferedReader(new FileReader(fSqlScript.getAbsolutePath()));

BufferedReader stdIn = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s;
String fileInput = br.readLine();

while (fileInput != null) {

    bufferedwriter.write(fileInput);

    while ((s = stdIn.readLine()) != null) {
        logger.info("OUTPUT FROM PROG: " + s);
    }

    fileInput = br.readLine();
}

if (process.waitFor() == 0) {
    logger.info("Process finished");
}
else {
    logger.error("Error!");

    // Get input streams
    BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    System.out.println("Standard error: ");
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
    }
}

As I understand it is important to read what the external program prints out so it won't block or stop working. That's why I read a line from statements.sql (through the BufferedReader br) and write it to the process's OutputStream. Then I read what the program will print out (logging that output). If there is nothing (left) to read I read the next line from the statements.sql. This will be repeated until there is nothing left to read from said file.
If I execute this code, my logger will log the following:
INFO  Executing command: cmd /c "C:\Program Files\Apache Software Foundation\bin\sqlite3cipher.exe" "C:\Program Files\Apache Software Foundation\pages\dbdir\testdb"
ERROR Error!
Standard error:
Access denied

In this case, the code at least terminates resulting in an empty file testdb. In another approach I left cmd in the command but skipped the /c resulting in following output:
INFO  Executing command: cmd "C:\Program Files\Apache Software Foundation\bin\sqlite3cipher.exe" "C:\Program Files\Apache Software Foundation\pages\dbdir\testdb"
INFO  OUTPUT FROM PROG: Microsoft Windows [Version 6.3.9600]
INFO  OUTPUT FROM PROG: (c) 2013 Microsoft Corporation. Alle Rechte vorbehalten.
INFO  OUTPUT FROM PROG:

The output is the same you get when you type cmd on the command line. And that's where execution stops.

tl;dr

*

*execution on command line directly works like a charm

*exact same command executed from Java doesn't work

*command prepended by cmd /c (as it apparently should be) and usage of the process's InputStream and OutputStream doesn't work: Access denied
I'm not sure what to do next, so I sincerely hope someone can help me.

A: So I solved the problem with the workaround I mentioned in update 3.
My Java code now looks like this (besides the cmdForRuntime variable it should be pretty much the same code as in the beginning, when I asked this question):
try {
        File fDb = new File(this.inputDirectory + File.separator + dbName);

        String cmdForRuntime =  "\"" + cmdScript.getAbsolutePath() + "\"" + " " +       // the script to be executed
                                "\"" + prog.getAbsolutePath() + "\"" + " " +            // sqlite3cipher.exe
                                "\"" + fDb.getAbsolutePath() + "\"" + " " +             // testdb
                                "\"" + fSqlScript.getAbsolutePath() + "\"";             // statements.sql

        logger.info("Executing command: " + cmdForRuntime );

        Process process = Runtime.getRuntime().exec( cmdForRuntime );

        BufferedReader stdIn = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String s;

        while ((s = stdIn.readLine()) != null) {
            logger.info("OUTPUT FROM PROG: " + s);
        }

        if (process.waitFor() == 0) {
            logger.info("Process finished");
        }
        else {
            logger.error("!!!! error !!!!");
            // Get input streams
            BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            System.out.println("Standard error: ");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }
        }
    }
    catch(Exception ioe) {
        ioe.printStackTrace();
    }

cmdForRuntime will read something like this (I will omit the paths, the only add to the confusion):
"SQLiteCipher.cmd" "sqlite3cipher.exe" "testdb" "statements.sql"

The content of the script looks like this:
%1 %2 < %3

This will invoke the sqlite3cipher.exe with the parameter testdb and a redirected input coming from statements.sql.
Critical is that the location of the script as well as the location of the exe is not a system folder.
If all these criteria are met everything works like a charm.

A: You are having User Account Control issue.
It seems like the program is running in non-elevated mode, to make changes to system directories the application need to run in elevated mode.
Running you program in elevated mode should solve the problem.


text:
Q: Removing a file that starts with a preifx using tar in Linux Is it possible to remove all files that start with certain name from a compressed tarball without extracting and recreating the archive again?

A: The tar file format is a streaming format, so it would be possible to do this by reading the old file, skipping over the unwanted file(s), and copying all the data you want to keep to a new tar file. If the tar file is also compressed (eg. .tar.gz), then you would have to uncompress, filter, recompress, and write.
I don't know of any existing tools to do this, but it should be reasonably straightforward using the Python tarfile module, for example.

A: You may post-process the tar stream with tardy, which can filter a tar file to remove (or rename) some files. You probably want to use the -EXclude option, or perhaps the -Remove_Prefix one. (tardy has case sensitive options).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does this async function run synchronously? Here's my code:
async function test() {
  console.log('TEST');
}

function go() {
  console.log('one');
  test();
  console.log('two');
}

go()

I've marked the test function as async, and I am not using await in the go method that calls it, so I expect the output to be this:
one
two
TEST

But the output comes out like this:
one
TEST
two

In my real use-case, test is a function that wraps some long-processing logic that I actually do want to happen asynchronously, not in-order.
Why isn't that happening here, and how can I fix it?

A: The body of an async function executes synchronously, until the first await statement. When it encounters an await expression it yields control to the calling function and is suspended. The part after the await expression is completed asynchronously.
As per the MDN docs:

The body of an async function can be thought of as being split by zero
or more await expressions. Top-level code, up to and including the
first await expression (if there is one), is run synchronously. In
this way, an async function without an await expression will run
synchronously. If there is an await expression inside the function
body, however, the async function will always complete asynchronously.
Code after each await expression can be thought of as existing in a
.then callback. In this way a promise chain is progressively
constructed with each reentrant step through the function. The return
value forms the final link in the chain.

This can be observed with the following example with no await, where the body of the function is executed synchronously:

async function testSync() {
  console.log("Runs synchronously");
}

console.log(1);

testSync();

console.log(2);

Here is an example where an awaited Promise makes the behavior asynchronous after the await:

async function testAsync() {
  console.log("Runs synchronously until here");
  await myPromise();
  console.log("Runs asynchronously here");
}

function myPromise() {
  return Promise.resolve();
}

console.log(1);

testAsync();

console.log(2);

This could be made to execute asynchronously in a number of ways. You can wrap your function in a setTimeout call:

function test() {
  console.log("I want to execute asynchronously");
}

console.log(1);
setTimeout(test, 0);
console.log(2);

Or you can do it through promise callbacks:

function test(){
 console.log("I want to run asynchronously");
}
console.log(1);
Promise.resolve().then(test).catch(e => console.error(e));
console.log(2);

Same can be done using queueMicrotask, docs here :

function test(){
 console.log("I want to run asynchronously");
}
console.log(1);
queueMicrotask(test);
console.log(2);

The difference between the setTimeout and the method using Promise callbacks is how they are queued for execution. There are two task queues, one is the task queue where the initial program execution, setTimeout, setInterval, requestAnimationframe, etc callbacks are queued and the other is the microtask queue where promise callbacks are queued.
When you enqueue a task from the task queue and there are tasks still left, the event loop will check the microtask queue and execute them all before taking up the next task from the task queue.
Here is a snippet demonstrating this:

function testTaskQueue(){
 console.log("Enqueued in the task queue");
}
function testMicroTaskQueue(){
 console.log("Enqueued in the microtask queue");
}

console.log(1);
setTimeout(testTaskQueue, 0);
Promise.resolve().then(testMicroTaskQueue);
queueMicrotask(testMicroTaskQueue);
console.log(2)

So depending on this, you can make your own async wrapper and pass your function to be executes as a callback:

function makeAsync(callback, ...params) {
  //enqueued intask queue
  setTimeout(callback, 0, ...params);
  //Or using microtasks
  Promise.resolve().then(() => test(...params)).catch(console.error);
}

function test(...params) {
  console.log("I want to run asynchronoulsy", ...params);
}
console.log(1)
makeAsync(test, 3);
console.log(2);


text:
Q: Filter a List of Dates by Day Number I'm attempting to filter a calendar (a list of dates) by day number, but struggling for a specific scenario!
The calendar would initially contain all dates over a specified range, say 31st Jan 2013 - 31st Jan 2015.  I would like to filter this list to contain only dates which match the first day number in the calendar, so for example if the first day in the calendar is 25, the new filtered calendar returned would be:

*

*25 Feb 2013

*25 Mar 2013

*25 Apr 2013

... etc
This first example is simple enough with LINQ
var calendar = ...code to get calendar from DB.

//Get Day Number of First Entry in Calendar (31st for example)
int day = calendar.Dates.Select(d => d.Date.Day).First();

//Filter the rest of the calendar by this date.
return new Calendar
{
    Dates = calendar.Dates.Where(c => c.Date.Day == day).ToList()
};

I get into difficulty when passing in say, 31.  My requirement is so that this is returned:

*

*31 Jan 2013

*28 Feb 2013

*30 Apr 2013

*31 May 2013

... etc
What's the best way to achieve this? It's pecking my brain on a Wednesday morning!
I would like if at all possible for the answer to be a perfect one-liner LINQ statement :)
Many thanks,
Alex

A: Dates = calendar.Dates.Where(c => c.Date.Day == Math.Min(day, DateTime.DaysInMonth(c.Year, c.Month))).ToList()

A: DateTime.DaysInMonth to the rescue!
return new Calendar
{
Dates = calendar.Dates.Where(c => c.Date.Day == Math.Min(day, DateTime.DaysInMonth(c.Year, c.Month))).ToList()
};


text:
Q: Does an estimator need to be unbiased in order to be sufficient? I am reviewing some theoretical statistics content, and I was wondering if an estimator need to be unbiased in order to be sufficient? Is there any way to prove this? Thanks!

A: No. You can multiply a sufficient estimator by anything (like, say, /(−1)) and it will stay sufficient but stop being unbiased


text:
Q: Passing the client certificate to the backend for mutual auth with AWS Load Balancer Controller I am using EKS/Fargate for K8s deployment and using AWS Load Balancer Controller. There are few use cases which needs to support mutual authentication. In my opinion mutual authentication is not supported in ALB rather in the AWS Gateway. Even though the Gateway support it there is a limitation that it cannot be used as individual cert per API. Hence I am looking at options to offload TLS in ALB and pass the certificate to backend for mutual authentication. Looking for a similar option like in Nginx controller as stated here.
Here is the annotation.
nginx.ingress.kubernetes.io/auth-tls-pass-certificate-to-upstream
Also I am aware that this can be directly done in the POD level with TLS termination if we use a NLB. However we enforces certain WAF rules from AWS which is not available to have in layer 4. Hence kindly looking for your input. Not sure such a feature is planned with ALB controller in the future.


text:
Q: Display friend Facebook on IOS I have trouble displaying list friend facebook, I'm using FBRequest, I have already get list friend but it's not showing in UITableView
Here is my code:
- (void)viewDidLoad
{
    [self.tblView setDataSource:self];
    [self.tblView setDelegate:self];
    [super viewDidLoad];
    [self loadFirst];
        _itemsNamesFriend = [[NSMutableArray alloc] init];
        if (FBSession.activeSession.isOpen) {

            FBRequest *friendRequest = [[FBRequest alloc] initWithSession:FBSession.activeSession graphPath:@"me/friends"];

            [friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                NSDictionary *resultDictionary = (NSDictionary *)result;
                _itemsNamesFriend = [resultDictionary objectForKey:@"data"];
                NSLog(@"%@",_itemsNamesFriend); //--> have data

            }];

            NSLog(@"%@",_itemsNamesFriend); //--> data is empty
            [self.tblView reloadData];
        }

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    NSLog(@"%d",_itemsNamesFriend.count);
    return _itemsNamesFriend.count;
}

A: Any modification done to variables inside the block don't show outside of it. So, you need to declare them with __block for the modifications done inside the block to be visible outside.
This is what you need to do in your .h file
__block NSMutableArray* _itemsNamesFriend;

That should solve you problem.


text:
Q: Recurrence relation for number of ways covering $3\times N$ rectangle with dominos Here is a problem:

Find a number of ways to cover $3\times N$ rectangle with $1\times 2$ and $2\times 1$ dominos.

For odd $N$, the answer is 0. For even $N$, I found the recurrence relation of $a_{n}$, the number of ways to cover $3\times n$ rectangle.
$$
a_{n} = 3a_{n-2} + \sum_{j=0}^{(n-4)/2} 2a_{2j}
$$
This can be proved in the following way: consider the right-most vertical line formed by dominos.

Then we will divide case by the number of blocks on the right of the line. If there are only 3 dominos, then we have 3 possibilities for the right side

and $a_{n-2}$ possibilities for the left side. This contributes $3a_{n-2}$ for the sum. If there are more than 3 dominos, i.e. $3j$ dominos for $j\geq 2$, then we have two possibilities for the right side

and $a_{n-2j}$ possibilities for the left side. This contributes $2a_{n-2j}$ for the sum. Now replace $n$ by $n-2$ and
$$
a_{n-2} = 3a_{n-4} + \sum_{j=0}^{(n-6)/2} 2a_{2j}.
$$
If we subtract two equations, we get
$$
a_{n} = 4a_{n-2} - a_{n-4}
$$
and using this, we can find the general formula for $a_{n}$.
However, I want to know if it is possible to show the above equation directly, by using simple arguments like above. (Find some bijections.) Is it possible to show $a_{n} + a_{n-4} = 4a_{n-2}$ directly? Thanks in advance.

A: Let $a_n$ be the number of ways to tile a $3\times n$ rectangle, let $b_n$ be the number of ways to tile a $3\times n$ rectangle minus its top left field (or equivalently: minus its bottom left field).
Then $$a_n=a_{n-2}+2b_{n-1}$$ because we either have three horizontal dominoes at the left edge (leaing a $3\times (n-2)$ rect), or in one of two different ways a vertical domino and then par force a horizontal domino (leavong a $3\times (n-1)$ rect minus one corner).
And $$b_n=a_{n-1}+b_{n-2}$$ because we either have a vertical domino at the left covering the lower left corner, or a horizontal domino and then par force two more horizontal dominoes.
Now
$$ \begin{align}a_n&=a_{n-2}+2b_{n-1}\\
&=a_{n-2}+2a_{n-2}+2b_{n-3}\\
&=a_{n-2}+2a_{n-2}+a_{n-2}-a_{n-4}\end{align}$$


text:
Q: Sqlite login Runtime error I'm new to Android and facing some problem in sqlite db while accessing db. I have created a table with default values, I'm trying to login with that default values so it's giving runtime error.
Here is my code:
MainActivity.java
package com.example.defaultdb;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
Button btn;
EditText ename, epass;
private Logindatabase logindb;
private SQLiteDatabase db;
Context context = this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        logindb = new Logindatabase(this);
        logindb = logindb.open();

        SQLiteDatabase sqLiteDatabase = logindb.getWritableDatabase();
        logindb = new Logindatabase(this);
        logindb.insertContact("harsh@me", "141");
        logindb.insertContact("leena@me", "120");
        logindb.insertContact("rahul@me", "921");

        Cursor allContacts = logindb.getAllContacts();

        //createDatabase();
        btn=(Button) findViewById(R.id.button1);
        ename=(EditText) findViewById(R.id.editText1);
        epass=(EditText) findViewById(R.id.editText2);

        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String userName = ename.getText().toString();
                String password = epass.getText().toString();

                String storedPassword = logindb.getSinlgeEntry(userName);

        if (epass.equals(storedPassword)) {
            Toast.makeText(MainActivity.this,
                    "Congrats: Login Successfull", Toast.LENGTH_LONG)
                    .show();

            Intent main = new Intent(MainActivity.this, Next.class);
            startActivity(main);
        } else {
            Toast.makeText(MainActivity.this,
                    "User Name or Password does not match",
                    Toast.LENGTH_LONG).show();
        }
    }
});

}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        logindb.close();
    }

}

Activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="35dp"
        android:ems="10"
        android:hint="email"
        android:inputType="textEmailAddress" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_alignRight="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="48dp"
        android:ems="10"
        android:hint="password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Login" />

</RelativeLayout>

DBHelper.java
package com.example.defaultdb;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {
    public DBHelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase _db) {
        _db.execSQL(Logindatabase.CREATE_TABLE_CONTACT);

    }

    @Override
    public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
        Log.w("TaskDBAdapter", "Upgrading from version " + _oldVersion + " to "
                + _newVersion + ", which will destroy all old data");
        _db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");

        onCreate(_db);
    }

}

Logindatabase.java
package com.example.defaultdb;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

public class Logindatabase extends SQLiteOpenHelper{

    public static interface CONTACT extends BaseColumns{
        static final String DATABASE_TABLE= "login";
        static final String KEY_EMAIL="email";
        static final String KEY_PASS="pass";

    }

    static final String CREATE_TABLE="CREATE TABLE IF NOT EXISTS";
    static final String KEY_ROWID="_id";
    static final String TAG="DBAdapter";
    static final String DATABASE_NAME= "MyDB";
    static final int DATABASE_VERSION=3;

    static final String CREATE_TABLE_CONTACT= CREATE_TABLE + CONTACT.DATABASE_TABLE +" ("+ CONTACT._ID + "INTEGER PRIMARY KEY," +
                                            CONTACT.KEY_EMAIL + "TEXT," + CONTACT.KEY_PASS + "TEXT DEFAULT 'TTEESSTT');";
    // static final String DROP_TABLE="DROP TABLE "+DATABASE_TABLE+" IF EXITS";

    SQLiteDatabase db;
    private DBHelper dbHelper;
    public Logindatabase(Context context)
    {
        super(context, DATABASE_NAME,null, DATABASE_VERSION);
        //this.context=context;
    //  DBHelper=new DatabaseHelper(context);
        //Message.message(context,"constructor called");
    }

    //open the database
    public Logindatabase open() throws SQLException{
        db =dbHelper.getWritableDatabase();
         return this;

    }

    @Override
    public void onCreate(SQLiteDatabase db){
        try{
            db.execSQL(CREATE_TABLE_CONTACT);
        }catch(SQLException e){
            //e.printStackTrace();

        }
    }

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

        Log.w(TAG, "Upgrading database from version" + oldVersion + " to " + newVersion + ",which will destroy all odl data");
                db.execSQL("DROP TABLE IF EXISTS" + CONTACT.DATABASE_TABLE);
                onCreate(db);
        }catch(SQLException e) {
            // TODO Auto-generated method stub

        }
    }

//closes the database
public void close()
{
    //DBHelper.close();
    close();
}
public SQLiteDatabase getDatabaseInstance() {
    return db;
}

public Cursor getAllContacts(){
    return getReadableDatabase().query(CONTACT.DATABASE_TABLE, null, null, null, null, null,null);

}

//insert values
public void insertContact(String email, String pass){
    ContentValues values = new ContentValues();
    values.put(CONTACT.KEY_EMAIL, email);
    if(pass!=null) {
        values.put(CONTACT.KEY_PASS, pass);
    }
     getWritableDatabase().insert(CONTACT.DATABASE_TABLE,null,values);
    //return logindb.insert(DATABASE_TABLE, null, initialValues);
}

public String getSinlgeEntry(String userName) {

    Cursor cursor = db.query("LOGIN", null, " KEY_EMAIL=?",
            new String[] { userName }, null, null, null);
    if (cursor.getCount() < 1) {
        cursor.close();
        return "NOT EXIST";
    }
    cursor.moveToFirst();
    String password = cursor.getString(cursor.getColumnIndex("KEY_PASS"));
    cursor.close();
    return password
}

}

A: You have made no space between CREATE_TABLE and CONTACT.DATABASE_TABLE, the string would be:
CREATE TABLE IF NOT EXISTSlogin

and this will defenitely lead into an error. It must be for example:
CREATE_TABLE + " " +CONTACT.DATABASE_TABLE

to build a proper String, add a space between these two, then it will be:
 CREATE TABLE IF NOT EXISTS login

But without seeing a stacktrace, we can´t give you a concrete answer


text:
Q: A matrix with positive principal minors has positive eigenvalues if it is real. Let $A$ be an $n\times n$ matrix, not necessarily symmetric, and suppose all principal minors of $A$ are positive. How to show that any real eigenvalue of $A$ is must be positive?

A: You should be able to find this result on some reference books on advanced linear algebra. I haven't any relevant book at hand, but this result seems obvious: as $A$ is a P-matrix, its adjugate matrix has a positive diagonal; therefore, by Jacobi's formula and by mathematical induction on the size of $A$, we have $\frac d{dt}\det(A+tI)=\operatorname{tr}(\operatorname{adj}(A+tI))>0$ when $t\ge0$. Since $\det(A)$ is also positive, the polynomial $\det(A+tI)$ cannot have a positive real root and hence the characteristic polynomial $\det(tI-A)$ cannot have any negative real root.


text:
Q: Does the restriction to hyperplanes determines a line bundle? Supose $L$ and $L'$ are holomorphic line bundles over $\mathbb{CP}^n$ such that $L|_{H} \simeq L'|_{H}$ for every hyperplane $H \subset \mathbb{CP}^n$. Does it follow that $L \simeq L'$?
Using the fact that every $x \in \mathbb{CP}^n$ is contained in a hyperplane one gets that $L_x \simeq L'_x$ for every $x$ but I don't know how to prove that the isomorphisms glue to a global one.

A: Yes. Actually if two holomorphic line bundles $L,L'$ on $\mathbb C \mathbb P^n \quad (n\geq 2)$ coincide on just one hyperplane, then they are already isomorphic.
This is because  a holomorphic line bundle on $\mathbb C \mathbb P^n$ is of the form $\mathcal O_{\mathbb C \mathbb P^n}(r) \;  (r\in \mathbb Z)$ and its restriction to $H$ is $\mathcal O_H(r)\simeq \mathcal O_{\mathbb C \mathbb P^{n-1}}(r) .\;$
So that $r$, an integer which suffices to characterize the line bundle, is determined by its restriction to $H$.


text:
Q: How to set callback url in Facebook realtime updates using nodejs Is there any way that I can do realtime update from Facebook in localhost and if it can not how to set the callback url?

A: try using "passport" for authentication in node.js...
you can set the call back url as follows.....
passport.use(new FacebookStrategy(
{
            clientID: FACEBOOK_APP_ID,
            clientSecret: FACEBOOK_APP_SECRET,
            callbackURL: "your url"
}


text:
Q: INSERT to a table with only one serial-column doesn't actually insert anything I have a postgres database with the following table:
CREATE TABLE stocks
    (
       id serial PRIMARY KEY
    );

and another table that is as follows:
CREATE TABLE stock_attributes
    (
       id serial PRIMARY KEY,
       market_id TEXT,
       short_name TEXT,
       full_name TEXT,
       isin TEXT,
       stock_id serial REFERENCES stocks(id)
    );

This is my attempt at normalizing, so forgive me if It's wrong but, I'm trying to insert a new row into stocks table and then use the id on another insert into the 2nd table:
INSERT INTO stocks DEFAULT VALUES RETURNING id;

The query goes through, and it returns a new id, but when I run the 2nd query into the stock_attributes table, I get an error that relation id doesn't exist on stocks table.
INSERT INTO stock_attributes AS a (market_id, short_name, full_name, isin, stock_id) VALUES (%s, %s, %s, %s, %s);

This one fails with
insert or update on table "stock_attributes" violates foreign key constraint "stock_attributes_stock_id_fkey"
DETAIL:  Key (stock_id)=(3) is not present in table "stocks".

I'm using psycopg2 with python.
Here is the code, pretty much copied from postgres python guides:

def execute(sql,args):
    conn = None
    try:
        # read database configuration
        params = config()
        # connect to the PostgreSQL database
        conn = psycopg2.connect(**params)
        # create a new cursor
        cur = conn.cursor()
        cur.execute(sql, args)
        conn.commit()
        # close communication with the database
        cur.close()
        print("SQL executed")
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()

def execute_and_return(sql, args):
    """ insert a new vendor into the vendors table """
    conn = None
    rows = None
    try:
        # read database configuration
        params = config()
        # connect to the PostgreSQL database
        conn = psycopg2.connect(**params)
        # create a new cursor
        cur = conn.cursor()
        cur.execute(sql, args)
        rows = cur.fetchall()
        # close communication with the database
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()
    return rows

A: Your key reference to the stocks tables is incorrect. You have:
stock_id serial REFERENCES stocks(id)

when it should be:
 stock_id integer REFERENCES stocks(id)

Serial creates a sequences of type integer and sets the column type to integer with a default value of nextval("<generated sequence name>"). If you change the type from serial to integer on the foreign key, it should work.


text: Q: Unable to create web site project using VS 2010 Here is My current versionTrying to create my first website using Visual Studio 2010. I configured IIS, installed ASP.NET MVC4 (not sure if I need it though). But still unable to see anything when clicking Visual Basic or VisualC#.  What am I missing?


text:
Q: How to export on premise database as bacpac directly to AZURE blob using command line We were able to create the bacpac using the below command,
C:\Program Files (x86)\Microsoft SQL Server\140\DAC\bin>
sqlpackage.exe /Action:Export /ssn:. /sdn:demo  /tf:d:\bacpac\demo.bacpac
However we want to automate the below action,

Also can this be done via SSMS using something similar
BACKUP DATABASE  demo
TO URL = @FullName
WITH CREDENTIAL = democredential;

A: You can use Azcopy to upload those bacpac files to an Azure BLOB Storage account as shown below:
AzCopy /Source:"d:\bacpac" /Dest:"https://exampleaccount.blob.core.windows.net/bacpacs" /DestKey:storageaccountkey /Pattern:*.bacpac

Hope this helps.

A: You can achieve this using Powershell Script,
$exportRequest = New-AzureRmSqlDatabaseExport -ResourceGroupName $ResourceGroupName -ServerName $ServerName `
  -DatabaseName $DatabaseName -StorageKeytype $StorageKeytype -StorageKey $StorageKey -StorageUri $BacpacUri `
  -AdministratorLogin $creds.UserName -AdministratorLoginPassword $creds.Password

To check the Status of the Export you can use the below one
$exportStatus = Get-AzureRmSqlDatabaseImportExportStatus -OperationStatusLink $exportRequest.OperationStatusLink
[Console]::Write("Exporting")
while ($exportStatus.Status -eq "InProgress")
{
    Start-Sleep -s 10
    $exportStatus = Get-AzureRmSqlDatabaseImportExportStatus -OperationStatusLink $exportRequest.OperationStatusLink
    [Console]::Write(".")
}
[Console]::WriteLine("")
$exportStatus

Refer here
If you want to Automate this by using Azure Automation RunBook


text:
Q: Java 8 JRE download API Is there any API to get the latest JAVA 8. For my automatic build system I need to get the latest version.
something like:
wget https://oracle.com/api/download/jre/8/Linux x64/lastest
which would give me the latest version (build version in this case u131, as of 05.05.17)
Or would i need to go to
http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html , do the acceptLicense-JS, parse the html and get the link myself?

A: For my automatic build system I need to get the latest version.
You can use either weget or curl to do this.

Solution 1 Using wget
Use wget and use a special cookie to bypass the licence agreement:

a single cookie is all that is needed to bypass this (you still have to agree to the terms to install)

The cookie is:
Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie

Example

if you want to download jdk7u4 for 64-bit Linux (e.g., Ubuntu) using wget, you can use:
wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u4-b20/jdk-7u4-linux-x64.tar.gz"

Source Download Oracle Java JRE & JDK using a script

Solution 1 Using curl
There is a shell script that completely automates the download.
downloadJavaAutomatic.ksh
#!/bin/ksh

###################################
## Overview
###################################

# Downloads JDK & JRE from download.oracle.com by first walking possible combinations of available version/build numbers.
# Once a version/build is found, subsequent attempts in the same family are primed to avoid walking the entire tree again.
#
# version=<x> represents the highest attempted version number while walking the tree
# build=<y> represents the highest attempted build number while walking the tree
#
# Adjust "BASE" to control which versions are downloaded.  A value of 8 corresponds to Java-v1.8.x
# Likewise a value of "6 7 8" equates to Java-v1.6.x, Java-v1.7.x, Java-v1.8.x
#
# Adjust "PLATFORMS" to match the architecture platforms you wish to download.
#
# Reference URLS:
# https://gist.github.com/P7h/9741922
# http://download.oracle.com/otn-pub/java/jdk/8u40-b26/jre-8u40-windows-x64.exe
# http://download.oracle.com/otn-pub/java/jdk/8u40-b27/jdk-8u40-macosx-x64.dmg

###################################
## Usage
###################################

# downloadJavaAutomatic.ksh
# Finds and downloads current Java versions

# downloadJavaAutomatic.ksh [-f <file>]
# Skips version/build find routing, uses external <file>
# which contains a list of URLs to be downloaded.

###################################
## Config
###################################
version=99
build=30

set -A BASE 8 7 6
set -A BASE 7
set -A PLATFORMS -- -linux-x64.tar.gz -linux-i586.tar.gz -macosx-x64.dmg -windows-i586.exe -windows-x64.exe

###################################
## Subroutines
###################################

doCountCurl() {
    ps -ef | egrep -ie "curl.*${cookie}" | grep -vi grep | wc -l
}

doGetURL() {
    printf "\n$URL\n"
    Cookie="Cookie:oraclelicense=accept-securebackup-cookie"
    curl -O -L -S -H "${Cookie}" --progress-bar --connect-timeout 55 --fail -k "${1}"
    if [[ $? -ne 0 ]]; then
        echo ERROR - download failed.
    fi
}

doTestURL() {
    uri_local=$1
    base_local=$2
    version_local=$3
    build_local=$4
    platform_local=$5
    type_local=$6

    Cookie="Cookie:oraclelicense=accept-securebackup-cookie"
    URL="http://download.oracle.com/${uri_local}${base_local}u${version_local}-b${build_local}/${type_local}-${base_local}u${version_local}${platform_local}"
    curl --output /dev/null -L -sS -H "${Cookie}" --head --connect-timeout 15 --max-time 30 --fail -k "${URL}" 2>/dev/null
    if [[ $? -eq 0 ]]; then
        echo $URL >> $urlFile
        printf  "$version_local" > $tmpVersion
        printf  "$build_local" > $tmpBuild
        printf  "${URL}" > $tmpFile
        break
    fi
}

doFindVersionBuild() {
    URI=$1
    BASE=$2
    PLATFORM=$3
    TYPE=$4

    ### If available use version to limit tree walking
    if [[ -e $tmpVersion ]]; then
        version_cnt=$(( `cat $tmpVersion` ))
    else
        version_cnt=$version
    fi

    while [[ $version_cnt -ge 1 ]] && [[ ! -e $tmpFile ]]; do

        ### If available use build to limit tree walking
    if [[ -e $tmpBuild ]]; then
            build_cnt=$(( 10 + `cat $tmpBuild` ))
        else
            build_cnt=$build
        fi

        ### Keep going until a version is found
    while [[ $build_cnt -ge 1 ]] && [[ ! -e $tmpFile ]]; do
            ### Limit HTTP connections to avoid saturating connection
        maxHTTP=50; while [[ `doCountCurl` -ge ${maxHTTP} ]]; do sleep 1; done

            ### Send to background to speed up process
            doTestURL ${URI} ${BASE} ${version_cnt} ${build_cnt} ${PLATFORM} ${TYPE} &
            (( build_cnt-=1 ))
        done

        (( version_cnt -= 1 ));
        sleep 1
    done

    ### Wait for current version/build series to finish before starting next round
    while [[ `doCountCurl` -gt 0 ]]; do sleep 1; done

    ### Save results to VERSION array.  Highest version will be element #1
    set -A VERSION dummy `[[ -e $tmpFile ]] && sort -nr $tmpFile`
    if [[ "${VERSION[1]}" != "" ]]; then
        echo ${VERSION[1]}
    else
        printf -- "${TYPE}-${BASE}u??${PLATFORM} - No Version found.\n"
    fi

    ### Cleanup
    if [[ -e $tmpFile ]]; then
        rm $tmpFile
    else
        [[ -e $tmpVersion ]] && rm $tmpVersion
        [[ -e $tmpBuild ]] && rm $tmpBuild
    fi
}

doDownload() {
    printf "\nDownloading...\n"
    for URL in $( grep -vi "#" $urlFile ); do
        doGetURL "$URL"
    done
}

#########################
### Main
#########################
tmpFile=$$-tmp.txt
tmpVersion=$$-version.txt
tmpBuild=$$-build.txt
urlFile=url.txt

clear
if [[ $1 = "-f" ]] && [[ -r "$2" ]]; then
    echo "Search for version/build bypassed.  Using URLs within file: $2"
    urlFile=$2
    doDownload
else
    printf "Searching for available versions...\n\n"

    for base in ${BASE[@]}; do
        for type in $(echo jre jdk); do
            printf "# `date`\n" >> $urlFile
            for platform in ${PLATFORMS[@]}; do
                URI=otn-pub/java/jdk/
                doFindVersionBuild ${URI} ${base} ${platform} ${type}
            done
        done
        ### Delete version and build markers before attempting next BASE version.
        [[ -e $tmpVersion ]] && rm $tmpVersion
        [[ -e $tmpBuild ]] && rm $tmpBuild
    done
    doDownload
fi

[[ -e $urlFile ]] && rm $urlFile

Source Java-JRE-JDK-Downloader


text:
Q: What is the difference between these two ajax scripts? I'm running into difficulty with the JSON cross domain policy issue. After a little experimentation I was able to get this code working, but I came across a situation where I had two pieces of code which seem like they should be exactly the same, but only one works.
The JSON I am accessing is here

http://www.aph.com/files/partners/aphnonstopproducts/json/aphnonstopproductsjson.json

This file appears to be straightforward JSONP: it doesn't take any parameters, and JSON padded with a function call called jsonCallBack. It appears to be valid JSON.
Here's the first set of code which I tried to use to grab this JSON data:
$.getJSON("http://www.aph.com/files/partners/aphnonstopproducts/json/aphnonstopproductsjson.json?callback=jsonCallback", function (data) {
                //This will not alert
                alert(data.APHNonStopProducts.Carpark[0].Airport.airportcode);
            });

My understanding was that you could replace the callback=? with the name of the function wrapper in order to have that data passed to the anonymous function. This code shows the following error in Chrome Dev tools:

XMLHttpRequest cannot load
  http://www.aph.com/files/partners/aphnonstopproducts/json/aphnonstopproductsjson.json?callback=jsonCallback.
  Origin http://fiddle.jshell.net is not allowed by
  Access-Control-Allow-Origin.

It's worth noting that if leave the URL as aphnonstopproductsjson.json?callback=? and have a named function present in my code then the data is retrieved properly and the named function called (although the anonymous one still isn't)
Here's the second code, which works:
$.ajax({
url: "http://www.aph.com/files/partners/aphnonstopproducts/json/aphnonstopproductsjson.json?callback=?",
       dataType: 'json',
       jsonp : "callback",
       jsonpCallback: "jsonCallback",
       success: function(data) {
           //This alert will fire
           alert(data.APHNonStopProducts.Carpark[0].Airport.airportcode);
       }
   });
});

In this call, I'm specifying that the parameter name should be callback, and the function name should be jsonCallback. So in essence, isn't that the same as the first code? If so, why does the first code fail?
See both pieces of code here: http://jsfiddle.net/3EXca/ (You should receive an alert which says "ABZ")

A: The problem is that the server doesn't support JSONP properly.  Without a callback parameter, there should not be a callback.  Instead, it already has a jsonCallback.  There may be a way to override that, but I can't guess the parameter.
For $.getJSON to work with JSONP, the server has to support JSONP with some callback parameter name.
The second works because you're forcing jQuery to use the function name jsonCallback.  The:
jsonp: 'callback'

doesn't matter since it always wraps with jsonCallback anyway.


text:
Q: Updating the JSON file with Knockout.js I am very new to programming in general and Knockout.js therefore what I ask would be very basic. I am trying to make a form with Knockout.js. Just as practice I want to make this page in which everytime someone update the fields and click submit it map it to JSON and alert how it will look like as JSON. By this code that I have it binds properly but it doesn't update the JSON file. What's wrong with it?
Here are my codes:
var User = {
Email : ko.observable(''),
Password : ko.observable(''),
FullName : ko.observable('')
};

ko.applyBindings(User);

var JsonData=ko.toJSON(User);

function submit(){
alert (JsonData)
 }

and my html:

<title> Test Knockout</title>

<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">

<form data-bind="submit: submit" data-bind="foreach:friends">

<input type="Email" class="form-control input-lg" placeholder="*Email" data- bind="value:Email">
<input type="password" class="form-control input-lg" placeholder="*Password" data-bind="value:Password">
<input type="text" name="FullName" id="FullName" class="form-control input-lg" placeholder="Full Name" data-bind="value:FullName">
<button type="submit">Submit</button>

</form>

Thanks

A: here's a working fiddle of your code:  http://jsfiddle.net/dwqZw/1/
html:
<form data-bind="submit: submit">

        <input type="Email" class="form-control input-lg" placeholder="*Email" data-bind="value: user.Email, valueUpdate: 'input'" />
        <input type="password" class="form-control input-lg" placeholder="*Password" data-bind="value: user.Password, valueUpdate: 'input'" />
        <input type="text" name="FullName" id="FullName" class="form-control input-lg" placeholder="Full Name" data-bind="value: user.FullName, valueUpdate: 'input'" />
        <button type="button" data-bind="click: submit">Submit</button>

</form>

javascript:
var user = {
    Email: ko.observable(''),
    Password: ko.observable(''),
    FullName: ko.observable(''),
};

function submit() {
    var json = ko.toJSON(user);
    alert(json);
}

var viewModel = {
    user: user,
    submit: submit
};

ko.applyBindings(viewModel);


text:
Q: in react-paginate package what is the purpose of herfBuilder                <ReactPaginate
                hrefBuilder={(currentPage) => { hello }}
                previousLabel={"previous"}
                nextLabel={"next"}
                breakLabel={"..."}
                pageCount={pageCount}
                marginPagesDisplayed={2}
                pageRangeDisplayed={3}
                onPageChange={handlePageClick}
                containerClassName={"pagination justify-content-center my-5 "}
                pageClassName={"page-item"}
                pageLinkClassName={"page-link"}
                previousClassName={"page-item"}
                previousLinkClassName={"page-link"}
                nextClassName={"page-item"}
                nextLinkClassName={"page-link"}
                breakClassName={"page-item"}
                breakLinkClassName={"page-link"}
                activeClassName={"active"}
            />

acctully  i  want  to  make a  new link every  time  when i  click  the  new page button


text:
Q: MonkeyRunner generates zombie processes I am using MonkeyRunner for Android Automation Testing on a real device and run overnight tests. During one of those extensive automated tests I have discovered that whenever MonkeyRunner takes a screenshot, a zombie process is created on the devices internal system. Here you can see below the zombie processes when I run adb shell ps command:

As the zombie processes increase, the device becomes unresponsive and it starts hanging up. In MonkeyRunner, taking screenshot is the only way of verification. Thus, this issue is highly critical when running extensive tests that take many hours.
I have also seen this that says

The framebuffer_service is not doing a "wait" for the spawned
  screencap process to complete. Consequently, the child processes
  become zombie processes.

and suggests modifying the adb source code itself. However, I think there must be any other solution without going deep down to the source code.
Any ideas / suggestions how to solve this issue?

A: I've seen that depends very much on the android version and screencap implementation.
You can run this test (which succeeds on KitKat but may fail on previous versions) to verify your case.
#! /usr/bin/python -u
# -*- coding: utf-8 -*-
'''
Copyright (C) 2014  Diego Torres Milano
'''

import sys
import unittest

from com.dtmilano.android.adb.adbclient import AdbClient

VERBOSE = True
TIMES = 40
SLEEP = 0

def repeat(times):
    def repeater(t):
        def caller(*args):
            for f in (t,)*times:
                if VERBOSE:
                    sys.stdout.write('.')
                f(*args)
                if SLEEP:
                    time.sleep(SLEEP)
        return caller
    return repeater

class TakeSnapshotTests(unittest.TestCase):

    def setUp(self):
        self.device = AdbClient(serialno=serialno)

    def tearDown(self):
        pass

    @repeat(TIMES)
    def testSnapshot(self):
        self.device.takeSnapshot(reconnect=True).save('/dev/null', 'PNG')
        out = self.device.shell('ps | grep screencap').split('\n')
        if len(out) > 1:
            self.fail(out)

    @staticmethod
    def main():
        unittest.main()

if __name__ == '__main__':
    if len(sys.argv) >= 2:
        serialno = sys.argv.pop(1)
    else:
        serialno = '.*'
    TakeSnapshotTests.main()


text:
Q: Combining multiple column vectors into larger column vector I am starting off with 32 column vectors such as [1;2;3;4]. All of them are in this format and I would like to combine them into 2 different column vectors like so:
chan0=[adc0;adc2;adc4...]
chan2=[adc1;adc3;adc5...]

So chan0 would look something like:
[0;1;2;3;4;5;6;7;8;9;...]

I've tried
for i=0:31
    data_in = dlmread(['raw\adc',num2str(i),'.txt']);
    if(mod(i,2)==0)
        chan0=chan0+data_in;
    else
        chan2=chan0+data_in;
    end
end

First off I obviously get an error saying chan0 is undefined, so what should I define chan0 and chan2 as?
Second, even then would this code give me the vectors I want?
Third, might as well as while I'm here, to write both chan0 and chan2 to a txt file it would be
dlmwrite('raw\chan0.txt',chan0);
dlmwrite('raw\chan2.txt',chan2);

right?
Thank you,
Tyler

A: You can try this-
chan0=[];
chan2=[];
for i=0:31
    data_in = dlmread(['raw\adc',num2str(i),'.txt']);
    if(mod(i,2)==0)
        chan0=[chan0;data_in];
    else
        chan2=[chan2;data_in];
    end
end


text:
Q: Why is Magento logo shown as favicon in view source even after changing it in front-end and admin panel? This question might have been asked before but didn't help.
I have changed the favicon both in front-end and adminpanel of magento. But whenever I do view source or view any particular image from site. The magento favicon shows up. This happens only in chrome.
I have flushed all cache including theme related cache, reindexed the pages and disabled the compilation.
Any related help appreciated.

A: Browser cache. In this case - Google Chrome cache.


text:
Q: Uniqueness of additive inverse Using only these properties:
A1. $x + (y+z) = (x+y) + z$
A2. $x + y = y + x$
A3. There is an
integer zero such that $x + 0 = x$
A4. To each integer $x$ there
corresponds an integer $(-x)$ such that $x+(-x)=0$
Show that given $x$, $(-x)$ is unique based on A1-A4
So far I've gotten

*

*Assume A1-A4, $y=-x$, $z=-x$, and $y \neq z$

*For all $x$: $x+y = 0$ based on A4

*For all $x$: $x+z = 0$ based on A4

*If $x=z$, $z+y = 0$

*If $x=y$, $y+z = 0$
However, I'm stuck from here, any tips on how to continue the proof?

A: Suppose $x$ has two inverses, $-x$ and $(-x) + y$ where $y\neq 0$. Then,
$x+((-x)+y) =0$
must hold. By A1, we have
$x+((-x)+y) = (x+(-x)) +y = 0 + y =y \neq 0$
which is a contradiction
$\implies y=0$
or, $(-x) + y = (-x)$ is the single unique inverse of $x$.

A: Let $x_{1}$ and $x_{2}$ both be additive inverses of $x$. This means that
$x+x_{1}=0$ ---(1)
and
$x+x_{2}=0$ ---(2).
By pre-adding $x_{2}$ to (1),
$x_{2}+(x+x_{1})=x_{2}+0$
$(x_{2}+x)+x_{1}=x_{2}$ (by A1)
$(x+x_{2})+x_{1}=x_{2}$ (by A2)
$0+x_{1}=x_{2}$ (by A4)
$x_{1}+0=x_{2}$ (by A2)
$x_{1}=x_{2}$ (by A3) as desired


text:
Q: Multiple tag value in AWS It is possible to set multiple value in a aws:PrincipalTag for IAM policy ?
Currently, I have federated users with a project attribute in their JWT and
depending on this value I can give access to a specific "folders" in my s3 bucket.
For a JWT with following value:
"https://aws.amazon.com/tags": {
    "principal_tags": {
        "project": [
            "foo"
        ]
    }
}

and my AWS policy:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "TagBasedAccess",
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::myawesomebucket",
            "Condition": {
                "StringLike": {
                    "s3:prefix": "${aws:PrincipalTag/project}/*"
                }
            }
        }
    ]
}

It grant user access to arn:aws:s3:::myawesomebucket/foo/ with success.
Now I will make it work for multiple values in the project attribute (give access to multiple s3 "folder"). But I have no idea how to perform this.
EDIT:
in AWS documentation (AWS doc):

you can include multiple values in a single tag with a custom
separator. In this example, you could attach the team = Engineering:QA
tag to Zhang.
To control access to engineers in this example using the team
tag, you must create a policy that allows for every configuration that
might include Engineering, including Engineering:QA

but they dont say how to perform this...

A: There is an AWS document relating to this question:
https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_multi-value-conditions.html#reference_policies_multi-key-or-value-conditions
Direct quote from the document:

To compare your condition against a request context with multiple key values, you must use the ForAllValues or ForAnyValue set operators. These qualifiers add set-operation functionality to the condition operator so that you can test multiple request values against multiple condition values. Additionally, if you include a multivalued key in your policy with a wildcard or a variable, you must also use the StringLike condition operator.

Please refer the original documents for more information. You might want to know, for example, how condition operators and condition blocks work in this context.


text:
Q: I use Steam to log in, how do I use this logon for stackoverflow.com? There is no option to use Steam for logon on Stackoverflow and logging in with StackExchange Account does not work apparently, because I never created one with this account.

A: You can manually enter the Steam OpenID URL (http://steamcommunity.com/openid) by clicking "Show more login options..." and then putting that URL into the box. Then you should be able to log in with Steam normally, and the accounts will be associated automatically.
Alternatively, you can associate another OpenID account with your account on this site by going to your user page and clicking "my logins" at the top. Then you should be able to click "add more logins..." to associate another account with this one. Then you can use that account to log in to stackoverflow.


text:
Q: improving views performace in sql server 2012 I have one view vwBalance which returns more than 150.000.000 rows, bellow is the code:
SELECT    *
FROM            dbo.balance INNER JOIN
                         dbo.NomBalance   ON dbo.balance.IdNomBil = dbo.NomBalance.Id

But I want to transpose the values return so I use a PIVOTE function like this:
SELECT  An, cui,caen, col1, col2, ... col 100
FROM   (SELECT     cui, valoare, cod_campbil,caen,An
        FROM vwBilant  WITH (NOLOCK)
        p PIVOT (MAX(valoare) FOR cod_campbil IN ( col1, col2, ... col100   ) AS pvt

The questions are:

*

*Should i use query hint inside the view vwBalance? This hint could improve or could lock the transpose action?

*It's a problem if I use NOLOCK hint instead of the other query hints?

*There are better ways to improve transposing many columns?

Thanks!

A: I can give the following adviсes:

*

*you can use hint readpast if it does not broke your business logic

*you can create clustered index for this view. It materialize you view, but performance of changing operation will be decreased for all tables that are used in this view.

*also, you should check indexes for fields that you use in join and where clauses.

*and you can use preprocessing. So, you insert this values in some
    another table (for example at night). In this case you can use
    columnstore index or just make page compression for this table
    as well as you can use page compression for all tables that are
    used in this view.


text:
Q: Strange behavior of MySQL SELECT When the variable NUMBER_OF_ITERATIONS is set to 1, everything works fine...but when I change it to any value greater than 1 I get some problems.
First of all, in this case when i print the value of res i get an huge number (like 18446744073709551615).
Second, but most important, in this case the script can't process data because the lenght of value is always 0...
if __name__ == '__main__':

    NUMBER_OF_ITERATIONS = 2

    conn = DBconnection()   # return a database connection

    for i in range( NUMBER_OF_ITERATIONS ):
        cursor = conn.cursor()
        res = cursor.execute( 'SELECT field
                                 FROM table
                                WHERE other_field = 0
                                LIMIT 10 LOCK IN SHARE MODE' )
        print '# of selected rows: ' + str(res)

        values = []
        for elem in cursor.fetchall():
            if elem != None:
                values.append( list(elem).pop() )

        if len( values ) != 0:
            # do something...

        else:
            print 'NO VALUES AVAILABLE'
            cursor.close()
            break

    conn.close()
    print 'DONE'

I'm using the InnoDB storage engine and simultaneously at this script there is another script python that is uploading data on the same table (using the construct LOAD DATA INFILE).
I thought that it could be due to a table lock caused by the load data, but what's the difference from one to 2 (or more) iterations? With one iteration all works good, while with 2 even the first iteration goes bad. I can't get the point.

A: I was unable to reproduce the problem using the following code. Can you modify it to demonstrate the error?
import config
import MySQLdb
import multiprocessing as mp
import random
import string
import time

def random_string(n):
    return ''.join(random.choice(string.letters) for _ in range(n))

def generate_data():
    conn=MySQLdb.connect(
        host=config.HOST,user=config.USER,
        passwd=config.PASS,db='test')
    cursor=conn.cursor()
    while True:
        with open('/tmp/test.dat','w') as f:
            for _ in range(20):
                f.write('{b}\n'.format(b=random_string(10)))
        # sql='LOCK TABLES foo WRITE'
        # cursor.execute(sql)
        sql="LOAD DATA INFILE '/tmp/test.dat' INTO TABLE test.foo"
        cursor.execute(sql)
        conn.commit()
        # sql='UNLOCK TABLES'
        # cursor.execute(sql)
        time.sleep(0.05)

def setup_innodb(connection):
    cursor=connection.cursor()
    sql='DROP TABLE IF EXISTS foo'
    cursor.execute(sql)
    sql='''\
        CREATE TABLE `foo` (
          `bar` varchar(10) NOT NULL
        ) ENGINE=InnoDB
        '''
    cursor.execute(sql)
    connection.commit()

if __name__ == '__main__':
    NUMBER_OF_ITERATIONS = 20
    conn=MySQLdb.connect(
        host=config.HOST,user=config.USER,
        passwd=config.PASS,db='test')
    setup_innodb(conn)

    # Start a process which is "simultaneously" calling LOAD DATA INFILE
    proc=mp.Process(target=generate_data)
    proc.daemon=True
    proc.start()

    for i in range( NUMBER_OF_ITERATIONS ):
        cursor = conn.cursor()
        # sql='''SELECT field
        #        FROM table
        #        WHERE other_field = 0
        #        LIMIT 10 LOCK IN SHARE MODE'''
        # sql='LOCK TABLES foo READ'
        # cursor.execute(sql)
        sql='''SELECT *
               FROM foo
               LOCK IN SHARE MODE
               '''
        res = cursor.execute(sql)
        print '# of selected rows: ' + str(res)
        values = cursor.fetchall()
        # http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
        # Locks set by LOCK IN SHARE MODE and FOR UPDATE reads are released when
        # the transaction is committed or rolled back.
        conn.commit()
        time.sleep(0.1)

    conn.close()
    print 'DONE'

yields
# of selected rows: 0
# of selected rows: 40
# of selected rows: 80
# of selected rows: 120
# of selected rows: 160
# of selected rows: 180
# of selected rows: 220
# of selected rows: 260
# of selected rows: 300
# of selected rows: 340
# of selected rows: 360
# of selected rows: 400
# of selected rows: 440
# of selected rows: 460
# of selected rows: 500
# of selected rows: 540
# of selected rows: 580
# of selected rows: 600
# of selected rows: 640
# of selected rows: 680
DONE


text:
Q: How to get user's permission sets in Data Repeaters filters I have custom field (multiselect picklist) on Question object, which we use to filter the displayed records in accordance with his permissoin sets. On visualforce pages it's implemented using SOQL filtering.
But also we use salesforce community and site.com pages in our project, where Question records are displayed with Data Repeaters. And I want to implement similar filtering functionality here. Maybe someone know how can I get access to current user's permission sets in Data Repeaters filters or how can I implement this in other ways?

A: Unfortunately, there seems to be no way of referencing a User's permission set in filters (and thus Data Repeaters).
What I'd do in this situation is leverage a hierarchy-custom setting. This would allow you to specify a certain value, based on the user's profile, while you can add exceptions pretty easily for certain users.
In the filter (formula only) you can then simply evaluate the custom setting value as {!$Setup.CustomSettingName__c.CustomFieldName__c} and it'll return the current user's specific value.
Would that be a viable option for you?


text:
Q: External service call with Java 11 HttpClient sync vs async My microservice is calling an external service POST call and I want to use Java 11 Httpclient. Here how shall the send() and sendAsync() methods can make difference? I have tested with multiple amount of request, almost same latency. I tried executing 100 endpoint call for my service with 10 or 20 thread or more. The result for both methods are almost same.
I use sendAsync() with thenApply().get in response receive.
I would like to know what is preferred way and why? Is using async is also fast(which is not as per my current result)?
Thanks in advance for your answers!

A: Here's a test of both methods:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.Builder;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class HttpClientTest {
    static final int REQUEST_COUNT = 100;
    static final String URI_TEMPLATE = "https://jsonplaceholder.typicode.com/posts/%d";

    public static void main(final String[] args) throws Exception {
        final List<HttpRequest> requests = IntStream.rangeClosed(1, REQUEST_COUNT)
                .mapToObj(i -> String.format(URI_TEMPLATE, i))
                .map(URI::create)
                .map(HttpRequest::newBuilder)
                .map(Builder::build)
                .collect(Collectors.toList());
        final HttpClient client = HttpClient.newBuilder()
                .executor(Executors.newFixedThreadPool(REQUEST_COUNT))
                .build();
        final ThrowingFunction<HttpRequest, String> sendSync =
            request -> client.send(request, BodyHandlers.ofString()).body();
        final ThrowingFunction<CompletableFuture<HttpResponse<String>>, String> getSync =
            future -> future.get().body();
        benchmark("sync", () -> requests.stream()
                .map(sendSync)
                .collect(Collectors.toList()));
        benchmark("async", () -> requests.stream()
                .map(request -> client.sendAsync(request, BodyHandlers.ofString()))
                .collect(Collectors.toList()) // materialize to send the requests
                .stream()
                .map(getSync)
                .collect(Collectors.toList()));
    }

    static void benchmark(final String name, final Supplier<List<String>> supplier) {
        new Thread(() -> {
            final long start = System.nanoTime();
            System.out.printf("%s: start%n", name);
            final List<String> result = supplier.get();
            final Duration duration = Duration.ofNanos(System.nanoTime() - start);
            final int size = result.stream()
                    .mapToInt(String::length)
                    .sum();
            System.out.printf("%s: end, got %d chars, took %s%n", name, size, duration);
        }, name).start();
    }

    @FunctionalInterface
    static interface ThrowingFunction<T, R> extends Function<T, R> {
        default R apply(final T t) {
            try {
                return applyThrowing(t);
            } catch (final Exception e) {
                throw new RuntimeException(e);
            }
        }

        R applyThrowing(T t) throws Exception;
    }
}

Example output:
sync: start
async: start
async: end, got 26118 chars, took PT1.6102532S
sync: end, got 26118 chars, took PT4.3368509S

The higher the parallelism level of the API, the better the asynchronous method will perform.


text:
Q: Why is my If function not working Javascript? I'm making a function that changes the place of text.It is conditional on the contents of the html element. It's supposed to check if the element contains text. If it does, it will change the contents of the second element. If it doesn't, I want it to stop the function. Any help?

function transferText() {
  if (document.getElementById('aaa') !== '') {
    document.getElementById('bbb').innerHTML = document.getElementById('aaa').innerHTML;
  } else {
    return;
  }
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

<button onclick="transferText()"> click me</button>

bbb

A: As others pointed out, you are comparing an HTMLElement to an empty string.
The following works:

function transferText() {
  if (document.getElementById('aaa').innerHTML !== '') {
    document.getElementById('bbb').innerHTML = document.getElementById('aaa').innerHTML;
  } else {
    return;
  }
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

eeee

<button onclick="transferText()"> click me</button>

bbb

A: It is working, document.getElementById('aaa') is checking the element exists, which will always be true. This then sets the value of 'bbb' to the value of 'aaa', which in your example, is ''.


text:
Q: Phase diagram of ${\rm O}(3)$ lattice model and mean field theory In David Tong: Lectures on Statistical Field Theory Problem Sheet 1 exist task:

I fully understand this problem and I know solution: section 17.2.
I am interested in application of mean field theory to this problem. Essence of problem in founding number of configurations $\Omega(\vec{m})$ with fixed average spin $\vec{m}$:
$$
\vec{m} = \frac{1}{N} \sum_i \vec{s}_i
$$
And if one know this, one can easily obtain effective free energy $f(\vec{m})$:
$$
e^{-\beta N f(\vec{m})} = \Omega(\vec{m}) e^{-\beta E(\vec{m})}
$$
From here I can easily study properties of effective free energy and understand qualitative this phase diagram.
Could somebody explain me how to calculate $\Omega(\vec{m})$?


text:
Q: Keeping an optimise log file for a predetermined number of requests? I need to log certain requests made to my app being developed in Flask.
I know in advance whether the request is a candidate to be that needs to be logged or not.
I'll have at most 1000 requests to be logged. This is an upper limit, but it will probably be lower. The number is still uncertain for now, as we're adding those,  but it won't be once deployed. Each request will generate on average two A4 text.

*

*I wanted to save the content, the time, the filenames (usually at most 2 to 3 files) that came in with the requests.

*I don't mind the space this log file will take up.

*I would like it to be fast to open, and fast to search the log for previously done requests. I'll have a preference for fast opening and logging into the file new information, more than the searching itself, since it'll be just a few hundreds of  requests.

Should I pickle, save in a json, or use some other format?
The way I was thinking of structuring the information would be this:
{ "past_request": <sorted_list_filenames>,
  "filename_1" : {"content":..., "time_requested":...,...},
  "filename_102" : {"content":..., "time_requested":...,...}
...


text:
Q: C++ directory listing acting weird So I'm making a CMD implementation on Linux, but I ran into some problem.
If I change the working directory using the CD command like this:
    /$CD home
Then if I run the ls command without anything
    /home$ls
It lists nothing unless I execute this:
cd ./
or this:
ls ./
and it works again.
main.cpp:
   #include <iostream>
#include <string>
#include <filesystem>
#include <boost/filesystem.hpp>
#include <sys/types.h>
#include <dirent.h>
#include "commands.h"
#include <vector>
#include <unistd.h>
using namespace std;
 string arr[4];
string out[4];
string dir("/");
void sep(string line)
{
 int i = 0;
 stringstream ssin(line);
 while (ssin.good() && i < 4){
 ssin >> arr[i];
 ++i;
 }
 for(i = 0; i < 4; i++){
 out[i]=arr[i];
 }

}

int main()
{
//startup text
 string input;
 cout << "Linux\n" << system("uname -r") <<"\n";
 while (true) {
 cout << std::filesystem::current_path();
 getline (cin,input);
sep(input);
 if (input=="ver")
 {
 ver();
}
//exit
 else if (out[0]=="exit")
 {
 return 0;
 }
 else if (input=="")
 {
 }
 //echo
 else if (out[0]=="echo")
 {
 cout << out[1] << "\n";
 }
 else if (out[0]=="ls"||out[0]=="dir")
 {
 if (out[1]==""){
 list_dir(std::filesystem::current_path());

 }
 else
 list_dir(out[1]);

 }
 else if (out[0]=="clear")
 {
 printf("\033[2J");
 printf("\033[H");

 }
 else if (out[0]=="exec")
 {
 string name=out[1];
 const char *namecc=name.c_str();
 open(namecc);
 }
 else if (out[0]=="cd")
 {

 const char *chd=out[1].c_str();
 cout << chd << "\n";

 chdir(chd);
 if (chdir(chd)==-1)
 {
 cout << "chdir() Returned -1,directory not exist or error\n";

 }

 }
 else cout << "Bad command or file name\n";

}

}

command.h:
 #include <iostream>
 #include <string>
 #include <sys/types.h>
 #include <sstream>
 #include <filesystem>
 #include <unistd.h>
 #include <boost/filesystem.hpp>
 #include <dirent.h>
 #include <stdio.h>
 using namespace std;
 using namespace boost::filesystem;
 namespace fs = std::filesystem;
 void ver()
 {
 std::cout << "CMD for linux 1.0\n";
 }

 int list_dir(string ddddd) {
 DIR *d;

 struct dirent *dir;
 const char* p=ddddd.c_str();
 d = opendir(p);

 if (d)

 {

 while ((dir = readdir(d)) != NULL)

 {

 printf("%s\n", dir->d_name);

 }

 closedir(d);

 }

 return 0;
 }

 int cd(string aa)
 {
 const char *bbbbb=aa.c_str();
 DIR* a=opendir(bbbbb);
 if (a)
 {
 return 0;
 }
 else return 1;
 }
 int open(const char* file)
 {
 FILE *handle = popen(file, "r");

 if (handle == NULL) {
 return 1;
 }

 char buf[64];
 size_t readn;
 while ((readn = fread(buf, 1, sizeof(buf), handle)) > 0) {
 fwrite(buf, 1, readn, stdout);
 }

 pclose(handle);

 return 0;
 }

btw I'm still not really good at c++ yet so if the code is unoptimized please give some suggestions about how can I make it better,thanks.


text:
Q: Why is this ideal generated by a regular sequence? This is a question regarding Exercise 18 in http://www.math.utah.edu/agtrtg/commutative-algebra/Boocher_lectures.pdf
Let $I$ be the ideal of the polynomial ring $k[a,b,c,d,e,f]$

$I=(a^2+b^2+ab+cd+ef,b^3-6abc+def,c^2e^2+f^4)$.

Krull's altitude theorem gives $\mathrm{ht}\;I\leq 3$. There is a term order such that the height of the initial ideal is 3. Why does this imply that $I$ is generated by a regular sequence?


text:
Q: Nativscript platform specific template not working Building an app in Nativescript 5.0 for both Android and iOS. For some reason the  and  tags don't seem to work as they should, or i might be doing it wrong.
<StackLayout>
<android>
    <ActionBar class="header" flat="true">
        <StackLayout orientation="vertical">
            <app-eon-colors-top></app-eon-colors-top>
            <GridLayout columns="auto, *, auto, auto" rows="2*">

            </GridLayout>
        </StackLayout>
    </ActionBar>
</android>
<ios>
    <ActionBar class="header" flat="false">
        <StackLayout orientation="horizontal">

        </StackLayout>
        <ActionItem ios.position="right">
            <StackLayout orientation="horizontal">

            </StackLayout>
        </ActionItem>
    </ActionBar>
</ios>
</StackLayout>

When running this template on android it only uses the code in the ios block, but on ios it seems to work fine.

A: That's NativeScript Core way of writing platform specific XML. With Angular, you could use directives, there is a Github issue that discusses about this problem and also provides sample code to implement this platform specific directive on your project.
Platform specific structural directive
import { Directive, ViewContainerRef, TemplateRef, Inject } from "@angular/core";
import { DEVICE } from "nativescript-angular/platform-providers";

import { Device, platformNames } from "platform";

@Directive({
    selector: "[appIfAndroid]"
})
export class IfAndroidDirective {
    constructor( @Inject(DEVICE) device: Device, container: ViewContainerRef, templateRef: TemplateRef<Object>) {
        if (device.os === platformNames.android) {
            container.createEmbeddedView(templateRef);
        }
    }
}

@Directive({
    selector: "[appIfIos]"
})
export class IfIosDirective {
    constructor( @Inject(DEVICE) device: Device, container: ViewContainerRef, templateRef: TemplateRef<Object>) {
        if (device.os === platformNames.ios) {
            container.createEmbeddedView(templateRef);
        }
    }
}

Once you import this directive in your module, then you could use *appIfAndroid / *appIfIos on any tag.


text:
Q: Outer container is not extending with the expand script So I have some function that expand and collaps based on hover and click. The function works fine on the basic test but it's not working on the site. When a user clicks on the Expand A and Expand B. The outer container expands with it as you can test it in jsFiddle . But when the same code is applied to the main site the outer container doesn't expand with the expanded div. Instead it has the expanded div if it's too long. What am I missing here?
Thanks in advance. Rex
P.S. I can't use the newer version of jQuery or the change the layout. That's the CMS is set up. However I can change the css properties and the javascript functions.
The jQuery script works fine on the test version: http://jsfiddle.net/rexonms/pXm62/
But it doesn't work on the site: http://boston.staging.ujcweb.org/expandable-box.aspx

A: There is a function named adjustLayout in your http://boston.staging.ujcweb.org/js/globalPage.js file which sets height of div#ctl00_ContentPlaceHolder1_supportingElements dynamically. Therefore your boxes can't push container.
You can try this; Change the toggle function at bottom of your http://boston.staging.ujcweb.org/local_includes/top-nav.js script to this:
$("a.trigger").click(function() {
    var $this = $(this),
        $container = $('#ctl00_ContentPlaceHolder1_supportingElements');
    if($this.hasClass('active')) {
        $container.height($container.data('height'));
    }
    else {
        $container.data('height', $container.height()).css('height', 'auto');
    }
    $(this).toggleClass("active").next().slideToggle("slow");
    return false; //Prevent the browser jump to the link anchor
});

A: I could not see anything on your fiddle. However, on the main site the container ctl00_ContentPlaceHolder1_supportingElements had a height set in the element's style tag that was 676px (may be dynamically set). That's where the issue was. Either eliminating that or changing it to a min-height worked for child element expansion.


text:
Q: Slide down animation to display errors I need help with the slide down animation that Facebook has on iOS that shows errors. In the attached image, it's the view that says "No Internet Connection" in white text on a black background.
It seems to slide down to display an error message, and after a while it slides back up. What is it called, and how can I implement this?

A: Check out Cocoa Controls, it contains custom controls for ios and Mac OS X (free and commercial).
Some notification classes for iOS:
JSNotifier
MessageBarManager
TSMessages

A: It's not a stock UI component, so it doesn't have a name.
If you want to replicate the same functionality you have to implement it on your own.
It doesn't look complicated though: a simple UILabel and an animation block should do the trick.


text:
Q: Ignore parameters from download url in Matomo statistics It is possible to ignore GET parameters form "normal" urls in Matomo, but I can't find the option to remove parameters from download links:
Examples:
www.domain.com/index.php?param=foo&file=myfile.pdf
www.domain.com/index.php?param=bar&file=myfile.pdf

Now I want to exclude the parameter param in the statistics, that the above example will be counted as the same url. Is this possible?

A: You can configure this in the Matomo settings:

You can easily ignore a number of parameters from the URLs, and prevent them from appearing in the "Behavior > Pages" report. Login as the Super User, go to Administration > Manage Websites > Global list of Query URL parameters to exclude field.
https://matomo.org/faq/how-to/faq_81/


text:
Q: Can I overload an operator in Objective-C? Is it possible to override operator use in Objective-C?
For example
myClassInstance + myClassInstance

calls a custom function to add the two.

A: Operator overloading is not a feature of Objective-C. If two instances of your classes can be added together, provide a method and allow them to be added using that method:
Thing *result = [thingOne thingByAddingThing:thingTwo];

Or, if your class is mutable:
[thingOne addThing:thingTwo];

A: You can do this now in Swift, a successor to objC. And since Objective-C and Swift are made to work together This could be interesting for you.

A: You may want to support subscripting for your object. Subscripting is not operator overloading, but it can be handy for a collection object. NSArray and NSDictionary both support subscripting. For example:
NSMutableArray *a = [NSMutableArray new];
a[0] = @"Hello";
The way to support index subscripting is to implement the following:
-(id)objectAtIndexedSubscript:(NSUInteger)idx;
 -(void)setObject:(id)newObject atIndexedSubscript:(NSUInteger)idx];

A: I know this is an old question but I just wanted to leave this answer here for anybody in the future that might want to know if this is a possibility.
The answer is YES!
You'll have to use a variant of Objective-C called Objective-C++.
As an example, say you created a new Objective-C command-line tool project. In order to allow C++ functionality, you'll need to rename "main.m" to "main.mm". Afterwards, you can mix C++ code in with your Objective-C code in the same file. There are some limitations, but I've tested operator overloading and it seems to work perfectly fine with Objective-C objects as far as I can tell.
I've included sample source code to give you an idea of how to do it:
//main.mm
#import <Foundation/Foundation.h>
#include <iostream>
#include <string>

std::ostream &operator<<(std::ostream &os, NSString *s) {
    os << [s UTF8String];
    return os;
}

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

        NSString *str = @"I'm an NSString!";
        std::cout << str << std::endl;

    }
    return 0;
}

Here's my output after building and running this code:

I'm an NSString!
Program ended with exit code: 0

Hopefully this will be of help to somebody!

A: No, you can't do this in Objective-C.

A: No, Objective-C does not support operator overloading.

A: First, operator overloading is evil.  Second, C doesn't have operator overloading, and Objective-C is a proper superset of C, which only adds a handful of keywords and a messaging syntax.
That being said, if you're using Apple's development environment, you can use Objective-C++ instead of Objective-C, which gives you access to all of C++'s mistakes and misfeatures, including operator overloading.  The simplest way to use Objective-C++ is just to change the extension on your implementation files from ".m" to ".mm"


text:
Q: Problems with WEBrick crashing Here are the details upon start up
=> Booting WEBrick
=> Rails 3.0.1 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2011-01-11 13:43:57] INFO  WEBrick 1.3.1
[2011-01-11 13:43:57] INFO  ruby 1.9.2 (2010-08-18) [i386-mingw32]
[2011-01-11 13:43:57] INFO  WEBrick::HTTPServer#start: pid=10216 port=3000
periodically WEBrick is crashing. The only error message is:

ActionController::RoutingError (No route matches "/thumbnails/missing.png"):

This error message occurs from time to time (I'm using paperclip), but doesn't cause a WEBrick crash each time it occurs. I've spent a little time trying to resolve the routing error - but haven't resolved it yet. I don't think that's the root cause of WEBrick crashing though, since it doesn't happen everytime.
Any help greatly appreciated.

A: Sorry, I don't know the answer to your question but I can offer a potential workaround you might be happy with: use Mongrel instead of WEBrick. Mongrel runs faster and is completely compatible. And maybe it won't crash when a route isn't found. Most Rails developers haven't used WEBrick in a few years.
To use Mongrel:
gem install mongrel

If Rails finds Mongrel it will use it automatically.
Hope that fixes it!

A: Mongrel does not solve the problem, at least on Windows 7 with Ruby 1.9.2 p180 and Rails 3.0.9.
I have found out that the code piece which causes the problem is (It is located in C:\Ruby192\lib\ruby\gems\1.9.1\gems\railties-3.0.9\lib\rails\rack\log_tailer.rb):
module Rails
  module Rack
    class LogTailer
      .
      .
      .

      def tail!
        @file.seek @cursor

        if !@file.eof?
          contents = @file.read
          @cursor = @file.tell
          $stdout.print contents
        end
      end
    end
  end
end

If you blank this method, WEBrick works fine again. I have done an intensive test on it with a lot of RoutingError thrown.
You can use this patch. Put it in the environment file:
module Rails
  module Rack
    class LogTailer

      def tail!

      end
    end
  end
end

The downside of this is that you won't see debug messages on your console.
To bypass this problem, you can use log4r to output debug messages on console instead.
Work like a charm for me.

A: Looks like webrick crash after an error/warning printed to the logger STDOUT. I workaround it by using thin which does't log to STDOUT.
gem install eventmachine --pre
gem install thin
thin start

env: win7x64, ruby 1.9.2 (2011-07-09) [i386-mingw32], Rails 3.0.9

A: Also see this: https://rails.lighthouseapp.com/projects/8994/tickets/5590-rails-30-crashes-ruby-192p0-on-repeated-browser-refresh
I've had luck with the Thin server.


text:
Q: iMacros "__undefined__" while trying to extract link using match keyword I am trying to make this work. Saving links in a .txt file based on a word/keyword match.
here is a code :
TAG POS=1 TYPE=h3 ATTR=class:r extract=htm
SET resultLink EVAL("var s='{{!EXTRACT}}';var match txt=\mmorpg\")
set !extract {{resultLink}}
SAVEAS TYPE=EXTRACT FOLDER=C:\tmp FILE=GameList.txt
set !extract null

But all I get is "__undefined__" in GameList.txt
Can someone help me?
Thanks!

A: As I understood your comment and after looking at http://www.mmorpg.com/gamelist.cfm, the code, probably, must be like this:
SET !EXTRACT_TEST_POPUP NO
SET !LOOP 1
TAG POS={{!LOOP}} TYPE=TD ATTR=CLASS:alt EXTRACT=HTM
SET !EXTRACT EVAL("'{{!EXTRACT}}'.match(/http.*html/)[0];")
SAVEAS TYPE=EXTRACT FOLDER=C:\tmp FILE=GameList.txt

Play it in loop mode with the max loop value, say, 841 (the max row of the table with links).

Obsolete info:
Try the second line of your macro as follows:
SET resultLink EVAL("('{{!EXTRACT}}'.match(/mmorpg/)) ? '{{!EXTRACT}}' : 'no match!';")


text:
Q: Can I code within latex? I want to make a slide show that displays different slides depending on input that I give it. Simple example: Given n, display 2n. Can Latex do this?
The idea is that the values in the slideshow will depend on how many people are in attendance, so I want to be able to change that number on the fly.


text:
Q: How to install AllJoyn on Fedora 19? Is there a procedure to install AllJoyn on Fedora 19?
AllJoyn site includes the installation procedure for Debian/Ubuntu Linux only.

A: I have used the build procedure for Debian to make the one for F19.
1. Build tools and libs
To install the equivalent of build-essential:
sudo yum groupinstall "Development Tools" "Development Libraries"

For the other packages, except ia32-libs:
sudo yum install gtk2-devel openssl-devel libxslt libxml2-devel

And for ia32-libs, I didn't found an adequate replacement. It looks like this package groups many others. For my case, I installed nothing. Apparently, my workstation contains already an adequate replacement (I use my workstation for development).
2. Install Python v2.6/2.7 (Python v3.0 is not compatible and will cause errors)
sudo yum install python

3. Install SCons v2.0
sudo yum install scons

4. OpenSSL
This package has been already installed in the first step.
The remaining steps are exactly the same as for Debian.


text:
Q: How should union of Objects with optional properties be defined with Flow? I have a function that deals with two type of parameters: string and object. There are 3 different object structure expected. That makes up to 4 possibles types:
type URL = string;
type Item = {| href: string |};
type ItemList = {| results: Item[] |};
type Params = {| offset?: number, limit?: number |};

So the function's options type is:
type Options = URL | Item | ItemList | Params;

And here's the actual function:
// No properties of "Params" are required
// so if they're all omitted, Params === {}
function request(opts: Options = {}) {
  if (typeof opts === 'string') {
    return 'opts is an URL';
  }

  if (typeof opts.href === 'string') {
    return 'opts is an item';
  }

  if (Array.isArray(opts.results)) {
    return 'opts is a list of items';
  }

  // Three of the four types are caught
  // we're left with "Params" which may or may not
  // have a "offset" and "limit" property.
  // Destructuring to undefined values is fine here.
  // Still, flow complains about the type not being met.
  const { offset, limit } = opts;
  return 'opts are parameters';
}

Flow is complaining about a few things:

*

*opts = {} throws an incompatibility error. Since no properties of Params are required, shouldn't empty objects match it too? Note that opts = { offset: undefined } clears the error.

*Properties "offset" and "limit" are declared not found. Since none of them are required, shouldn't undefined be valid values? And thus destructuring fine?

To summarize my question:
How do you define a type that accepts different types of object, with one having no required properties?
Edit: run the flow code in your browser.

A: Check out Flowtype - making a sealed empty object for an answer to your first question.
For your second, the answer basically is that Flow does not fully support this sort of type refinement. Disjoint unions were designed for this use case, though you do have to add a discriminator property to all of your objects. Obviously, this will require some nontrivial changes to your code. It's up to you to decide if this is feasible.
If it's not feasible, the best thing to do is probably to just cast through any in this function, and make sure you provide a type annotation for the return value. It looks like it's small enough that it's easy for a human to reason about, so the benefit of typechecking here may not be worth the effort. Of course that's a judgement call that is best left to you.


text:
Q: Extracting a copy of operands using Intel-pin I am a newbie to intel-pin,I am trying to do a bit width analysis on binaries.
I try to analyze the exact number of bits used for operands in each assembly instruction.
For example if an unsigned integer 15 has been stored then 4 bits enough.
To do this I need to get a copy of the operands. Is there any method to do this using intel-pin api.

A: Regarding memory operands, you can use INS_IsMemoryRead and INS_IsMemoryWrite to see if the instruction accesses memory, and then instrument it based on the number of memory operands (there can be more than one because some instructions implicitly access memory). Look at IARG_MEMORYREAD_EA and friends to get the memory read and write values in the analysis function.
To see the values in the actual registers you can use IARG_REG_VALUE.


text:
Q: Wpf Livecharts - Separator step value binding is not working Simply I want to add an X-axis separator with dynamic values in a Livecharts CartesianChart. But value binding is not working.
I am using LiveCharts 0.9.7 and .NET 4.5
I went through WPF Live-Charts -- Binding Separator in Code Not Working question but it didn't work on me since the code is different.
What I have tried is this which was in [https://lvcharts.net/App/examples/v1/wpf/Axes]:
In XAML:
<lvc:CartesianChart Series="{Binding SeriesCollection}">
    <lvc:CartesianChart.AxisX>
        <lvc:Axis Labels="{Binding Labels}">
            <lvc:Axis.Separator>
               <lvc:Separator IsEnabled="False" Step="{Binding Step}"></lvc:Separator>
            </lvc:Axis.Separator>
        </lvc:Axis>
    </lvc:CartesianChart.AxisX>
    <lvc:CartesianChart.AxisY>
       <lvc:Axis Title="Sold Items" LabelFormatter="{Binding YFormatter}"></lvc:Axis>
    </lvc:CartesianChart.AxisY>
</lvc:CartesianChart>

In CS:
 public SeriesCollection SeriesCollection { get; set; }
 public string[] Labels { get; set; }
 public Func<double, string> YFormatter { get; set; }
 public int Step { get; set; }

Here Step is the separator step value and it can be changed in runtime.
Every other bindings are working properly.
No error is given and X-axis separators are also displayed but not according to the Step value.
Kindly expect your help to fix this out!!