text:
Q: How to specify a memory area in Actual Hardware i.e. STM32F103RB In Keil uvision I can define a memory region by using MAP command.

MAP 0x3FFFFB44,0x3FFFFFF8 read write

OR
I could use the Memory Map dialog from Keil "Debug" dropdown, specifying memory areas for data storage and program execution.

However, what should I do to specify the memory region in actual hardware (in my case STM32F103RB)?
Is there a way to specify a memory region in STM32 ST-LINK Utility software before burning code in my stm32 microcontroller?
NOTE:
I want to be able to read/write in a memory region from 0x3FFFFB44,0x3FFFFFF8 which is inaccessible. Everything works fine in Keil Simulator after I add this  memory region range in Memory Map dialog. What should I do to be able to access this region in actual hardware?
Thanks

A: This region is not available on the real device.
If you had a look at the memory map from the datasheet you could see that the region is "reserved". If you want to select working region, please look at complete MemoryMap for your device.

Normally the area starting at
0x08000000 -> flash
0x20000000 -> sram
are available. The exact size of your device depends on your exact device.


text:
Q: Docker swarm and communication between containers I have a very big problem I'm struggling with for 3 days.
I use docker swarm on the remote server.
20 microservices are in the same network NetA and stack StackA.
Now I want to add Zipkin and Sleuth to my microservices to trace all requests.
All microservices are made by docker-compose file that looks like:
version: '3'

services:
  myservice1:
    image: myImage1
    depends_on:
      - myService2
      - myService3
    ports:
      - "8081:80"
    environment:
      - TZ=Europe/Warsaw

  myservice3:
    image: myImage2
    environment:
      - profile=${MY_PROFILE}
      - TZ=Europe/Warsaw

...

Now the question is - HOW to ADD Zipkin Server?
I've added Zipkin server from Docker Hub Image.
NOW my ZIpkin Service is:
- in a separate network ZIPN
- in a separate stack ZIPST
What should I do to send data do Zipkin by all my microservices?
What URL should i send in properties file:
spring.zipkin.base-url=http://zipkinserver_network_zipkin_server:9411/
Should it be maybe:
-container name (like my_zipkin_server) - but I use swarm so container name changes dynamically?
- network name?
I added an additional network NetA to my Zipkin container but it didn't solved my problem - there are no traces in my Zipkin UI.
Please help me, I spent 4 days with this problem without any success.
Zipkin server should be in a separate Stack because will be used by different applications.
There is only ONE case when Zipkin works: when I set Zipkin container name:
spring.zipkin.base-url=http://zipkinserver_container_name:9411/

A: First specify your own overlay network (see bottom of code below) and use it for your services.
version: '3'

services:
  myservice1:
    image: myImage1
    depends_on:
      - myService2
      - myService3
    ports:
      - "8081:80"
    environment:
      - TZ=Europe/Warsaw
    networks:
      - backbone

  myservice3:
    image: myImage2
    environment:
      - profile=${MY_PROFILE}
      - TZ=Europe/Warsaw
    networks:
      - backbone

networks:
  backbone:
   driver: overlay

Then in your compose file for your other services like ZIpkin, add the backbone network to its list. Eg:
version: '3'

services:
  ZIpkin:
    image: myZImage
    networks:
      - ZIPN
      - backbone

networks:
  backbone:
   external:
     name:  PROJ_backbone

Note that outside of the first compose file, you'll need to prefix the project name for your network. Unless you set the environment variable COMPOSE_PROJECT_NAME it will be the name of the directory that the compose file is in. Do a docker network ls to find out the full name of the network to use.

A: OK, so I solved my problem using only docker-compose files.
By Portainer I pasted my second docker-compose file in Stack section (I creaated new Stack):
version: '3'
services:

  my_name_zipkin: --> THIS NAME SHOULD WE USE WHEN WE'D LIKE TO COMMUNICATE WITH CONTAINER
    image: openzipkin/zipkin
    ports:
      - "9411:9411"
    networks:
      - zipkin
      - my_old_network_with_services
networks:
  zipkin:
  my_old_network_with_services:
    external: true

Now we should use 'my_name_zipkin' name to communicate with this service. Service name is the name we should use to communicate between containers.
So in properties file I set:
spring.zipkin.base-url=http://zipkin:9411/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Opacity and Angular UI Dropdown Toggle I have a really annoying problem with opacity settings combined with Angular Ui Bootstrap. I have a table with a dropdown toggle in each row. When I hover over the rows, the opacity settings change on the one the mouse is currently on.
Here are my CSS settings:
tr {
zoom: 1;
filter: alpha(opacity=70);
opacity: 0.7;
color: #292929;
}

tr:hover {
zoom: 1;
filter: alpha(opacity=100);
opacity: 1.0;
}

The dropdown toggle displays fine as long as I stay with the mouse on the menu. If I leave it, the dropdown-menu disappears behind the rows although in the CSS-settings the z-index for the dropdown-menu is set to 1000.
mouse inside menu http://imageshack.us/a/img10/8536/okqi.jpg
mouse inside dropdown-menu
mouse outside menu http://imageshack.us/a/img12/209/kipv.png
mouse outside dropdown-menu
Any help or hint would be awesome!!!


text:
Q: Getting Arduino LilyPad to switch BlueSmirf v2.11 to/from command mode A battery powered (2 x AA) Arduino LilyPad should switch a BlueSmirf v2.11 Bluetooth modem to/from command mode (see source code below). The BlueSmirf has been set to 9600 baud.
If the PC connects via Bluetooth (see source code below), the Arduino program runs fine at the beginning (sending multiple "ping\n"). After some time it (LilyPad/BlueSmirf) starts to also send "$$$" and "---\n" over the Bluetooth connection instead of switching to/from command mode.
Any ideas?
Regards,
tamberg
// Arduino source code:

void setup () {
  Serial.begin(9600);
}

void loop () {
    Serial.print("$$$");
    delay(2000); // TODO: Inquiry, etc.
    Serial.print("---\n");
    delay(100);
    Serial.print("ping\n");
    delay(2000);
}

// C# source code (runs on PC)

using System;
using System.IO.Ports;

class Program {

    static void Main () {
        SerialPort p = new SerialPort(
            "COM20", 9600, Parity.None, 8, StopBits.One);
        using (p) {
            p.Open();
            while (p.IsOpen) {
                Console.Write((char) p.ReadChar());
            }
        }
    }
}

A: From the datasheet, page 6:

NOTE1 : You can enter command mode
  locally over the serial port at any
  time when not connected. Once a
  connection is made, you can only enter
  command mode if the config timer has
  not expired. To enable continuous
  configuration, set the config timer to
  255. Also, if the device is in Auto Master mode 3, you will NOT be able to
  enter command mode when connected over
  Bluetooth.

My guess would be that the config timer is expiring.


text:
Q: Button active,focus not working on Mac FireFox? I have problems with Mac Firefox/Chrome/Safari and Window/Chrome when I create a button with active, hover and focus. The hover works but the active and focus do not. All three of them work perfectly only on Window/Firefox.
I used css to do it. Any suggestion ?
Here is my CSS:
.navList button:hover,
.navList button:active,
.navList button:focus{ /* Changed */
border-color: black;
border-style: solid;
background: rgb(73,155,234); /* Old browsers */
background: -moz-linear-gradient(top,  rgb(73,155,234) 0%, rgb(32,124,229) 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgb(73,155,234)), color-       stop(100%,rgb(32,124,229))); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top,  rgb(73,155,234) 0%,rgb(32,124,229) 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top,  rgb(73,155,234) 0%,rgb(32,124,229) 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top,  rgb(73,155,234) 0%,rgb(32,124,229) 100%); /* IE10+ */
background: linear-gradient(to bottom,  rgb(73,155,234) 0%,rgb(32,124,229) 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#499bea', endColorstr='#207ce5',GradientType=0 ); /* IE6-9 */
}

Here is html:
<ul id="List" class="navList">
<button id="eButton" class="moduleButton">Employees</button>
<button id="iButton" class="moduleButton">Inventory</button>
</ul>

A: You have to stick to a certain chronological order of the pseudo classes:

*

*:link

*:visited

*:focus

*:hover

*:active
See http://www.w3.org/TR/CSS2/selector.html#dynamic-pseudo-classes for more details.


text:
Q: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 407 Proxy Authorization Required" I was trying to hit the https url for google api.
Using the code below but its giving some errors.
but i can hitting  one google api http url and its working very well without any  error
DataInputStream di = null;

FileOutputStream fo = null;

byte[] b = new byte[1];

// PROXY
System.setProperty("https.proxyHost", "my proxy");
System.setProperty("https.proxyPort", "8080");

Authenticator.setDefault(new PasswordAuthenticator());

URL u = new URL("https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Vict&types=geocode&language=fr&sensor=true&key=keyforuse");

HttpURLConnection con = (HttpURLConnection) u.openConnection();

sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String encodedUserPwd = encoder.encode("domain\\user:password"
        .getBytes());
con.setRequestProperty("Proxy-Authorization", "Basic "
        + encodedUserPwd);

di = new DataInputStream(con.getInputStream());
// result = parseJSON(di);
while (-1 != di.read(b, 0, 1)) {
    System.out.print(new String(b));
}

but getting error below
java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 407 Proxy Authorization Required"
    at sun.net.www.protocol.http.HttpURLConnection.doTunneling(HttpURLConnection.java:1648)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:164)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1172)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
    at kf.store.locator.googlemaps.test.main(test.java:58)

any help????

A: You may not need the domain in front of the username. I had a very similar issue, and I fixed it when I removed the domain in front of the username. Since the proxy server is on a domain, I think it implies that your under the same domain.

A: I fixed it by authenticating to the proxy server with my user name and password. If you are on your company's network , it can be your sso cred too.
The equivalent of this will be like this :
-Dhttp.proxyUser=myusername
-Dhttp.proxyPassword=mypassword
-Dhttp.proxyHost=myproxyserver.com
-Dhttp.proxyPort=9000


