text:
Q: Yii 2 is adding a hyphen to the start of the sort name when using createUrl() I'm using Yii 2 and I have created a Pagination and Sort system and have the following code:
Here is the generalized code:
$sql = $this->db->createCommand("SELECT COUNT(*) FROM some_table WHERE some_id=:some_id");
$sql->bindValue(':some_id', $this->some_id);
$count = $sql->queryScalar();

$dataProvider = new SqlDataProvider([
    'sql' => 'SELECT * FROM some_table WHERE some_id=:some_id',
    'params' => [':some_id' => $this->some_id],
    'totalCount' => $count,
    'sort' => [
        'attributes' => [
            'sort_way_1' => [
                'asc' => ['col_1' => SORT_DESC, 'col_2' => SORT_ASC, 'col_3' => SORT_ASC],
                'desc' => ['col_1' => SORT_DESC, 'col_2' => SORT_DESC, 'col_3' => SORT_DESC],
                'default' => SORT_DESC,
                'label' => 'Sort Way 1',
            ],
            'sort_way_2' => [
                'asc' => ['col_1' => SORT_DESC, 'col_4' => SORT_ASC, 'col_3' => SORT_ASC],
                'desc' => ['col_1' => SORT_DESC, 'col_4' => SORT_DESC, 'col_3' => SORT_DESC],
                'default' => SORT_DESC,
                'label' => 'Sort Way 2',
            ],
            'sort_way_3' => [
                'asc' => ['col_1' => SORT_DESC, 'col_5' => SORT_ASC, 'col_3' => SORT_ASC],
                'desc' => ['col_1' => SORT_DESC, 'col_5' => SORT_DESC, 'col_3' => SORT_DESC],
                'default' => SORT_DESC,
                'label' => 'Sort Way 3',
            ],
            'sort_way_4' => [
                'asc' => ['col_1' => SORT_DESC, 'col_6' => SORT_ASC, 'col_3' => SORT_ASC],
                'desc' => ['col_1' => SORT_DESC, 'col_6' => SORT_DESC, 'col_3' => SORT_DESC],
                'default' => SORT_DESC,
                'label' => 'Sort Way 4',
            ],
        ],
        'enableMultiSort' => false,
        'defaultOrder' => ['sort_way_1' => SORT_DESC],
    ],
    'pagination' => [
        'defaultPageSize' => $this->per_page,
        'pageSize' => $this->per_page,
        'pageSizeLimit' => [5,100],
        'pageSizeParam' => 'per_page',
        'totalCount' => $count,
    ],
]);

Now for my sorting links I attempted to create the URL's with the createUrl method and everything works fine, except for the fact it appends a - to the start of the sort attribute name in the URL (apart from the first sort method).
Example:
http://example.com/some_dir/?page=1&sort=sort_way_1 (good)
http://example.com/some_dir/?page=1&sort=-sort_way_2 (bad)

I then tried doing it with the LinkSorter Widget but I got the same results.
I dug into the code a bit and found the below code inside the sort.php createSortParam method:
foreach ($directions as $attribute => $direction) {
    $sorts[] = $direction === SORT_DESC ? '-' . $attribute : $attribute;
}

This appears to be the culprit for the appended hyphen, but I'm not sure why it does it or why it doesn't add it to the first sorting attribute.
Does anyone have any more info on this or how to get around it? As with the appended hyphens the requested sorting method is coming back as invalid.


