text:
Q: Writing from file to file program I'm trying to make a program that reads a line from the database.txt and writes an odd/even numbered lines to files 1.txt and 2.txt. F.e. 1st(odd) line of the database.txt goes to 1.txt and the 2nd(even) line of the database.txt goes goes to 2.txt
Here's the code I got so far:
import java.io.*;
import java.util.Scanner;

public class Main {

    public Main(){
        op(null);
    }

    public void op(String args[]){
        try{
            FileReader fr = new FileReader("database.txt");
            BufferedReader reader = new BufferedReader(fr);
            String line = reader.readLine();
            Scanner scan = null;
            int ln = 1;
            String even = "2txt";
            String odd = "1.txt";
            while ((line=reader.readLine())!=null){
                scan = new Scanner(line);
                if(ln%2==0){
                    wtf(even, line);
                }else{
                    wtf(odd, line);
                }
                ln++;
                line=reader.readLine();
            }
            reader.close();
        }
        catch (FileNotFoundException e){
            System.out.println("File not found");
        }
        catch (IOException e) {
        System.out.println("Impossibru to read");
        }
    }

    public void wtf(String filename, String ltw){
        try
        {
            FileReader fr = new FileReader(filename);
            BufferedReader reader = new BufferedReader(fr);
            String line = reader.readLine();

            FileWriter writer = new FileWriter(filename);
            BufferedWriter bw = new BufferedWriter(writer);
            while(line==null){
                bw.write(ltw);
                bw.newLine();
            }
            bw.close();
        }
        catch ( IOException e)
        {
        }
    }
    }

At the moment its on an infinite loop reads only the 2nd line and spams it to 1.txt

A: Within the:
if(ln%2==0)

block you also need to add ln++;
Also move the
line=reader.readLine();

to directly outside the else block.
As an alternative, this is a somewhat reworked method:
Remove all of the line=reader.readLine();s including the first.
Rewrite the loop as:
while ((line=reader.readLine())!=null){

        if(ln%2==0){
            wtf(even, line);
        }else{
            wtf(odd, line);

        }
        ln++;
}

A: You are not incrementing the line count.
  while (line!=null){
                scan = new Scanner(line);
                if(ln%2==0){
                    wtf(even, line);
                    ln++;
                }else{
                    wtf(odd, line);
                    ln++;
                    line=reader.readLine();
                }
            }
            reader.close();
        }

A:       if(ln%2==0){
            wtf(even, line);
        }else{
            wtf(odd, line);
             } //<------------here ?
            ln++;
            line=reader.readLine();
    // }
    }
    reader.close();