text:
Q: Problema con ListView al iniciar la aplicación Estoy creando una aplicación en Android Studio que utiliza ListView en el MainActivity y se llena desde un Activity secundario que sale cuando toco un botón "agregar". El detalle es que al momento de iniciar la aplicación de una vez me salta el error de Se ha detenido y automáticamente se cierra.
Estoy usando 2 ListView, ya que una es para saldosNegativos y la otra para saldosPositivos. Aquí dejo el código de las dos clases que estoy utilizando para saber si me pueden corregir.
Este es el MainActivity:
public class PaginaInicio extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pagina_inicio);

    Button agregarSaldo = (Button)findViewById(R.id.botonNuevoSaldo);
    ListView listaSaldosPositivos = (ListView)findViewById(R.id.listViewSaldoPositivo);
    ListView listaSaldosNegativos = (ListView)findViewById(R.id.listViewSaldoNegativo);
    TextView totalSaldo = (TextView)findViewById(R.id.textSaldoTotal);

    agregarSaldo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent irASaldo = new Intent(getApplicationContext(),nuevoSaldo.class);
            startActivity(irASaldo);
        }

    });

        ArrayList<Saldo> elSaldoPositivoQueLlego = (ArrayList<Saldo>) getIntent().getSerializableExtra("saldosPositivos");
        ArrayList<Saldo> elSaldoNegativoQueLlego = (ArrayList<Saldo>) getIntent().getSerializableExtra("saldosNegativos");
        double resultado = 0;
        double resultado2 = 0;

    if(elSaldoPositivoQueLlego!=null || elSaldoNegativoQueLlego!=null) {
        String[] montosPositivos = new String[elSaldoPositivoQueLlego.size()];
        String[] montosNegativos = new String[elSaldoNegativoQueLlego.size()];
        for (int i = 0; i < elSaldoPositivoQueLlego.size(); i++) {
            double monto = elSaldoPositivoQueLlego.get(i).getMonto();
            String titulo = elSaldoPositivoQueLlego.get(i).getTitulo();
            String descripcion = elSaldoPositivoQueLlego.get(i).getDescripcion();
            montosPositivos[i] = String.valueOf(monto);
            montosPositivos[i] = titulo;
            montosPositivos[i] = descripcion;
            resultado = monto + resultado;
        }
        for (int j = 0; j < elSaldoNegativoQueLlego.size(); j++) {
            double monto = elSaldoNegativoQueLlego.get(j).getMonto();
            String titulo = elSaldoNegativoQueLlego.get(j).getTitulo();
            String descripcion = elSaldoNegativoQueLlego.get(j).getDescripcion();
            montosNegativos[j] = String.valueOf(monto);
            montosNegativos[j] = titulo;
            montosNegativos[j] = descripcion;
            resultado2 = monto + resultado;
        }
        double total = resultado + resultado2;
        totalSaldo.setText("$ " + total);

        if (!elSaldoPositivoQueLlego.isEmpty()) {
            ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, montosPositivos);
            listaSaldosPositivos.setAdapter(itemsAdapter);
        } else {
            if (!elSaldoNegativoQueLlego.isEmpty()) {
                ArrayAdapter<String> itemsAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, montosNegativos);
                listaSaldosNegativos.setAdapter(itemsAdapter2);
            }
        }
    }
}

Y esta es la clase secundaria de donde me estoy trayendo los datos para mostrar en las ListView:
public class nuevoSaldo extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nuevo_saldo);

    final EditText saldoIngresado = (EditText)findViewById(R.id.editTextSaldoIngresado);
    final EditText tituloIngresado = (EditText)findViewById(R.id.editTextTituloIngresado);
    final EditText descripcionSaldo = (EditText)findViewById(R.id.editTextDescripcionSaldo);
    final RadioButton ingreso = (RadioButton)findViewById(R.id.radioBotonIngreso);
    final RadioButton gasto = (RadioButton)findViewById(R.id.radioBotonGasto);
    final Button añadir = (Button)findViewById(R.id.botonAñadirMontoNegativoOPositivo);
    final Button cancelar = (Button)findViewById(R.id.botonCancelarNuevoSaldo);

    final ArrayList <Saldo> saldoIngreso = new ArrayList<>();
    final ArrayList <Saldo> saldoGasto = new ArrayList<>();

    final Intent irAInicio = new Intent(this.getApplicationContext(),PaginaInicio.class);
    añadir.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Saldo elSaldo = new Saldo();
            double saldo = Double.parseDouble(saldoIngresado.getText().toString());
            String titulo = tituloIngresado.getText().toString();
            String descripcion = descripcionSaldo.getText().toString();

            if (ingreso.isChecked()) {
                elSaldo.setMonto(saldo);
                elSaldo.setTitulo(titulo);
                elSaldo.setDescripcion(descripcion);
                saldoIngreso.add(elSaldo);
           }else {
               if(gasto.isChecked()){
                    elSaldo.setMonto(saldo);
                    elSaldo.setTitulo(titulo);
                    elSaldo.setDescripcion(descripcion);
                saldoGasto.add(elSaldo);
            }
            }
            saldoIngresado.setText("");
            tituloIngresado.setText("");
            descripcionSaldo.setText("");
            irAInicio.putExtra("saldosPositivos", saldoIngreso);
            irAInicio.putExtra("saldosNegativos", saldoGasto);
            Toast.makeText(getApplicationContext(), "Monto agregado con éxito", Toast.LENGTH_SHORT).show();
        }
    });

    cancelar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(irAInicio);
        }
    });

}

A: hijo te esta complicando la vida...
Usar el Intent no es seguro..por que cuando quieres volver a la actividad anterior los datos se pierden..
sugerencia...te recomiendo usar clases genéricas..para enviar tus datos y obtenerlos desde el Adaptador.
Aquí un buen ejemplo...
https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView


text:
Q: Why does OLEDB (or Access?) rewrite WHERE clause I'm facing a strange situation where OledbDataAdapter rearranges the WHERE clause of my query, thus shuffling all parameters. In addition, it doesn't recognize one of the parameters used in the query. Here's how it goes:
A simple table with 4 columns (and infinite rows :)):
Name       varchar(50)
Category   varchar(20)  //One of around 15-20 possible values
YR         int          //Year
Period     int          //Month

User will query this table using Year, Month and a comma-separated list of categories that he's interested in. Since .NET doesn't support multi-valued parameters through IN operator, what I do is to accept the list of categories as comma-separated list and then prepend and append a comma to this list within the query and use built-in INSTR() function to filter results for desired categories. User can also supply an empty string for categories filter in which case query will need to return all results (i.e. no filter on categories).
Therefore my query looks like this:
SELECT * FROM [Table1] WHERE
       YR = ? AND
       Period = ? AND
       (LTRIM(RTRIM(?)) = '' OR INSTR(1, ?, ',' + Category + ',') > 0)

This worked with MDBs in the past. But recently I tried it against an ACCDB. The first thing I noted is that when I try to run the query in OledbDataAdapter wizard, Visual Studio rewrites it as:
SELECT * FROM [Table1] WHERE
       (YR = ? AND Period = ? AND LTRIM(RTRIM(?)) = '') OR
       (YR = ? AND Period = ? AND INSTR(1, ?, ',' + Category + ',') > 0)

In other words, it has rearranged the condition A AND B AND (C OR D) as (A AND B AND C) OR (A AND B AND D).
This would have been fine with me, but the additional problem is that this changes the number of parameters from 4 to 6; the query therefore doesn't return any results even when it should. Moreover, it doesn't recognize that last parameter (the question mark within INSTR function) at all.
So my questions are:

*

*Who is rewriting the query (OledbDataAdapter, Access query parser or something else)?

*Why is it doing so? Optimization? Apparently my version of the WHERE clause is more efficient.

*Why doesn't it see the last parameter?

*How to fix/workaround this issue? (plz do not suggest using 2 separate queries for it).


text:
Q: Limit evaluate $ \lim\limits_{x \to - \infty } {{|\arcsin ({2 \over x})|} \over {\arctan ({5 \over x})}} $ Please help me with this limit without using L'Hôpital's rule. I would by happy if you use simple solving. Thank you as much as I can ;).
$ \lim\limits_{x \to - \infty } {{|\arcsin ({2 \over x})|} \over {\arctan ({5 \over x})}} $

A: Hint
$$\frac{\arcsin(u)}{\arctan(v)}=\frac{\arcsin(u)}{u}\cdot \frac{u}{v}\cdot \frac{v}{\arctan(v)}.$$
Therefore, if $u(x),v(x)\underset{x\to a}{\longrightarrow} 0$, $$\lim_{x\to a}\frac{\arcsin(u(x))}{\arctan(v(x))}=\lim_{x\to a}\frac{u(x)}{v(x)}.$$

A: All you need to know are
(1) $|x| > 0$ if $x \ne 0$.
(2) $\lim_{x \to 0} \frac{f(x)}{x}
= 1$
for all the functions
and their inverses
mentioned in this problem.


text:
Q: Behaviour of and operator in javascript I am checking for the values of AND operator in javascript, the below code for some reason returning 0.  Can someone explain actual behavior of AND operator here?
var result = 88 && 6 && 0 && null && 9;
alert(result);

A: && evaluates as the left hand side if the left hand side is false, otherwise it evaluates as the right hand side.
(88) && (6 && 0 && null && 9)

88 is true, so the right hand side is evaluated.
(6) && (0 && null && 9)

6 is true, so the right hand side is evaluated.
(0) && (null && 9)

0 is false, so it is the result.


text:
Q: ArangoDB AQL Non Case Sensitive Comparison Let's imagine I have a few simple docs stored in an Arango collection like so:
[
    {"type":Cat, "quality":Fuzzy}
    {"type":Dog, "quality":Barks}
    {"type":Rabbit, "quality":Hoppy}
    {"type":Pig, "quality":Chubby}
    {"type":Red Panda, "quality":Fuzzy}
    {"type":Monkey, "quality":Hairy}
]

Now let's say a user initiates a search in my application for all animals that are 'fuzzy', all lower case. Is there a way with AQL to make a comparison that is not case sensitive? So for instance:
FOR a IN animals
    FILTER a.type.toLowerCase() == fuzzy
    RETURN a

Now I know the above example doesn't work, but it would be nice if there was a way to do this. Thanks!

A: There is a LOWER string function in AQL which you can try to use in your query like this:
FOR a IN animals
    FILTER LOWER(a.quality) == 'fuzzy'
    RETURN a


text:
Q: issue executing many queues at same time php i am running a game based on php. that is based on queues
each task is stored in db table queues with type and end time
if time is now , then it should be executed directly .
the issue is that when we have a lot of tasks at same time , then time becomes negative and this is so bad ..
it is a timing game , delay is a big issue
we use vps server , 4cpu , 8 rams
this is the responsible code :
   public function processQueue($type = 3, $playerId = 0)
    {
        global $gameConfig;
        $this->load_model('Mutex', 'mutex');
        $this->mutex->releaseOnTimeout();
        if ($this->mutex->lock()) {
            $this->processTaskQueue($type, $playerId);
            // to make it weekly put "/2" after it
            $row = db::get_row("SELECT gs.cur_week w1, CEIL((TO_DAYS(NOW())-TO_DAYS(gs.start_date))) w2 FROM g_settings gs");
            if (($row['w2'] - $row['w1']) >= 1) {
                db::query("UPDATE g_settings gs SET gs.cur_week=:cur", array(
                    'cur' => intval($row['w2'])
                ));
                $allP = db::get_all("SELECT p.id FROM p_players p WHERE 1 ");
                $Ids2 = "";
                foreach($allP as $Ids)
                {
                    $Ids2 .= ($Ids2 == "" ) ? $Ids['id'] : ",".$Ids['id'];
                }
                $Ids2 = "(".$Ids2.")";
                db2::query("UPDATE p_players p SET p.gold_num=p.gold_num+:gold WHERE p.is_active=1 and p.id IN $Ids2",array('gold' =>200));
                $this->setWeeklyMedals(intval($row['w2']));
            }
            $this->mutex->release();
        }
    }