text:
Q: Android activity error 5 Good day for all the guru's of developing here, first of all, sorry for my bad english but I have an error in a Android app that I'am developing and I couldn`t fix it, and I google it and don't find any answer.
The logcat
09-28 13:21:59.360    2085-2085/com.colpsic.domain.colpsic_app I/art﹕ Not late-enabling -Xcheck:jni (already on)
09-28 13:21:59.360    2085-2085/com.colpsic.domain.colpsic_app I/art﹕ Late-enabling JIT
09-28 13:21:59.362    2085-2085/com.colpsic.domain.colpsic_app I/art﹕ JIT created with code_cache_capacity=2MB compile_threshold=1000
09-28 13:21:59.384    2085-2085/com.colpsic.domain.colpsic_app W/System﹕ ClassLoader referenced unknown path: /data/app/com.colpsic.domain.colpsic_app-2/lib/x86
09-28 13:21:59.387    2085-2085/com.colpsic.domain.colpsic_app D/AndroidRuntime﹕ Shutting down VM
09-28 13:21:59.387    2085-2085/com.colpsic.domain.colpsic_app E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.colpsic.domain.colpsic_app, PID: 2085
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.colpsic.domain.colpsic_app/com.colpsic.domain.colpsic_app.PrincipalActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.Activity.findViewById(Activity.java:2090)
            at com.colpsic.domain.colpsic_app.PrincipalActivity.<init>(PrincipalActivity.java:22)
            at java.lang.Class.newInstance(Native Method)
            at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-28 13:22:01.785    2085-2085/? I/Process﹕ Sending signal. PID: 2085 SIG: 9

PrincipalActivity.java
package com.colpsic.domain.colpsic_app;

import android.content.Intent;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class PrincipalActivity extends AppCompatActivity {
    EditText EdtxtCedula=(EditText)findViewById(R.id.lblCedula);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_principal);

        Button btnAceptar=(Button)findViewById(R.id.BtnAceptar);

        btnAceptar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean existeDocumento;
                existeDocumento = conection();
                validacionDocumento(existeDocumento);
            }

        });
    }

    private void validacionDocumento(boolean validar) {
        if (validar==true){
            Intent intent = new Intent(PrincipalActivity.this, ProfesionalActivity.class);
            Bundle b = new Bundle();
            b.putInt("CEDULA", Integer.parseInt(EdtxtCedula.getText().toString()));
            intent.putExtras(b);
            startActivity(intent);
        }else{
            EdtxtCedula.setText("");
        }
    }

    private boolean conection() {
        final String url = "jdbc:mysql://";
        final String user = "";
        final String pass = "";
        boolean resultadoConexion = false;
        TextView lblCambio=(TextView)findViewById(R.id.lblBienvenido);
        try{

            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection con = DriverManager.getConnection(url, user, pass);
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("select * from usuarios where id="+EdtxtCedula.getText());
            //ResultSetMetaData rsmd = rs.getMetaData();
            //rs.next();
            //lblCambio.setText(rs.getString(1));
            while (rs.next()){
                if ( rs.getRow() == 0 )
                {
                    //es un result set vacío
                     Toast toast = Toast.makeText(getApplicationContext(), "La cedula no existe", Toast.LENGTH_SHORT);
                     toast.show();
                     resultadoConexion = false;

                }else{
                    //el result set tiene datos
                        //Toast toast = Toast.makeText(getApplicationContext(), "Conexion exitosa", Toast.LENGTH_SHORT);
                        //toast.show();
                        lblCambio.setText(rs.getString(2));
                        resultadoConexion = true;
                }
            }
            con.close();

        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return resultadoConexion;
    }

}

activity_principal.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:id="@+id/layContenedor"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".PrincipalActivity"
    android:gravity="center">

    <ImageView  android:id="@+id/imgLogo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/colpsic_logo"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="354dp"
        android:contentDescription="@string/logo_descripcion">
    </ImageView>

    <RelativeLayout   android:id="@+id/layTexto"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignTop="@+id/imgLogo"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="134dp">

        <TextView  android:id="@+id/lblBienvenido"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="@string/bienvenido"
            android:layout_gravity="center_horizontal"
            android:textSize="32sp"
            android:textColor="#0107ff"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" />

        <TextView   android:id="@+id/lblMensaje_Bienvenida"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="@string/mensaje"
            android:layout_gravity="center_horizontal"
            android:textColor="#2514ff"
            android:layout_below="@+id/lblBienvenido"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="39dp" />

        <EditText android:id="@+id/lblCedula"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/cedula"
            android:textColorHint="#CFCFCF"
            android:inputType="number"
            android:layout_below="@+id/lblMensaje_Bienvenida"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="49dp" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/BarraBotones"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true"
        style="?android:attr/buttonBarStyle">

        <Button android:id="@+id/BtnAceptar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/Aceptar"
            style="?android:attr/buttonBarButtonStyle" />

        <Button android:id="@+id/BtnCancelar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/salir"
            style="?android:attr/buttonBarButtonStyle" />

    </LinearLayout>

</RelativeLayout>

AndroidManifiest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.colpsic.domain.colpsic_app" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".PrincipalActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ProfesionalActivity"
            android:label="Profesional" >
        </activity>
    </application>

</manifest>

A: please remove this EditText EdtxtCedula=(EditText)findViewById(R.id.lblCedula); from PrincipalActivity and put it into onCreate method
public class PrincipalActivity extends AppCompatActivity {

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_principal);

        Button btnAceptar=(Button)findViewById(R.id.BtnAceptar);
        EditText EdtxtCedula=(EditText)findViewById(R.id.lblCedula);

A: The following line needs to go inside of a method. (in this case, onCreate)
EditText EdtxtCedula=(EditText)findViewById(R.id.lblCedula);

It crashes because by the time this line is called, setContentView has not been called for the activity, so it doesn't know where to find your EditText
Put it with your other views, like this
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_principal);

    Button btnAceptar=(Button)findViewById(R.id.BtnAceptar);
    EditText EdtxtCedula=(EditText)findViewById(R.id.lblCedula);

    btnAceptar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean existeDocumento;
            existeDocumento = conection();
            validacionDocumento(existeDocumento);
        }

    });
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Return status in Nodejs caused Network request failed This is a newbie question about return in Nodejs (10.16) and express (4.16.4), front end is react native 0.59. Here is the code on Nodejs server returning a status 200 after successful query:
router.post('/new', [auth_deviceid, auth_userinfo, auth_role(['admin', 'eventer', 'messager'])], async (req, res) => {
    //prepare obj msg....

    try {
        await msg.save();
        msg.user_name = req.body.alias;
        msg.user_avatar = req.user.user_data.avatar;
        const io = req.app.get("io");
        const socket_id = req.body.socket_id;
        const socket = io.sockets.connected[socket_id];
        const room = msg.event_id.toString();
        socket.join(room);
        socket.to(room).emit("event message", msg);
        console.log("after emit to room : ", room); //<<<==this line shown in console screen
        return res.status(200); //<<<=== hang here with no error thrown. But instead  res.status(200).send("I am ok") is working.
    } catch (err) {
        console.log("Error in saving/braodcasting a new message", err);
        return res.status(400).send(err.message);
    };

});

The above code is called in react native with the code below:
async _onSend(messages = []) {
      //do something...

      let obj = JSON.stringify({
        _device_id: DeviceInfo.getUniqueID(),
        sender_id: this.state.myself.id,
        sender_grpmember_id:(this.props.grpmember_id || this.props.navigation.state.params.grpmember_id),
        alias:this.props.alias,
        socket_id: this.props.socket.id,
        data: {
          msg_body:messages[0].text,
          upload_content_info: ""
        },
        event_id: this.props.navigation.state.params.eventId,
        _grpmember_id:(this.props.grpmember_id || this.props.navigation.state.params.grpmember_id),
        _group_id:(this.props.group_id || this.props.navigation.state.params.group_id),
      });
      try {
        let url = `${GLOBAL.BASE_URL}/api/messages/new`;
        console.log("Chat message URL : ", obj);
        let res = await fetch(url, {
          method: "POST",
           headers: {
            'Accept': 'application/json, text/plain',
            'Content-Type': 'application/json',
            "x-auth-token": result.password,
            "x-auth-secret" : result.username,
          },
          body: obj,
        });
      }
      catch (err) {
        console.log("Error in saving message : ", err);
      };
    }

On console screen, received the error below:
09-25 17:19:20.325 15181 15252 I ReactNativeJS: 'Chat message URL : ', '{"_device_id":"0cfce7b7e86fa397","sender_id":1,"sender_grpmember_id":1,"alias":"jc","socket_id":"z-8JjwQvKo6ed57KAAAB","data":{"msg_body":"hello","upload_content_info":""},"event_id":1,"_grpmember_id":1,"_group_id":"1"}'
09-25 17:19:20.345 15181 15252 I ReactNativeJS: In GiftedChat render :
09-25 17:20:35.554 15181 15252 I ReactNativeJS: 'Error in saving message : ', { [TypeError: Network request failed]
09-25 17:20:35.554 15181 15252 I ReactNativeJS:   line: 24115,
09-25 17:20:35.554 15181 15252 I ReactNativeJS:   column: 31,
09-25 17:20:35.554 15181 15252 I ReactNativeJS:   sourceURL: 'http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false' }

Why the return res.status(200) is causing the error of Network request failed?

A: Your request takes about 15s, as you point, return res.status(200); just only set http status code for the response, to finish a request you would use res.json, res.send or res.end.
In this case, I think you only need send a success with http status code is 200,
You could use res.sendStatus(200); (res.sendStatus is shorthand for implementing res.status and res.send)  instead of res.status(200).


text:
Q: Thread-Switching in PyDbg I've tried posting this in the reverse-engineering stack-exchange, but I thought I'd cross-post it here for more visibility.
I'm having trouble switching from debugging one thread to another in pydbg. I don't have much experience with multithreading, so I'm hoping that I'm just missing something obvious.
Basically, I want to suspend all threads, then start single stepping in one thread. In my case, there are two threads.
First, I suspend all threads. Then, I set a breakpoint on the location where EIP will be when thread 2 is resumed. (This location is confirmed by using IDA). Then, I enable single-stepping as I would in any other context, and resume Thread 2.
However, pydbg doesn't seem to catch the breakpoint exception! Thread 2 seems to resume and even though it MUST hit that address, there is no indication that pydbg is catching the breakpoint exception. I included a "print "HIT BREAKPOINT" inside pydbg's internal breakpoint handler, and that never seems to be called after resuming Thread 2.
I'm not too sure about where to go next, so any suggestions are appreciated!
    dbg.suspend_all_threads()
    print dbg.enumerate_threads()[0]
    oldcontext = dbg.get_thread_context(thread_id=dbg.enumerate_threads()[0])
    if (dbg.disasm(oldcontext.Eip) == "ret"):
        print disasm_at(dbg,oldcontext.Eip)
        print "Thread EIP at a ret"
        addrstr = int("0x"+(dbg.read(oldcontext.Esp + 4,4))[::-1].encode("hex"),16)
        print hex(addrstr)
        dbg.bp_set(0x7C90D21A,handler=Thread_Start_bp_Handler)
        print dbg.read(0x7C90D21A,1).encode("hex")
    dbg.bp_set(oldcontext.Eip + dbg.instruction.length,handler=Thread_Start_bp_Handler)
    dbg.set_thread_context(oldcontext,thread_id=dbg.enumerate_threads()[0])
    dbg.context = oldcontext
    dbg.resume_thread(dbg.enumerate_threads()[0])
    dbg.single_step(enable=True)
    return DBG_CONTINUE

Sorry about the "magic numbers", but they are correct as far as I can tell.

A: One of your problems is that you try to single step through Thread2 and you only refer to Thread1 in your code:
dbg.enumerate_threads()[0] # <--- Return handle to the first thread.

In addition, the code the you posted is not reflective of the complete structure of your script, which makes it hard to judge wether you have other errors or not. You also try to set breakpoint within the sub-brach that disassembles your instructions, which does not make a lot of sense to me logically. Let me try to explain what I know, and lay it out in an organized manner. That way you might look back at your code, re-think it and correct it.
Let's start with basic framework of debugging an application with pydbg:

*

*Create debugger instance

*Attache to the process

*Set breakpoints

*Run it

*Breakpoint gets hit - handle it.

This is how it could look like:
from pydbg import *
from pydbg.defines import *

# This is maximum number of instructions we will log
MAX_INSTRUCTIONS = 20

# Address of the breakpoint
func_address = "0x7C90D21A"

# Create debugger instance
dbg = pydbg()

# PID to attach to
pid = int(raw_input("Enter PID: "))

# Attach to the process with debugger instance created earlier.
# Attaching the debugger will pause the process.
dbg.attach(pid)

# Let's set the breakpoint and handler as thread_step_setter,
# which we will define a little later...
dbg.bp_set(func_address, handler=thread_step_setter)

# Let's set our "personalized" handler for Single Step Exception
# It will get triggered if execution of a thread goes into single step mode.
dbg.set_callback(EXCEPTION_SINGLE_STEP, single_step_handler)

# Setup is done. Let's run it...
dbg.run()

Now having the basic structure, let's define our personalized handlers for breakpoint and single stepping. The code snippet below defines our "custom" handlers. What will happen is when breakpoint hits we will iterate through threads and set them to single step mode. It will in turn trigger single step exception, which we will handle and disassemble MAX_INSTRUCTIONS amount of instructions:
def thread_step_setter(dbg):
    dbg.suspend_all_threads()
    for thread_id in dbg.enumerate_threads():
        print "Single step for thread: 0x%08x" % thread_id
        h_thread = dbg.open_thread(thread_id)
        dbg.single_step(True, h_thread)
        dbg.close_handle(h_thread)

    # Resume execution, which will pass control to step handler
    dbg.resume_all_threads()

    return DBG_CONTINUE

def single_step_handler(dbg):
    global total_instructions
    if instructions == MAX_INSTRUCTION:
        dbg.single_step(False)
        return DBG_CONTINUE
    else:
        # Disassemble the instruction
        current_instruction = dbg.disasm(dbg.context,Eip)
        print "#%d\t0x%08x : %s" % (total_instructions, dbg.context.Eip, current_instruction)
        total_instructions += 1
        dbg.single_step(True)

    return DBG_CONTINUE

Discloser: I do not guarantee that the code above will work if copied and pasted. I typed it out and haven't tested it. However, if basic understanding is acquired, the small syntactical error could be easily fixed. I apologize in advanced if I have any. I don't currently have means or time to test it.
I really hope it helps you out.


text:
Q: Save Tag values into text file I just want to ask if it is possible to save/export the values/data in a html Select Tag using javascript or jquery into text file?
This is my select tag.
<select id="mySelect" style="width: 581px; height:300px;" rows="10" multiple="multiple"></select>

Then Im trying to use this javascript code, got it from the internet but it did'nt work. It creates a text file but it didnt get the values/data of the select tag.
function saveTextAsFile()
{
    var textToWrite = document.getElementById('mySelect').value;
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    var fileNameToSaveAs = "directive.txt";

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if ($('#sel1').val() == '')
        {
            alert('Please select ACCOUNT NAME, SCHEDULE and TASK first.');
        }
        else
        {
          window.webkitURL != null;
          downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
        }
    downloadLink.click();
}

var button = document.getElementById('save');
button.addEventListener('click', saveTextAsFile);
button.addEventListener('click', doClear);

A: Select elements have <option> children. MDN's example:

<!-- The second value will be selected initially -->
<select name="text"> <!--Supplement an id here instead of using 'text'-->
  <option value="value1">Value 1</option>
  <option value="value2" selected>Value 2</option>
  <option value="value3">Value 3</option>
</select>

So, you would var myOptions = document.GetElementByName("text") then iterate over myOptions .pushing each value (or whatever you want) into an array. Then write that array to your textfile.

A: I saw there was no  tag in your html. I think there must be  tag in the  and  tag. I improved your code as follows:

<body>

<label for="mySelect">Form input without an associated label </label>
<select id="mySelect" style="width: 581px; height:300px;" rows="10" multiple="multiple">
    <option id="id1" value="value1">id1</option>
    <option id="id2" value="value2">id2</option>
    <option id="id3" value="value3">id3</option>
    <option id="id4" value="value4">id4</option>
    <option id="id5" value="value5">id5</option>
</select>
<button id="save">save</button>
<script>
    function saveTextAsFile() {
        var textToWrite = document.getElementById('mySelect').value;
        var textFileAsBlob = new Blob([textToWrite], {type: 'text/plain'});
        var fileNameToSaveAs = "directive.txt";

        var downloadLink = document.createElement("a");
        downloadLink.download = fileNameToSaveAs;
        downloadLink.innerHTML = "Download File";
        console.log("innerHTML -> " + downloadLink.innerHTML);
//        if ($('#sel1').val() == '') {
//            alert('Please select ACCOUNT NAME, SCHEDULE and TASK first.');
//        }
//        else {
            window.webkitURL != null;
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
//        }
        downloadLink.click();
    }

    var button = document.getElementById('save');
    button.addEventListener('click', saveTextAsFile);
</script>
</body>

A: if you have below HTML select element,
<select id="mySelect">
   <option value="volvo">Volvo</option>
   <option value="saab">Saab</option>
   <option value="opel">Opel</option>
   <option value="audi">Audi</option>
</select>

I tested and below code is working. Basically as suggested by Ron above, you need to iterate over the options and add them to a string to print it on the text file.
function saveTextAsFile() {
    var textToWrite = "";
    $('#mySelect>option').each(function () {
        textToWrite += this.value + " ";
    });
    var textFileAsBlob = new Blob([textToWrite], {
        type: 'text/plain'
    });
    var fileNameToSaveAs = "directive.txt";

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if ($('#sel1').val() == '') {
        alert('Please select ACCOUNT NAME, SCHEDULE and TASK first.');
    } else {
        window.webkitURL != null;
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    }
    downloadLink.click();
}

var button = document.getElementById('save');
button.addEventListener('click', saveTextAsFile);


text: Q: How Hibernate ensure DB data integrity? How will Hibernate ensure that the DB data is not compromised by any means(including back end change). Say for instance if I have loaded some employee data using hibernate, mean while someone modified some column (say salary) using back end tools. Now when I try to save the entity in hibernate cache, how will hibernate checks if data is same as was fetched?


text:
Q: Can CSS file loading be deferred via http LINK header and does that block rendering If we use the http link header to provide a link to a CSS file very early on what browsers would NOT download this link and are there any browsers for which a CSS file provided this way would block rendering the "above the fold content"?
This would be the HTTP header:
Link: <style.css>; rel="stylesheet"

This an untested PHP implementation of the same thing (if one does not configure apache to do it like hinted at in the link above):
<?php
header('Link: <style.css>; rel="stylesheet"');
?>

Question: cross browser compatibility and render blocking behavior

A: Apologies in advance that my response is not directly in reference to use of the http Link header. If the objective is to try and load non-critical CSS asynchronously(in the background without blocking page rendering), this can be achieved with JavaScript. See the loadCSS project for some good documentation and examples.
Normally, all CSS files included in a standard way(e.g. <link href="path/to/mystylesheet.css" rel="stylesheet">) do in fact block page rendering until ALL stylesheets have finished loading. This is for good performance reasons by browsers in order to prevent multiple re-layouts and re-paints when loading a page after each stylesheet finishes loading.
The idea with this solution is basically to alter the media type for the non-critical stylesheet(s) to something the browser will see as unimportant for page rendering(e.g. "only x"), and then manually switch the media type back to the standard "all" (or other value as needed), which is likely after then resource is finished loading, but could be further deferred if desired based on your use case.
This method is pretty reliable as long as you only need to to support relatively modern browsers. I've used it in production for content thats had millions of pageviews. You may be able to implement something similar using the Link header but you'd still need some client side script in place to detect when the resource finished loading and to switch the media type back to "all".

A: I am not sure if you can do that with a header() function, but non-blocking css can be done with JavaScript - see this paste: http://pastebin.com/TYcnb99m
It uses local storage as cache for loaded css files and is non-blocking.
Some more links:

*

*https://gist.github.com/scottjehl/87176715419617ae6994

*https://github.com/filamentgroup/loadCSS/
Hope this helps.


text:
Q: SharePoint 2010 Calendar Error when change Content Type Recently a calendar was created in a Site Collection with a personal content type and a personal column. When I tried to save after adding a new event or modifying the event, I have the famous error an expected error was occurred.
My log file in the severity is Unexpected:

System.NullReferenceException : Object reference not set to an
  instance of an object     �
  Microsoft.SharePoint.Applications.GroupBoard.WebControls.OverbookField.get_IsRecurrence()
  �
  Microsoft.SharePoint.Applications.GroupBoard.WebControls.OverbookField.BuildSPItem()
  �
  Microsoft.SharePoint.Applications.GroupBoard.WebControls.OverbookField.IsOverbook()
  �
  Microsoft.SharePoint.Applications.GroupBoard.WebControls.OverbookField.Validate()
  � System.Web.UI.Page.Validate()     �
  System.Web.UI.WebControls.Button.RaisePostBackEvent(String
  eventArgument)     �
  System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
  sourceControl, String eventArgument)     �
  System.Web.UI.Page.ProcessRequestMain(Boolean
  includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  Severity High:
MetadataNavigationContext Page_InitComplete: No XsltListViewWebPart
  was found on this
  page[/sites/Sites/Lists/Calendar/NewForm.aspx?RootFolder=Lists%2FCalendar&ContentTypeId=0x01003DA6D35AEEEB8C4AA5AC98EB36858C88&IsDlg=1].
  Hiding key filters and downgrading tree functionality to legacy
  ListViewWebPart(v3) level for this list.


text:
Q: GitHub Actions Job Based on Multiple Conditions from Inputs I've been trying to create conditions for Jobs in GitHub Actions but I can't seem to get it working
I have the following Inputs:
on:
  workflow_dispatch:
    inputs:
      env:
        description: 'Select the Environment'
        type: choice
        required: true
        options:
        - SIT
        - UAT
      op:
        description: 'Deploy or Delete Apps'
        type: choice
        required: true
        options:
        - Deploy
        - Delete
      ver:
        description: 'Type the app version'
        required: true

and the below jobs:
jobs:
  create-sit-app:
    runs-on: ubuntu-latest
    name: 'Deploy App for SIT'
    if: |
      (${{ github.event.inputs.env }} == 'SIT' && ${{ github.event.inputs.op }} == 'Deploy')

    steps:
........
........
........

I also tried this
(${{ github.event.inputs.env == 'SIT' }} && ${{ github.event.inputs.op == 'Deploy' }})

And this
${{ github.event.inputs.env == 'SIT' }} && ${{ github.event.inputs.op == 'Deploy' }}

A: Managed to do it like this:
    if: (github.event.inputs.env == 'SIT' && github.event.inputs.op == 'Deploy')


text:
Q: plugins update error "Some plugins require plugin JNA to be installed netbeans" i am trying to install a plugin embedded-browser, but it's showing me error, i am using netbeans version 12.0 on arch linux.
Some plugins require plugin JNA to be installed.
The plugin JNA is requested in version >= 1.3 (release version 1) but only 2.3 (of release version different from 1) was found.

The following plugin is affected:
               Embedded Browser UI - XUL Runner

i ahev searched on the plugin portal but there is no plugin for jna i am also getting the same error when updating plugins..but with just diffrent plugin affected..
Some plugins require plugin JNA to be installed.
The plugin JNA is requested in version >= 1.11 (release version 1) but only 2.3 (of release version different from 1) was found.
The following plugin is affected:
              Subversion SvnKit Client Library

A: Refer to https://issues.apache.org/jira/browse/NETBEANS-4704 "I solved the problem by unchecking the NetBeans 8.2 Plugin Portal."
This worked for me too.


text:
Q: NSString substituting NSData possible, what are consequences? Suppose I'm storing a stream of ASCII, say 0x0a0b0c00. What would happen to the data if I store it in an NSData instance vs. an NSString?  Would the data get converted into something else?  I'm a little confused because they are both buffers holding the exact same thing.

A: NSData is a container to store, as its name suggests, raw binary data. NSData makes no assumptions of the format of the binary data. It can be text, images, audio, etc.
NSString interprets the data as text with a given encoding: which could be ASCII, Unicode, etc. In most cases, NSString will copy the bytes to its internal data structure to store the raw binary.
If it's not text, use NSData. It's clearer in code to know what's being managed and avoids having to fight string encodings.


text:
Q: Sort names from sql to categories in A-Z order Im trying to print a names from sql on php page and sort it in categoris
My rows:
1 anna
2 alena
3 benny
4 dolev
5 niv

I want to print it like this:
A
alena
anna

B
benny

D
dolev

N
niv

EDIT:
I tried
while($row_keke = mysql_fetch_array($result_skey002))
{
    $name = $row_keke['name2'];

    if (in_array($name[0], $heb_a_z)) {
    echo $name[0]."
".$name."

";
    }
}

But you see what the problem with this ..
Thanks for everybody .. ! :)

A: Could try something like:
$lastFirst = '';

while($row_keke = mysql_fetch_array($result_skey002))
{

  $name = $row_keke['name2'];

  if($name[0] != $lastFirst){
     echo "
".strtoupper($name[0])."
";
     $lastFirst = $name[0];
  }

  echo $name."
";

}

I haven't tested this, but it should achieve the result you're looking for.


text:
Q: How to specify Dagger 2 Qualifier Annotation to Provider function Constructor parameter? I have my Dagger 2 Qualifier defined
@Qualifier
@MustBeDocumented
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
annotation class TrackerQualifier(val value: TrackerType)

enum class TrackerType {
    INTERNAL,
    EXTERNAL
}

And it works well, with
@Provides
@TrackerQualifier(TrackerType.INTERNAL)
@Singleton
UsageTracker providesInternalTracker(InternalTracker analyticsTracker) {
    return new UsageTracker(analyticsTracker);
}

@Provides
@TrackerQualifier(TrackerType.EXTERNAL)
@Singleton
UsageTracking providesExternalTracker(ExternalTracker eventTracker) {
    return eventTracker;
}

However, if I like to send it though to another injected module.
@Provides
fun provideCommonImage(
        imageEngine: ImageEngine,
        externalUsageTracking: UsageTracking) =
        CommonImage(imageEngine, externalUsageTracking)

It will compile fail, as it doesn't know is the externalUsageTracking: UsageTracking above is INTERNAL or EXTERNAL. How could I annotate it to the parameter?

A: try to explicit the qualifier.
@Provides
fun provideCommonImage(
        imageEngine: ImageEngine,
        @TrackerQualifier(TrackerType.EXTERNAL) tracker: UsageTracker) =
        CommonImage(imageEngine, tracker)


text:
Q: autovacuum analyze paralyzing tables On some tables, an autovacuum: VACUUM ANALYZE public.some_table process will run for 30 min to as long as 10 hours. During this time, updates to the table in question are often locked for 10+ minutes.
As soon as I cancel the auto-vac process, the code that depends on updating those tables is suddenly able to finish executing.
The tables being affected range from 78 GB to 7 GB with millions of rows each on an AWS RDS db.m4.10xlarge with PostgreSQL 9.6.3.
What settings do I need on a per table or system basis to make sure we get a performance boost from auto-vac analyze without interfering with critical query execution speed? If that is too much of a shot in the dark, what query could I run to tell what settings would be optimal for our setup?
These tables have a LOT of updates/deletes/inserts every minute, would changing FILLFACTOR help here as well to reduce the need for auto-vac? I've been iffy on this because some of the most commonly updated columns have indexes and I also don't know how to analyze the tables to tell if fill factor would really be beneficial.
Currently, fill factor is 100% on all tables. Here are other relevant performance settings for the database (let me know if I missed anything salient):
autovacuum = on
autovacuum_analyze_scale_factor = 0.05
autovacuum_analyze_threshold = 50
autovacuum_freeze_max_age = 200000000
autovacuum_max_workers = 3
autovacuum_multixact_freeze_max_age = 400000000
autovacuum_naptime = 30
autovacuum_vacuum_cost_delay = 20
autovacuum_vacuum_cost_limit = -1
autovacuum_vacuum_scale_factor = 0.1
autovacuum_vacuum_threshold = 50
autovacuum_work_mem = -1
effective_io_concurrency = 1
log_autovacuum_min_duration = -1
maintenance_work_mem = 2702336
max_parallel_workers_per_gather = 0
max_worker_processes = 8
rds.force_autovacuum_logging_level = disabled
shared_buffers = 5151945
temp_buffers = 1024
vacuum_cost_delay = 0
vacuum_cost_limit = 200
vacuum_cost_page_dirty = 20
vacuum_cost_page_hit = 1
vacuum_cost_page_miss = 10
vacuum_defer_cleanup_age = 0
vacuum_freeze_min_age = 50000000
vacuum_freeze_table_age = 150000000
vacuum_multixact_freeze_min_age = 5000000
vacuum_multixact_freeze_table_age = 150000000
work_mem = 4096


text:
Q: How to show keyboard whenever input the text box I'm new to Worklight and having many troubles with it.
I'm developing an app using BingMaps. In my app, I use a Search button. When a user wants to search some location, my app show a text box, then user type an address. (When user use this button, must touch the text box one more times to show the keyboard)
But I don't know how to show the keyboard with the text box whenever a user touches the Search button.
This is my code.

    Search Box: <input id="txtSearchA" style="width:213px" type="text">

    <button id="btSearch" onclick="LoadSearchModule()" type="button">Search</button>

A: A keyboard usually comes to view when the focus is on an input field.
From your description I understand that in your case the text field is hidden, and in order to display it the end-user taps the "search" button,
So what I would try to do is: once pressing the search button, that field will get auto-focus thus the keyboard should come to view as well.
I haven't tried this yet myself so I cannot be certain:

*

*Try adding the autofocus HTML5 attribute to your text field. See if that's suffice

*In case 1 above will show a keyboard even when the text field is hidden, try adding it dynamically upon tapping the "search" button.


text:
Q: risk-ratio confidence-interval - but weighted? I have survey data, with weights that adjust the sample to be nationally representative, from two time points. There is a binary presence/absence variable. Presence increases from time 1 to time 2. I would like to put a confidence interval around the percentage increase. This would be a risk ratio confidence interval, which is straightforward unweighted. But, I can't find any method for a risk-ratio confidence-interval that allows weighting. Is there any known? An R implementation would be ideal.
As a crude method I have thought of calculating confidence intervals around the proportion at time 1 and proportion at time 2, for which weighted methods do exist (https://onlinelibrary.wiley.com/doi/abs/10.1002/sim.4780131009) and then using ratios between these intervals. But (a) I don't know an R implementation, and (b) I don't know how valid this would be be.
Help much appreciated!

A: I've now done it by bootstrapping, where I used the survey weights as sampling probabilities for by bootstrap samples. I'm not 100% certain this is valid but I have a strong hunch that this is probably OK.


text:
Q: Update/delete queries cannot be typed I want to implement update query in JPA. I tried this:
public void updateTransactionStatus(String uniqueId, String type, String status) throws Exception {

        String hql = "update " + PaymentTransactions.class.getName()
                + " e SET e.status = :status WHERE e.unique_id = :unique_id AND e.type = :type";
        TypedQuery<PaymentTransactions> query = entityManager.createQuery(hql, PaymentTransactions.class).setParameter("status", status).setParameter("unique_id", uniqueId).setParameter("type", type);
        query.executeUpdate();
    }

But I get Update/delete queries cannot be typed. What is the proper wya to implement this?> I tried to replace TypedQuery with Query but I get The type Query is not generic; it cannot be parameterized with arguments <PaymentTransactions>

A: In general if you do not need to you should avoid using batch updates with JPA unless they are triggered from within a REQUIRES_NEW marked transaction (and thats the only operation).
It seems that you need to perform an update on one unique entry so I would suggest a query followed by a modification, thats it:
// retrieve

PaymentTransactions paymentTransaction =
     entityManager.createQuery("select t from " + PaymentTransactions.class.getName()
          + " where e.unique_id = :unique_id AND e.type = :type "
      , PaymentTransactions.class);
      .setParameter("unique_id", uniqueId).setParameter("type", type)
      .getSingleResult();

// modify

paymentTransaction.setStatus(status);

Here is the place for a TypedQuery.
As long as your method is within a transactional context, thats all you need to do to update the entry.


text:
Q: SQL: calculate value based on two different conditions Below is my table schema:- Appointments
--------------------------------------
| schID | appointment_date | amount | location |
--------------------------------------

I want to fire a single query where I can get the sum of amount, total appointment_date this year i.e 2016 and remaining appointment_date this year i.e 2016.
So I wrote the below query to calculate the above fields:-
SELECT sum(a.amount) as total,
       count(distinct a.appointment_date) as total_appointment,
       count(distinct a2.appointment_date) as remaining appointments
from Appointments a
LEFT JOIN Appointments a2 ON a.schID = a2.schID
WHERE a2.appointment_date > GETDATE() AND year(a.appointment_date) = 2016
group by a.location

The above query doesnt return value as per requirement :(
The database belongs to SQL Server.

A: You can use conditional aggregation for this:
SELECT sum(amount) as total,
       count(appointment_date) as total_appointment,
       count(DISTINCT CASE
                WHEN appointment_date > GETDATE() AND YEAR(appointment_date) = 2016
                  THEN DATE(appointment_date)
             END) as remaining appointments
from Appointments a
group by a.location

A: You shouldn't need a join for this type of query:
SELECT sum(a.amount) as total, count(a.appointment_date) as total_appointment,
       sum(case when a.appointment_date > getdate() then 1 else 0
           end) as remaining appointments
from Appointments a
where year(a.appointment_date) = year(GETDATE() );

If you need the breakdown by location, then include location in both the select and group by clauses.


text:
Q: MongoDB Exception caching while updating data Hello every one I'm new to mongodb. While i updating the table i have to get the return values in result. But it return undefined ,But in the case of find and insert the value in table it works properly.
  bands.update({name:'Hollywood Rose'}, {$set:{year:2000}}, function(err, result) {
console.log("result----"+result) // it returns undefined
        if (!err)
return context.sendJson(result, 404);
    })

;

A: This code work in my case while i update value in the table in mongodb i did this code in playframe work for java . Hope it also help in you case.
    MongoClient mongo=new MongoClient("localhost",27017);
    /*mongo.setWriteConcern(WriteConcern.JOURNALED);*/
    DB db = mongo.getDB("webportal");
    DBCollection coll=db.getCollection("userdb");
    //ObjectId id= new ObjectId(userid);
    BasicDBObject doc2 = new BasicDBObject();
    doc2.put("_id",userid);
    BasicDBObject updateDocument = new BasicDBObject();
    updateDocument .append("$set", new BasicDBObject("username", username1).append("password", password1).append("email", email1));
    coll.update(doc2, updateDocument);


text:
Q: RequestBody JSON format has single quotes I have a controller class in my SpringBoot app.
@RestController
@RequestMapping("/{database}/alerts")
public class ControllerB {
  @Autowired private ServiceB serviceB;

  @Autowired
  private B b;

  @Autowired
  ControllerB(B b,ServiceB serviceB){
      this.b = b;
      this.serviceB = serviceB;
  }

  @RequestMapping(method = RequestMethod.POST)
  public B dosomethingCrazy(@RequestBody BImpl bimpl)  {

      String response = serviceB.dosomethingImportant();
      return bimpl;

  }

}

The problem arises when the requestBody has a single quote in the value. For example if the requestbody is {"name" : "peter o'toole"}, it throws a http 400

"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"JSON parse error: Unexpected end-of-input in VALUE_STRING

Any idea how Jackson can map a single quote value to the object field?

A: Set the following property in your application.properties file:
spring.jackson.parser.allow-single-quotes=true

A: Create this class to setup the Jackson and enable Single quotes:
@Configuration
public class JsonConfigurer {

    @Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.build();
        objectMapper.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES)
        return objectMapper;
    }

}

A: Not sure what version of Spring Boot you are using. With 1.4.3.RELEASE, I can curl just fine like this to my endpoint:
curl -X POST --header "Content-Type: application/json" --header "Accept: */*" -d "{\"name\":\"peter o'toole\"}" "https://localhost:5443/test"

I should add though that our Jackson version is 2.7.2. I am not sure if that causes it to work.


text:
Q: Display/format UTC time in angular I have converted a bunch of dates in my controller to UTC in order to display the in the view.
Im running into a weird problem trying to format them though..
{{ '2016-07-22T10:45:00.000Z' | date : "shortTime"}}

I would expect that code to display something like:
//10:45

Instead it displays
//3:45 AM

3:45 is the local time on my computer.
Any idea what causes this or how I can display 10:45?

A: Try this...
All you need to do is adding : 'UTC' after the format string.
{{ '2016-07-22T10:45:00.000Z' | date:' HH:mm:ss ' : 'UTC' }}


text: Q: Transformation of random variables and Jacobian When transforming 2+ continuous random variables, you use a Jacobian matrix and compute the determinant. Do you also compute the Jacobian for discrete random variables?


text:
Q: c++ two digit hexadecimal to decimal converter I am trying to write a program that will allow a user to enter a two digit hexadecimal number and have it converted to an integer.  The only problem is that I am unable to have a user enter a char value into the program. Here is my code as it stands now.
#include <iostream>

using namespace std;

int main()
{
int val1, val2;
int decval;

cout << "Enter the first hex value: ";
cin >> val1;
cout << "Enter the second hex value: ";
cin >> val2;

if (val1 >=65 && val1 <=70)
{
val1 = (val1-55)*16;
    if (val2 >= 65 && val2 <= 70)
    {
        val2 -= 55;
        decval = val1+val2;
        cout << decval;
    }
    else if (val2 >= 0 && val2 <=9)
    {
        val2 = val2;
        decval = val1 + val2;
        cout << decval;
    }
    else
       cout << "Error";
}
else if (val1 >= 0 && val1 <=9)
{
    val1 = val1*16;
    if (val2 >= 65 && val2 <= 70)
    {
        val2 -= 55;
        decval = val1+val2;
        cout << decval;
    }
    else if (val2 >= 0 && val2 <=9)
    {
        decval = val1 + val2;
        cout << decval;
    }
}
else
{
    cout << "Error";
}


text:
Q: ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'dict' I'm trying to insert a dataframe using the query
engine = create_engine('scot://pswd:xyz@ hostnumb:port/db_name')
dataframe.to_sql('table_name', engine, if_exists='replace')

but one column is a dictionary and I'm unable to insert it, only the column name is getting inserted.
I tried to change the type of the column in postgres from text to json object. still not able to insert.
I tried to use json.dumps() but still facing the issue.getting an error as "dtype: object is not JSON serializable"

A: Try specifying the dtype. So in your example, you would say
dataframe.to_sql('table_name', engine, if_exists='replace',dtype =
                {'relevant_column':sqlalchemy.types.JSON})


text:
Q: Error-Implement interface in python 3.2 with the module overloading I am try to implement a interface in python with  the module "overloading"
http://www.python.org/dev/peps/pep-3124/#interfaces-and-adaptation
The problem is that no found the module overloading when a try to run with python3.2
 from overloading import abstract
 from overloading import Interface

 ImportError: No module named overloading

how to fix my problem?.

A: A PEP is a Python Enhancement Proposal. Not all PEPs are accepted. Due to some uncertainties about implementation, the author of PEP 3124 decided to defer the proposal. However, note that this was in 2007 with no progress since then, so I wouldn't hold my breath waiting for this one.
If you're after a mechanism for interface checking, you might be able to use the abc module in the standard library, which roughly covers the same interface & adaptation ground that PEP 3124 proposed.
For a more full featured solution, I highly recommend zope.interface. If you're put off by the zope namespace (you shouldn't be, it's totally independent) there are other lightweight interface solutions such as visage.


text:
Q: VBFP doesnt work probably in aqua-sim I used  VBF routing, in aqua-sim.  However, i noticed that the source packet never reaches the sink! and consumed energy exceed the initial energy!
what is the causes for that?
Here is the tcl file
  set opt(chan)     Channel/UnderwaterChannel
    set opt(prop)       Propagation/UnderwaterPropagation
    set opt(netif)      Phy/UnderwaterPhy
    set opt(mac)        Mac/UnderwaterMac/BroadcastMac
    set opt(ifq)        Queue/DropTail/PriQueue
    set opt(ll)     LL
    set opt(energy)         EnergyModel
    set opt(txpower)        2.0
    set opt(rxpower)        0.75
    set opt(initialenergy)  10000
    set opt(idlepower)      0.008
    set opt(ant)            Antenna/OmniAntenna
    set opt(filters)        GradientFilter    ;# options can be one or more of
                                    ;# TPP/OPP/Gear/Rmst/SourceRoute/Log/TagFilter
    set opt(minspeed)           0.2  ;#minimum speed of node
    set opt(maxspeed)           3   ;#maximum speed of node
    set opt(speed)              0.5  ;#speed of node
    set opt(position_update_interval) 0.3  ;# the length of period to update node's position
    set opt(packet_size) 50  ;#50 bytes
    set opt(routing_control_packet_size) 20 ;#bytes

    set opt(ifqlen)     500 ;# max queue length in if
    set opt(nn)     401 ;# number of nodes
    set opt(x)      3000    ;# X dimension of the topography
    set opt(y)          3000  ;# Y dimension of the topography
    set opt(z)              1000
    set opt(seed)       11
    set opt(stop)       5000    ;# simulation time
    set opt(prestop)        4990     ;# time to prepare to stop
    set opt(tr)     "test.tr"   ;# trace file
    set opt(datafile)   "test.data"
    set opt(nam)            "test.nam"  ;# nam file
    set opt(adhocRouting)   Vectorbasedforward
    set opt(width)           100
    set opt(interval)        10.0
    set opt(range)           500    ;#range of each node in meters

    if { $argc > 0 } {
      set opt(seed) [lindex $argv 0]
      set opt(nn) [lindex $argv 1]
      set opt(datafile) [lindex $argv 2]
    }

    puts "the file name is $opt(datafile)"
    puts "the sending interval is $opt(interval)"

    # ==================================================================

    LL set mindelay_        50us
    LL set delay_           25us
    LL set bandwidth_       0   ;# not used

    Queue/DropTail/PriQueue set Prefer_Routing_Protocols    1

    # unity gain, omni-directional antennas
    # set up the antennas to be centered in the node and 1.5 meters above it
    Antenna/OmniAntenna set X_ 0
    Antenna/OmniAntenna set Y_ 0
    #Antenna/OmniAntenna set Z_ 1.5
    Antenna/OmniAntenna set Z_ 0.05
    Antenna/OmniAntenna set Gt_ 1.0
    Antenna/OmniAntenna set Gr_ 1.0

    Agent/Vectorbasedforward set hop_by_hop_ 0

    Mac/UnderwaterMac set bit_rate_  1.0e4 ;#10kbps
    Mac/UnderwaterMac set encoding_efficiency_ 1
    Mac/UnderwaterMac/BroadcastMac set packetheader_size_ 0 ;# #of bytes

    # Initialize the SharedMedia interface with parameters to make
    # it work like the 914MHz Lucent WaveLAN DSSS radio interface
    Phy/UnderwaterPhy set CPThresh_  10  ;#10.0
    Phy/UnderwaterPhy set CSThresh_  0    ;#1.559e-11
    Phy/UnderwaterPhy set RXThresh_  0    ;#3.652e-10
    #Phy/WirelessPhy set Rb_ 2*1e6
    Phy/UnderwaterPhy set Pt_  0.2818
    Phy/UnderwaterPhy set freq_  25  ;# 25khz
    Phy/UnderwaterPhy set K_ 2.0    ;# spherical spreading

    # Initialize Global Variables
    #
    #set sink_ 1
    set ns_ [new Simulator]
    set topo  [new Topography]

    $topo load_cubicgrid $opt(x) $opt(y) $opt(z)
    #$ns_ use-newtrace
    set tracefd [open $opt(tr) w]
    $ns_ trace-all $tracefd

    set nf [open $opt(nam) w]
    $ns_ namtrace-all-wireless $nf $opt(x) $opt(y)

    set data [open $opt(datafile) a]

    set total_number  [expr $opt(nn)-1]
    set god_ [create-god  $opt(nn)]

    $ns_ at 0.0 "$god_  set_filename $opt(datafile)"

    set chan_1_ [new $opt(chan)]

    global defaultRNG
    $defaultRNG seed $opt(seed)

    $ns_ node-config -adhocRouting $opt(adhocRouting) \
             -llType $opt(ll) \
             -macType $opt(mac) \
             -ifqType $opt(ifq) \
             -ifqLen $opt(ifqlen) \
             -antType $opt(ant) \
             -propType $opt(prop) \
             -phyType $opt(netif) \
             #-channelType $opt(chan) \
             -agentTrace OFF \
                     -routerTrace OFF \
                     -macTrace ON\
                     -topoInstance $topo\
                     -energyModel $opt(energy)\
                     -txPower $opt(txpower)\
                     -rxPower $opt(rxpower)\
                     -initialEnergy $opt(initialenergy)\
                     -idlePower $opt(idlepower)\
                     -channel $chan_1_

puts "Width=$opt(width)"
#Set the Sink node

set node_(0) [ $ns_  node 0]
$node_(0) set sinkStatus_ 1
$god_ new_node $node_(0)
$node_(0) set X_  2000
$node_(0) set Y_  2000
$node_(0) set Z_  1
$node_(0) set -cx 2000
$node_(0) set -cy  2000
$node_(0) set -cz  1
$node_(0) set passive 1

set rt [$node_(0) set ragent_]
$rt set control_packet_size  $opt(routing_control_packet_size)

set a_(0) [new Agent/UWSink]
$ns_ attach-agent $node_(0) $a_(0)
$a_(0) attach-vectorbasedforward $opt(width)
$a_(0) cmd set-range $opt(range)
$a_(0) cmd set-target-x 2000
$a_(0) cmd set-target-y 2000
$a_(0) cmd set-target-z 1
$a_(0) cmd set-filename $opt(datafile)
$a_(0) cmd set-packetsize $opt(packet_size) ;# # of bytes

for { set i 1 } { $i<$opt(nn)-1 } {incr i } {

set node_($i) [$ns_  node $i]
$node_($i) set sinkStatus_ 1
$god_ new_node $node_($i)
$node_($i) set passive 1

set rt [$node_($i) set ragent_]
$rt set control_packet_size  $opt(routing_control_packet_size)

$node_($i) set max_speed $opt(maxspeed)
$node_($i) set min_speed $opt(minspeed)
#$node_($i) set position_update_interval_ $opt(position_update_interval)

set a_($i) [new Agent/UWSink]
$ns_ attach-agent $node_($i) $a_($i)
$a_($i) attach-vectorbasedforward $opt(width)
$a_($i) cmd set-range $opt(range)
$a_($i) cmd set-target-x -20
$a_($i) cmd set-target-y -10
$a_($i) cmd set-target-z -20
$a_($i) cmd set-filename $opt(datafile)
$a_($i) cmd set-packetsize $opt(packet_size) ;

}

Then i give the position of all my nodes from 1-399, as the following
$node_(1) set X_ 2136.167656
$node_(1) set Y_ 295.493365
$node_(1) set Z_ 584.859352
$node_(2) set X_ 38.448393
$node_(2) set Y_ 1111.699107
$node_(2) set Z_ 375.380589
$node_(3) set X_ 1937.160663
$node_(3) set Y_ 1171.175274
$node_(3) set Z_ 532.478177
..
$node_(399) set X_ 234.898387
$node_(399) set Y_ 1004.866538
$node_(399) set Z_ 985.310608

the source node and the rest of tcl file is:
#Set the source node
set node_($total_number) [$ns_  node $total_number]
$god_ new_node $node_($total_number)

$node_($total_number) set  sinkStatus_ 1

$node_($total_number) set X_  1650.370304
$node_($total_number) set Y_  1166.115416
$node_($total_number) set Z_  274.908599
$node_($total_number) set-cx  1650.370304
$node_($total_number) set-cy  1166.115416
$node_($total_number) set-cz  274.908599
set rt [$node_($total_number) set ragent_]
$rt set control_packet_size  $opt(routing_control_packet_size)

set a_($total_number) [new Agent/UWSink]
$ns_ attach-agent $node_($total_number) $a_($total_number)
$a_($total_number) attach-vectorbasedforward $opt(width)
$a_($total_number) cmd set-range $opt(range)
$a_($total_number) cmd set-target-x 2000
$a_($total_number) cmd set-target-y 2000
$a_($total_number) cmd set-target-z 1
$a_($total_number) cmd set-filename $opt(datafile)
$a_($total_number) cmd set-packetsize $opt(packet_size) ;# # of bytes

set start_time 1.33
for { set j 1 } { $i<$opt(nn)-1 } {incr j } {
    $a_($j) set data_rate_ [expr 1.0/$opt(interval)]
    $ns_ at $start_time "$a_($j) cbr-start"
    set start_time [expr $start_time+0.5 ]
    $ns_ at $opt(stop).001 "$a_($j) terminate"
}

# make nam workable
set node_size 10
for {set k 0} { $k<$opt(nn)} {incr k} {
$ns_ initial_node_pos $node_($k) $node_size
}

set opt(stop2) [expr $opt(stop)+200]

puts "Node $total_number is sending first!!"
#$ns_ at 1.33 "$a_($total_number) cbr-start"
#$ns_ at $opt(stop).001 "$a_($total_number) terminate"

$ns_ at $opt(stop2).002 "$a_(0) terminate"

$ns_ at $opt(stop2).003  "$god_ compute_energy"
$ns_ at $opt(stop2).004  "$ns_ nam-end-wireless $opt(stop)"
$ns_ at $opt(stop2).005 "puts \"NS EXISTING...\"; $ns_ halt"

 puts $data  "New simulation...."
 puts $data "nodes  = $opt(nn), maxspeed = $opt(maxspeed), minspeed = $opt(minspeed), random_seed = $opt(seed), sending_interval_=$opt(interval), width=$opt(width)"
 puts $data "x= $opt(x) y= $opt(y) z= $opt(z)"
 close $data
 puts "starting Simulation..."
 $ns_ run


text:
Q: how can I show the data label on the dot of the graph? ng2chart https://valor-software.com/ng2-charts/#/LineChart
That is the link I followed for the line chart. I was able to show the data on the pie graph but it seems like different on this line chart. Like the graph below, how can I show data on the graph?
Update
I added a long line of code below. Typescript file can be also found in the the link above.

html

            <canvas
                baseChart
                height="30vh"
                width="70vw"
                [datasets]="lineChartData"
                [labels]="lineChartLabels"
                [options]="lineChartOptions"
                [colors]="lineChartColors"
                [legend]="lineChartLegend"
                [chartType]="lineChartType"
                [plugins]="lineChartPlugins"
                (chartHover)="chartHovered($event)"
                (chartClick)="chartClicked($event)"
            ></canvas>

ts
import { Component, OnInit, ViewChild } from "@angular/core";
import { BaseChartDirective, Color, Label } from "ng2-charts";
import { ChartDataSets, ChartOptions } from "chart.js";
import * as pluginAnnotations from "chartjs-plugin-annotation";

@Component({
    selector: "kt-chart1",
    templateUrl: "./chart1.component.html",
    styleUrls: ["./chart1.component.scss"],
})
export class Chart1Component implements OnInit {

    public lineChartData: ChartDataSets[] = [
        {
            data: [180, 33, 200, 300, 333, 270, 200],
            label: "Cost",
            yAxisID: "y-axis-1",
        },
    ];
    public lineChartLabels: Label[] = [
        "01/05/2020",
        "02/05/2020",
        "03/05/2020",
        "04/05/2020",
        "05/05/2020",
        "06/05/2020",
        "07/05/2020",
  ];

    public lineChartOptions: ChartOptions & { annotation: any } = {
        plugins: {
            labels: {
                fontColor: ["green", "white", "red"],
                precision: 2,
                textShadow: true,
                render: function (args) {

                    return args.value + "(" + args.toFixed(1) + "%)";
                },
                position: "inside",
            },
            datalabels: {
                formatter: () => {
                    return null;
                },
            },
        },
        responsive: true,
        scales: {
            // We use this empty structure as a placeholder for dynamic theming.
            xAxes: [{}],
            yAxes: [
                {
                    id: "y-axis-1",
                    position: "right",
                    gridLines: {
                        color: "rgba(255,0,0,0.3)",
                    },
                    ticks: {
                        fontColor: "red",
                    },
                },
            ],
    },

        annotation: {
            annotations: [
                {
                    type: "line",
                    mode: "horizontal",
                    scaleID: "y-axis-1",
                    value: "200",
                    borderColor: "red",
                    borderWidth: 2,
                    label: {
                        enabled: true,
                        fontColor: "orange",
                        content: "200",
                    },
                },
            ],
        },
        tooltips: {
            callbacks: {
                label: (item, data) => {
                    console.log(item);
                    return "Cost: " + item.xLabel + " " + item.yLabel;
                },
            },
        },
    };
    public lineChartColors: Color[] = [
        {
            // grey
            backgroundColor: "rgba(148,159,177,0.2)",
            borderColor: "rgba(148,159,177,1)",
            pointBackgroundColor: "rgba(148,159,177,1)",
            pointBorderColor: "#fff",
            pointHoverBackgroundColor: "#fff",
            pointHoverBorderColor: "rgba(148,159,177,0.8)",
        },
        {
            // dark grey
            backgroundColor: "rgba(77,83,96,0.2)",
            borderColor: "rgba(77,83,96,1)",
            pointBackgroundColor: "rgba(77,83,96,1)",
            pointBorderColor: "#fff",
            pointHoverBackgroundColor: "#fff",
            pointHoverBorderColor: "rgba(77,83,96,1)",
        },
        {
            // red
            backgroundColor: "rgba(255,0,0,0.3)",
            borderColor: "red",
            pointBackgroundColor: "rgba(148,159,177,1)",
            pointBorderColor: "#fff",
            pointHoverBackgroundColor: "#fff",
            pointHoverBorderColor: "rgba(148,159,177,0.8)",
        },
    ];
    public lineChartLegend = true;
    public lineChartType = "line";
  public lineChartPlugins = [pluginAnnotations];

    @ViewChild(BaseChartDirective, { static: true }) chart: BaseChartDirective;

    constructor() {}

    ngOnInit() {

  }

    public randomize(): void {
        for (let i = 0; i < this.lineChartData.length; i++) {
            for (let j = 0; j < this.lineChartData[i].data.length; j++) {
                this.lineChartData[i].data[j] = this.generateNumber(i);
            }
        }
        this.chart.update();
    }

    private generateNumber(i: number) {
        return Math.floor(Math.random() * (i < 2 ? 100 : 1000) + 1);
    }

    // events
    public chartClicked({
        event,
        active,
    }: {
        event: MouseEvent;
        active: {}[];
    }): void {
        console.log(event, active);
    }

    public chartHovered({
        event,
        active,
    }: {
        event: MouseEvent;
        active: {}[];
    }): void {
        console.log(event, active);
    }

    public hideOne() {
        const isHidden = this.chart.isDatasetHidden(1);
        this.chart.hideDataset(1, !isHidden);
    }

    public pushOne() {
        this.lineChartData.forEach((x, i) => {
            const num = this.generateNumber(i);
            const data: number[] = x.data as number[];
            data.push(num);
        });
        this.lineChartLabels.push(`Label ${this.lineChartLabels.length}`);
    }

    public changeColor() {
        this.lineChartColors[2].borderColor = "green";
        this.lineChartColors[2].backgroundColor = `rgba(0, 255, 0, 0.3)`;
    }

    public changeLabel() {
        this.lineChartLabels[2] = ["1st Line", "2nd Line"];
        // this.chart.update();
    }
}

A: Instead of using chartjs-plugin-annotation, you can draw the labels directly on the canvas using the Plugin Core API. It offers a number of hooks that can be used to perform custom code. In your case, you could use the afterDraw hook and register it in the ngOnInit method as follows:
ngOnInit(): void {
  Chart.pluginService.register({
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0']; // would be 'y-axis-1' in your code sample
      ctx.save();
      chart.data.labels.forEach((l, i) => {
        var value = chart.data.datasets[0].data[i];
        var x = xAxis.getPixelForValue(l);
        var y = yAxis.getPixelForValue(value);
        ctx.textAlign = 'center';
        ctx.font = '12px Arial';
        ctx.fillStyle = 'red';
        ctx.fillText(value, x, y - 15);
      });
      ctx.restore();
    }
  });
}

Please have a look at this StackBlitz to see how it works.


text:
Q: Google maps getting overlay error I am working in google maps...
i did the bellow application and it was working fine then suddenly it stoped working and I trace it from the begining and I found that when I add
 mapOverlays = mapView.getOverlays();

the application stops working...
I need a help please
public class MapGtugActivity extends MapActivity implements OnClickListener  {
MapView mapView ;
MyLocationOverlay compass ;
MapController controller ;
Drawable drawable ;
Drawable drawable2 ;
List<Overlay> mapOverlays ;
GeoPoint point1 ;
GeoPoint point2 ;
GeoPoint point3 ;
MapItemizedOverlay custom ;
MapItemizedOverlay custom2 ;
//List <GeoPoint> LGP ;
 GeoPoint LGP[] = new GeoPoint[6] ;
 Button AddLayers ;

 int x , y ;
 GeoPoint touchedpoint ;
 long start ;
 long stop ;

   CharSequence[] items = {"Layer1", "Layer2"};
   boolean[] itemsChecked = new boolean[items.length];

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    MapView mapview = (MapView) findViewById(R.id.mapview) ;
    mapview.setBuiltInZoomControls(true) ;

    mapOverlays = mapView.getOverlays();

}

@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}

public void onClick(View v) {
    // TODO Auto-generated method stub

}

}

A: You can only make calls to getOverlays after you have added overlays. I think its returning nullpointerException at that point (because ur calling it in onCreate). Because when getOverlays() is called there is no overlay defined on ur map for it to get.


text:
Q: Mounting an old LVM hard drive in Fedora 17 gives error message On Fedora 17, I am trying to mount a hard drive as slave using the following command:
mount /dev/sda5 /mnt/fedora8

And I get this error:
mount: unknown filesystem type 'LVM2_member'

How do I mount this hard drive?

A: How to mount a LVM drive as slave from Fedora 17
Do all of the following logged in as root.
Make sure lvm2 is installed on your system (With fedora 17, it is already installed.  Check to make sure)
yum info lvm2

Returns results:
Installed Packages
Name        : lvm2
Arch        : x86_64
Version     : 2.02.95

Load the necessary module(s):
modprobe dm-mod

dm-mod is the module for the 'device mapper'.  This produces no output, if you are using fedora then you already have 'device mapper'and the above command doesn't do anything, run it anyway just in case.
Scan your system for LVM volumes and identify in the output the volume group name that has your Fedora volume (mine proved to be VolGroup00):
vgscan

Results:
Reading all physical volumes.  This may take a while...
Found volume group "VolGroup00" using metadata type lvm2

So it's telling me my VolGroup00 is of type lvm2.  That's nice.
lvs gives us more information about the volume groups:
lvs

Results:
LV       VG         Attr     LSize   Pool Origin Data%  Move Log Copy%  Convert
LogVol00 VolGroup00 -wi-ao-- 461.53g
LogVol01 VolGroup00 -wi-a---   1.94g

Here, The VolumeGroup 'VolGroup00' is the one I'm interested in mounting.
You'll have to activate the volume:
vgchange -ay VolGroup00

Results:
2 logical volume(s) in volume group "VolGroup00" now active

So it's telling me that my VolGroup00 is now active.  That's good.
You'll have to make a directory to mount to:
mkdir /mnt/fedora8

Finally, mount your partition like this:
mount /dev/VolGroup00/LogVol00 /mnt/fedora8/

change directory into /mnt/fedora8 and you see the filesystem contents:
bin   dev  home  lost+found  misc  net  proc  sbin     srv  tmp  usr
boot  etc  lib   media       mnt   opt  root  selinux  sys  u01  var

Sources:
http://www.itbox4vn.com/2011/06/fixed-unknown-filesystem-type.html
http://www.linux-sxs.org/storage/fedora2ubuntu.html


text:
Q: Zooming beyond 13 throws resolution error in ArcGis JS API I have a very basic example for a map:
(JsFiddle)
require(["esri/map"],
    function(Map) {
        var baseMap = new Map("map", {
            basemap: "terrain",
            center: [10, 51],
            zoom: 12,
            maxZoom: 22
        });
    });

When I exceed a certain zoom level I am receiving the following error:
init.js:587 Uncaught TypeError: Cannot read property 'resolution' of undefined
at Object.__getExtentForLevel (init.js:587)
at Object._extentUtil (init.js:579)
at Object._wheelZoom (init.js:1254)
at Object.<anonymous> (init.js:63)
at Object.c [as onMouseWheel] (init.js:119)
at Object._fire (init.js:1279)
at Object._onMouseWheelHandler (init.js:1286)
at HTMLDivElement.<anonymous> (init.js:63)

A couple of other applications hosted internally using the same code (but based on 3.13) are able to zoom in until one can see all street names and house numbers.
What is causing these errors?

A: It looks like the "terrain" basemaps' resolution is not as high as one could wish for as an end user and ESRI forgot to limit the zooming capability on that basemap.
Switching to osm, topo or streets resolves the issue.
The solution is to change basemap: "terrain", to basemap: "topo",.


text:
Q: When should I use "difference" or "differences"? Dictionaries (http://www.macmillandictionary.com/dictionary/british/difference http://www.ldoceonline.com/dictionary/difference) say "difference" can be used both as a countable noun and an uncountable noun. I am confused with it. I am wondering when I should use "difference" or "differences".

A: Think it in a normal way. When do you use 'car' and 'cars'? There is a car, if there's only one car and there are cars, when there are more than one. Clear?
Similarly, we use a singular form when we mean or expect one difference.

There is a difference in the quality of these two items. This one has a 'thicker' plastic.

So, the 'thickness of the plastic' used for that thing is the difference (only one difference) you find.
On the other hand, we use a plural form when we expect more than one difference.

Find the three differences in these two pictures

You asked when to use what? It's worth to note that when we talk about a disagreement, we generally use the plural form (Probably it's because we are not sure the number of differences!)

They had a terrible argument a few weeks ago, but now they've settled/resolved their differences.


text:
Q: Execute a function when a nodejs event is received I might missing something basic, but here is my goal: I have a small instant chat example based on tutorial found here Instant Chat for drupal
The principle is to connect to a nodejs server that basically just broadcast all messages it receives.
I have this function on the client side (inside a drupal tpl.php file):
(function($) {
  var myNick = 'me';
  var socket = io.connect('http://<?php print $_SERVER['SERVER_ADDR'] ?>:8081');

  socket.on('connect', function() {
    $('#chat').addClass('connected');
  });

  socket.on('user message', message);

  function message(from, msg) {
    if (msg == 'GO') {
      ** EXECUTE A FUNCTION HERE **
    } else { //display the message and sender
      $('#lines').append($('<p>').append(from, msg));
    }
  }

  $(document).ready(function() {

    $('#send-message').submit(function() {
      message(myNick, $('#messageinput').val());
      socket.emit('user message', $('#messageinput').val());
      clear();
      $('#lines').get(0).scrollTop = 10000000;
      return false;
    });

    function clear() {
      $('#message').val('').focus();
    };

  });
})(jQuery);

When I send a message with content =GO, the submit is executed, the message(..,..) function is called and my specific function is executed properly.
But when I receive a GO message, the socket.on event triggers,  message() function is called, but my specific function is NOT executed.
Any Idea how I can fix this?
Many thanks for your help.
Michael.


text:
Q: How to filter an array of object inside an array of objects based on an array and also remove properties of that object? let array1= [
    { "id": 100, name: "A", "details": [{"year": "2012"},{"data": "Test1"}]},
    { "id": 101, name: "B", "details": [{"year": "2013"},{"data": "Test2"}]},
    { "id": 102, name: "C", "details": [{"year": "2014"},{"data": "Test3"}]}
];

const array2= ['2012'];

Result I wanted
{ "id": 100, name: "A", "details": [{"year": "2012"}]}

I know i can filter the array with this code
array1.filter(o =>
  o.details.some(p=> {
    return array2.includes(p.year)
  })
)

But is there a way to remove the objects as well.

A: We can reduce to avoid multiple steps
This reduce filters and deletes part of the details array

let array1 = [
    { "id": 100, name: "A", "details": [{"year": "2012"},{"data": "Test1"}]},
    { "id": 101, name: "B", "details": [{"year": "2013"},{"data": "Test2"}]},
    { "id": 102, name: "C", "details": [{"year": "2014"},{"data": "Test3"}]}
];

const array2 = ['2012'];

let array3 = array1.reduce((acc, {id,name,details}) => {
  if (array2.includes(details[0].year)) {
    acc.push({ id, name, details: details[0] })
  }
  return acc
}, [])

console.log(array3)


text:
Q: Memory leaks when iterating over mongo data stream using NodeJS I am streaming in data from a mongodb collection, doing some calculations with the data at hand and then storing it back in mongo.  The process runs fine through the first 50k or so records and then after that it gets bogged down.  The first 50k records it seems to store 2-3k records per second, then closer to 2 per second.
var stream = Schema.find().stream();
stream.on('data', function (doc) {
  pauseStream(this);
  total++;
  OtherSchema.find().exec(function(err,others) {
   doc.total = others.data + doc.data;
   doc.save(function(err) {
     written++;
   });
  });
});

function pauseStream(stream) {
  if((total > (written + 50)) && !timedout) {
    timedout = true;
    stream.pause();
    setTimeout(function() {
      timedout = false;
      pauseStream(stream);
    }, 100);
  }
  else {
    stream.resume();
  }
}

I am trying to control the flow to only 50 outstanding updates at a time, I have changed this number up and down, no change in where it all gets hung up. What am I doing wrong? Some sort of memory leak it seems like.  When I use memwatch the stats at 50k look like:
{ num_full_gc: 2368,al: 168610
  num_inc_gc: 55680,
  heap_compactions: 2368,
  usage_trend: 4177.7,
  estimated_base: 89033445,
  current_base: 121087440,
  min: 15957344,
  max: 366396904 }

A: Try setting a batchSize instead of pausing the stream yourself.
var stream = Schema.find().batchSize(50).stream();

A: I suspect leak may be in your code. You use doc in internal callback closure.
Try to tell GC doc is not necessary anymore after it is saved.
OtherSchema.find().exec(function(err,others) {
   doc.total = others.data + doc.data;
   doc.save(function(err) {
     written++;
   });
   doc = null;//tell GC to free doc
  });


text:
Q: vis.js network -- fixed position for tooltip/popup How does one get a "fixed" position (like for example the center of the node/edge) for tooltip/popup in vis.js network using javascript?
Right now, the tooltips move as the mouse cursor is moving and therefore is not possible to copy the text which is in the tooltip! The tooltip should be "fix" and not move in order to allow the user to "catch it" using the mouse and copy (and paste it lated) that text which is inside it.
Here is the standard Javascript code where by default the tooltip/popup is "running away" from the mouse.

<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.2.0/vis.min.css" rel="stylesheet" type="text/css" />

...


text:
Q: Links as Variables in other File my problem is that i have a navbar and need to put i on each page.
So Home, Profile, Search, Add have the same navbar fixed in bottom.
Now i want to save the links to the page in a diffrent file.
So something like:

  Home
  Profile
  Search
  Add

is this even possbile with GET or POST?
Thank you

A: I think you need to create a page with your code:
header.php

  Home
  Profile
  Search
  Add

In each page you can call that with
<?php include ('header.php'); ?>

A: The way I include a nav menu to be used on different pages is with PHP's include statement include().
<?php include("path_to_header"); ?>

What I recommend is to create a few extra files: path.php and header.php to hold your nav menu.
The path.php file should be located in the root of your project so that __FILE__ provides the actual root project path.
<?php
define("ROOT_PATH", realpath(dirname(__FILE__)));
?>

Next, handle the header being in a separate file header.php for reference.

    Home
    Profile
    Search
    Add

Then in each of your pages include() the path.php file and also the header.php with another include statement where ever you choose.
<?php include("path.php"); ?>
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>El test</title>
        <link rel="stylesheet" href="style.css">

        <?php include(ROOT_PATH . "/header.php"; ?>


text:
Q: passing javascript variable into embedded survey form I've looked around a lot but can't seem to find the best way to go about this. How can I input the variable values (p1, p2, p3) into the URL at the bottom of this code?
I'm taking variables that are formatted with "+"'s as spaces, formatting them to have "%20" as spaces; then, passing them into the link at the bottom of this code used for this embedded typeform.

A: Your getParameterByName function requires two arguments but is only given one. You should pass in the data-url property of the div by using .dataset.url.

function getParameterByName(name, url) {
   if (!url) url = window.location.href;
   name = name.replace(/[\[\]]/g, "\\$&");
   var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
   results = regex.exec(url);
   if (!results) return null;
   if (!results[2]) return '';
   console.log('The value of ' + name + ' is: ' + results[2].replace(/\+/g, " "));
   return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var p1 = getParameterByName('p1', document.getElementsByClassName('typeform-widget')[0].dataset.url)
var p2 = getParameterByName('p2',document.getElementsByClassName('typeform-widget')[0].dataset.url)
var p3 = getParameterByName('p3', document.getElementsByClassName('typeform-widget')[0].dataset.url)

p1 = p1.replace(/\+/g, "%20");
p2 = p2.replace(/\+/g, "%20");
p3 = p3.replace(/\+/g, "%20");


text:
Q: Command with a space after it Is it possible to define a command \MyCommand which does not swallow the next space (standard) but inserts a real space after itself only if the next symbol followed by it is a real space-symbol or CR? The command is supposed to have no arguments.

A: No, because the following space has been swallowed by TeX's parser already before the command itself runs.


text:
Q: std::initializer_list as constructor argument in template class I'm trying to use std::initializer_list in a constructor to accept variable number of arguments. With non-template class it works fine, but with template class it gives compiling errors. Could anyone possiblly point me to the right direction? My g++ is capable of C++17.
#include <iostream>
#include <vector>
#include <type_traits>
#include <initializer_list>

struct Nontemplate
{
    // std::initializer_list for a function taking variable number of arguments
    template <class Iterator>
    Nontemplate(std::initializer_list<Iterator> list) {
        std::cout << "size: " << list.size() << std::endl;
        for(auto it : list) {
            std::cout << *it << std::endl;
        }
    }
};

template <class T, class TIterator>
struct Template
{
    std::vector<T> vec;

    Template(std::initializer_list<TIterator> list)
    {
        if(!std::is_same<typename std::iterator_traits<TIterator>::value_type, T>::value)
            throw std::runtime_error("Iterator value type is not the expected.");

        std::cout << "size: " << list.size() << std::endl;

        vec.clear();
        vec.reserve(list.size());
        for(T val : list)
            vec.push_back(val);
    }
};

int main()
{
    double vec[] = {0,1,2,3,4,5};

    Nontemplate cls0({vec, vec+2, vec+3, vec+4}); // no problem
    //Template cls1({vec, vec+2, vec+3, vec+4});  // compiling error
    return 0;
}

Thanks in advance.

A: Template cls1({vec, vec+2, vec+3, vec+4}) has no ways to deduce T.
You might use
Template<double, double*> cls1({vec, vec+2, vec+3, vec+4});
or provide custom deduction guide:
template <typename It>
Template(std::initializer_list<It>)
-> Template<typename std::iterator_traits<It>::value_type, It>;

Or simplify your class to remove that T
template <class TIterator>
struct Template
{
    using T = typename std::iterator_traits<TIterator>::value_type;
    std::vector<T> vec;

    Template(std::initializer_list<TIterator> list)
    {
        std::cout << "size: " << list.size() << std::endl;

        vec.clear();
        vec.reserve(list.size());
        for(T val : list)
            vec.push_back(val);
    }
};


text:
Q: Restore Search service on different Server or Farm , with different topology We have a SharePoint 2016 on-prem Search Farm as below
Our production farm has 2 pairs of search servers with 2 search indexers / query processors & 2 crawlers
Our test environement farm has one (01) search server

how we can retore the search service in the test environnement , from the production farm , Knowing that we tried that but we got the following error :

*

*InvalidTopologyException: Could not find a valid server in the farm with server name :

*The specified component exists. You must specify a name that does not exist.

*Aborted due to error in another component.
Thanks

A: You need to backup search databases in SQL server of your Prod environment then restore them in the SQL server of your test environment.
After that, restore Search service application with using the existing databases.
More information, you can refer to:
SharePoint 2013 – Restore Search Service Application on different Server or Farm

A: You only need the Admin DB. So you should only restore the one database. (singular) Performing the restore does not recreate the previous topology, you still have to do that in a second step.


text:
Q: how to access another user1s table in sql developer database? BBMA.SALES_BKP TABLE IS THERE IN BBMP SCHEMA(user)
I WANT TO ACCESS "SALES_BKP TABLE" through DUMMY(its different user)

A: Here's how.
SQL> create user dummy identified by dummy
  2    default tablespace user_data
  3    temporary tablespace temp
  4    quota unlimited on user_data;

User created.

SQL> grant create session, create table to dummy;

Grant succeeded.

SQL> create user bbma identified by bbma
  2    default tablespace user_data
  3    temporary tablespace temp
  4    quota unlimited on user_data;

User created.

SQL> grant create session to bbma;

Grant succeeded.

Now, create table and let another user select from it.
SQL> connect dummy/dummy@orcl
Connected.
SQL> create table sales_bkp(id number, value number);

Table created.

SQL> insert into sales_bkp values (1, 100);

1 row created.

SQL> grant select on sales_bkp to bbma;                  --> this

Grant succeeded.

SQL> connect bbma/bbma@orcl
Connected.
SQL> select * from dummy.sales_bkp;                      --> note owner name

        ID      VALUE
---------- ----------
         1        100

SQL>


text:
Q: Redirect according to roles I have two roles: administrator and users. In my login page, how do I redirect each of these two roles to a different page? For example, once an administrator has logged in they should be redirected to Page A while a user should be redirected to Page B. I have created the login control in login page and I used forms authentication.

A: Just check their role and do a normal Response.Redirect like so:
void btnLogin_Click(object sender, EventArgs e)
{
    if (HttpContext.Current.User.IsInRole("Administrators"))
        Response.Redirect("~/PageA.aspx");
    else
        Response.Redirect("~/PageB.aspx");
}

A: First create the Column of UserRole with UserName and Password in Database.When the User logs In, If the user is valid, then return the UserRole Value of the user from Database. Check the role at the time of login process and redirect the user on the base of value.


text:
Q: How to get the common values among lists in dataframe column? So I have a tsv file in the following format:
Gene   version   start           end
ADK    1         23,45,67,89     30,51,79,96
ADK    2         23,67,89        30,79,96
ADK    3         23,89           30,96

I want to create a dictionary with only the start and ends which are common across all 3 versions for a particular gene. The dictionary should be in the following format:
{'ADK':{'start':[23,89], 'end':[30.96]}

The code that I am trying till now is:
def get_strong_ranges(file):
    for entry in utils.records_iterator(file):
        if entry['gene'] not in gene_exons:
            gene_exons[entry['gene']] = {'start': list(),'end': list()}
        gene_exons[entry['gene']]['start'].append(entry['start'])
        gene_exons[entry['gene']]['end'].append(entry['end'])

However, I am yet to sort out the common ones. Any suggestions on how to do that.

A: df = pd.DataFrame({'gene': ['ADK', 'ADK', 'ADK'], 'version': [1,2,3], 'start': [[23,45,67,89], [23,67,89], [23,89]], 'end': [[30,51,79,96], [30,79,96], [30,96]]})

df
Out[14]:
  gene  version             start               end
0  ADK        1  [23, 45, 67, 89]  [30, 51, 79, 96]
1  ADK        2      [23, 67, 89]      [30, 79, 96]
2  ADK        3          [23, 89]          [30, 96]

Convert the start column from lists to numbers:
start_df = df.explode('start')
start_df
Out[16]:
  gene  version start               end
0  ADK        1    23  [30, 51, 79, 96]
0  ADK        1    45  [30, 51, 79, 96]
0  ADK        1    67  [30, 51, 79, 96]
0  ADK        1    89  [30, 51, 79, 96]
1  ADK        2    23      [30, 79, 96]
1  ADK        2    67      [30, 79, 96]
1  ADK        2    89      [30, 79, 96]
2  ADK        3    23          [30, 96]
2  ADK        3    89          [30, 96]

count the number of versions per value of "start":
start_df_counts = start_df.groupby(['gene', 'start'])['version'].count()
Out[19]:
gene  start
ADK   23       3
      45       1
      67       2
      89       3
Name: version, dtype: int64

compare it to the number of unique versions:
start_df_counts == len(set(start_df['version']))
Out[20]:
gene  start
ADK   23        True
      45       False
      67       False
      89        True
Name: version, dtype: bool

Take only those values:
start_df_counts[start_df_counts == len(set(start_df['version']))]
Out[30]:
gene  start
ADK   23       3
      89       3
Name: version, dtype: int64

Now, group by the gene and convert to list:
start_df_common = start_df_counts[start_df_counts == len(set(start_df['version']))]
start_df_common = start_df_common.reset_index()
start_df_common.groupby('gene')['start'].apply(list)
Out[35]:
gene
ADK    [23, 89]

and finally, we can convert it to dict:
final_start_dict = start_df_common.groupby('gene')['start'].apply(list).to_dict()
final_start_dict
Out[38]: {'ADK': [23, 89]}

Now you can apply the same for the end column.
Hope it helps :)


text:
Q: How can Dijkstra's algorithm apply to both undirected and directed algorithm in one program? The graph is represented in the format as below:
MAX 12
NODE 1 1
NODE 2 2
NODE 3 3
NODE 4 4
NODE 5 5
NODE 6 6
NODE 7 7
NODE 9 9
NODE 8 8
NODE 10 10
NODE 11 11
NODE 12 12
EDGE 1 2
EDGE 2 3
EDGE 3 4
EDGE 4 5
EDGE 5 6
EDGE 6 7
EDGE 7 8
EDGE 8 9
EDGE 9 10
EDGE 10 11
EDGE 11 12
EDGE 1 12
EDGE 1 3
EDGE 1 4
EDGE 1 6
EDGE 1 8
EDGE 1 11
EDGE 1 10
EDGE 6 10
EDGE 3 6
EDGE 4 6
EDGE 5 7
EDGE 9 11

I need to use the adjacent list to read in those edges. But if I want to use it as an undirected graph, that is , ignore all the directness of all edges. How could I know the connectivity of each pair of nodes?
For example, the shortest distance between (NODE 2, NODE 8) is 2 (2->1>8) in the undirected graph, but using the Dijkstra's algorithm to this graph gets 4 (2->3->6->7->8). How could I represent the undirected graph while still using the same technique to read in edges?

A: If you really don't want to change the technique of reading in the edges you'd have to iterate over all the other nodes to see if your node is in their adjacency-list instead of the other way around.
This will increase your running time by quite a bit while not saving you much storage so I'd advise to just change the technique of reading in the edges.


text:
Q: How can i create font family from assets folder? I want load my fonts from assets folder to my font resource xml file
In fact, I want something like @asset for load it.

font-family1.xml
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@asset/fontOne/a" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@asset/fontOne/a_italic" />
</font-family>

A: If you want to set your font to all texts, use caligraphy library.
And if you want to set your font to specific text, use TypeFace instead.

A: You need to put .ttf files inside a subfolder in assets folder and then you can load them but I recommend using Calligraphy as it makes everything much easier and cleaner.

A: You can build your own font class
final class FontsOverride {

    static void setDefaultFont(Context context,
                               String staticTypefaceFieldName, String fontAssetName) {
        final Typeface regular = Typeface.createFromAsset(context.getAssets(),
                fontAssetName);
        replaceFont(staticTypefaceFieldName, regular);
    }

    private static void replaceFont(String staticTypefaceFieldName,
                                    final Typeface newTypeface) {
        try {
            final Field staticField = Typeface.class
                    .getDeclaredField(staticTypefaceFieldName);
            staticField.setAccessible(true);
            staticField.set(null, newTypeface);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

and inside your Application Class
 @Override
    public void onCreate() {
        super.onCreate();

        FontsOverride.setDefaultFont(this, "SERIF", "fontOne/a.ttf");
    }

And inisde your style
    <!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="android:textColorHint">@color/main_color</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:typeface">serif</item>
</style>