update:
   while((line=reader.readLine())!=null){
               *
               *
               *
            line=reader.readLine() ; //is this line  required ?

update:
Check this also in wtf()
 while(line==null){
                bw.write(ltw);
                bw.newLine();
        }

A: Your infinite loop is happening here:
if(ln%2==0)
    wtf(even, line);

ln starts at 0. 0 % X = 0, therefore it is always considered an even number, and you just keep spamming out to the same line. Add the increment to your even clause.
Interesting side note
You have another infinite loop, because if the value is even, or 0, then you never read the next line.
Solution
if(ln%2==0){
    wtf(even, line);
    ln ++;
    line = reader.readline();

A: The problem was with the wtf method. Your endless loop was in there when you wrote:
while(line==null){
                bw.write(ltw);
                bw.newLine();
}

BufferedReader states it returns null if the end of the stream has been reached.  Since your files are initially empty (I'm assuming), this will constantly be true, and you will continue writing new lines and your String.
I was playing around with your code and rewrote it to something like this.
import java.util.*;
import java.io.*;
public class fread {
  public static void main (String[] args) {
    Scanner scan = new Scanner(System.in);

    String even = "2.txt";
    String odd = "1.txt";
    String line = "";

    int lineNumber = 0;

    while (scan.hasNext() )
    {
      line = scan.nextLine();
      if (lineNumber++ % 2 == 1)
        writeText(even, line);
      else
        writeText(odd, line);
    }
  }
  static void writeText(String filename, String ltw)
  {
    try
    {
      BufferedWriter bw = new BufferedWriter(new FileWriter(filename, true));
      bw.write(ltw);
      bw.newLine();
      bw.close();
    }
    catch ( IOException e)
    {
      e.printStackTrace();
    }
  }
}

It uses input redirection, so typing java fread < database.txt will give you your results, however this only does appends to a file. If your files do not exist, or are initially empty, this will work as you expect. You'll have to specify this code to the needs of the program. Regardless, you should be able to take my writeText method and incorporate it into your program to be able to to get yours working.


text:
Q: Cambiar el formato en que exporto un csv desde Node Js Buen día,
Soy nuevo en Nodejs y estoy teniendo un problema para esperar por requests, tengo un código en el cual hago llamadas a una URL para obtener datos dentro de un loop (for) en el cual defino la pagina a la que llamo, el problema es que las requests tardan distinto tiempo en llegar y por tanto al no esperarse entre ellas, llegan en distinto orden rompiéndome el código, no he encontrado la manera de esperar que una request termine antes de empezar la siguiente, probé con await y con promises pero probablemente lo haya utilizado mal.
Gracias de antemano.

A: probablemente tengas que utilizar promises y la funcion Promise.all(listaPromises), la cual termina cuando todas las promises de listaPromises terminaron. Tené en cuenta que listaPromises es un iterable, por lo cual puede ser un array o cualquier otra forma de iterable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extracting POST response data returns NOT_FOUND I was hoping someone may be able to help with the following issue I have.
I have a 'HTTP Request' sampler that makes a POST request.  The response data for this request as per the results tree is:
<script>window.document.location.href='handler.ashx?act=wzfin\x26req=nav\x26mop=requirements!new_finish_wiz\x26pk=0c86ea74-c067-4bcf-a49d-be7d0e420fbf';</script>

I want to grab the value for the pk parameter in the response URL above and store in a variable called REQUIREMENT_ID.  I have set up a 'Regular Expression Extractor' for the sampler and set it up as per below:

*

*Apply to: Main Sample Only

*Field to Check: Response message

*Reference Name: REQUIREMENT_ID

*Regular Expression: (?<=pk=)(.*)(?=\')

*Template: $1$

*Match No: 1

*Default Value: NOT_FOUND

However, when I run this, NOT_FOUND is being returned.  Any ideas what I might be doing wrong?
`Regular Expression Extractor screenshot

A: Change your regular expression to this <script>.+pk=(.*?)'
And change your field to check to Body

A: Try this: ".pk=(.?)'"
Not to sure why you way doesn't work to be honest.


text:
Q: Python TypeError: not all arguments converted during string formatting, while passing parameter to a PostgreSQL query I know this question have been asked before but any of the answers was helpful for me, I am using Basic module(psycopg2) in python trying to pass an external parameter row[1] into a Postgres Query which is:
 print row[1], type(row[1])

630776863141535744 <type 'str'>

when I run the following code I face TypeError: not all arguments converted during string formatting
for row in rows:
   t=row[1]
   PSQL1="SELECT occorrenza.tag from occorrenza where tweet=%s and tag in ( select pk_tag from hashtag where isentity=FALSE);"
   c.execute(PSQL1,t)

also I have tried the following code and have the same error :
for row in rows:
    c.execute("SELECT occorrenza.tag from occorrenza where tweet=%s and tag in ( select pk_tag from hashtag where isentity=FALSE);",row[1])

I have changed many other parts like putting '%s'instead of %s
but I still have error!

A: The second parameter to execute() should be a tuple in your case:
for row in rows:
    c.execute("SELECT occorrenza.tag from occorrenza where tweet=%s and tag in ( select pk_tag from hashtag where isentity=FALSE);", (row[1], ))


text:
Q: Android Studio: Working with parameters Could someone explain to me how parameters work in java? I am using
Android Studio and would like to know if I am trying to get params from a url connection should I use this (my code):
            params.put("Pass", password);

            params.put("Username", email);

"Pass" is where the user passwords are stored on my online database.
"Username" is where the user emails are stored on my online database.

A: As someone commented you should not send passwords in plain text to your server. Make sure to use a SSL/TLS (https) layer to protect your data.
Other than that you should be able to use that code.


text:
Q: First page Look Fine but giving wrong results in next pages Laravel vue I am facing issue in laravel pagination. First page of record is showing exactly that I am looking for but giving the wrong results in second or next pages.
I don't know what i am doing wrong.. I also checked the json data not getting the exactly result according to the search query.
        $lawcase =DB::table('cases');
    if($request->cases_ids){
        $lawcase=$lawcase->whereIn('id1',$request->cases_ids);
    }
    /***********Case Law Search *********/
    if($request->case_keyword){
        $lawcase=$lawcase->where('detail3','like','%'.$request->case_keyword.'%');
    }
    /******Citation Search End*******/
    $lawcase=orderBy('id1','desc')->paginate(30);
    return response()->json(['lawcase'=>$lawcase,'search_count'=>$lawcase->total()], 200);

In Vue js (Frontend)
  <nav class="navigation pagination">
        <div class="nav-links">
            <paginate :page-count="lastpage" :click-handler="getPageRecord" :prev-text="'Prev'" :next-text="'Next'">
            </paginate>
        </div>
    </nav>

Here is the page record:
        getPageRecord(pageNum) {
            $('#preloader').modal('show')
            axios.get('/cases/getCase?page=' + pageNum).then(response => {
                this.casesList = response.data.lawcase.data;
                $("html, body").animate({ scrollTop: 300 }, "slow");
                $('#preloader').modal('hide')
            })
        }


text:
Q: How to specify c header file in android.mk file i had a c source folder name "clib" and in that , i have some example files like 1.h ,1.c , 2.h ,2.c,3.c,3.h and out side that folder i have 4.h , 4.c , 4_jni.h , 4_jni.c
Now to build ".so" i created my android.mk something like this
LOCAL_PATH := $(call my-dir)
MY_PATH := $(LOCAL_PATH)
include $(call all-subdir-makefiles)
include $(CLEAR_VARS)
LOCAL_PATH := $(MY_PATH)
LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog
LOCAL_MODULE := clib
TIME_SYNC_PATH := ../../../clib
LOCAL_SRC_FILES := \
                    4_jni.c \
                    4.c     \
                    $(TIME_SYNC_PATH)/1.c \
                    $(TIME_SYNC_PATH)/2.c \
                    $(TIME_SYNC_PATH)/3.c \
$(BUILD_SHARED_LIBRARY)

Here 4.h includes 1.h file
So my real problem is when i tried to build .so file it gives me a error some like this
fatal error: 1.h: No such file or directory
if i remove the 1.h from 4.h , everything is building fine , but i had a large c library
with same kind of folder structure , and some of .h file contains few marcos defined ....
So Please any suggestion how to include  .h which is in different folder..

A: You need to specify a LOCAL_C_INCLUDES location.
This variable holds the locations of your header files like :
LOCAL_C_INCLUDES := $(LOCAL_PATH)/src/include/

You can of course specify multiple locations :
LOCAL_C_INCLUDES := $(LOCAL_PATH)/src/include/
LOCAL_C_INCLUDES += $(LOCAL_PATH)/project2/src/include/

Note that when this variable is evaluated by the ndk-build utility, its value is considered to be relative to $(LOCAL_PATH), so you need to use $(LOCAL_PATH) when giving a path in LOCAL_C_INCLUDES.


text:
Q: Why is setattr not working when importing differently in python? I changed the value of a constant using setattr.
from core import constants

setattr(constants, "VERSION", "1.0.0")

Now, this still prints 0.1.0 (The older value defined in the constants)
from core.constants import VERSION

print(VERSION)

But, this prints 1.0.0 as expected.
from core import constants

print(constants.VERSION)

Why is this? And what can I do to change the value in first case too.
EDIT:
The constants is not actually a constants.py file but a directory constants with __init__.py file. And have the following content.
VERSION = "0.1.0"


text:
Q: Application Insights added ConnectedService.json file to my project, Do I have to deploy it to the production server? Follow up to this question:
Application Insights added ConnectedService.json file to my project, what does this do?
When I create a deployment package, via "Publish..." option, the package also include the following folder and files:
Service References\Application Insights\ConnectedService.json
I do not want to deploy something that is not required at runtime. Do I have to include the folder and file in my production server deployment?

A: No.  Those files are only used by visual studio for its information, to know what services have been added and give you links back to them inside VS. None of that needs to be deployed.  those files can all be set to do not copy/etc.


text:
Q: Detect when call, mic, or location banners pop up - iOS Swift Is there a listening function that will allow you to adjust a view's layout when a banner pops up at the top? (i.e. the banners that say "touch to return to call", "recording", "maps is using your location", etc.)

A: It should call your viewWillLayoutSubviews() method. You can override and adjust the view accordingly as per the view bounds. More info here
https://developer.apple.com/reference/uikit/uiviewcontroller/1621437-viewwilllayoutsubviews
Swift code:
override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        // Use self.view.bounds to do what you want to

    }

Objective C code:
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];

    // use self.view.bounds to do what you want to
}


text:
Q: Unable to capture sent messages on Android Please I need to capture sms that's being sent out in an Android phone and log it somewhere. So far my attempts don't seem to work.
Here is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.secure.sms"
    android:versionCode="1"
    android:versionName="0.1" >

    <uses-sdk android:minSdkVersion="8" />

    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.WRITE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name="org.secure.sms.SecureMessagesActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".MyAlarmService" />

        <receiver
            android:name="org.secure.sms.SmsReceiver"
            android:exported="true" >
            <intent-filter android:priority="999" >
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

        <receiver android:name="org.secure.sms.ServiceReceiver">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        </intent-filter>
        </receiver>

        <activity
            android:name="org.secure.sms.MyAlarmService"
            android:label="@string/title_activity_my_alarm_service" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="org.secure.sms.SecureMessagesActivity" />
        </activity>

    </application>

</manifest>

Here is my observer class
package org.secure.sms;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;

public class ServiceObserver extends ContentObserver {
private Context mContext;

//private String contactId = "", contactName = "";
private String smsBodyStr = "", phoneNoStr = "";
private long smsDatTime = System.currentTimeMillis();
static final Uri SMS_STATUS_URI = Uri.parse("content://sms/out");

public ServiceObserver(Handler handler, Context ctx) {
    super(handler);
    mContext = ctx;
}

public boolean deliverSelfNotifications() {
    return true;
}
public void onChange(boolean selfChange) {
    try{
        //Log.e("Info","Notification on SMS observer");
        Cursor sms_sent_cursor = mContext.getContentResolver().query(SMS_STATUS_URI, null, null, null, null);
        if (sms_sent_cursor != null) {
            if (sms_sent_cursor.moveToFirst()) {
                String protocol = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("protocol"));
                Log.e("Info","protocol : " + protocol);
                int type = sms_sent_cursor.getInt(sms_sent_cursor.getColumnIndex("type"));
                    Log.e("Info","SMS Type : " + type);
                    // for actual state type=2
                    if(type == 2){

                        smsBodyStr = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("body")).trim();
                        phoneNoStr = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("address")).trim();
                        smsDatTime = sms_sent_cursor.getLong(sms_sent_cursor.getColumnIndex("date"));

                        Log.e("Info","SMS Content : "+smsBodyStr);
                        Log.e("Info","SMS Phone No : "+phoneNoStr);
                        Log.e("Info","SMS Time : "+smsDatTime);
                    }
                }
            }

        else
            Log.e("Info","Send Cursor is Empty");
    }
    catch(Exception sggh){
        Log.e("Error", "Error on onChange : "+sggh.toString());
    }{
    super.onChange(selfChange);
}

}
}

Here is the observer registration
final Uri SMS_STATUS_URI = Uri.parse("content://sms/out");
        ServiceObserver smsSentObserver = new ServiceObserver(new Handler(), this);
        this.getContentResolver().registerContentObserver(SMS_STATUS_URI, true, smsSentObserver);

Edit:
The app is now working fine but am only able to capture SMS when I only visit the app, though Android showing the process and service running in the backgroud. Here is the code I've put on pause
I've registered a service and have this code on pause, but still if phone goes iddle, it says one service and one process running, but not capturing sms only unless I visit the app.
protected void onPause() {
    if(!TrackerService.isRunning){

        serviceIntent = new Intent(MainActivity.this, TrackerService.class);
        startService(serviceIntent);

        mServiceReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(TrackerService.mAction);
        registerReceiver(mServiceReceiver, intentFilter);

     }

    super.onPause();
}

A: try using this
final Uri SMS_STATUS_URI = Uri.parse("content://sms");

A: I had the same issue and seems an Android bug. The solution I founded is here. First you have to use:
final Uri SMS_STATUS_URI = Uri.parse("content://sms");

This will recieve sent and received SMS, to know which of them is you have to use this code:
Register the observer:
contentResolver = this.getContentResolver();
        contentResolver.registerContentObserver(Uri.parse("content://sms"), true, new mObserver(new Handler()));

The observer itself:
class mObserver extends ContentObserver {

        // Constructor
        public mObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);

            Log.i("SMSTracker","onChange()");

            // Uri to get all the SMS (sent and received)
            Uri uriSMS = Uri.parse("content://sms");
            Cursor cur = contentResolver.query(uriSMS, null, null, null, null);
            cur.moveToNext();

            // Debug
            final String[] names = cur.getColumnNames();
            for(int n = 0; n < cur.getColumnNames().length; ++n){
                Log.i("SMSTracker", "Column[" + n + "] = " + names[n] + " --> " + cur.getString(cur.getColumnIndex(names[n])));
            }
            Log.i("SMSTracker", "SMS length: " + cur.getString(cur.getColumnIndex("body")).length() );

            final int type = cur.getInt(cur.getColumnIndex("type"));

            // type == 2 means a successfully sent message and type == 1 means a received message
            if( (type == 2 || type == 1) && (!lastID.contentEquals(cur.getString(cur.getColumnIndex("_id")))) ){
                String protocol = cur.getString(cur.getColumnIndex("protocol"));
                String smsString = cur.getString(cur.getColumnIndex("body"));
                lastID = cur.getString(cur.getColumnIndex("_id"));

                // Sent SMS
                if(protocol == null){

                }
                // Received SMS
                else{

                }
            }
        }
    }

When protocol == null you have sent a SMS else you have received one. (type == 2 || type == 1) is because SMS seems to be sent in stages, when type == 1 or type == 2 the SMS was sent or received. All is based on my experiences hope they can help you!


text:
Q: How to devide numbers? I need to divide all natural numbers from 1 to n into three sets so that the sum of the numbers in each set is the same. If it can't, return -1
The output should be, for example n = 5:
2
1 4

2
2 3

1
5

I try to do this by my code:
n = int(input())

def divide_numbers(n):
    if n * (n + 1) / 2 % 3 == 0:

        numbers = [i for i in range(1, n+1)]
        total_sum = sum(numbers)
        set_sum = total_sum // 3
        sets = [[], [], []]
        for num in numbers:
            if sum(sets[0]) + num <= set_sum and len(sets[0])<2:
                sets[0].append(num)
            elif sum(sets[1]) + num <= set_sum and len(sets[1])<2:
                sets[1].append(num)
            else:
                sets[2].append(num)
        return sets
    else:
        return -1

a = divide_numbers(n)
if a != -1:
    first = a[0]
    len_first = len(first)
    second = a[1]
    len_second = len(second)
    thired = a[2]
    len_thired = len(thired)
    print(len_first)
    print(*first)
    print(" ")
    print(len_second)
    print(*second)
    print(" ")
    print(len_thired)
    print(*thired)

else: print(a)

but the output is for n = 5:
2
1 2

1
3

2
4 5

I know that the condition that the sum of the numbers in the set must be equal is not met, how can I fix this?


text:
Q: How to specify -march=native using pragmas (or otherwise) in gcc I would like to specify the compiler options for my C code that will be compiled in gcc.  I need to do this from within the code because of the way the code will be deployed.  This is the code currently which appears to successfully specify the optimization flags.
#pragma GCC optimize ("-O3,-ffast-math")
typedef float v4sf __attribute__ ((vector_size (16)));
typedef union {
  v4sf v;
  float e[4];
} float4;
typedef struct {
  float4 x;
  float4 y;
} complex4;
static complex4 complex4_mul(complex4 a, complex4 b) {
  return (complex4){a.x.v*b.x.v -a.y.v*b.y.v, a.y.v*b.x.v + a.x.v*b.y.v};
}
complex4 f4(complex4 x[], int n) {
  v4sf one = {1,1,1,1};
  complex4 p = {one,one};
  for (int i = 0; i < n; i++) p = complex4_mul(p, x[i]);
  return p;
}

However I would also like to specify -march=native. Is this possible
  somehow from within the code?

I did try #pragma GCC optimize ("-O3,-ffast-math, -march=native"), but the -march=native part just appears to be ignored. See: https://godbolt.org/g/FjbRcV.

A: Now I understand. I far as I know there is no other way than using #pragma GCC target
For example:
#pragma GCC target ("arch=skylake-avx512")
But it does not accept native as a parameter. I have added it to your godbolt
https://godbolt.org/g/vm1ZBa
IMO it is wrong approach as they should be passed to the compiler using the command line parameters and properly written makefile

A: So upon consideration it looks like
#pragma GCC target "arch=native"

causes barfing in gcc/config/i386/i386.c, here -
3066 /* Override various settings based on options.  If MAIN_ARGS_P, the
 3067    options are from the command line, otherwise they are from
 3068    attributes.  */
 3069
 3070 static void
 3071 ix86_option_override_internal (bool main_args_p,
 3072                                struct gcc_options *opts,
 3073                                struct gcc_options *opts_set)
 3074 {
  ...
3699   else if (i == pta_size)
 3700     error ("bad value (%s) for %sarch=%s %s",
 3701            opts->x_ix86_arch_string, prefix, suffix, sw);
 3702

I don't see any code in that function that can handle 'native' as an x_ix86_arch_string ..
Instead it looks like 'native' is processed and 'real cpu is detected' earlier on in the command line processing sequence in gcc/config/i386/driver-i386.c:
368 /* This will be called by the spec parser in gcc.c when it sees
369    a %:local_cpu_detect(args) construct.  Currently it will be called
370    with either "arch" or "tune" as argument depending on if -march=native
371    or -mtune=native is to be substituted.
372
373    It returns a string containing new command line parameters to be
374    put at the place of the above two options, depending on what CPU
375    this is executed.  E.g. "-march=k8" on an AMD64 machine
376    for -march=native.
377
378    ARGC and ARGV are set depending on the actual arguments given
379    in the spec.  */
380
381 const char *host_detect_local_cpu (int argc, const char **argv)

So, to summarize, what you are asking for requires a change to gcc .. dynamic cpu determination in gcc seems to be done only once, early on, and even then only if asked for (triggered by command line arguments), this is completed well before any parsing or #pragma processing is started.
Getting dynamic cpu determination aka 'arch=native' functionality in gcc's #pragma sounds more like a feature request for them than a bug fix.


text:
Q: General error with PDO and SQL create temporary table I am using php PDO and I have this error when I use the query below,
SQLSTATE[HY000]: General error

query,
            CREATE TEMPORARY TABLE temp_tb
            SELECT * FROM person;

            ALTER TABLE temp_tb
            DROP type;
            SELECT *
            FROM temp_tb AS p

            LEFT JOIN user AS u
            ON p.person_id = u.person_id

            LEFT JOIN category AS c
            ON u.category_id = c.category_id

            WHERE u.signature = ?

They query is to create a temp table and then to drop a column from that temp table, then join it with other tables.
It returns result OK when I query it directly on phpMyAdmin but not through PDO. Something I have done wrong in the query or the PDO? How can I get around to this?
EDIT:
PDO,
public function fetch_object($query, $params = array())
    {
        try
        {
            # prepare the query
            $stmt = $this->connection->prepare($query);

            # if $params is not an array, let's make it array with one value of former $params
            if (!is_array($params)) $params = array($params);

            # execute the query
            $stmt->execute($params);

            # return the result
            return $stmt->fetchObject();
            //return $stmt->fetch(PDO::FETCH_OBJ);
        }
        catch (PDOException $e)
        {
            # call the get_error function
            $this->get_error($e);
        }
    }

$user = $this->database->fetch_object($sql,$authenticated_user);

error,
SQLSTATE[HY000]: General error

A: The problem is that you use several queries in one call (create temp table, alter it and then select from it). Read about multiple queries in one call here


text:
Q: Tracker.autorun behaviour on multiple and nested reactive vars I could not find detailed info on on the behaviour of Tracker.autorun in Meteor.
E.g. inside of the autorun function what happens (and why):

*

*if I get the same reactive var twice

*if I get Meteor.user() and Meteor.userId()

*what about reactive vars got in functions nested inside the autorun function

*what about multiple different reactive vars

A: I found a great article about the topic: Meteor Tracker Manual
The Tracker functions (so called computations) are updated whenever the client is idle (this is called Flush-Cycle). If any reactive variable within a computation did change since the last flush it is rerun. This implies that for my questions 1, 2 & 4 this means the computation is only called once. Even if many different variables are updated.
For the nested function question I wrote a test. As it seems even very deeply nested reactive variables are tracked. So one has to be really careful which functions to call within a Tracker function. Since they may contain reactive vars which are then tracked too.


text:
Q: Android Libgdx writeString, nothing happens This works just fine :
FileHandle handle = Gdx.files.internal("data/data.txt");
String dataFile = handle.readString();

But when I do this, nothing happens to the file and no error happens either :
FileHandle handle = Gdx.files.local("data/data.txt");
handle.writeString( "Hello world", false );

I've added this to the manifest file :
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

A: Could you try to use the permission:
WRITE_EXTERNAL_STORAGE?
It seems that the permission you are trying to use: WRITE_INTERNAL_STORAGE does not exist.
Please check on this list:
http://developer.android.com/reference/android/Manifest.permission.html


text:
Q: Power BI - Use an unrelated table to find valid combinations of data I think I can ask this question without any example data:
Let's say I have a large table, maybe 100 columns and a million rows. On each row, there are only a few valid combinations of data, but that only applies to five of the columns. The other 95 columns can really be anything.
I have another validation table of just those five relevant columns, where each row is a valid combination of values. Can I use this to create a "Valid/Invalid" flag on the main table?
I was thinking that we wouldn't be making a relationship between these tables, although, every validation column will also exist in the main table, so I suppose you could? In my real-world case there are no good primary keys, but if the solution is a many-to-many relationship I'll edit the question and title here.
Edit: the above was answered but here's a more difficult variation:
What if rows in the main table don't all include all five validation values? The validation table shows valid combinations, but nulls are allowed in the main table?


text:
Q: Is there any free/opensource vbscript compiler? I need to compile a wmi vbscript to executable (to automate configuration in several computers). Any free vbscript compiler or any other suggestions?

A: One thing I would be especially concerned about in doing this is you must really trust the product that is compiling the script. After all, what better way to embed a virus or worm than to offer a free compiler that compiles your VBScript into an unreadable executable.

A: Currently, the best known opensource client side vbscript is baleas2.
If you are talking about server side vb like scripting, then the option list is very big as follows: instant-asp (ib4j-tomcat, java), rbsp (realbasic-server-pages), pbsp (purebasic-server-pages), run-basic (libertybasicscript), and so on with almost all the completely developed commercial alternatives to vb.
Regarding other windows based opensource basic variant in the area of basicwebscripting currently are maven-sb4j, scriptbasic and gbs3 (gambas server pages). Then freebasic server pages may soon be yet another option in the future (after development for curl and proxyserver / fastcgi support).
You may also try using maven-sb4j for jbasic, jabaco, scriptbasic-japi and yabasic-japi.

A: Try http://www.xneat.com/application-builder/index.htm
looks trusted

A: ok that's interesting i guess, and I fully understand your point!
you can use the WSH Encoder here (Windows Script Host), it's for free you can encrypt your scripts and this way no one can read them (just the not curious ones!)
and if you are looking for some strong and hard work also encryption you can try this book here

A: Try vbs to exe. It's command line but works fine.
http://www.f2ko.de/programs.php?lang=en&pid=v2e


text:
Q: How to insert into one table values from a variable and other table I have written the following query to insert values from one table to other along with some variables.
But the syntax seems to be incorrect as i am unable to get the result:
INSERT INTO [tran].[ohlc_price]
                   ([symbol_id]
                   ,[timestamp]
                   ,[datetime]
                   ,[open_price]
                   ,[high_price]
                   ,[low_price]
                   ,[close_price]
                   ,[digits]
                   ,[type]
                   ,[created_date]
                   ,[created_by])
        values (
                @get_symbol_id, select
                #temp_ohlc.timestamp,
                #temp_ohlc.datetime,
                #temp_ohlc.open_price,
                #temp_ohlc.close_price,
                #temp_ohlc.high_price,
                #temp_ohlc.low_price,
                #temp_ohlc.digits,
                #temp_ohlc.type from #temp_ohlc,
                @get_date,
                user_name()
                )

What is wrong in syntax. Please help.
I am getting error:

Msg 156, Level 15, State 1, Procedure ohlc_price_save, Line 119 [Batch
Start Line 9] Incorrect syntax near the keyword 'select'.

A: You wouldn't use values and select but just a select:
INSERT INTO [tran].[ohlc_price]
                   ([symbol_id]
                   ,[timestamp]
                   ,[datetime]
                   ,[open_price]
                   ,[high_price]
                   ,[low_price]
                   ,[close_price]
                   ,[digits]
                   ,[type]
                   ,[created_date]
                   ,[created_by])
        select
                @get_symbol_id,
                #temp_ohlc.timestamp,
                #temp_ohlc.datetime,
                #temp_ohlc.open_price,
                #temp_ohlc.close_price,
                #temp_ohlc.high_price,
                #temp_ohlc.low_price,
                #temp_ohlc.digits,
                #temp_ohlc.type,
                @get_date,
                user_name()
                from #temp_ohlc;

As you can see you can have your constant value variables (@get_date, @get_symbol_id) and scalar functions (user_name()) as if they were fields of #temp_ohlc temporary table. They would be generated as values per insert row.
(Please tag your database, it is SQL server, isn't it?)

A: The syntax for INSERT does not allow what you are doing, so try:
INSERT INTO [tran].[ohlc_price](
    [symbol_id]
   ,[timestamp]
   ,[datetime]
   ,[open_price]
   ,[high_price]
   ,[low_price]
   ,[close_price]
   ,[digits]
   ,[type]
   ,[created_date]
   ,[created_by])

select
   @get_symbol_id,
   #temp_ohlc.timestamp,
   #temp_ohlc.datetime,
   #temp_ohlc.open_price,
   #temp_ohlc.close_price,
   #temp_ohlc.high_price,
   #temp_ohlc.low_price,
   #temp_ohlc.digits,
   #temp_ohlc.type,
   @get_date,
   user_name()
FROM #temp_ohlc;


text:
Q: Characters turning up in POST data I'm running a high traffic ssl website with apache/mod_wsgi/python. Very occasionally (around 10x in 3 months) I've seen some extra garbage characters in post data.
Usually it's been in the form of a extra char at the end.
('access.uid', 'allow\xba')
('checksum', 'b219d6a006ebd95691d0d7b468a94510496c5dd8\xff')

Once though it was in the middle of someone's password. Something like:
('login_password', 'samplepass\xe7word')

I've tried to reconstruct the request with all the same headers but I haven't been able to duplicate the error. Anyone have any ideas about what could be causing this or any ideas of how I could go about reproducing and fixing this problem?
(Copied from below):
I'm using apache-2.2.17_1 – Peter Mar 15 at 18:09
I'm using mod_wsgi-3.3_1 on one machine and mod_wsgi-2.8_1 on another. I've seen this error on both.

A: What version of Apache are you using? From memory, somewhere around Apache 2.2.12-2.2.15 there were various SSL fixes. You might want to ensure you are using Apache 2.2.15 or later.

A: what happens if you print eval("u'%s'"%garbled_text)? does the output look likely (I understand that you may not be able to post sensitive data)
It looks to me like somewhere it's assuming you're reading ASCII even though you've told it to read utf-8.
Can we see the code that reads this POST data into python, or where it is specified and from what input form?

A: Since you said all errors occurred in IE 7 or 8 I'm starting to suspect the error occurs client-side in the browser. I've never heard of anything like this error and I have no clue what otherwise could cause it server-side except for hardware failure (though that seems weird too since  only one character is added). Perhaps you should suggest your users to upgrade to a decent browser?

A: This looks very much like chunked HTTP/1.1.
Use an appropriate handler to un-chunk it prior to parsing. See [1], [2].
Another option is to only accept HTTP/1.0 which doesn't have chunking at all, but this may have downsides.


text:
Q: In h5py, do I need to call flush() before I close a file? In the Python HDF5 library h5py, do I need to flush() a file before I close() it?
Or does closing the file already make sure that any data that might still be in the buffers will be written to disk?
What exactly is the point of flushing? When would flushing be necessary?

A: No, you do not need to flush the file before closing. Flushing is done automatically by the underlying HDF5 C library when you close the file.

As to the point of flushing. File I/O is slow compared to things like memory or cache access. If programs had to wait before data was actually on the disk each time a write was performed, that would slow things down a lot. So the actual writing to disk is buffered by at least the OS, but in many cases by the I/O library being used (e.g., the C standard I/O library). When you ask to write data to a file, it usually just means that the OS has copied your data to its own internal buffer, and will actually put it on the disk when it's convenient to do so.
Flushing overrides this buffering, at whatever level the call is made. So calling h5py.File.flush() will flush the HDF5 library buffers, but not necessarily the OS buffers. The point of this is to give the program some control over when data actually leaves a buffer.
For example, writing to the standard output is usually line-buffered. But if you really want to see the output before a newline, you can call fflush(stdout). This might make sense if you are piping the standard output of one process into another: that downstream process can start consuming the input right away, without waiting for the OS to decide it's a good time.
Another good example is making a call to fork(2). This usually copies the entire address space of a process, which means the I/O buffers as well. That may result in duplicated output, unnecessary copying, etc. Flushing a stream guarantees that the buffer is empty before forking.


text:
Q: Pulling directories and files from a website via http in VB I have a website that is basically just a file repository, and I want others to be able to download these files via a nice VB application. The networking side of VB is a little foreign to me, so I'm having trouble grasping the intricacies. Basically, I want to pull the directory and file information (names and paths are all that's needed at first) into a tree view in my application (given a base directory).
A month ago I had this working fully, but today, without changing any of my code, the methods I was using are now throwing an exception at me. At this point, I'm willing to re-write this part to make it cleaner and more reliable, but I need some guidance on the best way to do this, starting from the function called when I click my button to show the listing.
Initially, I was getting a string and breaking it into an array, but for some reason, the GetStringAsync line is now throwing a "the remote party has closed the transport stream" exception at me. But even if someone knew how to fix this issue, I want a more reliable and robust way to iterate over all the directories in a "list directories" website. The line is shown below just for illustration. This function is being awaited in another that catches the exception. I didn't show any of the parsing that happens later since it fails immediately upon the request.
Public Async Function GetRemoteFileInfos(remoteAddress As String) As Task(Of IEnumerable(Of RemoteFileInfo))
Dim results As New List(Of RemoteFileInfo)
Dim htmlText As String

Using client As New HttpClient
  htmlText = Await client.GetStringAsync(remoteAddress)

End Using

Return results.ToArray

Maybe I'm just misunderstanding the async flow, which is why I'd like to start over anyway, and have some more experienced programmers guide me through perhaps a basic understanding of how this part of the program needs to function. Note, I don't want to use FTP, I'd like to not force users to install any extra plugins, and the base directory is https://update.nerfarena.net/.

A: This works well. Now for getting the information out of the string I leave this to you.
    Dim httpc As New HttpClient
    httpc.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml")
    httpc.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0")
    Dim response As String = Await (httpc.GetStringAsync("https://update.nerfarena.net/"))

A: After speaking with my web host about the issue, they told me to make sure the security protocol I was using was TLS 1.1 or 1.2 as 1.0 had been disabled on the host platform. A quick search yielded some ways to opt in to newer TLS versions, and the one that seems to be working for me now is:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

Thanks everyone for all the help, I appreciate it!


text:
Q: MobaXterm - warn "are you sure you want to close this session"? Is there a way to make MobaXterm to popup a warning "are you sure you want to close this session" when hitting the "x" close button of a session tab?
Too often I accidentaly close my sessions :(

A: -> Press 'Settings' icon on the top toolbar
-> Terminal
-> click checkbox 'Prompt before exit' at the right bottom


text:
Q: Project Euler 35: HashSet gives incorrect results I wrote a Java program for Project Euler #35: Circular Primes:

The number, 197, is called a circular prime because all rotations of
  the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31,
  37, 71, 73, 79, and 97.
How many circular primes are there below one million?

My code compiles and runs fine, however, it gives different results depending on the data structure I use.
The algorithm works like this:

*

*Get pre-calculated primes. This is the call to MathUtils.getPrimes(1000000), which gets all primes equal to or less than a million. I store this in another Set because it is implemented by returning a subset, and performance is ridiculously terrible unless I copy the primes into their own data structure.

*While the set of primes is not empty, get the next prime.

*Get all rotations of that prime. E.g. 197, 971, 719. These rotations need not be prime themselves, because I need to verify them anyway.

*If the prime set contains all of the rotations, add the count of the rotations to a running total.

*Remove all of the rotations from the set of primes if they exist.
I noticed two weird things about this code. If I use a TreeSet to store the primes the performance is very fast and it produces correct results:

Answer: 55
  Time: 76ms

If I switch to a HashSet the performance is a lot worse and the results are incorrect.

Answer: 50
  Time: 2527ms

I put code at the top to double check that the sets both contain the same values before the code runs, and they always do.

*

*Why does using the HashSet produce incorrect results as compared to the TreeSet? There are no nulls or other weird values, only positive, distinct Integer instances. The sets start out containing the exact same data. The algorithm is the same, because it is the exact same code. Due to ordering differences between the implementations and the size of the data, it is nigh impossible to compare the state of the algorithms as they are running. If I reduce the input size, the two produce the same results up to 100,000.

*Why does the TreeSet perform so much faster than the HashSet, when it has to perform all of those removals and tree rotations that are not applicable to a HashSet? Looking at the code for HashMap which backs HashSet, there is no resizing or shuffling of contents going on other than that localized to a specific bin. Furthermore, the primes are fairly evenly distributed. While there is no easy way to validate, I would expect that there would not be the worst-case performance issue of many items occupying a small number of bins in the table.
Code follows. You can switch the Set implementation by swapping the variable names at the top.
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.NavigableSet;
import java.util.TreeSet;

public class Problem_0035 {

  public static void main(String[] args) {
    // Swap these two variable names to compare.
    Collection<Integer> primes = new TreeSet<>(sieve(1000000));
    Collection<Integer> primes2 = new HashSet<>(sieve(1000000));
    if (!primes.containsAll(primes2) || !primes2.containsAll(primes)
        || (primes.size() != primes2.size())) {
      System.out.println("Primes are not the same!");
    }
    final long start = System.currentTimeMillis();
    int result = 0;
    // Keep getting a prime and checking for its rotations. Remove the primes checked.
    while (!primes.isEmpty()) {
      Integer next = primes.iterator().next();
      Collection<Integer> rotations = getRotations(next);
      if (primes.containsAll(rotations)) {
        result += rotations.size();
      }
      primes.removeAll(rotations);
    }
    System.out.println("Answer: " + result);
    // 55
    System.out.println("Time: " + (System.currentTimeMillis() - start) + "ms");
  }

  /** Enumerate all rotations of the given integer. */
  private static Collection<Integer> getRotations(Integer argValue) {
    Collection<Integer> results = new LinkedList<>();
    final int start = argValue.intValue();

    // Count the digits
    int magnitude = 1;
    for (int i = start; i > 9; i /= 10) {
      magnitude *= 10;
    }

    int current = start;
    do {
      results.add(Integer.valueOf(current));
      current = ((current % 10) * magnitude) + (current / 10);
    } while (current != start);

    return results;
  }

  /** Sieve of Eratosthenes. */
  private static Collection<Integer> sieve(int argCeiling) {
    NavigableSet<Integer> primes = new TreeSet<>();
    for (int i = 2; i <= argCeiling; ++i) {
      primes.add(Integer.valueOf(i));
    }
    for (Integer number = primes.first(); number != null; number = primes.higher(number)) {
      int n = number.intValue();
      for (int i = n * 2; i <= argCeiling; i += n) {
        primes.remove(Integer.valueOf(i));
      }
    }
    return primes;
  }

 //
 // Filter the set through this method to remove the problematic primes.
 // See answers for an explanation.
 //

 /**
   * Any prime number with a zero or five anywhere in its number cannot have prime
   * rotations, since no prime can end in five or zero. Filter those primes out.
   */
  private static Collection<Integer> filterImpossiblePrimes(Collection<Integer> in) {
    Collection<Integer> out = new TreeSet<>();
    for (Integer prime : in) {
      if (!willBeRotatedComposite(prime)) {
        out.add(prime);
      }
    }
    return out;
  }

  /** If the prime is guaranteed to be rotated to a composite, return true. */
  private static boolean willBeRotatedComposite(Integer prime) {
    int p = prime.intValue();
    boolean result = false;
    if (p > 10) {
      while (p > 0) {
        // Primes must end in 1, 3, 7, or 9. Filter out all evens and 5s.
        if ((p % 5 == 0) || (p % 2 == 0)) {
          result = true;
          break;
        }
        p /= 10;
      }
    }
    return result;
  }

}

A: There's 2 bugs in your code:
1) The order does matter. Example: 2 is a prime number which passes the rotations test. 20 is not. A rotation of 20 is 2. Your code will therefore remove 2 and not count it, if it randomly iterates over 20 first. Here's a change to the getRotations function which would cause Tree/Hash Set to have equivalent results:
int current = start;
do {
   int currMagnitude = 1;
   for (int i = current; i > 9; i /= 10) {
      currMagnitude *= 10;
   }
   if (currMagnitude == magnitude)
       results.add(current);
   current = ((current % 10) * magnitude) + (current / 10);
} while (current != start);

2) You're deleting elements from a collection while you iterate over it. You're not supposed to do this in Java. I suspect if you modified your code like this both TreeSet and HashSet would have roughly equivalent speed:
Collection<Integer> primesCopy = new HashSet<>(primes);
for(Integer i in primesCopy) {
     if(!primes.contains(i)) continue;
     // rest of code as it was

A: Some fiddling around shows that the most expensive bit with the hashset is finding the next prime to check via Integer next = primes.iterator().next(); - on my machine, the version using the hashset takes almost exactly 4 seconds, of which it spends roughly 3.9 seconds with iterator-related business.
HashSet is based on HashMap, and its iterator has to step through all buckets until it finds a non-empty one; as far as I can tell from a skim of the source code of HashMap, it does not resize itself after a delete, i.e. once you bring it to a certain capacity, you will have to resize manually if you don't insert into it. This might have the effect that once you deleted a sizable portion of the elements of the HashSet, most of its buckets are empty, so finding the first non-empty bucket becomes expensive. My best guess regarding why removing from a HashSet doesn't trigger a resize is that it wasn't built with saving space and quick iteration in mind.
This doesn't happen with the treeset; it remains pretty shallow (log2 128000 is roughly 17, so that's about its maximum depth since there are between 75k and 80k primes below 10^6), and all it needs to do is step through to its leftmost element to find the next one.
That doesn't explain the whole affair for my machine though, since even ignoring that, the hashset is about 30% more expensive than the treeset. My best guess why that happens is that hashing Integers is extra load that is more expensive than finding integer keys in a treeset, but that's really barely a guess, certainly not a solid argument.


text:
Q: Can't get host migrated from godaddy to Route 53 I'm trying to move the domain and so far I set the nameservers in godaddy to be the same ones as from Route 53.
I'm wondering what I should set my A name to, should it be an IP? I used S3 to host my website and have A pointed at its alias.
I also have a cname pointing www.helpsaverosie.com to www.helpsaverosie.com.s3-website-us-west-2.amazonaws.com/
I followed the guide here

I purchased the domain through Go daddy and it worked before migrateing to Route 53, which now the website cannot be found.
*EDIT For some reason even the s3 bucket with www. apended doesn't work
www.helpsaverosie.ca.s3-website-us-west-2.amazonaws.com
*EDIT Godaddy images

A: Here is an example of my route 53 records for a s3 hosted website, these settings work. If you have the equivalent setup, then your problem might be at the godaddy end, not the r53 end.

A: So basically you are seetting the Route 53 nameservers inside your domain records. That is fine if you want to set them for a sub domain but not for the main domain. For the main domain you need to follow their instructions:

If your domain name is registered with us, use the following instructions to set custom name servers for it.
To Set Custom Nameservers for a Domain Name Registered with Us
Log in to your Account Manager.
Next to Domains, click Launch.
Select the domain name(s) you want to modify.
From the Nameservers menu, select Set Nameservers.
Under Setup type, select Custom.
Select Add Nameservers.
Enter the two nameservers your hosting provider gave you.
Click Add Nameserver if you have more than two nameservers.
Click Save.

Here's the link: http://support.godaddy.com/help/article/664/setting-nameservers-for-your-domain-names


text:
Q: Rearrange this formula to obtain GRR from known power I have a formula to find power from a set of known variables. I would like to rearrange it to get one of the variables, GRR, given that I know all the others and that I know how much power I want. Can you help?
The formula is:
power = $P(Z>T+\sqrt{NCP})$
where $NCP = \dfrac{(2Nv)(1-v)p^2(1-p)^2(GRR-1)^2}{(vc+(1-v)o)(1-(vc+(1-v)o))(1+p(GRR-1))^2(1-K)^2}$
and $P$ = probability, $Z$ is the tail of the Z distribution, and all others are variables ($v$ and $c$ are separate variables, $GRR$ is a single variable, p is a variable)
Basically: can you rearrange for GRR?

A: Yes. Once you have NCP determined from the first equation, put it into the second. Take square root of both sides and bring the equation to the form
$$
\frac{GRR-1}{1+p(GRR-1)} = \text{known quantity}
$$
Denoting the "known quantity" by $k$,
$$
GRR = 1+\frac{k}{1-pk}
$$


text:
Q: How to use matplotlib in Kivy with kv file? I am trying to plot a matplotlib chart on my kivy App.
I found this on internet
plt.plot([1, 23, 2, 4])
plt.ylabel('some numbers')

class MyApp(App):

    def build(self):
        box = BoxLayout()
        box.add_widget(FigureCanvasKivyAgg(plt.gcf()))
        return box

MyApp().run()

It works perfectly for me but when I use
 box.add_widget(FigureCanvasKivyAgg(plt.gcf()))

it plots ALL the plt.plots of my python file and I would like to plot only one ! I already tried to name my plot like
fig=plt.plot(..)

and then to do
 box.add_widget(FigureCanvasKivyAgg(plt.gcf(fig)))

But it doesn't work !
Thanks for helping me :)


text:
Q: How to release a PARTIAL_WAKE_LOCK set through MediaPlayer? I'm setting a PARTIAL_WAKE_LOCK for my MediaPlayer instance using:
mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

How can I release it? Is it done in MediaPlayer.release() (I can't see anything about it in the doc)?

A: It is released on MediaPlayer.release(), MediaPlayer.stop(), and MediaPlayer.reset(). It's also released onCompletion and onError.
Looking through the source for MediaPlayer here:
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.2.2_r1/android/media/MediaPlayer.java#MediaPlayer
It looks like MediaPlayer.stayAwake() is responsible and this will release the wakelock.
private void stayAwake(boolean awake) {
    if (mWakeLock != null) {
        if (awake && !mWakeLock.isHeld()) {
            mWakeLock.acquire();
        } else if (!awake && mWakeLock.isHeld()) {
            mWakeLock.release();
        }
    }
    mStayAwake = awake;
    updateSurfaceScreenOn();
}

This is a private method but it is called in various states, for example in release() stayAwake(false) is called.
Just search through for mWakeLock and stayAwake(false) and you'll see. I've also checked as far back as 1.5 and it's the same.


text:
Q: Desktop indexing with KDE I have just upgraded to KDE 4.13 on Arch Linux and it has brought my system to a screeching halt. I am pretty sure it has something to do with Baloo the new desktop search indexing system. I am not sure I ever use desktop search although I use kontact and the associated programs (e.g., kmail, korganizer, and kaddressbook). What exactly does Baloo do and how does it interact with Nepomuk and Akonadi and KDE PIM/kontact and what would happen if I disable it by blacklisting my home directory?

A: Nepomuk is no more, Baloo completely replaces Nepomuk and offers the files indexing features previously offered by Nepomuk.
Baloo also interacts with Akonadi and offers mail indexing and all the other semantic capabilities related to Kontact apps.
The Baloo file-indexing and mail-indexing features are completely indipendent. Disabling the file indexer will not cause the mail indexer to stop. Currently (KDE SC 4.13.0) is not possible to disable the mail-indexing features without recompiling the PIM components and apps.
To disable the file indexer there are currently two methods:

*

*add your home directory into the Baloo blacklist in System settings

*add Hidden=True into ~/.kde4/share/autostart/baloo_file.desktop
the baloo_file.desktop file can be copied into your home from /usr/share/autostart/baloo_file.desktop
The first method is more user friendly but it does not always work (a bug exists in the KDE bugtracker about this issue).
In a future version a enable/disable switch will be provided to disable the file indexer in a more intuitive way.
I tried the file-indexer shorty but gave up due to slowdowns and disabled it. On the other hand, I find the email-indexing feature quite useful and not intrusive.


text:
Q: Image goes out from the div I have a
 and inside there is text and an image. I give a background to the section but don´t apply to the image. The image has bootstrap class. What am I doing wrong? Thank you.

Title here

paragraph

A: You need overflow: hidden; in your about class.
.about {
    background: red;
    overflow: hidden;
}


text:
Q: Why WriteFile to NDIS send duplicate frames? Hello everyone and thanks in advance for the help,
I am using the WriteFile function (fileapi.h) to send frames to the NDIS driver at Ethernet Layer 2 level, directly between MAC addresses.
The frames are sent correctly, but in any of the tests I did, the frames are sent duplicated. I detected this by capturing the output with WireShark, where the following is represented:
Within the frame I send, I increment a counter on each send. This counter is repeated in two consecutive frames, which have different frame numbers assigned by WireShark.
This is not something that happens randomly due to the loss of messages in the network, and the forwarding of messages by another device in the network. It happens on every frame that is sent, they are exactly the same, including the counter which is incremented every two frames.
Questions:

*

*Is there a parameter in the NDIS driver that sets this duplicate output.

*Am I misinterpreting the WireShark capture.

I saw this post, and did as recommended by uninstalling and installing Ncap and WinCap, but it made no difference.
Thank you very much. Best regards.
bSuccess = (BOOLEAN)WriteFile(
            Handle,
            pWriteBuf,
            PacketLength,
            &BytesWritten,
            NULL);
        DWORD err = GetLastError();
        printf("ERROR: %i", err);
        if (!bSuccess)
        {
            PRINTF(("DoWriteProc: WriteFile failed on Handle %p\n", Handle));
            break;
        }

A: Solved, I answer to my question.
The compilation of the NDIS driver that I am using, comes prepared with the NDIS_SEND_FLAGS_CHECK_FOR_LOOPBACK flag in the send.c file.
For this reason, and following the explanations of this page, it is possible to cancel the duplicated messages in the computer of origin, since in the computer of destiny, finally these did not arrive to be an internal loop.
Best regards.


text:
Q: Dynamically Created TextBox AutoPostBack on TextChanged but Event Function is not called everybody,
I have been trying for days now to solve this problem with no success.
I have textboxes in table cells which are created dynamically upon button click. Three of these buttons will take a value, calculation method (% or Const Value) and the value to apply respectively. Below is the function which creates these TB's among other controls.
    protected void btnAddService_Click(object sender, EventArgs e)
{
    TableRow r = new TableRow();
    TableCell c0 = new TableCell();
    TableCell c1 = new TableCell();
    TableCell c2 = new TableCell();
    TableCell c3 = new TableCell();
    TableCell c4 = new TableCell();
    TableCell c5 = new TableCell();     // Management Fees (% or Const)
    TableCell c6 = new TableCell();     // Management Fees Value
    TableCell c7 = new TableCell();     // Remarks

    service s = new service();

    if (serCount == 0)
    {
        tblHeader.Visible = true;
    }

    // Add the Services DropDownList...
    DropDownList ddlS = new DropDownList();
    ddlS.ID = "ddlServices" + serCount;

    ddlS.Items.Add("Management");
    ddlS.Items.Add("MEP");
    ddlS.Items.Add("Landscaping");
    ddlS.Items.Add("Pest Control");
    ddlServices.Add(ddlS);
    ddlS.CssClass = "form-control";
    ddlS.Width = Unit.Percentage(100);

    c0.Controls.Add(ddlS);
    c0.Width = Unit.Percentage(15);

    s.serviceName = "Management";

    // Add Subcontracted Checkbox...
    CheckBox chkSubCont = new CheckBox();

    chkSubCont.ID = "chkSubCont" + serCount;
    chkSubContracted.Add(chkSubCont);

    c1.Controls.Add(chkSubCont);
    c1.Width = Unit.Percentage(5);
    c1.HorizontalAlign = HorizontalAlign.Center;

    s.subcontracted = false;

    // Add Subcontracted Value...
    TextBox txtSubContVal = new TextBox();
    txtSubContVal.ID = "txtSubcontractVal" + serCount;
    txtSubContVal.CssClass = "form-control";
    txtSubContVal.Attributes.Add("placeholder", "0.000");
    txtSubContVal.Style.Add("text-align", "right");
    txtSubcontValue.Add(txtSubContVal);

    c2.Controls.Add(txtSubContVal);
    c2.Width = Unit.Percentage(10);

    s.subcontValue = 0;

    // Add Management Fees Type (% or Const)...
    DropDownList ddlMFT = new DropDownList();
    ddlMFT.Items.Add("%");
    ddlMFT.Items.Add("Value");
    ddlMFT.CssClass = "form-control";
    ddlMFT.Width = Unit.Percentage(100);
    ddlMFT.ID = "ddlManFeesType" + serCount;
    ddlManFeesType.Add(ddlMFT);

    c5.Controls.Add(ddlMFT);
    c5.Width = Unit.Percentage(5);

    // Add Management Fees Value...
    TextBox txtMFVal = new TextBox();
    txtMFVal.CssClass = "form-control";
    txtMFVal.Attributes.Add("placeholder", "0.000");
    txtMFVal.Style.Add("text-align", "right");
    txtMFVal.Width = Unit.Percentage(100);
    //  txtMFVal.ID = "txtManFeesValue" + serCount;
    txtMFVal.AutoPostBack = true;
    txtMFVal.TextChanged += new EventHandler(txtManFeesVal_TextChange);
    txtManFeesValue.Add(txtMFVal);

    c6.Controls.Add(txtMFVal);
    c6.Width = Unit.Percentage(10);

    // Add Manpower Value...
    TextBox txtManp = new TextBox();
    txtManp.ID = "txtManpower" + serCount;
    txtManp.CssClass = "form-control";
    txtManp.Attributes.Add("placeholder", "0");
    txtManp.Style.Add("text-align", "center");

    txtManPower.Add(txtManp);

    c3.Controls.Add(txtManp);
    c3.Width = Unit.Percentage(10);

    s.manPower = 0;

    // Add Quoted Value...
    TextBox txtQuotVal = new TextBox();
    txtQuotVal.ID = "txtQuotedValue" + serCount;
    txtQuotVal.CssClass += "form-control";
    // txtQuotVal.Text = "0.000";
    txtQuotVal.Attributes.Add("placeholder", "0.000");
    txtQuotVal.Style.Add("text-align", "right");
    txtQuotVal.AutoPostBack = true;
    txtQuotVal.ClientIDMode = ClientIDMode.Static;
    txtQuotVal.TextChanged += (o, ep) => {
        TextBox t = sender as TextBox;

        if (t.Text == "")
        {
            t.Text = "0.000";
        }

        txtPrjValue.Text = (int.Parse(txtPrjValue.Text) + int.Parse(t.Text)).ToString();
    };

    txtQuotValue.Add(txtQuotVal);

    c4.Controls.Add(txtQuotVal);
    c4.Width = Unit.Percentage(10);

    // Add Remarks Box...
    TextBox txtRem = new TextBox();
    txtRem.ID = "txtRemarks" + serCount;
    txtRem.CssClass += "form-control";
    txtRem.ClientIDMode = ClientIDMode.Static;
    txtRem.Width = Unit.Percentage(100);
    txtRemarks.Add(txtRem);

    c7.Controls.Add(txtRem);
    c7.Width = Unit.Percentage(35);

    s.quotedValue = 0;

    // Add the cells to the new row...
    r.Cells.Add(c0);
    r.Cells.Add(c1);
    r.Cells.Add(c2);
    r.Cells.Add(c5);
    r.Cells.Add(c6);
    r.Cells.Add(c3);
    r.Cells.Add(c4);
    r.Cells.Add(c7);

    // Add the new row...
    tblServices.Rows.Add(r);

    serCount++;

    // Postback to refresh contents from Server Side...
    string scriptRefresh = "document.getElementById('" + btnASPClickMe.ClientID + "').click();";
    Page.ClientScript.RegisterStartupScript(typeof(Page), "refreshscript", scriptRefresh, true);
}

Upon TextChanged of txtMFVal text, it does PostBack but it doesn't call the attached event handler, shown below:
    protected void txtManFeesVal_TextChange(object sender, EventArgs e)
{
    TextBox txtMFV = sender as TextBox;

    // Get the parent cell of the TextBox...
    TableRow tr = txtMFV.Parent.Parent as TableRow;
    TextBox txtSCV = tr.Cells[2].Controls[0] as TextBox;
    TextBox txtMFT = tr.Cells[5].Controls[0] as TextBox;
    double scv = Double.Parse(txtSCV.Text);
    double mfv = Double.Parse(txtMFV.Text);
    double v = 0;

    if (txtMFT.Text == "%")
    {
        v = (scv * mfv) / 100;
    }
    else
    {
        v = scv + mfv;
    }

    TextBox txtQP = tr.Cells[6].Controls[0] as TextBox;
    txtQP.Text = v.ToString();

    // Postback to refresh contents from Server Side...
    string scriptRefresh = "document.getElementById('" + btnASPClickMe.ClientID + "').click();";
    Page.ClientScript.RegisterStartupScript(typeof(Page), "refreshscript", scriptRefresh, true);

}

I have tried so many tricks I have found on the net and all didn't work.
Please, help.
Thanks,


text:
Q: ExecCommand not working on all systems I am running the following piece of code in Delphi :-
            procedure TWebBrowserFrame.CopyToClipboard;
            var
               doc : IHTMLDocument2;
            begin
              SelectAll;//doc.execCommand('SelectAll', false, 0);
              doc := browser.document as IHTMLDocument2;
              if (doc <> nil ) then
              begin
                doc.execCommand('Copy', false, 0);
              end;
            end;

I am trying to copy the contents of Ihtmldocument2 component to clipboard. This code is running on some systems but not working on others.It's not running on windows 2008server r2 and few windows 7 machine. I see on all systems that the content gets highlighted (so selectAll should be running).But the content is not copied to clipboard.
I have tried the stated on https://msdn.microsoft.com/en-us/library/aa663363.aspx .
I have ensured dhtmled.ocx and triedit.dll is registered (I am not sure about the version though).
Also I explored the process happening through procmon.exe. I saw on the machine where copyto clipboard is successful triedit.dll is getting called more times than in the machine where it is not working.Also there is no call to mshtml.dll in the machine where it is working but there is a call(or two) on the machine where it is not working.
Can anyone please suggest any solution or workaround for this problem?Also if there is any other way to copy to clipboard from browserframe directly?
thanks!


text:
Q: How to mock an external dependency method callback params in Nodejs? Let's say that I have the following:
lib/modules/module1.js
var m2 = require('module2');

module.exports = function(){
    return {
        // ...
        get: function(cb){
            m2.someMethod(params, function(error, data){
                if(error){
                    cb(error)
                }

                cb(null, data)
            })
        },
        // ...
    }
}

Now let's say that I have a set of tests in another dir, e.g. tests/testModule1.js. From this file, I create an instance of module1 to peform some tests.
I would like to mock the objects passed by the m2.someMethod to it's callback function (not the cb function), from the file testModule1.js.
I've looked into Sinon.js, but I couldn't figure a way to do this. Actually, I that even possible?
Thanks.

A: You could use something like proxyquire, but I'm not a fan of modifying the built in require.
Personally, I would suggest rewriting your code to use dependency injection:
module.exports = function(m2){
    return {
        // ...
        get: function(cb){
            m2.someMethod(params, function(error, data){
                if(error){
                    cb(error)
                }

                cb(null, data)
            })
        },
        // ...
    }
}

Note that I moved m2 to be a parameter in your exported function. Then somewhere else (app, or main, or whatever), you could do this:
app.js
var module1Creator = require('module1');
var module2 = require('module2');
var module1 = module1Creator(module2);

Then when you need to test it...
testModule1.js
var module1Creator = require('module1');
// inject the "fake" version containing test data, spies, etc
var module2Mocked = require('module2mock');
var module1 = module1Creator(module2mocked);

A: I would normaly agree that about changing the design and, as suggested by @dvlsg, DI would be my choice as well.
However, the project I'm working on is already on the move, and has a considerable size. By doing this change would imply in a huge manpower cost that, in this case specifically, might not be worth doing it.
As a solution, I've realized that once you do a require('someModule'), the someModule is loaded and it's stored as a singleton, in some sort of global cache (I don't fully understand this mechanism, but I'll look into it), and doesn't matter if you require('someModule') from another file, you will receive the cached version.
So, if in lib/modules/module1.js I do require('module2'), module2 is loaded and stored in this cache and, I can require('module2') and mock it in tests/testModule1.js. This will reflect when the get() from lib/modules/module1.js is called.
For that, I used Sinon.js to create the mocks in the test files.
The procedure above actually solved my problem, in a way that I didn't have to change the whole design, and I was able to do the tests. Thats why I'm posting this as an answer. However, I'll not set this as the correct answer here because, as I said before, I don't fully understand this mechanism and change required modules is not a good practice.
I would like to see what other devs have to say about this and, if the discussion leads to acceptance, I'll ultimately set this as correct.


text:
Q: Receiver not receiving intent Seems likes a no-brainer. Why is my receiver receiving the intent? I'm declaring this receiver in the onCreate method in my main activity class.
    IntentFilter filter = new IntentFilter();
    filter.addAction(WidgetProvider.ACTION_OPEN_ACTIVITY);

    registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            // No toast is shown.
            Toast.makeText(MainActivity.this,"Intent received",Toast.LENGTH_SHORT).show();
        }
    }, filter);

    Intent intent = new Intent(this,MainActivity.class);
    intent.setAction(WidgetProvider.ACTION_OPEN_ACTIVITY);
    sendBroadcast(intent);

A: Replace:
Intent intent = new Intent(this,MainActivity.class);
intent.setAction(WidgetProvider.ACTION_OPEN_ACTIVITY);

with:
Intent intent = new Intent(WidgetProvider.ACTION_OPEN_ACTIVITY);

You cannot use an explicit Intent with a dynamically-registered receiver and MainActivity is not a BroadcastReceiver.


text:
Q: Send commands between two computers over the internet I wish to control my computer (and usb devices attached to the computer) at home with any computer that is connected to the internet. The computer at home must have a program installed that receives commands from any other computer that is connected to the internet. I thought it would be best if I do this with a web interface as it would not be necessary to install software on that computer. For obvious reasons it would require log in details.
Extra details: The main part of the project is actually a device that I will develop that connects to the computer's usb port. Sorry if it was a bit vague in my original question. This device will perform simple functions such as turning lights on etc. At first I will just attempt to switch the lights remotely using the internet. Later on I will add commands that can control certain aspects of the computer such as the music player. I think doing a full remote desktop connection to control my device is therefore not quite necessary. Does anybody know of any open source projects that can perform these functions?
So basically the problem is sending encrypted commands from a web interface to my computer at home. What would be the best method to achieve this and what programming languages should I use? I know Java, Python and C quite well, but have very little experience with web applications, such as Javascript and PHP.
I have looked at web chat examples as it is sort of similar concept to what I wish to achieve, except the text can be replaced with commands. Is this a viable solution or are there better alternatives?
Thank you

A: You can write a WEB APPLICATION. The encryption part is solved by simple HTTPS usage. On the server side (your home computer with USB devices attached to it) you should use Python (since you're quite experienced with it) and a Python Web Framework you want (I.E. Django).

A: While it is an interesting programming question, perhaps you should ask it on ServerFault instead? There you can probably get a lot of nice input on web-based administration / control tools.

A: VNC
SSH
Remote Desktop (Windows)

A: Unless this is a "for fun" project for you, there are about a jillion things out there that already do this. And if you want to control a computer from a web browser, be prepared to require installing some kind of custom plugin - since browsers can't touch arbitrary files on the local filesystem, execute local applications, or do other things that are flagrant security risks.
I've been using VNC for over a decade - free and easy.
http://en.wikipedia.org/wiki/Virtual_Network_Computing

A: Well, I think that java can work well, in fact you have to deal with system calls to manage usb devices and things like that (and as far as I know, PHP is not the best language to do this). Also shouldn't be so hard to create a basic server/client program, just use good encryption mechanism to not show commands around web.

A: I you are looking for solution you could use from any computer anywhere in the worls without the need to install any software on client pc, try logmein.com (http://secure.logmein.com).
It is free, reliable, works in any modern browser, you don't have to remmeber IPs and hope they won't change, ...
Or if this is a "for fun project" why not write a php script, open port 80 in your router so you can access you script from outside, possibly dynamically link some domain to your IP (http://www.dyndns.com/). In the script you would just login and then for example type the orders in textfield in some form in your script. Lets just say you want to do some command prompt stuf, so you will basically remotely construst a *.bat file for example. Then the script stores this a fromtheinternets.bat to a folder on your desktop that is being constantly monitored for changes. And when such a change is found you just activate the bat file.
Insecure? Yes (It could be made secureER)
Fun to write? Definitely
PS: I am new here, hope it's not "illegal" to post link to actual services, instead of wiki lists. This is by no means and advertisement, I am just a happy user. :)


text:
Q: python with pandas: select column with multi header I read an xlsx file with two headers into a panda dataframe. Now I fail to select a row according to header 1 or two.
Googeling my probelm did not bring up an answer which worked, so I try it here
My Excel looks like this:
Here you see an excerpt of the test excel:

Now I read the excel file into pandas like this:
df = pd.read_excel('XLsample.xlsx', sheet_name=0, header=[0,1], index_col=0)

How can I read a column dependent on header 0 or 1 ? I mean something like this:
persons = df[header[1]]['Name']

numbers = df[header[0]]['int']

thx for your support

A: Use DataFrame.xs:
persons = df.xs('Name', axis=1, level=1)

numbers = df.xs('int', axis=1, level=0)


text:
Q: How do i send messages to Azure Service Bus after completion of activity in Azure data Factory I am trying to send a message to azure service bus through REST API after an activity is completed in Azure data factory pipeline. But how can i generate access token to send messages inside azure data factory.
Azure data factory has only on web activity through which i can call rest endpoints, Is there a solution possible with it.

A: There is two ways to send messages from ADF to a Service Bus.
First, you need to grant the Azure Service Bus data sender role.

You can then send messages using a copy activity, which allows you to send an entire data set, or using a web activity, which allows you to send a body or a parameter.
Settings in Linked Service for Copy Activity:

Settings in Web Activity:

A: I recommand that you could use the Azure Httptrigger function to that.
You could implement send message with Azure httptigger function. And Call Http trigger function in the Azure datafactory.
For more information about Azure Httptrigger function, please refer to this tutorial.
And then we could use the Web activity to call an Azure function endpoint from a Data Factory pipeline.

A: There is a way to use the ADF web activity with to interact with the Service Bus REST api directly using the ADF's managed identitity.
It requires granting relevant permission on the Service Bus namespace for the ADF's managed identity (e.g. by assigning the Azure Service Bus Data Sender role). Rather than generating an access token, you can use the managed identity authentication option in the web activity and set the resource value as https://servicebus.azure.net.
For a worked example please take a look at my blog post on sending messages to service bus from ADF.


text:
Q: Installing nbextensions for Jupyter on AWS-GLUE local setup ( docker image ) - getting permission issue I am trying to install nbextensions for my Jupyter notebook , but getting a user permission error . After reading through multiple websites ,  I have added --user, but the issue persists.
This is being run on a MACBook
Steps for setting this up :
Install Docker
Pull AWS - Glue image from Dockerhub
start the docker

docker run -it -v ~/.aws:/home/glue_user/.aws -v
$JUPYTER_WORKSPACE_LOCATION:/home/glue_user/workspace/jupyter_workspace/
-e AWS_PROFILE=$PROFILE_NAME -e DISABLE_SSL=true --rm -p 4040:4040 -p 18080:18080 -p 8998:8998 -p 8888:8888 --name  glue_jupyter_lab
amazon/aws-glue-libs:glue_libs_3.0.0_image_01
/home/glue_user/jupyter/jupyter_start.sh

The notebook is working and I am able to run code. However ,for ease of coding trying to install the NBExtensions, which is failing.
> sh-4.2$ jupyter contrib nbextension install --user Traceback (most
> recent call last):   File
> "/home/glue_user/.local/bin/jupyter-contrib", line 8, in <module>
>     sys.exit(main())   File "/usr/local/lib/python3.7/site-packages/jupyter_core/application.py",
> line 264, in launch_instance
>     return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs)   File
> "/usr/local/lib/python3.7/site-packages/traitlets/config/application.py",
> line 845, in launch_instance
>     app.initialize(argv)   File "/usr/local/lib/python3.7/site-packages/traitlets/config/application.py",
> line 88, in inner
>     return method(app, *args, **kwargs)   File "/usr/local/lib/python3.7/site-packages/jupyter_core/application.py",
> line 235, in initialize
>     self.parse_command_line(argv)   File "/usr/local/lib/python3.7/site-packages/traitlets/config/application.py",
> line 88, in inner
>     return method(app, *args, **kwargs)   File "/usr/local/lib/python3.7/site-packages/traitlets/config/application.py",
> line 685, in parse_command_line
>     return self.initialize_subcommand(subc, subargv)   File "/usr/local/lib/python3.7/site-packages/traitlets/config/application.py",
> line 88, in inner
>     return method(app, *args, **kwargs)   File "/usr/local/lib/python3.7/site-packages/traitlets/config/application.py",
> line 604, in initialize_subcommand
>     self.subapp.initialize(argv)   File "/usr/local/lib/python3.7/site-packages/traitlets/config/application.py",
> line 88, in inner
>     return method(app, *args, **kwargs)   File "/usr/local/lib/python3.7/site-packages/jupyter_core/application.py",
> line 235, in initialize
>     self.parse_command_line(argv)   File "/usr/local/lib/python3.7/site-packages/traitlets/config/application.py",
> line 88, in inner
>     return method(app, *args, **kwargs)   File "/usr/local/lib/python3.7/site-packages/traitlets/config/application.py",
> line 685, in parse_command_line
>     return self.initialize_subcommand(subc, subargv)   File "/usr/local/lib/python3.7/site-packages/traitlets/config/application.py",
> line 88, in inner
>     return method(app, *args, **kwargs)   File "/usr/local/lib/python3.7/site-packages/traitlets/config/application.py",
> line 604, in initialize_subcommand
>     self.subapp.initialize(argv)   File "/usr/local/lib/python3.7/site-packages/traitlets/config/application.py",
> line 88, in inner
>     return method(app, *args, **kwargs)   File "/usr/local/lib/python3.7/site-packages/jupyter_core/application.py",
> line 239, in initialize
>     self.migrate_config()   File "/usr/local/lib/python3.7/site-packages/jupyter_core/application.py",
> line 165, in migrate_config
>     migrate()   File "/usr/local/lib/python3.7/site-packages/jupyter_core/migrate.py", line
> 245, in migrate
>     with open(os.path.join(env['jupyter_config'], 'migrated'), 'w', encoding='utf-8') as f: PermissionError: [Errno 13] Permission denied:
> '/home/glue_user/.jupyter/migrated'

A: You cannot really install NBExtensions on the docker image. I moved to using VSCode, which was a much friendly editor to use.


text:
Q: How to Handle errors on ExtJs I want to be able to catch any error thrown on my screen. So far my  code is this:
Ext.application({
    errorHandler:function(err){
        alert(err.msg);
        return true;
    },
    requires: [
        'Ext.ux.ajax.JsonSimlet',
        'Ext.ux.ajax.SimManager'
    ],

    views: [
        'Admin.view.something',
        'Admin.view.somethingController'
    ],

    name: 'Admin',

    launch : function() {Ext.create('Admin.view.something');
    Ext.Error.notify = false;
    Ext.Error.handle = this.errorHandler;
    }
});

The problem is, I have some objects that may be undefined. If I do something like undefined.properties, the error handling doesn't catch it.
I know about functions like "Ext.isDefined()", but for this case I really need to handle all generic errors in the same way.

A: Ext.Error.handle only handles errors raised by Ext.raise according to the documentation.
A solution to handle plain javascript errors is the error event on the browsers window.
You can attach an handler with window.addEventListener('error', function(event) { ... }) to it.
The following code should catch all errors in your project.
launch : function() {
    Ext.Error.notify = false;
    Ext.Error.handle = this.errorHandler;
    window.addEventListener('error', this.errorJsHandler);
    Ext.create('Admin.view.something');
},
errorJsHandler: function(err) { // err = ErrorEvent Object https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent
        alert(err.message);
        return true;  // prevent the firing of the default event handler
},


text:
Q: XMLRAD.Projects.xml copy file error when running XMLRAD I freshly unpack and run XMLRAD from XMLRAD.org (stable release), but still get this error:
  The specified file or path was not found : Cannot copy file C:\Delos\xmlrad\Bin\Data\XMLRAD.Projects.xml to C:\Delos\xmlrad\Data\XMLRAD.Projects.xml

The same if I try to change install folder location or run as console or service... Any idea ?

A: You raised a very interesting showstopper in the build,
I have been able to reproduce and locate the problem,
I am submitting a patch,
a new stable build will be available shortly,
your feedback is very valuable.


text:
Q: Random mic permission popup after configuring AdMob After installing AdMob framework with cocoapods and configuring reward video ad my app started to ask for Microphone permission on launch. I don't do any audio-related stuff in it so it's a very little chance I have triggered it myself outside of AdMob framework... Is there any way to prevent this?

A: You can get rid of this following this steps:

*

*Go to "Security & Privacy" Settings on macOS.

*Select "Microphone" on the left panel.

*Uncheck the Xcode option on the right panel.


text:
Q: angular 1.5 (components): how to use directives with es6? in folder directives i created two files: directives.js and color.js
directives i've imported into app.js
directives.js:
import angular from 'angular';

import ColorDirective from './color';

const moduleName = 'app.directives';

angular.module(moduleName, [])

  .directive('color', ColorDirective);

export default moduleName;

color.js
import angular from 'angular';

let ColorDirective = function () {

  return {
    link: function (scope, element) {
      console.log('ColorDirective');
    }
  }

}

export default ColorDirective;

and on one element in component i've added color as attr.
But it's not working. I mean inner link loop. Why? What i have wrong coded? How to use directives with angular 1.5 & es2016 ?

A: I'm not very familiar with es6 syntax but here is the typescript's way I'm using:
class ColorDirective implements angular.IDirective {

    constructor() { }

    link(scope, iElement, iAttrs, ngModelCtrl) {

    }

    /**
    * Instance creation
    */
    static getInstance(): angular.IDirectiveFactory {
        // deendency injection for directive
        // http://stackoverflow.com/questions/30878157/inject-dependency-to-the-angularjs-directive-using-typescript
        let directive: angular.IDirectiveFactory = () => new ColorDirective();
        directive.$inject = [];
        return directive;
    }
}

angular
    .module('moduleName')
    .directive('color', ColorDirective.getInstance());

EDIT: after some research, I've found the es6 way to do the same thing as above:
import angular from 'angular';

class ColorDirective {

    constructor() {

    }

    link(scope, element) {
      console.log('ColorDirective');
    }

    static getInstance() {
        var directive = new ColorDirective();
    }
}

export default ColorDirective.getInstance();

A: From what you have written its not possible to see the problem. The code you provide works, assuming that you have included your module into the page and the code is correctly compiled.
I have put your code into a fiddle, https://jsfiddle.net/fccmxchx/
let ColorDirective = function () {
  return {
    link: function (scope, element) {
      console.log('ColorDirective');
      element.text('ColorDirective');
    }
  }
}

angular.module('app.directives', [])
  .directive('color', ColorDirective);

unfortunately I cannot split your code into modules, but that is what your code is trying to do


text:
Q: Reinforcement Learning with Oracle Policy I'm working on a reinforcement learning problem. The simulation environment is pretty simple (like those maze problems) so I can manually work out its solution. The idea I have is: since I can work out the optimal policy of the environment, is it possible to just use this optimal policy to train the agent, without using Q-learning or policy gradient at all?
Now It seems like a typical imitation learning problem to me now, so instead of doing actual reinforcement learning, I can just do supervised learning. I'm not familiar with this field, a few questions on the details are

*

*In that case, what should my agent try to learn from my optimal policy? Should it try to learn the value function, or advantage function, or regret of the system with state as input? Or should it directly learn the action with given state?

*Can someone point me to some classical papers or tutorials on imitation learning?

*Does this idea also applies to a stochastic environment?

A:
is it possible to just use this optimal policy to train the agent, without using Q-learning or policy gradient at all?

Yes it is, but you have to decide what it is you want to train the agent to do.

In that case, what should my agent try to learn from my optimal policy?

The two obvious choices are:

*

*Copy the optimal policy. This is a relatively straightforward supervised learning problem. Create a dataset of states and actions, and learn $\pi(a|s) = \mathbf{Pr}\{A_t = a | S_t = s\}$

*Learn a value function. To do this you would need to use a reinforcement learning algorithm with a fixed target policy. Most value-based reinforcement learning algorithms have a variant for prediction instead of control that can learn value functions given a fixed policy. Usually that variant is the first one studied, as preeiction is a problem you need to solve before the more complex issue of modifying policies to solve control problems.
Neither of these are required. You have to decide what it is you want the agent to learn, given that you already have the optimal policy.

Does this idea also applies to a stochastic environment?

Yes, provided you are certain that the policy you want to copy or learn value functions for is one of interest to you. It doesn't need to be an optimal policy for you to be interested in it, e.g. it might be a current policy in use and you have been asked to copy it or evaluate it.


text:
Q: Rxjs Distinct operator with key selector in Angular 2 http? i my angular 2 service i have this method :
  notify(userID: string) {
   return Observable.interval(5000)
      .map(() => this.baseUrl + '/notification/GetUnseen?userId=' + userID)
      .switchMap(url => {
         this.datatService.set(url);
         return this.datatService.get();
    })
     .flatMap(response => response.json().slice())
     .distinct(function (x) { return x.id });
   }

How can i use the distinct operator with key selector in this cas ?
When i try to do it i have this error : Property 'id' does not exist on type '{}'.
UPDATE :
The final result i get with this method is :
  {
  id:"f3055770-6e66-4936-8e9a-732b53121549"
  message:"Empty Notification for test ......"
  navigationLink:"/api/home"
  seen:false
  sendedOn:"2016-12-02T15:19:44.856Z"
  userId:null
  }

I would like to filter the result, so if i already have the notification i dont want to get in again

A: I don't know exactly how your data structure looks like, but from the example code I guess that you try to map an array to an Observable sequence with this code part:
(...).flatMap(response => response.json().slice())

What you would need to do is create a new Observable sequence with Observable.from and then use switchMap to get it back into the original stream. Then you can use the distinct operator as wished. See this code sample:
const str = JSON.stringify([{id: 1}, {id: 1}, {id: 2}, {id: 1}]);

Rx.Observable.of(str)
  .map(x => JSON.parse(x)) // replication of your sample code until this line
  .switchMap(x => Rx.Observable.from(x))
  .distinct(x => x.id)
  .subscribe(x => console.log(x));

// output:  { id: 1 }
//          { id: 2 }

Live code on JSBin