public function processTaskQueue($type, $playerId)
    {
        $p_type = QS_ACCOUNT_DELETE . ',' . QS_MERCHANT_GO . ',' . QS_MERCHANT_BACK . ',' . QS_WAR_REINFORCE . ',' . QS_WAR_ATTACK . ',' . QS_WAR_ATTACK_PLUNDER . ',' . QS_WAR_ATTACK_SPY . ',' . QS_CREATEVILLAGE . ',' . QS_TROOP_TRAINING . ',' . QS_SITE_RESET . ',' . QS_CROP_DELETE . ',' . QS_ARTEFACTS_RAISE .','. QS_TATAR_RAISE;
        if ($type == 1) {
            $expr = "((q.player_id=" . $playerId . " AND q.proc_type!=" . QS_TROOP_TRAINING . ") OR q.proc_type IN (" . $p_type . "))";
        } elseif ($type == 2) {
            $expr = "(q.player_id=" . $playerId . " OR q.proc_type IN (" . $p_type . "))";
        } else {
            $expr = "q.proc_type!=" . QS_TROOP_TRAINING;
        }
        $result = db::get_all("SELECT  q.id, q.player_id, q.village_id, q.to_player_id, q.to_village_id, q.proc_type, q.building_id, q.proc_params, q.threads, q.execution_time, TIMESTAMPDIFF(SECOND, NOW(),q.end_date) remainingTimeInSeconds FROM p_queue q WHERE TIMESTAMPDIFF(SECOND, NOW(),(q.end_date - INTERVAL (q.execution_time*(q.threads-1)) SECOND)) <= 0 AND $expr ORDER BY TIMESTAMPDIFF(SECOND, NOW(),(q.end_date - INTERVAL (q.execution_time*(q.threads-1)) SECOND)) ASC");
        foreach ($result as $resultRow) {
            $remain = $resultRow['remainingTimeInSeconds'];
            if ($remain < 0) {
                $remain = 0;
            }
            $resultRow['threads_completed_num'] = $resultRow['execution_time'] <= 0 ? $resultRow['threads'] : floor(($resultRow['threads'] * $resultRow['execution_time'] - $remain) / $resultRow['execution_time']);
            if ($this->processTask($resultRow)) {
                unset($result);
                $this->processQueue($type, $playerId);
                break;
            }
        }
        unset($result);

    }

we need help , i am willing to pay as well if needed ..


text:
Q: Point to Point environment ->Restful After I read that sentence:

SOAP was designed for a distributed computing environment whereas
  REST was designed for a point to point environment.

I searched about DCE and point to point environment. I learned about DCE but I found nothing about point to point environment. So what is it?

A: I believe "SOAP was designed for a distributed computing environment" boils down to meaning SOAP is an RPC mechanism. From what I understand, "point to point environment" is really just another way of saying that the protocol implementing the style is client/server and only supports unicast addressing.
It's a meaningless contrast, really. And, if my understanding is correct, the "point to point environment" bit is rubbish - HTTP might not support anything other than unicast addressing of resources, but that doesn't mean that any other protocol supporting the RESTful style, hypothetical or otherwise, couldn't have an addressing mechanism for resources that mapped onto potentially multiple resources.
Of course, I'm only making an educated guess.

A: REST - Used on the web for a larger scale internet applications and websites(twitter.com) Point To Point = internet.
SOAP - Used in Busienss Systems, Commonly Used With Existing XML Schema from third parties.


text:
Q: How to automatically download files from github without copying the repository I have a number of scripts that I use almost everyday in my work. I develop and maintain these on my personal laptop. I have a local git repository where I track the changes, and I have a repository on github to which I push my changes.
I do a lot of my work on a remote supercomputer, and I use my scripts there a lot. I would like to keep my remote /home/bin updated with my maintained scripts, but without cluttering the system with my repository.
My current solution does not feel ideal. I have added the following code belowto my .bashrc. Whenever I log in, my repository will be deleted, and I then clone my project from github. Then I copy the script files I want to my bin, and make them executable.
This sort of works, but it does not feel like an elegant solution. I would like to simply download the script files directly, without bothering with the git repository. I never edit my script files from the remote computer anyway, so I just want to get the files from github.
I was thinking that perhaps wget could work, but it did not feel very robust to include the urls to the raw file page at github; if I rename the file I suppose I have to update the code as well. At least my current solution is robust (as long as the github link does not change).
Code in my .bashrc:
REPDIR=mydir
if [ -d $REPDIR ]; then
    rm -rf $REPDIR
    echo "Old repository removed."
fi
cd $HOME
git clone https://github.com/user/myproject
cp $REPDIR/*.py $REPDIR/*.sh /home/user/bin/
chmod +x /home/user/bin/*

Based on Kent's solution, I have defined a function that updates my scripts. To avoid any issues with symlinks, I just unlink everything and relink. that might just be my paranoia, though....
function updatescripts() {
DIR=/home/user/scripts
CURR_DIR=$PWD
cd $DIR
git pull origin master
cd $CURR_DIR
for file in $DIR/*.py $DIR/*.sh; do
    if [ -L $HOME/bin/$(basename $file) ]; then
        unlink $HOME/bin/$(basename $file)
    fi
    ln -s $file $HOME/bin/$(basename $file)
done
}

A: on that remote machine, don't do rm then clone, keep the repository somewhere, just do pull. Since you said you will not change the files on that machine, there won't be conflicts.
For the scripts files. Don't do cp, instead, create symbolic links (ln -s) to your target directory.


text:
Q: Переход на HTTPS WordPress Хочу установить https на сайт. Во всех инструкциях сказано, что нужно поменять Адрес WP и сайта в общих настройках, однако мне WP не дает этого сделать. Прав достаточно, для уверенности даже нового юзера заводил. Что можно сделать?

A:
Во всех инструкциях сказано, что нужно поменять Адрес WP и сайта в
общих настройках, однако мне WP не дает этого сделать.

Если ВП "не дает этого сделать" значит адреса могут быть прописаны в конфиге или в файле функций темы.
Но заменить в настройках - этого не достаточно. Менять протокол нужно с пом специальных плагином, делающих корректную замену в базе - с учётом сериализованных данных. Например при помощи https://wordpress.org/plugins/better-search-replace/

A: Я обычно использую плагин Really Simple SSL. После активации он проверяет действительно ли на хостинге к домену имеется сертификат, и если всё ок - в один клик делает все необходимые операции по переходу на https.


text:
Q: Sequential updates to ranges in Google Sheets API via pygsheets I'm trying to update some cell ranges with defined format, but I'm running into a problem when the ranges overlap. For example, if I have a range of cells A1:C3 and I want to set cells A2:B2 to have a green background color, and then to have them all have bold font style, the result is only the latter - the background color of the previous cells is overwritten by the bold style. If I do it in the reverse order, the cells have green background but no bold font.
I'm using pygsheets library and this is roughly how my calls work:
# wks is a worksheet object from the created spreadsheet
wks.range("A2:B2", "range").apply_format(L_GREEN_BG, fields="userEnteredFormat")
wks.range("A1:C3", "range").apply_format(BOLD, fields="userEnteredFormat")

The BOLD and L_GREEN_BG are cell objects initialized with a dictionary in json-like format specified by Google Sheets API to match these updates.
My question is: is there any way to not overwrite previously made changes? Doing it sequentially like this would be a lot more handy than making more complex updates to singular cells.

A: if you want other properties to be unchanged, be more specific on the fields. So in your first case set fields='userEnteredFormat\backgroundColor' and in your second request "userEnteredFormat\textFormat"

A: OK, upon reading the source code of the pygsheets library I think I know why this happens. The apply_format method sends a repeatCell request, which basically copies all of the provided cell's properties and applies them to the all of the cells in provided range. So when I provide a cell (the BOLD/L_GREEN_BG objects, which are just a dummy cell objects with only one property defined) with only bold font style, all of the cells in range get all of it's properties, along with default values. Every other subsequent call works similarly.


text:
Q: Inserir coluna Oracle, apos uma coluna existente Estou precisando de ajuda. Tenho a tabela USUARIO, aonde tenho as colunas LOGIN, SENHA  porem preciso incluir a coluna chamada DATACRIACAO, porém gostaria de saber como inserir essa coluna DATACRIACAO após a coluna LOGIN, estou trabalhando com o Oracle 11g.

A: Para adicionar a coluna datacriacao na tabela usuario
ALTER TABLE usuario
ADD (datacriacao date)

Porém não é indicado alterar a sequencia das colunas assim como você quer, aqui é explicado o motivo


text:
Q: Understanding the meaning of $d\omega = (\frac{\partial Q}{\partial x} - \frac{\partial P}{\partial y})dxdy$ Let $D \subseteq \mathbb{C}$, $\omega  = P dx+Q dy$ $1-$form over $D$, is said "of class $C^{1}$", if $P,Q : D \longmapsto \mathbb{C}$ are of class $C^{1}$.
In this case we define formally $d\omega = (\frac{\partial Q}{\partial x} - \frac{\partial P}{\partial y})dxdy$
I do understand that with this definition it follows almost directly the following particular case of Green Stokes theorem as a consequence of Fubini Tonelli :
$\textbf{Theorem :}$ $\omega$ $1-$form of class $C^{1}$ over a right-angled $R \subseteq D$, then $\int_{\partial R} \omega = \int_{R} d\omega$
But are there any other reason to this definition ? In my eyes could just be seen a definition to prove the theorem, what I would like, is to find a deeper meaning which makes the definition well defined, and useful.

A: You do not "formally define" $d\omega$ in that way. Let $\omega = P dx + Qdy$ as you have. This is a $1$--form, the space of $1$--forms is commonly denoted $\Omega^1$. The exterior derivative $d : \Omega^1 \to \Omega^2$ takes is defined by $$d\omega = \left( \frac{\partial P}{dx} dx \right) \wedge dx + \left( \frac{\partial Q}{dx} dx \right) \wedge dy + \left( \frac{\partial P}{dy} dy \right) \wedge dx + \left( \frac{\partial Q}{dy} dy \right) \wedge dy.$$ Since $dx \wedge dx =0$, and $dy \wedge dy =0$ , we see that the first and last terms are zero. Moreover, since $dx \wedge dy = - dy \wedge dx$, we get $$d \omega = \left( \frac{\partial Q}{dx} - \frac{\partial P}{dy} \right) dy \wedge dx.$$
A clean exposition of the proof of Green's theorem is given by Joyce: https://mathcs.clarku.edu/~djoyce/ma131/greenproof.pdf


text:
Q: Join takes too long I have this query that takes about 5 minutes to run in Oracle:
select t1.A,t2.B,t2.C,t2.D,t2.E
from TABLE1 t1 join TABLE2 t2
on t2.X = t1.Y
where t1.F = <integer>
and t2.G = <integer>
and t1.H = <integer>

t1 has 1.7 million rows and t2 has 31 million. I have indices on t2.X and t1.F. Tried adding indices on t1.Y, t2.G and t1.H but they didn't help. Any ideas how I can improve performance of this join?

A: Looking at all the fields involved, a covering index on each table would involve may columns
t1: Y, F, H, A
t2: X, G, C, D, E

How selective are ANY of the criteria: t2.X, t2.G or t1.Y, t1.F, t1.H ?
If none of the individual columns are selective enough (ideally 0.5% or less), you may want to create a or several covering index that involve multiple columns, for example
t2 (G, X)
t1 (H, F, Y)

Note: The order of columns in an index is very important - always put the most selective (the one that divides the column data into the most distinct sets) first.
At the expense of storage, you can make the index COVER the query by providing all the necessary columns in the index itself.  This means the query does not need to go back to table data at all.
create index ix_t2 on t2 (G,X) INCLUDE (C,D,E)
create index ix_t1 on t1 (H,F,Y) INCLUDE (A)

EDIT
Looks like I slipped a SQL Server DDL in there.  In Oracle, you would have to expand the index to become t2 (G,X, C,D,E) - but that increases selectivity requirements for index usage since the index key becomes very long.


text:
Q: Regex for searching strings matching the following one I am searching strings matching the following one in my source code:
<CONSTANT_STRING_1> <CONSTANT_STRING_2> <VARIABLE_DIGITS> <CONSTANT_STRING_3>

where
<CONSTANT_STRING_1>, <CONSTANT_STRING_2> and <CONSTANT_STRING_3> are constant strings like "ABC", ""DEF" and "GHI".
<VARIABLE_DIGITS> is a random number of 14 digits like "12345678901234"
Note: there are white spaces between words.
What I am looking for is to search <CONSTANT_STRING_1> <CONSTANT_STRING_2> <WHATEVER> <CONSTANT_STRING_3>. How can I build the Regex?

A: I am reading that by "constant string" you mean character strings? If so the below should work to find that full string you are looking for. Btw the website linked below is really great for visualizing this type of problem... give it a try :)
(([a-zA-Z]+\s){2})[0-9]{14}\s([a-zA-Z]+)$

Debuggex Demo
To break it down...
(([a-zA-Z]+\s){2}) means a string of one or more characters comprised of either LC or UC letters followed by a space and that whole thing (chars + space) repeated twice
[0-9]{14}\s 14 digits followed by a space. As @Avinash said \d{14}\s is another way of writing this portion
([a-zA-Z]+)$ Another string of one or more characters. The $ indicates that this ends the string you are searching for

A: You could try the below regex.
<CONSTANT_STRING_1> <CONSTANT_STRING_2> \d{14} <CONSTANT_STRING_3>

Where, \d{14} matches exactly the 14 digit number.


text:
Q: How to locate environment path in codename one For the following commands to work, make sure you have "ant", "mvn", and "git" in your environment PATH.
pls I need to add the following to the environment part.
$ git clone https://github.com/shannah/cn1-iap-demo-server
$ cd cn1-iap-demo-server
$ ant install-deps.

I dont know how to locate environment path on my system. pls help

A: That's Unix/Linux and unrelated to Codename One. One would setup an environment path as such:
export PATH=/path/to/ant/binary:$PATH


text:
Q: Old ansible playbook executes everytime I have written an ansible(2.0) playbook for installing sonarqube on a box. I changed a detail in the sonarqube role as I was facing an issue. It seems like ansible doesn't detect the change as I change my playbook. I have tried commenting/ deleting the tasks. I have used --flush-cache, but it didn't work.
Any help will be appreciated. Please let me know if any other detail is required from my side.

A: Very weird issue. The ansible playbook was checked-in my git repository.
On the go modifications of the code was not working. I had to commit the changes and pull the changes to make it work. Looks like the caching was from git side.


text:
Q: jquery mobile - Dynamically created items are not removed on page back & forth I have two pages inside a single html:

Please choose a date and group:

    <input type="text" class="datepicker" />
    <input type="button" value="Register" onclick="LoadRegister()"/>

                    Name

    <input type="button" value="Save" onclick="SaveRegister()"/>

The user picks the date from the select page and on hitting the button the following is called:
    function LoadRegister(){

    var today = new Date(picker.get());

    $.mobile.pageContainer.pagecontainer("change", '#mainregister', {
        transition: 'flip'
    });

    GetRegister(today, 2);
}

The GetRegister() function loads data and creates some elements dynamically (mostly radio buttons inside a fieldset).
This all works great. However, if the user goes back to the select page to choose a different date, then hits the button again the page is incorrect - I can see that the old fieldsets that were created on the first load are still there.
How can I get remove these dynamically created items (effectively reload mainregister page as per the HTML and start again)?

A: I am not sure if this is the correct way of doing it, but worked for me:
$('#tblregisterbody').empty();

I simply clear the element which contains the dynamically generated elements within the LoadRegister function before doing the page change.
function LoadRegister(){

var today = new Date(picker.get());
$('#tblregisterbody').empty(); // This clears the table with the dynamic elements
$.mobile.pageContainer.pagecontainer("change", '#mainregister', {
    transition: 'flip'
});

GetRegister(today, 2);

}


text:
Q: How can I determine the source and/or contents of a .swp file? I have a >36 GB file at $HOME/.swp on macOS. The file is over 2 years old, I'd like that space back, but I'm super curious as to what it could be.
How can I figure out what app/process/program made it and whether it's trying to help me like save some state I've since thought lost?


text:
Q: Can't match tuple inside of foldl I have the following code, which should™ convert an excel column type its corresponding number. For example AA into 27 and AB into 28:
import Data.Char (ord)
import Data.List (foldl1')

columnToNumber :: String -> Int
columnToNumber s = foldl1' (\acc (i, v) -> acc + 26 ^ i * v) (values s)
  where values s = zip (reverse [0..(length s)]) ((\c -> ord c - 64) <$> s)

The idea is to take the string "AA" convert it to the corresponding numbers
["A", "A"] -> [1, 1]

and zip it with the base so from right to left 26^0, 26^1, 26^2, and so on.
zip [1, 0] [1, 1] -> [(1, 1), (0, 1)]

That way the result of the fold would be
26^1 * 1 + 26^0 * 1 = 27

Unfortunately, I'm getting the following errors and I'm not sure why:
ExcelSheetColumn.hs:7:34:
    Couldn't match expected type 'Int'
                with actual type '(Integer, Int)'
    In the pattern: (i, v)
    In the first argument of 'foldl1'', namely
      '(\ acc (i, v) -> acc + 26 ^ i * v)'
    In the expression:
      foldl1' (\ acc (i, v) -> acc + 26 ^ i * v) (values s)

ExcelSheetColumn.hs:7:63:
    Couldn't match type '(Int, Int)' with 'Int'
    Expected type: [Int]
      Actual type: [(Int, Int)]
    In the second argument of 'foldl1'', namely '(values s)'
    In the expression:
      foldl1' (\ acc (i, v) -> acc + 26 ^ i * v) (values s)

Could someone help me out?

A: to get it compiling you actually just have to switch foldl1' to foldl' and add the starting accumulator:
import Data.Char (ord)
import Data.List (foldl')

columnToNumber :: String -> Int
columnToNumber s = foldl' (\acc (i, v) -> acc + 26 ^ i * v) 0 (values s)
  where values s = zip (reverse [0..(length s)]) ((\c -> ord c - 64) <$> s)

if you add the suggestion Free_D made (start at length s - 1):
columnToNumber :: String -> Int
columnToNumber s = foldl' (\acc (i, v) -> acc + 26 ^ i * v) 0 (values s)
  where values s = zip (reverse [0..(length s -1)]) ((\c -> ord c - 64) <$> s)

you get the desired results:
λ> columnToNumber "AA"
27
λ> columnToNumber "AB"
28

I don't know if you actually gonna need this but hey why not:
what you probably don't like is that columnToNumber "A1" is 11 - to fix this you need to tread digits differently from letters:
columnToNumber :: String -> Int
columnToNumber s = foldl' (\acc (i, v) -> acc + 26 ^ i * v) 0 (values s)
  where values s = zip (reverse [0..(length s -1)]) (parse <$> s)
        parse c
          | c >= '0' && c <= '9' = ord c - ord '0'
          | otherwise = ord c - 64

A: Looking at the definition of foldl1', it has to take two things that are of the same type and produce something similar
*Main Data.List> :t foldl1'
foldl1' :: (a -> a -> a) -> [a] -> a

But foldl is what you want:
*Main Data.List> :t foldl
foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b

So essentially this:
import Data.Char (ord, toUpper)

columnToNumber :: String -> Int
columnToNumber s = foldl (\acc (i, v) -> acc + 26 ^ i * v) 0 $ values s where
    values s = zip [l - 1, l - 2 ..0] ((\c -> (ord.toUpper) c - 64) <$> s) where
        l = length s


text:
Q: How to bulk upload json records to elasticsearch fast? I've read the docs on bulk upload
I generated a file with 1 json per line that's about 160 gigs. The bulk upload it looks like I'd have to put some kind of schema info before each line inserted, which would blow up the size of the file.
To bulk upload my 1 json per line file, I use gnu parallel to post with curl
cat out.json  | parallel -j 32 --pipe -N1 curl -XPOST 'http://localhost:9200/xxx/yyy' --data-binary  @-

This is really slow though. I could also run the job on a machine that has an SSD, take snapshot, then load onto server without one. What techniques do you use for fastest bulk upload?

A: I think you can take a look at logstash with json input file.
Input filter plugin configs. Since logstash also says that logstash is faster as long as services are fast.Since reading json is very heavy filesystem operation (disk io cost will be high).
If your cluster suffers from write performance.consider adding a buffer queue for holding data.If your data feed to ES exceeds the Elasticsearch cluster's ability to ingest the data, you can use a message queue as a buffer. By default, Logstash throttles incoming events when indexer consumption rates fall below incoming data rates. Since this throttling can lead to events being buffered at the data source, preventing backpressure with message queues becomes an important part of managing your deployment.


text:
Q: Twitter API v2 - Rate Limit I'm accessing Twitter's API v2 and have Academic Research access.
I am interested in pulling as much data as possible, but am getting rate limited.
I am using tweepy in Python to extract the data, and the call "search_all_tweets"
I am looping the extraction for each day and limiting tweets extracted per day. By using time.sleep() I can modify how many tweets I can extract per 15 minutes.
Twitter has published this to answer my question, however I am still in doubt which category and thereby limit I am under:
https://developer.twitter.com/en/docs/twitter-api/rate-limits#v2-limits
Can anybody help to clarify how many tweets I can extract per 15 minutes before getting rate limited?
Thanks in advance

A: Go to the Twitter developper portal, select your app in your project and, at the bottom of the Settings tab, check if you have activated the Read and Write permissions in the OAuth 1.0a authentication. If not, activate them and regenerate your tokens.


text:
Q: Non-normality in MANOVA with significant planned contrasts versus non-significance in Kruskal-Wallis- A Conundrum I am conducting a between groups analysis for 3 groups (N=26, one control group and two experimental groups) with 4 dependent variables. I initially planned to conduct a MANOVA, however I am not meeting normality (significant skewness and kurtosis using z > 2.58) and homogeneity of variance assumptions for 2 of the DVs. Following a log transformation, one DV was corrected by the other has remained significantly skewed.
I initially decided to conduct a Kruskal-Wallis non-parametric test. However, due to a non-significant main effect I was unable to carry out post hoc contrasts. The initial MANOVA I conducted was significant on all DVs for several planned contrasts (control vs both experimental groups- one of my study's main hypotheses), however it seems I will be unable to report these findings if I choose a non-parametric test as above.
Is there any way I can

*

*Report these contrasts in MANOVA despite non-normality?

*Conduct planned contrasts in Kruskal-Wallis (which does not seem like an option according to Field, 2004)

*Use an alternative analysis?


text:
Q: D3 Bar Chart Axis quirk I have this code: https://plnkr.co/edit/t1GKaQOGnFxkTMK03Ynk
  var MIN = 60;
  var HR = MIN * 60;
  var tripDomain = [0, 15*MIN, 30*MIN, 45*MIN, 60*MIN, 90*MIN, Math.max(24*HR, d3.max(data))];

  var bins = d3.histogram()
    .thresholds(tripDomain)(data);

  var x = d3.scaleOrdinal()
    .domain(tripDomain)
    .range(tripDomain.map((_,i) => (i/(tripDomain.length-1))*width));

   // ...more code...

  chart.append("g")
    .attr("class", "axis axis--x")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

That renders a histogram correctly. The only issue is that the axis first tick is painting 0 and 61 on top of each other. It should be only 0... not sure where the 61 is coming from (it's the first value of the data) but I don't see how it ended up in the axis.
Notice the first value on the axis... Could you shed some light on this issue?

A:
...not sure where the 61 is coming from.

It's coming from the scale's domain, which you are changing when you append the rectangles and the texts! And that's the expected behaviour, since you're using an ordinal scale.
Explanation:
Your x scale domain is well defined:
[0, 900, 1800, 2700, 3600, 5400, 1280703]

However, in your first bin, you have this (as array properties):
[x0: 61, x1: 900]

So, whenever you use the x0 of the first bin with the x scale, for instance:
.attr("transform", function(d){
    return "translate(" + x(d.x0) + "," + y(d.length) + ")";
});

...you're actually introducing a new value in the domain (for a detailed explanation, see my answer here), since there is no 61 in the x scale domain.
By the way, this new value is introduced at the end of the domain and, despite being very close to 0, that 61 is actually the last tick.
Solution:
Declare the unknown:
var x = d3.scaleOrdinal()
    .unknown(0)

Here is your updated plunker: https://plnkr.co/edit/n1IoEkHcL0sGUraDVCfc?p=preview


text:
Q: How to make a droplet on mac osx with automator? I readed some tutorials about making droplets with apple script or with automator's help.
First, I need to know if these droplets only works with the drag n drop file action, or if you can do the action in the current directory you are.And if the last answer is yes, how to do with automator?
This was a general question.
In my case. I need a droplet in my finder toolbar that when I click on in it search for all file with a specific extensions and drop to trash. I try with automator but I can't fine the action for selecting files in the current directory, only found the general find. Because I will can be in any other possible directory I need to know how to do this.
It's not a problem writing some applescript, I don't know it but I can learn:)

A: To create a droplet with Automator, you select application, when Automator asks you what you want to create.
The description given by the application, when you select application is the following:

Applications are self-running workflows. Any files or folders dropped onto an Application will be used as input to the workflow.

I think it means that only dropped files / directory will be passed to the workflow. I tested it, and I can confirm it works in that way.


text:
Q: How do i set values back into a map in jquery? This is the code that of my jsp page which displays a window with columns.Each column corresponds to a form
<%@include file="/WEB-INF/jsp/include/pagedirectives.jsp"%>

<%@include file="/WEB-INF/jsp/include/page.topmessagebox.jsp"%>

            Label
            <c:forEach var="i" begin="1" end="5" step="1" varStatus ="status">
            Form ${(pageNumber * 5) + i}
            </c:forEach>

        <c:forEach items="${eformDetailsList}" var="eformDetails"
            varStatus="status">

                    <c:out value="${eformDetails.label}" />
                     <input type="hidden" id="label_${eformDetails.id}_0" value="${eformDetails.label}" name="label_0"></input>
                     <input type="hidden" id="index_${eformDetails.id}_0" value="${eformDetails.id}" name="index_0"></input>

                <c:if test="${eformDetails.controlType==1}">

                        <input id="eformDetail_${eformDetails.id}_0" class="eformDetail" type="text" value="" name="form_0"></input>

                        <input id="eformDetail_${eformDetails.id}_1" class="eformDetail" type="text" value="" name="form_1"></input>

                        <input id="eformDetail_${eformDetails.id}_2" class="eformDetail" type="text" value="" name="form_2"></input>

                        <input id="eformDetail_${eformDetails.id}_3" class="eformDetail" type="text" value="" name="form_3"></input>

                        <input id="eformDetail_${eformDetails.id}_4" class="eformDetail" type="text" value="" name="form_4"></input>

                </c:if>

        </c:forEach>
        <c:if test="${empty eformDetailsList}">

                There is no eform associated with this Service Type

        </c:if>

This is the jquery used to obtain the values from the jsp page :
var labels0=$('input[name="label_0"]').map(function(){
    return $(this).val() }).get();
var index0=$('input[name="index_0"]').map(function(){
    return $(this).val() }).get();
var fields0 = $('input[name="form_0"]').map(function(){
    return $(this).val() }).get();
var fields1 = $('input[name="form_1"]').map(function(){
    return $(this).val() }).get();
var fields2 = $('input[name="form_2"]').map(function(){
    return $(this).val() }).get();
var fields3 = $('input[name="form_3"]').map(function(){
    return $(this).val() }).get();
var fields4 = $('input[name="form_4"]').map(function(){
    return $(this).val() }).get();

On click of save,I have saved the values.When i open the form again i want the saved values to re-appear in my text boxes.Is there a way to re set the values back to the map?

A: (I think you should do it with jsp..)
Anyway, assuming you have the js array:
var label_0_values = ['value 1', 'value 2', ...];

With jQuery, you would populate like this:
$('input[name="label_0"]').each(function(i){
   $(this).val(label_0_values[i]);
});

And the same for your other inputs
Hope this helps. Cheers


text:
Q: Why this loops infinitely? I'm simply trying to print the elements of the array. From the output i can see that the loop goes beyond my array's allocated memory.
.386 ; 386 Processor Instruction Set

.model flat,stdcall

option casemap:none
include \masm32\include\masm32rt.inc
include \masm32\include\windows.inc
include \masm32\include\kernel32.inc
includelib \masm32\lib\kernel32.lib

.data

array DWORD 72,50,22,0
asd DWORD ?

start:

mov ecx, 4
mov edi, 0
//-- loop start--//
loop_start:

mov eax, [array + edi * 4]

push offset asd
push eax
call dwtoa

Invoke StdOut, addr asd

inc edi  //incrementing edi
dec ecx  // decrementing ecx
cmp ecx,0 // comparing ecx against 0

jne loop_start // if not equal loop again
//--loop end--//

invoke ExitProcess, 0
end start

Here is the output

EDIT: tried to add at the end
cmp ecx,0
je loop_end

loop_end:
Invoke ExitProcess,0

none of these worked.
Thanks in advance.

A: It seems that these two instructions change the ecx register:
call dwtoa
Invoke StdOut, addr asd

My guess would be at dwtoa it might return the length of the asci array returned in the ecx register.
Try this:
loop_start:

mov eax, [array + edi * 4]

push ecx // saving ecx before call

push offset asd
push eax
call dwtoa

Invoke StdOut, addr asd

pop ecx // restore the ecx from before the calls.

inc edi  //incrementing edi
dec ecx  // decrementing ecx
cmp ecx,0 // comparing ecx against 0

jne loop_start // if not equal loop again


text:
Q: ld: library not found for -lPods-... with custom build configuration I added a testing-configuration to add preprocessor macros when running unit tests, now I can't run my unit tests any more with that configuration in place, I always get
```ld: library not found for -lPods-MyProject```

my testing scheme:

what am I missing here?


text:
Q: Entity Framework - Attaching Entities - Attach Navigation Properties? I have the following generic code to update a disconnected entity:
public T UpdateItem(T entity)
{
    this._dbSet.Attach(entity);
    this._dbContext.Entry(entity).State = System.Data.EntityState.Modified;

    this._dbContext.SaveChanges();

    return entity;
}

If my entity contains navigation properties, those do not get attached and set to modified. Is there a way I can change this generic method to attach and set to modified, all navigation properties as well?

A: You can do it with reflection. Here's an extension method to find all the related collections. If all of your Entities implement some standard interface you'll be able to make a similar method to find the non collection navigation properties (that implement your interface).
public static class ContextExtensions
{
    public static IEnumerable<IEnumerable<dynamic>> GetCollections(this object o)
    {
        var result = new List<IEnumerable<dynamic>>();
        foreach (var prop in o.GetType().GetProperties())
        {
            if (typeof(IEnumerable<dynamic>).IsAssignableFrom(prop.PropertyType))
            {
                var get = prop.GetGetMethod();
                if (!get.IsStatic && get.GetParameters().Length == 0)
                {
                    var enumerable = (IEnumerable<dynamic>)get.Invoke(o, null);
                    if (enumerable != null) result.Add(enumerable);
                }
            }
        }
        return result;
    }
}

This should add the current objects navigation properties
var collections = entity.GetCollections();
foreach (var collection in collections)
{
    foreach (var r in collection)
    {
        if (_this._dbSet.Entry(r).State == System.Data.EntityState.Detached)
        {
            this._dbSet.Attach(r);
            this._dbContext.Entry(r).State = System.Data.EntityState.Modified;
        }
    }
}


text:
Q: Get client IP adress trough Heroku I have a Heroku app with Cloudflare and I try to display a different version according to the localization of the client.
It works well in developpment but it's not the case in production (the /en is always displayed, not the /fr).
I use the express-ip npm package.
The code:
const express = require('express');
const router = express.Router();

const expressip = require("express-ip");

router.use(expressip().getIpInfoMiddleware);

router.get("/", function ipFrance(req, res) {
  const ipInfo = req.ipInfo;
  const ipInfoRegion = req.ipInfo.region;
  const ipInfoCountry = req.ipInfo.country;

  //var message = `Hey, you are browsing from ${ipInfoRegion}, ${ipInfoCountry}`;
  if(ipInfoCountry == "FR" || ipInfoRegion == "Wallonia") {
      res.redirect("/fr");
  } else {
      res.redirect("/en");
  }
});

module.exports = router;

A: Don't offer translations based on IP address. There's an HTTP header for that, and an express API method req.acceptsLanguages() which uses that header:
router.get("/", function (req, res) {
  if (req.acceptsLanguages("fr")) {
    res.redirect("/fr");
  } else {
    res.redirect("/en");
  }
});

Some French-native people may like browsing in English, and other parts of the world may prefer to browse in French. Let them make that decision, don't make it for them.


text:
Q: Detecting and fixing corrupted indeces in Postgresql? Today I encountered a case where a record was missing in query result while existed in the table. I traced back the problem to probably a corrupted index. After I did REINDEX the problem was solved.
The thing is that normally when I run reports I get more than a 10000 records. It is impossible for me to know if there are missing records. Today I was lucky to find the problem.
Is there a way to get a notification when an index is corrupted?
If not, how do I write a function that will REINDEX all indeces in my Schema?

A: Index corruption is very bad problem. I think you need to diagnose and fix this fundamentally and not try to band aid it in your query. It might be caused by poor administrative actions like kill -9 of any of Postgres processes etc.
To your question: there is no verifier tool AFAIK. I believe that a query that scans the whole index e.g. sort on index will find damaged pages in indeces.
I recommend you to read this blog.


text:
Q: How to reuse form in codeigniter for update and add Hello i want to reuse a form in codeigniter but problem is the update form is populated one the page has load. Here is a sample form.
 <?php
  $attributes = array('class' => 'form-horizontal', 'id' => 'addPersonnel');
  echo form_open($form_submission, $attributes);
  ?>
        <input type="text" name="name" value="<?php echo set_value('name')?"> >
        <input type="text" name="rank" value="<?php echo set_value('rank')?"> >
        <button type="submit" class="btn btn-primary">Save</button>
  <?php echo form_close()?>

My problem here lies in the set_value() method of the form_validation class since it will have conflict with populating the form if updating.

A: In your controller update function add a condition like:
if ($this->input->server('REQUEST_METHOD') === 'POST') {
    $this->_get_userinfo_form_fields();
} else {
    $this->_get_userinfo_form_fields($user_data); //$user_data from database
}

For add function you can directly call - $this->_get_userinfo_form_fields();
Then declare a function as below:
protected function _get_userinfo_form_fields($user_data = array()) {
    $this->data['rank'] = array(
        'placeholder' => 'Rank',
        'name'        => 'rank',
        'id'          => 'rank',
        'class'       => '',
        'value'       => isset($user_data['rank']) ? $user_data['rank'] :set_value('rank',$this->input->post('rank',TRUE)),
        'style'       => '',
    );

    //Add rest of the fields here like the above one
}

In view file add code like:
 <?php echo form_input($rank);?>


text:
Q: frequency generator / counter I want to generate a precise frequency in the 500MHz range, and have therefore purchased a VCO (200MHz to 400MHz).
To measure the VCO output frequency, I'm trying to build a high frequency counter up to 500MHz.
The way I have been trying to do it, is using the MC100E016 (ECL Synchronous Binary Up Counter). Take the Q6 (/64) output and feed this into my oscilloscope (and later MCU). But this seems hard to get to work, because the PECL logic sets high demands on the input.
Do you have any good and easy way to build a frequency counter, or even just a divider would be fine (my 100MHz oscilloscope can measure the output from the divider).
Or even better, generate a 200MHz to 400MHz range frequency, who's frequency can be set (digital or what ever).

A: You can use several methods:
1) PLL - for example ADF4002 works up to 400 MHz. The resolution is limited, because it works by multiplying reference frequency. This chip will work with your VCO.
2) Integrated PLL synthesizer - ADF4350 can generated frequencies within 137-4400 MHz range with fairly good resolution. However, within your range the result will be more square wave rather than sine.
3) DDS - direct digital synthesis - AD9910 can generate frequencies up to 400 MHz with resolution under 1 Hz.
Trying to tune wideband VCO without any stabilization and measuring the result will not provide stable frequency.
Here is a list of PLL chips and PLL synthesizers made by ADI. Other vendors have some too, but usually working within GHz range.


text:
Q: While inserting uniqid() in to table id is not inserting in correct way While inserting uniqid() in my table using codeigniter insertion, that uniqid() is not insewrting in correct way like last inserted id is insertng in middle in middle of the data so, when I try to retrieve uniqid using MAX(ID) i am getting duplicate id..
so can any one help to resolve the issue how to overcome this and how to insert the id in sequence

A: SQL Server has build in support for generating incrementing IDs for columns. Try adding an IDENTITY column to your table. Note that you can't add an IDENTITY constraint to an existing column.
You have 2 options:

*

*Create a new table with identity & drop the existing table

*Create a new column with identity & drop the existing column

Read more here: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/04d69ee6-d4f5-4f8f-a115-d89f7bcbc032/how-to-alter-column-to-identity11?forum=transactsql


text:
Q: gRPC: How can I distinguish bi-streaming clients at server side? In this tutorial and example code, a server can call onNext() method on every stream observer, which will broadcast messages to all clients bi-streaming with the server. But there is no method to identify which observer corresponds to which client. How can a server push a message to specific client instead of broadcasting?
According to this answer it is possible to map each observer if client id is provided by metadata. It seems const auto clientMetadata = context->client_metadata(); part does the trick, but I'm working with Java, not C++. Are there any Java equivalent for getting the metadata at server side?

A: The answer depends a bit on how the clients will be identified. If the initial request provided a handle (like a username, but not registered ahead-of-time), then you could just wait for the first onNext():
  public StreamObserver<Chat.ChatMessage> chat(StreamObserver<Chat.ChatMessageFromServer> responseObserver) {
    return new StreamObserver<Chat.ChatMessage>() {
      @Override
      public void onNext(Chat.ChatMessage value) {
        String userHandle = value.getHandle();
        // observers would now be a map, not a set
        observers.put(userHandle, responseObserver);
        ...

Let's say instead that all users are logged in, and provide a token in the headers, like OAuth. Then you would use an interceptor to authenticate the user and Context to propagate it to the application, as in https://stackoverflow.com/a/40113309/4690866 .
  public StreamObserver<Chat.ChatMessage> chat(StreamObserver<Chat.ChatMessageFromServer> responseObserver) {
    // USER_IDENTITY is a Context.Key, also used by the interceptor
    User user = USER_IDENTITY.get();
    observers.put(user.getName(), responseObserver);
    return new StreamObserver<Chat.ChatMessage>() {
        ...

The first one is easier/nicer when the identification only applies to this one RPC. The second one is easier/nicer when the identification applies to many RPCs.


text:
Q: JSF Dabatabase connection I am trying to set up a connection to a database using JSF. I am using NetBeansIDE 8.0.2. The database is setup and when I first tested  the connection at database setup it connected fine. I also ran a query through NetBean to view all the tables in the database and it returned results without any issues. When I try to run the project it returns an error that says, Table/view 'ADDRESSES' does not exist. I have tried running the query in multiple ways, but no luck. Any ideas? I tried posting an image of my database, but I wasn't allowed to. Basically I have my database name, which is addressbook, default schema APP, and then my table addresses.
package addressbook;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.sql.DataSource;
import javax.sql.rowset.CachedRowSet;

@ManagedBean(name="addressBean")
@RequestScoped

public class AddressBean {
    private String lastName;
    private String street;
    private String city;
    private String state;
    private String zipCode;

@Resource(name="jdbc/addressbook")
DataSource datasource;

private String firstName;

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getStreet() {
    return street;
}

public void setStreet(String street) {
    this.street = street;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getState() {
    return state;
}

public void setState(String state) {
    this.state = state;
}

public String getZipCode() {
    return zipCode;
}

public void setZipCode(String zipCode) {
    this.zipCode = zipCode;
}

public ResultSet getAddresses() throws SQLException
{
    if(datasource == null)
        throw new SQLException("Unable to obtain datasource");

    Connection connection = datasource.getConnection();

    if(connection == null)
        throw new SQLException("Unable to connect to DataSource");

    try{

        PreparedStatement getAddresses = connection.prepareStatement("SELECT FIRSTNAME, LASTNAME, CITY, STREET, STATE, ZIP "
                + "FROM addresses ORDER BY LASTNAME, FIRSTNAME");

        CachedRowSet rowSet = new com.sun.rowset.CachedRowSetImpl();
        rowSet.populate(getAddresses.executeQuery());
        return rowSet;
    }finally{
        connection.close();
    }

}

public String save() throws SQLException
{
    if (datasource == null)
        throw new SQLException("Unable to obtain DataSource");

    Connection connection = datasource.getConnection();

    if(connection == null)
        throw new SQLException("Unable to connect to Datasource");

    try{

        PreparedStatement addEntry = connection.prepareStatement("INSERT INTO ADDRESSES" + "(FIRSTNAME,LASTNAME,STREET,CITY,STATE,ZIP"
        + "VALUES(?,?,?,?,?,?");
        addEntry.setString(1, getFirstName());
        addEntry.setString(2, getLastName());
        addEntry.setString(3, getStreet());
        addEntry.setString(4, getCity());
        addEntry.setString(5, getState());
        addEntry.setString(6, getZipCode());

        addEntry.executeUpdate();
        return "index";
    }finally
    {
        connection.close();
    }
}

}

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <title>Address Book</title>
    </h:head>
    <h:body>

Address Book

        <h:form>

<h:commandButton value="Add Entry" action="addentry"/>

        </h:form>
        <h:dataTable value="#{addressBean.addresses}" var="address"
                     rowClasses="oddRows,evenRows" headerClass="header"
                     styleClass="table" cellpadding="5" cellspacing="0">
            <h:column>
                <f:facet name="header">First Name</f:facet>
                #{address.FIRSTNAME}
            </h:column>
            <h:column>
                <f:facet name="header">Last Name</f:facet>
                #{address.LASTNAME}
            </h:column>
            <h:column>
                <f:facet name="header">Street</f:facet>
                #{address.STREET}
            </h:column>
            <h:column>
                <f:facet name="header">CITY</f:facet>
                #{address.CITY}
            </h:column>
            <h:column>
                <f:facet name="header">STATE</f:facet>
                #{address.STATE}
            </h:column>
            <h:column>
                <f:facet name="header">Zip Code</f:facet>
                #{address.ZIPCODE}
            </h:column>
        </h:dataTable>
    </h:body>


text:
Q: delayed job - RES keep growing I have some tasks which needs to rub in background so i was planning to use delayedjob gem but before put in development, i wanted to rub simple TEST to see RES consumption.
Simple Helper with no code
module TestjobHelper
  def self.imageprocess(gb)
    gb = nil
  end
end

Putting into  delay job
TestjobHelper.delay(:queue => 'testjob').imageprocess('gb')

Running Delayed Job queue command
RAILS_ENV=development script/delayed_job -i testjob --queue=testjob start

Above sample program, gives keep growing RES value even if there is nothing to do in delayed job function.
RES Output:
http://prntscr.com/9v17ah
http://prntscr.com/9v18he


text:
Q: Why does remote command by ssh read bashrc file? According to a document, it says:

When an interactive shell that is not a login shell is started, Bash reads and executes commands from ~/.bashrc, if that file exists.

I did a quick test:
At my server,
[USER@MYSERVER ~]$ cat .bashrc
...

echo 'I am in a bashrc file of my server'

...

At a remote server,
# unquoted
[USER@REMOTESERVER ~]$ ssh MYSERVER echo $-
I am in a bashrc file of my server
himBH

#quoted
[USER@REMOTESERVER ~]$ ssh MYSERVER 'echo $-'
I am in a bashrc file of my server
hBc

When command is unquoted, it seems to be run in an interactive shell, and when quoted, it seems to be run in a non-interactive shell.
Why is this so?
And both read the bashrc file of MYSERVER, which doesn't follow the rule in the document.
Any link or comment appreciated.

EDITED:
And it seems to be a non-login shell.
[USER@REMOTESERVER ~]$ ssh MYSERVER 'shopt -q login_shell && echo 1 || echo 2'
2

A: In the bash document, there says:

Invoked by remote shell daemon

Bash attempts to determine when it is being run with its standard input connected to a network connection, as when executed by the remote shell daemon, usually rshd, or the secure shell daemon sshd. If Bash determines it is being run in this fashion, it reads and executes commands from ~/.bashrc, if that file exists and is readable.

I missed this part...
Therefore, calling from ssh should read .bashrc file.
And ssh remote command is a non-interactive shell, as comments to the question explain.

A: The remote bash is indeed not started as an interactive shell (as we can see from the output from $-), so somewhat else must be sourcing your .bashrc. For sure, it is run as a login shell. Could it be that you have a ~/.bash_profile or ~.bash_login or ~/.profile, which explicitly sources .bashrc?


text:
Q: Why distance equals initial velocity times time Plus acceleration over two times time Squared? i am a beginner in physics and I do not understand why is the d=vi(t)+(1/2)a(t^2).

A: For a constant acceleration $a$,  $s = s_i + v_it + {{1} \over {2}}  a t^2$; $s_i$ is the location at the initial time, $v_i$ is the velocity at the initial time, and $t$ is the total time.  Your relationship assumes $s_i$ is zero.  I use $s$ instead of $d$ for distance to not confuse distance with the derivative used below.
Acceleration is defined as $a = d^2s/dt^2$ for distance $s$ for one dimensional motion.  (For general motion, acceleration is a vector $\vec a = {\vec d}^2s/dt^2$.) This differential equation can be solved for $s$ giving the above result.
Again, this result is for constant acceleration only.

A: So, this is easier when you learn calculus.
Without calculus, it requires one of many "magical" facts to cover the gap that calculus would do for you. Here is the simplest that I know: that under a circumstance of constant acceleration $a$ over a time $t$ from velocity $v_0$ to velocity $v_1=v_0 + a~t$, the average velocity can be written in two different ways:$$
v_\text{avg} = \frac{d}{t} = \frac{v_0 + v_1}2.
$$
That first equals sign is the definition of average velocity, the second equal sign is a relation that only holds for constant acceleration. If for example you had a sudden acceleration "kick" near the start time, then for almost all of the time your velocity would have been $v_1$ and that would be your average velocity. Or if you had had a sudden "kick" from $v_0$ to $v_1$ near the end of the time $t$, then for almost all of the time your velocity would have been $v_0$ and that would be your average velocity. There are lots of possibilities. But for constant acceleration it turns out that the average velocity is also the average of the starting and ending velocities, which makes constant acceleration very simple.
Anyway, if you substitute the above relation for $v_1=v_0+a~t$ into that expression and multiply both sides by $t$ you get the desired equation for $d$. So they are perfectly equivalent. In addition, by eliminating $t$ instead of $v_1$ you can instead prove the work energy theorem by a difference of squares factorization.


text:
Q: Programmatically grant android.permission.ACCESS_NOTIFICATION_POLICY permission during android integration tests Is there any way how to grant android.permission.ACCESS_NOTIFICATION_POLICY permission during Android tests?
Most of the permissions and even not runtime permission is easy to get in the test environment by calling
GrantPermissionRule.grant(
    android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
    android.Manifest.permission.READ_EXTERNAL_STORAGE,
    android.Manifest.permission.PACKAGE_USAGE_STATS,
    android.Manifest.permission.READ_PHONE_STATE
)

But I need to test NotificationListenerService functionality, which needs to enable Notification access. And this doesn't work.


text:
Q: JavaScript'ный CSS создает проблему в PHP
Как сделать чтобы и запись "A,Google" была так же в синем квадрате, как и "B, Yahoo!"?
Дело в том, что я задаю вот такой код в PHP:

<?php
while($row = mysql_fetch_assoc($result)) {
printf("

           %s
           %s

", $row['title'], $row['link']);
}
?>

А CSS код для TD находится в jS файле:
$('td').css({
'height' : grid_height,
'width' : grid_width,
'background-color' : '#69F'
});

$('table').css({
'position' : 'absolute',
'left' : '20px',
'top' : 0,
'bottom' : 0,
'right' : 0,
'margin-top' : margin_top
});

A: Измените позиционирование с absolute на relative, будет как-то так.
A:

<?php
while($row = mysql_fetch_assoc($result)) {
    printf("
%s	%s
", $row['title'], $row['link']);
}
?>

И, кстати, у вас всегда генерируется одна и та же айдишка — %s, %s	.


text:
Q: AddSelect using subqueries with multiple child element in Laravel App I'm trying to execute the below query:
$s = Year::whereBetween('year', [Carbon::now()->subYears(1), Carbon::now()->addYears(2)])
    ->addSelect(['test_column' => State::withCount(['projects' => function ($q) {
        $q->whereHas('technicalDescription', function ($q) {
            $q->where('start_year_id', '=', 'years.id');
        });
    }])->first()
])->get();

But I'm getting following error:

SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters (SQL: select {"id":1,"name":"Andaman & Nicobar Islands","country_id":null,"projects_count":0} from years where year between 2019-06-27 12:22:12 and 2022-06-27 12:22:12 and years.deleted_at is null)

As per above query I've Year model:
class Year extends AbstractModel {

    public function startedProjects()
    {
        return $this->belongsToMany(Project::class, 'project_technical_detail', 'start_year_id', 'project_id');
    }

    public function finishedProjects()
    {
        return $this->belongsToMany(Project::class, 'project_technical_detail', 'end_year_id', 'project_id');
    }

}

My State Model has:
class State extends AbstractModel {

    public function projects()
    {
        return  $this->hasMany(Project::class,'state','id');
    }

}

My Project Model has:
class Project extends AbstractModel {

    public function state()
    {
        return $this->belongsTo(State::class,'state','id');
    }

}

I want to have know the projects count which started in year in individual state Something like this:
data: [
    {
        "year": "2003",
        "Andaman": 0,
        "Maharastra": 10,
        "Gujrat": 233,
        ...
        ...
    },
    {
        "year": "2004",
        "Andaman": 10,
        "Maharastra": 80,
        "Gujrat": 123,
        ...
        ...
    },
    {
        "year": "2005",
        "Andaman": 20,
        "Maharastra": 40,
        "Gujrat": 103,
        ...
        ...
    }
]

I can do mapping of data to achieve the above output, but at-least my addSelect should work. Any better ideas are welcome. Thanks.


text: Q: How do I get from the universal product of the tensor product to other definitions. I was wondering how you can "derive" the common (or "classical") definition of the tensor product before the universal property was established (I think there is no need to repeat it here), i.e. a multilinear map of the cartesian product of $r$ copies of a vector space $V$ and $s$ copies of the dual space $V^*$ into, let's say, $\mathbb{R}$, from the universal defintion?


text:
Q: Two quick questions about convergence (in the context of pointwise vs. uniform convergence) I found this example online:

Let $\{f_{n}\}$
    be the sequence of functions on $(0,\infty)$
    defined by $f_{n}(x)=\frac{nx}{1+n^{2}x^{2}}$
   .This function converges pointwise to zero.
  Indeed, $(1+n^{2}x^{2})\sim n^{2}x^{2}$
    as $n$
    gets larger.
  So, $\underset{n\rightarrow\infty}{\lim}f_{n}(x)=\underset{n\rightarrow\infty}{\lim}f_{n}(x)=\frac{nx}{n^{2}x^{2}}.=\frac{1}{x}\underset{n\rightarrow\infty}{\lim}\frac{1}{n}=0.$
But for any $\epsilon<1/2$
   , we have
$|f_{n}(\frac{1}{n})-f(\frac{1}{n})|=\frac{1}{2}-0>\epsilon$
   .
Hence$ \{f_{n}\}$
    is not uniformly convergent.

*

*By the definition of pointwise convergence: $f_n(x)\rightarrow f(x)$ for all $x\in X$. But this does not seem to happen when $x=\frac{1}{n}$. So how can ${f_n}$ converge pointwise to zero for all $x\in (0,\infty)$ if $f_{n}(\frac{1}{n})=\frac{1}{2}$?

*Is it correct to think like this: If $ \{f_{n}\}$ was uniformly convergent, then if someone gave me an $\epsilon<1/2$, I should be able to find and $n\geq N$ so that  $|f_{n}(x)-f(x)|$ became smaller than $1/2$ for any $x \in (0,\infty)$, but this doesn't hold for any $x$ because we saw that $|f_{n}(\frac{1}{n})-f(\frac{1}{n})|=\frac{1}{2}-0>\epsilon$, so ${f_n(x)}$ cannot be uniformly convergent.

A: Pointwise convergence $f_n(x)\underset{n\to\infty}{\to}{f(x)}$ is convergence by $n$  at every (but fixed) argument $x$.


text:
Q: How to verify `extern "C"` definition signature matches implementation Given the following files:
main.rs:
mod ffi;
mod impl_do_print;

fn main() {
    unsafe {
        ffi::do_print(42.0);
    }
}

ffi.rs:
extern "C" {
    pub fn do_print(x: f32);
}

impl_do_print.rs:
#[no_mangle]
pub extern "C" fn do_print(x: i32) {
    println!("{}", x);
}

Obviously, the f32 of the definition and the i32 of the implementation don't match.
When I execute this, it prints:
1047505936

I understand that no_mangle is automatically considered unsafe, but is there any way I could ask the compiler to catch the mismatch, or would I have to write my own linter for this?
Usecase:
This question came up with generated FFIs. I am able to modify the implementation in any way possible, but I cannot edit the function definition, as it is generated via bindgen.

A: So far, two potentially viable solutions were proposed:

*

*Use the ffi.rs to auto-generate an implementation for the method that simply forwards the call to my own implementation. That way, the compiler would catch mismatching arguments.

*Use the ffi.rs to generate a type definition for the function. That way, you could write a compiler check to verify that the implementation matches the definition, like this: const _: fn_type = fn_impl.

Either way, it seems to require proc macros or an external generator.

After a little more experimenting, I managed to achieve a compile time check by utilizing a macro:
impl_do_print.rs:
#[no_mangle]
pub extern "C" fn do_print(x: i32) {
    println!("{}", x);
}

macro_rules! check_implementation_type {
    ($t:ty, $name:ident) => {
        const _: $t = $name;
        const _: $t = crate::ffi::$name;
    };
}

check_implementation_type!(unsafe extern "C" fn(i32), do_print);

This still requires me to write a check_implementation_type entry for every function I implement, but it gives me a reliable compile time error if either the ffi.rs or the implementation don't match:
error[E0308]: mismatched types
  --> src/impl_do_print.rs:9:23
   |
9  |         const _: $t = crate::ffi::$name;
   |                       ^^^^^^^^^^^^^^^^^ expected `i32`, found `f32`
...
13 | check_implementation_type!(unsafe extern "C" fn(i32), do_print);
   | --------------------------------------------------------------- in this macro invocation
   |
   = note: expected fn pointer `unsafe extern "C" fn(i32)`
                 found fn item `unsafe extern "C" fn(f32) {ffi::do_print}`
   = note: this error originates in the macro `check_implementation_type` (in Nightly builds, run with -Z macro-backtrace for more info)


text:
Q: Select a specific record in a group of records for all groups of records in MySQL I have a table that contains many different records for products specifications, the products may appear more than once in the table as they have different colors. In order to display the products in a screen I need to select a list of them with the color YELLOW, but if YELLOW is not present I need color BLUE, or else I don't want this product.
Simplified Products example:

+----+--------+
| ID | NAME   |
+----+--------+
|  1 | Prod A |
|  2 | Prod B |
|  3 | Prod C |
|  4 | Prod D |
+----+--------+

Simplied Spec table:

+----+------------+--------+
| ID | ID_PRODUCT | COLOR  |
+----+------------+--------+
|  1 |          1 | BLUE   |
|  2 |          1 | YELLOW |
|  3 |          2 | RED    |
|  4 |          2 | PINK   |
|  5 |          3 | BLUE   |
|  6 |          3 | GRAY   |
|  7 |          4 | YELLOW |
+----+------------+--------+

Expected results:

+----+------------+--------+
| ID | ID_PRODUCT | COLOR  |
+----+------------+--------+
|  2 |          1 | YELLOW |
|  5 |          3 | BLUE   |
|  7 |          4 | YELLOW |
+----+------------+--------+

Raw SQL for this example:

CREATE TABLE `colors` (
  `ID` int(11) NOT NULL,
  `ID_PRODUCT` int(11) DEFAULT NULL,
  `COLOR` varchar(16) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `products` (
  `ID` int(11) NOT NULL,
  `NAME` varchar(16) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `colors` VALUES (1,1,'BLUE'),(2,1,'YELLOW'),(3,2,'RED'),(4,2,'PINK'),(5,3,'BLUE'),(6,3,'GRAY'),(7,4,'YELLOW');

INSERT INTO `products` VALUES (1,'Prod A'),(2,'Prod B'),(3,'Prod C'),(4,'Prod D');

A: Here is one method:
select c.*
from colors c
where c.color = 'YELLOW'
union all
select c.*
from colors c
where c.color = 'BLUE' and
      not exists (select 1
                  from colors c2
                  where c2.id_product = c.id_product and c2.color = 'YELLOW'
                 );

A: Here's one option using conditional aggregation:
select id_product,
       max(case when color = 'YELLOW' then id
                when color = 'BLUE' then id
           end),
       max(case when color = 'YELLOW' then color
                when color = 'BLUE' then color
           end)
from colors
where color in ('YELLOW','BLUE')
group by id_product

*

*SQL Fiddle Demo

A: If it's always going to be blue and yellow comparison then I'd just use max() function, e.g.
select id, id_product, max(color) from colors
where color in ('BLUE','YELLOW')
group by id_product;


text:
Q: Numpy array assignment by boolean indices array I have a very large array, but I'll use a smaller one to explain.
Given source array X
X = [ [1,1,1,1],
      [2,2,2,2],
      [3,3,3,3]]

A target array with the same size Y
Y = [ [-1,-1,-1,-1],
      [-2,-2,-2,-2],
      [-3,-3,-3,-3]]

And an assigment array IDX:
IDX = [ [1,0,0,0],
        [0,0,1,0],
        [0,1,0,1]]

I want to assign Y to X by IDX - Only assign where IDX==1
In this case, something like:
X[IDX] = Y[IDX]

will result in:
X = [ [-1,1,1,1],
      [2,2,-2,2],
      [3,-3,3,-3]]

How can this be done efficiently (not a for-loop) in numpy/pandas?
Thx

A: If IDX is a NumPy array of Boolean type, and X and Y are NumPy arrays then your intuition works:
X = np.array(X)
Y = np.array(Y)
IDX = np.array(IDX).astype(bool)

X[IDX] = Y[IDX]

This changes X in place.
If you don't want to do all this type casting, or don't want to overwrite X, then np.where() does what you want in one go:
np.where(IDX==1, Y, X)


text:
Q: Aggregating a One-Hot Encoded feature in pyspark I am experienced in python but totally new to pyspark. I have dataframe that contains about 50M rows, with several categorical features. For each feature, I have One-Hot Encoded them. Here's a simplified but representative example of the code.
from pyspark.ml.feature import StringIndexer, OneHotEncoder
from pyspark.ml import Pipeline
df = sc.parallelize([
     (1, 'grocery'),
     (1, 'drinks'),
     (1, 'bakery'),
     (2, 'grocery'),
     (3, 'bakery'),
     (3, 'bakery'),
 ]).toDF(["id", "category"])

indexer = StringIndexer(inputCol='category', outputCol='categoryIndex')
encoder = OneHotEncoder(inputCol='categoryIndex', outputCol='categoryVec')

pipe = Pipeline(stages = [indexer, encoder])

newDF = pipe.fit(df).transform(df)

Giving output
+---+--------+-------------+-------------+
| id|category|categoryIndex|  categoryVec|
+---+--------+-------------+-------------+
|  1| grocery|          1.0|(2,[1],[1.0])|
|  1|  drinks|          2.0|    (2,[],[])|
|  1|  bakery|          0.0|(2,[0],[1.0])|
|  2| grocery|          1.0|(2,[1],[1.0])|
|  3|  bakery|          0.0|(2,[0],[1.0])|
|  3|  bakery|          0.0|(2,[0],[1.0])|
+---+--------+-------------+-------------+

I would now like to groupBy 'id' and aggregate the 'categoryVec' column with a sum, so I can get one row per id, with a vector that indicates which of the (possibly several) categories that customer was shopping in. In pandas this would be simply a case of applying sum/mean to each column produced in the pd.get_dummies() step, but here it doesn't seem to be so simple.
I will then pass the output to ML algorithms so I will need to be able to use VectorAssembler or similar on the output.
Oh, and I really need a pyspark solution.
Many thanks for your help!

A: You can use Counvectorizer for this. It converts category index array to encoded vector.
from pyspark.ml.feature import CountVectorizer
from pyspark.ml import Pipeline
from pyspark.sql.window import Window
from pyspark.sql import functions as F

df = sc.parallelize([
     (1, 'grocery'),
     (1, 'drinks'),
     (1, 'bakery'),
     (2, 'grocery'),
     (3, 'bakery'),
     (3, 'bakery'),
 ]).toDF(["id", "category"]) \
   .groupBy('id') \
   .agg(F.collect_list('category').alias('categoryIndexes'))

cv = CountVectorizer(inputCol='categoryIndexes', outputCol='categoryVec')

transformed_df = cv.fit(df).transform(df)
transformed_df.show()

results:
+---+--------------------+--------------------+
| id|     categoryIndexes|         categoryVec|
+---+--------------------+--------------------+
|  1|[grocery, drinks,...|(3,[0,1,2],[1.0,1...|
|  3|    [bakery, bakery]|       (3,[0],[2.0])|
|  2|           [grocery]|       (3,[1],[1.0])|
+---+--------------------+--------------------+


text:
Q: Vaadin close UI of same user in another browser/tab/system I'm doing a project in Vaadin 7. In that I need to implement something like below for the login.
A user 'A' is logged in to a system '1'. And again he logs into another system '2'. Now I want to know how to close the UI on the system '1'.
I tried something and can able to close the UI, If it is the same browser. But, for different systems/browser. I don't have any idea.
My Code:
private void closeUI(String attribute) {
        for (UI ui : getSession().getUIs()) {
            if(ui.getSession().getAttribute(attribute) != null)
                   if(ui.getSession().getAttribute(attribute).equals(attribute))
                         ui.close();

            }
}

Can anyone help me in this?

A: I have a situation similar to your where I need to display several info regarding all sessions. What I did was I created my own Servlet extending the VaadinServlet with a static ConcurrentHashmap to save my sessions info, and a SessionDestroyListener to remove any info from the map upon logout. Initially I also had a SessionInitListener where I added the info in the hashmap but I realized I only had the user information after authentication so I moved this part to the page handling the login.
I guess you could do something similar, or at least this should get you started:
public class SessionInfoServlet extends VaadinServlet {

  private static final ConcurrentHashMap<User, VaadinSession> userSessionInfo = new ConcurrentHashMap<>();

  // this could be called after login to save the session info
  public static void saveUserSessionInfo(User user, VaadinSession session) {
    VaadinSession oldSession = userSessionInfo.get(user);
    if(oldSession != null){
      // close the old session
      oldSession.close();
    }
    userSessionInfo.put(user, session);
  }

  public static Map<User, VaadinSession> getUserSessionInfos() {
    // access the cache if we need to, otherwise useless and removable
    return userSessionInfo;
  }

  @Override
  protected void servletInitialized() throws ServletException {
    super.servletInitialized();
    // register our session destroy listener
    SessionLifecycleListener sessionLifecycleListener = new SessionLifecycleListener();
    getService().addSessionDestroyListener(sessionLifecycleListener);
  }

  private class SessionLifecycleListener implements SessionDestroyListener {
    @Override
    public void sessionDestroy(SessionDestroyEvent event) {
      // remove saved session from cache, for the user that was stored in it
      userSessionInfo.remove(event.getSession().getAttribute("user"));
    }
  }
}


text:
Q: Can two Python programs write to different sheets in the same .xlsx file simultaneously? I am trying to create two python programs namely A and B. A will access 'test.xlsx'(excel file), create a sheet called 'sheet1' and write to 'sheet1'. Python program B will access 'test.xlsx'(excel file), create a sheet called 'sheet2' and write to 'sheet2' simultaneously.
Is it possible to do the above process?

A: To do that, you have to secure both programs from accessing the file at the same time.
For example, through a lock file.
This mechanism must be on both sides.
import os

from time import sleep
from os import path
# xlsx lib

FILENAME = 'test.xlsx'
LOCK_FILENAME = f'.~{FILENAME}'

while path.exists(LOCK_FILENAME):
    sleep(.1)

with open(LOCK_FILENAME, 'w') as f: ...

# do your code

os.remove(LOCK_FILENAME)

A: Generally operation of opening a file performed on an object is to associate it to a real file. An open file is represented within a program by a stream and any input or output operation performed on this stream object will be applied to the physical file associated to it.
The act of closing the file (actually, the stream) ends the association; the transaction with the file system is terminated, and input/output may no longer be performed on the stream. Python doesn't flush the buffer—that is, write data to the file—until it's sure you're done writing, and one way to do this is to close the file. If you write to a file without closing, the data won't make it to the target file.
When we are finished with our input and output operations on a file we shall close it so that the operating system is notified and its resources become available again.
There are to ways you can pick, either you open/close file synchronically or you will make a copy of your file and destroy it afterwards.