text:
Q: Cloudformation in create stack error: "ELB cannot be attached to multiple subnets in the same AZ" I trying to build infrastracture with Cloudformation json template. When I added two Subnets and SubnetRouteTableAssociation in both availability zones that i need. But creating process failing to create Loadbalancers with error:

CREATE_FAILED AWS::ElasticLoadBalancing::LoadBalancer Rest ELB cannot
  be attached to multiple subnets in the same AZ.

Here is the Parameters of AZs:
"AZs" : {
            "Description" : "The list of AvailabilityZones.",
            "Type" : "CommaDelimitedList",
            "Default" : "us-east-1a,us-east-1c"
        }

Here is Resources of  Subnets, SubnetRouteTableAssociation in both availability zones and ElasticLoadBalancing of Rest:
"PublicSubnet1a" : {
      "Type" : "AWS::EC2::Subnet",
      "Properties" : {
        "VpcId" : { "Ref" : "VPC" },
        "CidrBlock" : "10.0.0.0/24",
        "AvailabilityZone": {
          "Fn::Select": ["1", { "Ref": "AZs" }]
        },
        "Tags" : [
          {"Key": "Name", "Value": {"Fn::Join": ["", ["Offering-", {"Ref": "Env"}, {"Ref": "EnvNum"}, "-VPC"]]}},
          {"Key" : "Network", "Value" : "Public" }
        ]
      }
    },
     "PublicSubnet1c" : {
      "Type": "AWS::EC2::Subnet",
      "Properties": {
        "VpcId": { "Ref" : "VPC" },
        "CidrBlock": "10.0.1.0/24",
        "AvailabilityZone": {
          "Fn::Select": ["1", { "Ref": "AZs" }]
        },
        "Tags" : [
          {"Key": "Name", "Value": {"Fn::Join": ["", ["Offering-", {"Ref": "Env"}, {"Ref": "EnvNum"}, "-VPC"]]}},
          {"Key" : "Network", "Value" : "Public" }
        ]
      }
    },
"PublicSubnet1aRouteTableAssociation" : {
      "Type" : "AWS::EC2::SubnetRouteTableAssociation",
      "Properties" : {
        "SubnetId" : { "Ref" : "PublicSubnet1a" },
        "RouteTableId" : { "Ref" : "PublicRouteTable" }
      }
    },
    "PublicSubnet1cRouteTableAssociation" : {
      "Type" : "AWS::EC2::SubnetRouteTableAssociation",
      "Properties" : {
        "SubnetId" : { "Ref" : "PublicSubnet1c" },
        "RouteTableId" : { "Ref" : "PublicRouteTable" }
      }
    },
"RestELB" : {
        "Type" : "AWS::ElasticLoadBalancing::LoadBalancer",
        "DependsOn": "AttachGateway",
        "Properties": {
            "LoadBalancerName": {"Fn::Join": ["",["Rest-ELB-", {"Ref": "VPC"}]]},
            "CrossZone" : "true",
            "Subnets": [{ "Ref": "PublicSubnet1a" },{ "Ref": "PublicSubnet1c" }],
            "Listeners" : [
                {"LoadBalancerPort" : "80", "InstancePort" : "80","Protocol" : "HTTP"},
                {"LoadBalancerPort" : "6060", "InstancePort" : "6060","Protocol" : "HTTP"}
            ],
            "HealthCheck" : {
              "Target" : "HTTP:80/",
              "HealthyThreshold" : "3",
              "UnhealthyThreshold" : "5",
              "Interval" : "90",
              "Timeout" : "60"
            }
        }
    }

What I'm doing wrong?
Thanks!

A: "PublicSubnet1a" : {
    ...
    "AvailabilityZone": {
      "Fn::Select": ["1", { "Ref": "AZs" }] // <---- selects index 1 from AZs list
    },
    ...
"PublicSubnet1c" : {
    ...
    "AvailabilityZone": {
      "Fn::Select": ["1", { "Ref": "AZs" }] // <---- selects the same index 1 from AZs list
    },

both of your subnets are selecting the same index from AZs list (see "FN::select" statement). Change the select statement for PublicSubnet1a to be
"Fn::Select": ["0", { "Ref": "AZs" }]


text:
Q: Java dynamically generate SQL query - ATHENA I am trying to generate sql query based on user input. There are 4 search fields on the UI:
FIRST_NAME, LAST_NAME, SUBJECT, MARKS
Based on user input I am planning to generate SQL query. Input can be of any combination.
eg: select * from TABLE where FIRST_NAME="some_value";
This query needs to be generated when FIRST_NAME is given and other fields are null
select  * from TABLE where FIRST_NAME="some_value" and LAST_NAME="some_value";
This query needs to be generated when FIRST_NAME and LAST_NAME are given and other fields are null
Since there are 4 input fields, number of possible queries that can be generated are 24 (factorial of 4).
One idea is to write if condition for all 24 cases.
Java pseudo code:
String QUERY = "select * from TABLE where ";

if (FIRST_NAME!=null) {

    QUERY = QUERY + "FIRST_NAME='use_input_value';"

}
if (LAST_NAME!=null) {

    QUERY = QUERY + "LAST_NAME='use_input_value';"

}
if (SUBJECT!=null) {

    QUERY = QUERY + "SUBJECT='use_input_value';"

}
if (MARKS!=null) {

    QUERY = QUERY + "MARKS='use_input_value';"

}

I am not able to figure out how to generate SQL queries with AND coditions for multiple Input values.
I have been through concepts on dynamically generate sql query but couldn't process further.
Can someone help me on this.
FYI: I have been through How to dynamically generate SQL query based on user's selections?, still not able to generate query string based on user input.

A: Let's think about what would happen if you just ran the code you wrote and both FIRST_NAME and LAST_NAME are provided. You'll wind up with this:
select * from TABLE where FIRST_NAME='use_input_value';LAST_NAME='use_input_value';

There are two problems here:

*

*The query is syntactically incorrect.

*It contains the literals 'use_input_value' instead of the values you want.

To fix the first problem, let's first add and to the start of each expression, and remove the semicolons, something like this:
String QUERY = "select * from TABLE where";
if (FIRST_NAME!=null) {
    QUERY = QUERY + " and FIRST_NAME='use_input_value'";
}

Notice the space before the and. We can also remove the space after where.
Now the query with both FIRST_NAME and LAST_NAME will look like this:
select * from TABLE where and FIRST_NAME='use_input_value' and LAST_NAME='use_input_value'

Better but now there's an extra and. We can fix that by adding a dummy always-true condition at the start of the query:
String QUERY = "select * from TABLE where 1=1";

Then we append a semicolon after all the conditions have been evaluated, and we have a valid query:
select * from TABLE where 1=1 and FIRST_NAME='use_input_value' and LAST_NAME='use_input_value';

(It may not be necessary to append the semicolon. Most databases don't require semicolons at the end of a single query like this.)
On to the string literals. You should add a placeholder instead, and simultaneously add the value you want to use to a List.
String QUERY = "select * from TABLE where";
List<String> args = new ArrayList<>();
if (FIRST_NAME!=null) {
    QUERY = QUERY + " and FIRST_NAME=?";
    args.add(FIRST_NAME);
}

After you've handled all the conditions you'll have a string with N '?' placeholders and a List with N values. At that point just prepare a query from the SQL string and add the placeholders.
PreparedStatement statement = conn.prepareStatement(QUERY);
for (int i = 0; i < args.size(); i++) {
    statement.setString(i + 1, args[i]);
}

For some reason columns and parameters are indexed starting at 1 in the JDBC API, so we have to add 1 to i to produce the parameter index.
Then execute the PreparedStatement.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is the exact position of the content important while training a Keras model? My current position currently requires resolving captcha and I've been developing a model to recognize the each letter in the captcha. The captchas are always in the same font and style but with random background/text colors. Also they have random curved lines going through the image. This is an example:

I luckily found the source code of the captcha generator and I am able to generate any letter with any width/size combinations. I generated 35x35 300 samples for each letter like

 and I apply adaptive threshold to them. The results are like this
I use following layers:
model = Sequential([
Conv2D(filters=32, kernel_size=(3,3), activation='relu', padding='same', input_shape=(35,35,3)),
MaxPool2D(pool_size=(2,2),strides=2),
Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding='same'),
MaxPool2D(pool_size=(2,2),strides=2),
Flatten(),
Dense(units=62, activation='softmax')])

The training went not bad and I've reached to 0.85 accuracy.
However, when it comes to practice, I got weird results like it recognizes letter 'W' as 'x', letter 'p as Q' and so on. I would say I have ~60% success rate.
Now I want to train my model with more dataset. My question is the exact position of each letter in the 35x35 samples very important while training the dataset? Should I put images with different positions like    to feed the model with different combinations or the model itself handles this by itself when I give the letters in a fixed width/height combinations?
Also I would like to hear about your opinion about my general progress.
Thanks!


text:
Q: How to start an already named screen session? I can start a screen session with:
screen "commandhere"
which will start a screen session, running the "commandhere".
The question: how can I name this screen session automatically?

A: Use -S, for example:
screen  -S my-new-session sleep 100

You can then see a new session in a list of sessions:
$ screen -ls
There are screens on:
26667.my-new-session    (Attached)


text:
Q: RPostgres not setting correct character encoding I'm trying to get some data from a Postgres DB via the RPostgreSQL package. The character columns in the resulting data.frame have an unknown encoding:
Encoding(raw_orders$city)
  [1] "unknown" "unknown" "unknown" "unknown" "unknown" "unknown" "unknown" "unknown" "unknown" "unknown" "unknown" "unknown"

This despite me setting every imaginable encoding flag to UTF-8:
> dbGetQuery(connection_postgres, "SHOW CLIENT_ENCODING")
  client_encoding
1            UTF8

> dbGetQuery(connection_postgres, "SHOW SERVER_ENCODING")
  server_encoding
1            UTF8

> Sys.getlocale()
[1] "en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8"

How do I force UTF-8 for all character columns without having to manually set it via Encoding()?


text:
Q: Não consigo salvar dados do formulário pessoal nao estou conseguindo salvar os dados do meu formulário no banco.
tenho os seguintes arquivos:
functions.php
/**
 *  Cadastro de Notas
 */
function add() {
  if (!empty($_POST['nota'])) {

    $today =
      date_create('now', new DateTimeZone('America/Sao_Paulo'));
    $nota = $_POST['nota'];
    $aluno = $_POST['nota'];
    $nota['modified'] = $nota['created'] = $today->format("Y-m-d H:i:s");

    save('notas', $nota);
    header('location: index.php');
  }
}

add.php
<?php
  require_once('functions.php');
  add();
  index2();
  ?>

<?php include(HEADER_TEMPLATE); ?>

Cadastrar Nota

<form action="add.php" method="post">

      Aluno

      <select class="form-control">

      <?php if ($alunos) : ?>
      <?php foreach ($alunos as $aluno) : ?>

      <option value="<?php echo $aluno['AlunoID']; ?>" name="nota['AlunoID']"><?php echo $aluno['AlunoNome']; ?></option>

      <?php endforeach; ?>
      <?php else : ?>

      <option>SEM RESULTADOS</option>

      <?php endif; ?>

      </select>

      Materia
      <input type="text" class="form-control" name="nota['MateriaID']">

      Nota
      <input type="text" class="form-control" name="nota['Nota']">

      Data de Cadastro
      <input type="text" class="form-control" name="nota['created']" disabled>

      <button type="submit" class="btn btn-primary">Cadastrar</button>
      Cancelar

</form>

<?php include(FOOTER_TEMPLATE); ?>

o que pode ser?
qualquer ajuda será bem vinda.
desde ja obrigado pela sua atenção.

A: Acredito que o seu formulário esteja com alguns erros.
<form action="add.php" method="post">

      Aluno

      <select class="form-control">
        <?php if ($alunos) : ?>
          <?php foreach ($alunos as $aluno) : ?>
            <option value="<?php echo $aluno['AlunoID']; ?>" name="nota['AlunoID']"><?php echo $aluno['AlunoNome']; ?></option>

          <?php endforeach; ?>
        <?php else : ?>
        <option>SEM RESULTADOS</option>
        <?php endif; ?>
      </select>

      Materia
      <input type="text" class="form-control" name="nota['MateriaID']">

      Nota
      <input type="text" class="form-control" name="nota['Nota']">

      Data de Cadastro
      <input type="text" class="form-control" name="nota['created']" disabled>

      <button type="submit" class="btn btn-primary">Cadastrar</button>
      Cancelar

</form>

*

*Seu elemento select não possui o atributo name definido. Ao invés disso, você definiu o atributo em option. Remova do option e defina-o em select:
<select class="form-control" name="nota['AlunoID']">
   ...
</select>

*O campo nota['created'] está como disabled, então seu valor não será enviado na submissão do formulário. Não chega a ser um erro, visto que na função você redefine este valor, mas não faz muito sentido possuir um campo vazio e desativado por padrão no formulário.
Dentro da função add, você pode comentar a linha header e colocar var_dump($nota) para verificar se os dados do formulário estão chegando como esperado.


text:
Q: OpenOffice неведомые текстовые поля Понимаю что для профи вопрос покажется детским лепетом, но меня он поставил в тупик. Я только учусь, и формулировка вопроса без каких либо сносок и объяснений загоняет в ступор. Есть задание - создать таблицу в документе Writer и в ячейках сделать тестовые поля, дословно ( В ячейках где пользователь будет вводить собственные данные необходимо разместить текстовые поля).
Вставить числовое поле - ячейка С1, максимальное значение 1, по умолчанию 1, шаг значения 1.

A: Создание таблицы, надеюсь, проблемой не является. Покажу, как создать числовое поле.

*

*Создать новый текстовый документ.

*Включить панель элементов управления:

*Нажать кнопку показа дополнительных элементов:

*Нажать кнопку числового поля и нарисовать его (как прямоугольник) в документе:

*В контекстном меню открыть свойства элемента:

*В появившемся окне заполнить имя и требуемые поля:

*Выйти из режимов разработки и выделения:

*Поле можно заполнять и/или менять число стрелочками вверх/вниз.


text:
Q: Service returns a null pointer exception I created a service to get data from the /proc/meminfo and the service class is :
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Vector;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MonitorService extends Service{

Vector<String> memFree, buffers, cached, active, inactive, swapTotal,dirty;
int TOTAL_INTERVALS = 440;
private BufferedReader readStream;
private String x;
int memTotal;

private Runnable readRunnable = new Runnable() {
    public void run() {
        read(); // We call here read() because to draw the graphic we need
                // at less 2 read values.
        while (readThread == Thread.currentThread()) {
            try {
                read();
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
};

private Thread readThread = new Thread(readRunnable, "readThread");

class MyServiceDataBinder extends Binder {
    MonitorService getService() {
        return MonitorService.this;
    }
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    memFree = new Vector<String>(this.TOTAL_INTERVALS);
    buffers = new Vector<String>(this.TOTAL_INTERVALS);
    cached = new Vector<String>(this.TOTAL_INTERVALS);
    active = new Vector<String>(this.TOTAL_INTERVALS);
    inactive = new Vector<String>(this.TOTAL_INTERVALS);
    swapTotal = new Vector<String>(this.TOTAL_INTERVALS);
    dirty = new Vector<String>(this.TOTAL_INTERVALS);

}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return new MyServiceDataBinder();
}

private void read() {
    try {
        readStream = new BufferedReader(new FileReader("/proc/meminfo"));
        x = readStream.readLine();
        while (x != null) {

            /*
             * When the limit TOTAL_INTERVALS is surpassed by some vector we
             * have to remove all the surpassed elements because, if not,
             * the capacity of the vector will be increase x2.
             */
            while (memFree.size() >= this.TOTAL_INTERVALS)
                memFree.remove(memFree.size() - 1);
            while (buffers.size() >= this.TOTAL_INTERVALS)
                buffers.remove(buffers.size() - 1);
            while (cached.size() >= this.TOTAL_INTERVALS)
                cached.remove(cached.size() - 1);
            while (active.size() >= this.TOTAL_INTERVALS)
                active.remove(active.size() - 1);
            while (inactive.size() >= this.TOTAL_INTERVALS)
                inactive.remove(inactive.size() - 1);
            while (swapTotal.size() >= this.TOTAL_INTERVALS)
                swapTotal.remove(swapTotal.size() - 1);
            while (dirty.size() >= this.TOTAL_INTERVALS)
                dirty.remove(dirty.size() - 1);

            // We read the memory values. The percents are calculated in the
            // AnotherMonitor class.
            if (x.startsWith("MemTotal:"))
                memTotal = Integer.parseInt(x.split("[ ]+", 3)[1]);
            if (x.startsWith("MemFree:"))
                memFree.add(0, x.split("[ ]+", 3)[1]);
            if (x.startsWith("Buffers:"))
                buffers.add(0, x.split("[ ]+", 3)[1]);
            if (x.startsWith("Cached:"))
                cached.add(0, x.split("[ ]+", 3)[1]);
            if (x.startsWith("Active:"))
                active.add(0, x.split("[ ]+", 3)[1]);
            if (x.startsWith("Inactive:"))
                inactive.add(0, x.split("[ ]+", 3)[1]);
            if (x.startsWith("SwapTotal:"))
                swapTotal.add(0, x.split("[ ]+", 3)[1]);
            if (x.startsWith("Dirty:"))
                dirty.add(0, x.split("[ ]+", 3)[1]);
            x = readStream.readLine();
        }

        readStream.close();

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

}

The class where I call the created service :
 import java.text.DecimalFormat;
 import java.util.Vector;

 import android.app.Activity;
 import android.content.ComponentName;
 import android.content.Intent;
 import android.content.ServiceConnection;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.IBinder;
 import android.widget.TextView;

 import com.sliit.droidman.R;

 public class Processor extends Activity{

private TextView ram1, ram2, ram3, ram4, ram5, ram6, ram7;
private MonitorService MyMonitor;
private DecimalFormat myFormat = new DecimalFormat("##,###,##0");
private Handler myHandler;

private Runnable drawRunnable = new Runnable() {
    public void run() {
        setTextLabel(ram1,MyMonitor.memFree);
        setTextLabel(ram2,MyMonitor.buffers);
        setTextLabel(ram3,MyMonitor.cached);
        setTextLabel(ram4,MyMonitor.active);
        setTextLabel(ram5,MyMonitor.inactive);
        setTextLabel(ram6,MyMonitor.swapTotal);
        setTextLabel(ram7,MyMonitor.dirty);

        myHandler.postDelayed(this, 1000);
    }
};

private ServiceConnection MyService = new ServiceConnection() {

    public void onServiceDisconnected(ComponentName name) {
        // TODO Auto-generated method stub
        MyMonitor = null;
    }

    public void onServiceConnected(ComponentName name, IBinder service) {
        // TODO Auto-generated method stub
        MyMonitor = ((MonitorService.MyServiceDataBinder)service).getService();
        ram1.setText(myFormat.format(MyMonitor.memTotal) + " kB");
        myHandler.post(drawRunnable); <--- A null pointer Exceprtion occurs
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    startService(new Intent(this, MonitorService.class));
    setContentView(R.layout.resources_processor);

    ram1 = (TextView) findViewById(R.id.Appres_ProcessorInfo1);
    ram2 = (TextView) findViewById(R.id.Appres_ProcessorInfo2);
    ram3 = (TextView) findViewById(R.id.Appres_ProcessorInfo3);
    ram4 = (TextView) findViewById(R.id.Appres_ProcessorInfo4);
    ram5 = (TextView) findViewById(R.id.Appres_ProcessorInfo5);
    ram6 = (TextView) findViewById(R.id.Appres_ProcessorInfo6);
    ram7 = (TextView) findViewById(R.id.Appres_ProcessorInfo7);
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    bindService(new Intent(this, MonitorService.class), MyService, 0);
}

@Override
protected void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
    unbindService(MyService);
}

private void setTextLabel(TextView textView, Vector<String> y) {
        if (!y.isEmpty()) {
            textView.setText(myFormat.format(Integer.parseInt(y.firstElement())) + " kB");
            //textViewP.setText(myFormatPercent.format(Integer.parseInt(y.firstElement())* 100 / (float) myAnReaderService.memTotal) + "%");
        } else
            textView.setText("Value");
}

 }

The log cat out put :
07-13 10:20:08.109: E/AndroidRuntime(745): FATAL EXCEPTION: main
07-13 10:20:08.109: E/AndroidRuntime(745): java.lang.NullPointerException
07-13 10:20:08.109: E/AndroidRuntime(745):  at com.sliit.droidman.systemresources.Processor$2.onServiceConnected(Processor.java:49)
07-13 10:20:08.109: E/AndroidRuntime(745):  at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1097)
07-13 10:20:08.109: E/AndroidRuntime(745):  at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1114)
07-13 10:20:08.109: E/AndroidRuntime(745):  at android.os.Handler.handleCallback(Handler.java:615)
07-13 10:20:08.109: E/AndroidRuntime(745):  at android.os.Handler.dispatchMessage(Handler.java:92)
07-13 10:20:08.109: E/AndroidRuntime(745):  at android.os.Looper.loop(Looper.java:137)
07-13 10:20:08.109: E/AndroidRuntime(745):  at android.app.ActivityThread.main(ActivityThread.java:4745)
07-13 10:20:08.109: E/AndroidRuntime(745):  at java.lang.reflect.Method.invokeNative(Native Method)
07-13 10:20:08.109: E/AndroidRuntime(745):  at java.lang.reflect.Method.invoke(Method.java:511)
07-13 10:20:08.109: E/AndroidRuntime(745):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
07-13 10:20:08.109: E/AndroidRuntime(745):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-13 10:20:08.109: E/AndroidRuntime(745):  at dalvik.system.NativeStart.main(Native Method)
07-13 10:20:15.860: E/Trace(764): error opening trace file: No such file or directory (2)

I get a null pointer exception from the code that I have pointed out in the code. Please help me out to figure out the error that i DO in this section.
thank you.

A: This line:
 private Thread readThread = new Thread(readRunnable, "readThread");

You create this thread in service, but never start/call it. That is the reason your vectors are empty. Try starting it in onBind().


text:
Q: An error occurred when verifying security for the message - SAML Token Few years back we have developed a client to consume a usi-ws v2, this webservice uses a STS service v2. It was working fine.
But, now soap-ws v2 is updated to usi-ws v3 which in turns uses STS service v3.
Key differences are
1) usi-ws v3 uses <sp:Basic256Sha256Rsa15/> as AlgorithmSuite policy which matches STS service v3's AlgorithmSuite policy.
2) usi-ws v3 uses STS service v3 instead of STS service v2
I can integrate the change by two different approaches
First Approach
I use apache-cxf wsdl2java on usi-ws v3 to generate the client code. Below is sample endpoint code
private static void SetupRequestContext(IUSIService endpoint, X509Certificate certificate, PrivateKey privateKey)   {

        Map<String, Object> requestContext = ((BindingProvider)endpoint).getRequestContext();

        requestContext.put(XWSSConstants.CERTIFICATE_PROPERTY, certificate);
        requestContext.put(XWSSConstants.PRIVATEKEY_PROPERTY, privateKey);
        requestContext.put(STSIssuedTokenConfiguration.STS_ENDPOINT, "https://thirdparty.authentication.business.gov.au/R3.0/vanguard/S007v1.3/Service.svc");
        requestContext.put(STSIssuedTokenConfiguration.STS_NAMESPACE, "http://schemas.microsoft.com/ws/2008/06/identity/securitytokenservice");
        requestContext.put(STSIssuedTokenConfiguration.STS_WSDL_LOCATION, "https://thirdparty.authentication.business.gov.au/R3.0/vanguard/S007v1.3/Service.svc");
        requestContext.put(STSIssuedTokenConfiguration.STS_SERVICE_NAME, "SecurityTokenService");
        requestContext.put(STSIssuedTokenConfiguration.LIFE_TIME, 30);
        requestContext.put(STSIssuedTokenConfiguration.STS_PORT_NAME, "S007SecurityTokenServiceEndpoint");
        requestContext.put(BindingProviderProperties.REQUEST_TIMEOUT, REQUEST_TIMEOUT);
        requestContext.put(BindingProviderProperties.CONNECT_TIMEOUT, CONNECT_TIMEOUT);
    }

After configuring the endpoint context, I try to createUSI
endpoint.createUSI(createUsiRequest);

It throws below error (logs)
... LOGS before are removed
[main] WARN au.gov.abr.akm.credential.store.ABRRequester$ABRHttpPost - XML request is => <ns:requests  xmlns:ns="http://auth.sbr.gov.au/AutoRenew"><request id="ABRD:TESTDeviceID" credentialType="D"><cmsB64>[encoded data, 6888 characters]</cmsB64></request></ns:requests>
[main] INFO au.gov.abr.akm.credential.store.DaemonThreadFactory - Creating a new Thread in ThreadGroup: main
[pool-1-thread-1] WARN au.gov.abr.akm.credential.store.ABRRequester$ABRHttpPost - Constructing the response reader
[pool-1-thread-1] WARN au.gov.abr.akm.credential.store.ABRRequester$ABRHttpPost - java.net connection timeout = 0
[pool-1-thread-1] WARN au.gov.abr.akm.credential.store.ABRRequester$ABRHttpPost - java.net read timeout = 0
[main] INFO au.gov.abr.akm.credential.store.ABRKeyStoreImpl - correct password given, resetting bad password count to zero
[main] INFO au.gov.abr.akm.credential.store.ABRKeyStoreFactory - Will attempt to load the keystore, if the keystore doesn't exist then an exception will be thrown
[main] INFO au.gov.abr.akm.credential.store.ABRKeyStoreSerializerTransporterFactory - No custom Transporter specified, using the default File Transporter.
[main] INFO au.gov.abr.akm.credential.store.ABRKeyStoreSerializerTransporterFile - A keystore file has been passed through, keystore location is that of the provided file
[pool-1-thread-1] WARN au.gov.abr.akm.credential.store.ABRRequester - ABRRequester timeout = 60000ms
[pool-1-thread-1] INFO au.gov.abr.akm.cryptoOps.CredentialRequestResponse - XML Response length -> 358
[pool-1-thread-1] INFO au.gov.abr.akm.cryptoOps.CredentialRequestResponse - Auto-renew => ***BEGIN XML RESPONSE***
<?xml version="1.0" encoding="utf-8"?><responses xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://auth.sbr.gov.au/AutoRenew"><response id="ABRD:TESTDeviceID" xmlns=""><error><errorId>2106</errorId><errorMessage>Unrecognised error - 1137</errorMessage></error></response></responses>
******END XML******
[pool-1-thread-1] WARN au.gov.abr.akm.cryptoOps.CredentialRequestResponse - CredentialRequestResponse.processResponse (2106) Unrecognised error - 1137
javax.xml.ws.soap.SOAPFaultException: An error occurred when verifying security for the message.
    at com.sun.xml.ws.fault.SOAP12Fault.getProtocolException(SOAP12Fault.java:225)
    at com.sun.xml.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilder.java:122)
    at com.sun.xml.ws.client.dispatch.DispatchImpl.doInvoke(DispatchImpl.java:195)
    at com.sun.xml.ws.client.dispatch.DispatchImpl.invoke(DispatchImpl.java:214)
    at com.sun.xml.ws.security.trust.impl.TrustPluginImpl.invokeRST(TrustPluginImpl.java:624)
    at com.sun.xml.ws.security.trust.impl.TrustPluginImpl.process(TrustPluginImpl.java:170)
    at com.sun.xml.ws.security.trust.impl.client.STSIssuedTokenProviderImpl.getIssuedTokenContext(STSIssuedTokenProviderImpl.java:136)
    at com.sun.xml.ws.security.trust.impl.client.STSIssuedTokenProviderImpl.issue(STSIssuedTokenProviderImpl.java:74)
    at com.sun.xml.ws.api.security.trust.client.IssuedTokenManager.getIssuedToken(IssuedTokenManager.java:79)
    at com.sun.xml.wss.jaxws.impl.SecurityClientTube.invokeTrustPlugin(SecurityClientTube.java:655)
    at com.sun.xml.wss.jaxws.impl.SecurityClientTube.processClientRequestPacket(SecurityClientTube.java:264)
    at com.sun.xml.wss.jaxws.impl.SecurityClientTube.processRequest(SecurityClientTube.java:233)
    at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:629)
    at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:588)
    at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:573)
    at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:470)
    at com.sun.xml.ws.client.Stub.process(Stub.java:319)
    at com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:157)
    at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:109)
    at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:89)
    at com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:140)
    at com.sun.proxy.$Proxy44.createUSI(Unknown Source)
    at usi.gov.au.USITest.main(USITest.java:83)

Second Approach
2nd approach is that I directly call STS service v3 by generating wsdl2java client class. This approach is already answered here. But I couldn't understand the answer nor I was able to achieve the result by adding signatureAlgorithm="SHA256withRSA" in sp:AlgorithmSuite
<sp:AlgorithmSuite signatureAlgorithm="SHA256withRSA">
  <wsp:Policy>
    <sp:Basic256 />
  </wsp:Policy>
</sp:AlgorithmSuite>

OR
 <sp:AlgorithmSuite signatureAlgorithm="SHA256withRSA">
    <wsp:Policy>
      <sp:Basic256Sha256Rsa15 />
    </wsp:Policy>
 </sp:AlgorithmSuite>

Everytime I get
com.microsoft.schemas.ws._2008._06.identity.securitytokenservice.IWSTrust13SyncTrust13IssueSTSFaultFaultMessage: Could not validate the ActAs token

I can't understand that which approach is right and how to fix WSDL or my code to update the SecurityPolicy i.e. switchs from Sha1 to Sha256 with RSA.

A: You need updated STS 1.3 wsdl which does not require ActAs token as old one did


text:
Q: Failed to CREATE_FILE in hdfs I have a java program that try to write a file into hdfs, but i get this error message:
Failed to CREATE_FILE /data/xxx because DFSClient_attempt_1552693040212_69961_m_000000_0_1265362509_1 is already the current lease holder.


text:
Q: How to create a parameter in a hierarchical block that references an external/global variable? Many of the default blocks in GNU Radio Companion have their Sample Rate parameter set to samp_rate, and as such, when the blocks are added on to the canvas, they immediately take the value of the samp_rate variable (assuming it exists of course).
When creating your own hierarchical block, how can we specify that a parameter references an external/global variable? The Parameter block only accepts values.

A: There is no proper (unhacky) way to reference a "global variable" in the code.
You can always access the .py of the block and make it read a global variable.
The proper way to do this is to use the parameter block, and put in a variable name as the value. While editing the hierarchical block, the parameter block cannot access any variables. But you can still set the value of a parameter block to that of a variable, and by default it will read a variable on the top level with that variable name.
Say you have a parameter called "my_samp_rate". You can set the value of it to samp_rate (no quotes, not a string, rather the variable name). Inside the block it won't recognize any samp_rate value (because none was set).
HOWEVER when you place the new block inside a flowgraph, its default-value (which can be changed, mind you) would be samp_rate. If there is a variable in the flowgraph with the value of samp_rate, it will read the value and pass it as a parameter to the block. That way you can create a block that has a value that, by default, is bound to a variable on the top level.
The good thing about this approach is that it doesn't force anyone who uses the block to do so by using the variable you suggested. It's the default value, but if you want to bind the value of your parameter to that of a different variable, it's completely configurable.

A: The way I've done it is to use a Parameter block in the hierarchical block. I give this an ID of, e.g, freq_ratio, type float, default value of 0.5. Whereever I use a block (e.g. a Signal Source) that has a sample rate parameter (which, as you say, commonly defaults to samp_rate), I replace that with a 1.0, and I set the frequency to freq_ratio.
To use the block in a top level flow chart, the hierarchical block's freq_ratio has that default value of 0.5, but here in the top level that can be replaced with 1000.0 / samp_rate. That will have the Signal Source block inside produce me a signal at 1kHz, assuming the top block's samp_rate is used in a real device (e.g. an Audio Out block).
The point is that "sample rate" doesn't really mean anything as such in a GNU radio flowchart, except where it's used by a block that represents something physical (e.g. and Audio Out block, or a real SDR). So one can quite happily work with ratios.
Another way you can do it is to use two parameters in the hierarchical block. The first can be called samp_rate; give it a default value. The second can be called freq; again give it a default value. The Signal Source block in the hierarchical block can then use those two parameters for its sample rate and frequency. In the top level, you replace the default value for the hierachical block's sample rate parameter with samp_rate, and the default value for its frequency with what ever you want (a constant, some other variable, a Qt Range Widget's i.d, etc). The samp_rate you've typed here in the top block will be the top block's sample rate variable.
I've Not Really Answered Your Question Yet
Basically everything above is how it can be done for maximum convenience, but I'm afraid it's not possible to automagically directly use the top block's samp_rate for a block in hierarchical block. That's the answer, I'm afraid.
This makes sense; if you were writing source code, you'd not expect a function to be able to access a global variable that hadn't been defined in a scope that the function access.
What anerisgreat was saying in their second para:
You can always access the .py of the block and make it read a global variable.

is that, once GRC has generated all the .py source code files for you, you can then manually edit them so that the hierarchical block does use a samp_rate global variable instead of the value of one of its Parameter blocks.
That works because, by then, the function (or class + methods) that has been generated from the hierarchical block can now be given (by manually editting the .py files) sight of the scope where the top block's samp_rate has been defined. But this is a pretty unmaintainable approach to take.


text:
Q: Serializable and Row-based locking in MySQL I'm trying to convert a database from MsSQL to MySQL.
How exactly should the transaction configuration be done in MySQL for the Serializable isolation level that exists in MsSQL? Because MsSQL keyword didn't work.
Example;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
GO
BEGIN TRANSACTION;
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition
GO
COMMIT TRANSACTION;
GO
Except this; Is there a row-based locking feature when transacting on a row of the table between transaction begin and commit?
Example;
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition
// row-based locking for only condition
If it is disabled by default, what should I do to enable it?
Thank you.

A: did you start a transaction after set isolation level? it will set transaction level only for the next transaction. you could set it for all session via "SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE;". if you want to do it during create connection to the database server you can add "?sessionVariables=transaction_isolation='SERIALIZABLE'" at the end of the connection string. or you can execute once "SET SESSION TRA...SERIALIZABLE" as soon as you connect.


text:
Q: java.lang.NullPointerException getDouble How would I rewrite this code snippet into a form that doesn't produce java.lang.NullPointerException?
Intent bank_Amount_Intent = getIntent();
Bundle bundle = bank_Amount_Intent.getExtras();
double buyin_Money = bundle.getDouble("buyin", 0);
total = buyin_Money;
bank_Amount.setText(String.valueOf(currency_Format.format(buyin_Money)));

A: You first need to determine which variable is null, so use the debugger or proceed like so :
public int yourFunction(){
    Intent bank_Amount_Intent = getIntent();
    if (bank_Amount_Intent == null) {
        System.out.println("bank_Amount_Intent is null");
        return -1; //error #1
    }

    Bundle bundle = bank_Amount_Intent.getExtras();
    if (bundle == null) {
        System.out.println("bundle is null");
        return -2; //error #2
    }

    double buyin_Money = bundle.getDouble("buyin", 0);
    total = buyin_Money; // assuming "total" also is a double
    bank_Amount.setText(String.valueOf(currency_Format.format(buyin_Money)));
    return 0; //no error
}

You can then see in your console, which value was null. You can also use the returned value to determine the error code of that function.
When you know which value was null, you can do of two things : evaluate whether you want to keep it null or not
If you agree to keep a null value in that method, you can use it to pop an error or whatever you may want to do with a null value
If you don't want a null value, you can create an instance of an object of the type you need. eg, if bundle was null, you can to this : bundle = new Bundle();. Or you can preferably check why this value is null in the first place and correct the error. It is possible that an other function returns null and you only get the NullPointerException further in the execution.

A: Well Im gonna speculate based on the little amount of code shown. Since currency_Format its only shown being used Im assuming you have successfully instantiated it so that is not the source of the exception.
That leaves only bank_Amount_Intent and bundle.
While getIntent might return null on some extreme edge cases, my bet is on bundle, you are assuming the intent has a Bundle and might be where your null pointer resides.
try double buyin_Money = bundle == null ? 0: bundle.getDouble("buyin", 0);
that way to check first if the bundle if null, and if it is in fact null you set 0 value for your variable.

A: try{
      Intent bank_Amount_Intent = getIntent();
        Bundle bundle = bank_Amount_Intent.getExtras();
        double buyin_Money = bundle.getDouble("buyin", 0);
        total = buyin_Money;
        bank_Amount.setText(String.valueOf(currency_Format.format(buyin_Money)));
}
catch(Exception e)
{
e.printStackTrace();
}

this won't produce any exception but if you're trying to work on null object then you won't be able to get any result.
happy coding!!


text:
Q: Pusher: iOS Push Notification not arriving on phone I am trying to send push notifications for my app using Pusher.
I am following their tutorial (https://pusher.com/tutorials/push-notifications-ios/) to set it up. Thus far, I have enabled Push Notifications in XCode, created an instance and copied their code snippet.
Here is my AppDelegate.swift file (only relevant parts are included):
@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    let pushNotifications = PushNotifications.shared

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        self.pushNotifications.start(instanceId: [instanceId)
        self.pushNotifications.registerForRemoteNotifications()
        try? self.pushNotifications.addDeviceInterest(interest: "hello")
        return true
    }

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        self.pushNotifications.registerDeviceToken(deviceToken)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        self.pushNotifications.handleNotification(userInfo: userInfo)
    }
}

I am sending the push notification with the command
curl -H "Content-Type: application/json" \
     -H "Authorization: Bearer $SECRET_KEY" \
     -X POST "https://INSTANCE_ID.pushnotifications.pusher.com/publish_api/v1/instances/INSTANCE_ID/publishes" \
     -d '{"interests":["hello"],"apns":{"aps":{"alert":{"title":"Hello","body":"Hello, world!"}}}}'

After executing the curl command, I get the following message:
{"publishId":[publishId]}

However, no notification shows up on the iPhone that I am testing it on. The app is running in the background. Any help?
Thanks.

A: Cross-check all the points mentioned in the link first: https://developer.apple.com/library/archive/technotes/tn2265/_index.html

A: ensure your apns certificate is valid and you have set the appropriate capabilities in XCODE for push notifications

A: If you configure the release certificate, then only the release app can receive the push.

*

*Configure certificates and codes,plist...

*XCode->Product->Achive->Release..., upload .ipa.

*Install the app in testfight, then Push and receive notifications。


text:
Q: Certain games won't load - Nvidia Certain games on Steam won't load. I can't figure out why. I upgraded to kernel 3.14.4 from 3.13.39 and this problem won't go away:
[   81.122225] bbswitch: enabling discrete graphics
[   81.593271] [drm] Initialized nvidia-drm 0.0.0 20130102 for 0000:01:00.0 on minor 1
[   81.593276] NVRM: loading NVIDIA UNIX x86_64 Kernel Module  343.22  Thu Sep 11 16:27:43 PDT 2014
[   81.610223] vgaarb: this pci device is not a vga device
[   81.610534] nvidia 0000:01:00.0: irq 54 for MSI/MSI-X
[   81.614761] ACPI Warning: \_SB_.PCI0.PEG0.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20131218/nsarguments-95)
[   81.614842] ACPI Warning: \_SB_.PCI0.PEG0.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20131218/nsarguments-95)
[   81.614870] ACPI Warning: \_SB_.PCI0.PEG0.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20131218/nsarguments-95)
[   81.614896] ACPI Warning: \_SB_.PCI0.PEG0.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20131218/nsarguments-95)
[   81.614919] ACPI Warning: \_SB_.PCI0.PEG0.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20131218/nsarguments-95)
[   81.614944] ACPI Warning: \_SB_.PCI0.PEG0.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20131218/nsarguments-95)
[   81.614986] ACPI Warning: \_SB_.PCI0.PEG0.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20131218/nsarguments-95)
[   81.615010] ACPI Warning: \_SB_.PCI0.PEG0.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20131218/nsarguments-95)
[   82.652914] ACPI Error: Field [TMPB] at 274432 exceeds Buffer [ROM1] size 262144 (bits) (20131218/dsopcode-236)
[   82.652920] ACPI Error: Method parse/execution failed [\_SB_.PCI0.PEG0.PEGP._ROM] (Node ffff88022647fa00), AE_AML_BUFFER_LIMIT (20131218/psparse-536)
[   82.669967] ACPI Warning: \_SB_.PCI0.PEG0.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20131218/nsarguments-95)
[   82.841451] vgaarb: this pci device is not a vga device
[   83.314224] ACPI Warning: \_SB_.PCI0.PEG0.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20131218/nsarguments-95)
[   83.318847] [drm] Module unloaded
[   83.320680] bbswitch: disabling discrete graphics
[   83.320691] ACPI Warning: \_SB_.PCI0.PEG0.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20131218/nsarguments-95)
[   83.337618] pci 0000:01:00.0: Refused to change power state, currently in D0

My Xorg.8.log
$ cat /var/log/Xorg.8.log | grep EE
[    81.498] (II) NVIDIA(0): Creating default Display subsection in Screen section
    "Default Screen Section" for depth/fbbpp 24/32
[    81.498] (==) NVIDIA(0): Depth 24, (==) framebuffer bpp 32
[    81.498] (==) NVIDIA(0): RGB weight 888
[    81.498] (==) NVIDIA(0): Default visual is TrueColor
[    81.498] (==) NVIDIA(0): Using gamma correction (1.0, 1.0, 1.0)
[    81.498] (**) NVIDIA(0): Option "NoLogo" "true"
[    81.498] (**) NVIDIA(0): Option "ProbeAllGpus" "false"
[    81.499] (**) NVIDIA(0): Option "UseEDID" "false"
[    81.499] (**) NVIDIA(0): Option "UseDisplayDevice" "none"
[    81.499] (**) NVIDIA(0): Enabling 2D acceleration
[    81.499] (**) NVIDIA(0): Ignoring EDIDs
[    81.499] (**) NVIDIA(0): Option "UseDisplayDevice" set to "none"; enabling NoScanout
[    81.499] (**) NVIDIA(0):     mode
[    82.727] (II) NVIDIA(GPU-0): Found DRM driver nvidia-drm (20130102)
[    82.728] (II) NVIDIA(0): NVIDIA GPU GeForce GT 750M (GK107) at PCI:1:0:0 (GPU-0)
[    82.728] (--) NVIDIA(0): Memory: 2097152 kBytes
[    82.728] (--) NVIDIA(0): VideoBIOS: 80.07.9a.00.4b
[    82.728] (II) NVIDIA(0): Detected PCI Express Link width: 16X
[    82.728] (--) NVIDIA(0): Valid display device(s) on GeForce GT 750M at PCI:1:0:0
[    82.728] (--) NVIDIA(0):     none
[    82.728] (II) NVIDIA(0): Validated MetaModes:
[    82.728] (II) NVIDIA(0):     "NULL"
[    82.728] (II) NVIDIA(0): Virtual screen size determined to be 640 x 480
[    82.728] (WW) NVIDIA(0): Unable to get display device for DPI computation.
[    82.728] (==) NVIDIA(0): DPI set to (75, 75); computed from built-in default
[    82.728] (--) Depth 24 pixmap format is 32 bpp
[    82.728] (II) NVIDIA: Using 3072.00 MB of virtual memory for indirect memory
[    82.728] (II) NVIDIA:     access.
[    82.731] (II) NVIDIA(0): Setting mode "NULL"
[    82.731] (EE) NVIDIA(0): Failed to initiate mode change.
[    82.731] (EE) NVIDIA(0): Failed to complete mode change
[    82.738] Loading extension NV-GLX
[    82.741] (==) NVIDIA(0): Disabling shared memory pixmaps
[    82.741] (==) NVIDIA(0): Backing store enabled
[    82.741] (==) NVIDIA(0): Silken mouse enabled
[    82.742] (==) NVIDIA(0): DPMS enabled
[    82.742] Loading extension NV-CONTROL


text:
Q: How can I map file IO from a file to an existing device? As the title asks, how can I I map file IO from a file to an existing device?
I am using a higher level programming language on one of these common SoC single board computers running Linux. This language has a library to access the serial port to send TX and receive RX data. The library accesses /dev/ttyAMA0 to do reading and writing, but unfortunately when you create the Serial object it does so by opening /dev/ttyAMA0 using exclusive access denying other processes or even other instances of the Serial object from using /dev/ttyAMA0.
In my case I wanted to write two separate programs. One program that write to the serial port TX, and another program to read from the serial port RX, but this library won't allow it since its opens /dev/ttyAMA0 using exclusive access. I am thinking with Linux it should be possible to create a second or even a third file which would act as pseudo terminal or something and take any reads or writes and just map all IO access to /dev/ttyAMA0.
So my question is, how can I create a file (or a pseudo tty) on Linux that maps all reads and writes to a device like /dev/ttyAMA0?

A: Assuming /dev/ttyAMA0 is a device node, you could potentially create additional nodes with the same major/minor number which would map to the same device.
For example to do this for /dev/zero, find out what the major & minor numbers are:
carbon# ls -l /dev/zero
crw-rw-rw- 1 root root 1, 5 May 29 02:16 /dev/zero

Major number is 1, minor number is 5 and the device is a character one.
Create another device node with the same parameters, probably as root:
mknod /dev/zero-dup c 1 5

Now you can use /dev/zero-dup as a copy of /dev/zero.


text: Q: How to redirect sys log of ubuntu running on virtual machine to host? I have ubuntu installed on my VM(Vmwarefusion - version 7) running on my Mac book Pro. I am actually doing kernel development by writing kernel modules on ubuntu. If have a kernel crash, sometimes my vm is stuck and i have no way going back to terminal and viewing system logs using dmesg command. The only option left is rebooting the system and I have lost sys log which have dmesg output most of the times. So is there any way I could actually redirect sys log output to my host i.e my Mac Pro so that when I have kernel panic, I can go and look them.


text:
Q: How many tasks should be created for parallelizing independent distinct DB Calls? I have 5 parallel DB operations need to be executed independently. I know asking number of Cores and creating 4 or 8 ( In case 4 or 8 cores ) tasks would be costly.
DB Op result1 = db.Table1.Get(...).Join( anotherTable2)...Join()..
DB Op result2 = db.Table1.Get(...).Join( anotherTable2)...Join()..
DB Op result3 = db.Table1.Get(...).Join( anotherTable2)...Join()..
DB Op result4 = db.Table1.Get(...).Join( anotherTable2)...Join()..
DB Op result5 = db.Table1.Get(...).Join( anotherTable2)...Join()..
On the result of these operations , I have to decide, whether I should continue further or not.
For this, couple of tasks would be sufficient which would send calls to DB for execute these operations or 5 distinct tasks should be created? I don't internally tasks create how many threads to perform certain DB operation.
I am not thinking about parallelizing query itself.

A:
How many tasks should be created for parallelizing independent distinct DB
  Calls?

As many as you have independent distinct DB operations.
Wrong question.
The real question is - how many should be executed at the same time. Which means making your own limiting scheduler (copy/paste from internet). You can start at https://msdn.microsoft.com/en-us/library/ee789351(v=vs.100).aspx - "How to: Create a Task Scheduler That Limits the Degree of Concurrency"
And that is likely trial and error because it depends on the load and characteristics of the database server, NOT the computer your code runs on. Last time I did that it was with simple operations (not a lot of join) and against an Oracle ExaData and we literally used hundreds of threads in the applicaton in parallel (way more than cores because they were mostly WAITING FOR THE DATABASE SERVER). There is no way for the C# side to know when the db server overloads, so we got them as configuration value and made some trial/error runs to find good values for the scheduler.


text:
Q: How to create named soft links in a makefile? I'm exploring ways to improve code module integration and have found interest in using named soft links as opposed to include directories, mainly because that allows the integrator to set a directory name of any imported module to something guaranteed not to collide with the module built or any of its imported modules, as well as keeping imported modules from accidently intercepting eachother. However I'm not sure how to actually accomplish this in a makefile.
Here is the directory hierarchy and expected links:
+---proj1
|   +---inc
|   |       head.h
|   |
|   \---src
|           code.c
|
+---proj2
|   +---inc
|   |       head.h
|   |
|   \---src
|           code.c
|
\---proj3
    |   Makefile
    |
    \---src
        |   code.c
        |   head.h
        |
        +---A                  --> ../../proj1/inc
        |       head.h
        |
        \---B                  --> ../../proj2/inc
                head.h

In proj3/src/code.c i would have:
#include "head.h"
#include "A/head.h"
#include "B/head.h"

I think I need some way to run ln -s for each {directory,name} tuple prior to compiling the source, putting the link in the same directory as the source being compiled. Parsing INC=dir1 dir2 is simple enough, but how to represent and run ln -s for each pair/tuple in such a list? Or, if having a whole command in each element (ln -s dir1 localname), how to exec all of them?
Other suggestions would be deeply appreciated.

A: Something like this?
linkdirs := A B
dir_A := ../proj1/src
dir_B := ../proj2/src

.PHONY: all symlinks
all: symlinks hello
symlinks:
    $(eval $(patsubst %,ln -fs $$(dir_%) % &&,$(linkdirs)) true


text:
Q: Adding a child div inside a video element, not showing My goal is to have text over each video element (there are many of them). The video is showing, but the div inside it does not.
<video autoplay playsinline style="transform: rotate(0deg); width: 100%; height: 100%; position: relative">

test

</video>

In the element inspector, when I hover over the div, it does not show a box anywhere on the page. How to make it show up?

A: Video elements cannot contain elements inside, unless the video tag is not supported. This is common practice to display an error message explaining the browser doesn't support video.
Place your video inside an element (like a div) and add that div next to it, as a sibling to the video element and not a child. Use position to place it inside:

  <video autoplay playsinline style="transform: rotate(0deg); width: 100%; height: 100%; position: relative"></video>

test

Make sure you post your full code to ensure we can help you properly.


text:
Q: Problem in valuation theory Find $\alpha\in \mathbb{Q}$, such that $v_2(\alpha-1/3)\ge 2$, $v_3(\alpha-1/2)\ge 3$ and $|\alpha-1|_\infty<1/2$, where $v_p$ is the $p$-adic exponential valuation and $|\cdot|_\infty$ is the usual absolute value.
Thanks in advance!

A: The first two conditions are equivalent to $v_2(3\alpha-1)\ge2$ and $v_3(2\alpha-1)\ge3$. That is,
$$3\alpha-1\equiv 0 \mod 2^2\Bbb Z \qquad and \qquad 2\alpha-1 \equiv 0 \mod 3^3\Bbb Z.$$
Rewriting each side (note $2^{-1}\equiv 14\mod 27$), we obtain
$$\begin{cases} \alpha\equiv -1 \mod 4 \\ \alpha \equiv  14 \mod 27. \end{cases}$$
By CRT we have $\alpha=95 \mod 108$. We need $|p/q-1|_\infty <1/2$ while $pq^{-1} \equiv 95 ~(108)$. The two nontrivial factors of $95$ are $5$ and $19$; we have $5^{-1}\equiv 65$ and $19^{-1}\equiv 91 \mod 108$. The latter is close to $5+108=113$ in the $|\cdot|_\infty$ metric, so we check that $|113/91-1|_\infty<1/2$ indeed holds.
This gives $\alpha=113/91$ as one solution.

A: Hint: If $\alpha = \frac{a}{b}$ then
$\alpha-\frac{1}{2} = \frac{2a-b}{2b}$
$\alpha-\frac{1}{3} = \frac{3a-b}{3b}$
You need to make the first fraction divisible by a high power of 3, and the second divisible by a high power of 2. It's easiest to make $b$ relatively prime to 6 so you don't have to worry about the denominators. Pick such a $b$. Can you find an $a$ such that $2a-b$ is divisible by 27? Can you find an $a$ that makes $3a-b$ divisible by 4? Can you find an $a$ that does both? Finally, can you make $a$ close enough to $b$ so that $\frac{a}{b}$ is not too far from 1?


text:
Q: Android - Using this or getApplicationContext() in MyApplication class? I have created a MyApplication class that extends Application and have defined it in the manifest.
Within MyApplication's onCreate() method, is there any difference between using this or getApplicationContext() in order to get the application context?
(Presumably, the latter just exists because Application is a Context, but I just need to be sure.)

A: Your class MyApplication inherit indirectly from the Context class (Applicaiton > ContextWrapper > Context). So when you use the reference this as Context instance, you are just using the polymorphism concept.

is there any difference between using this or getApplicationContext() in order to get the application context?

There is no difference.


text:
Q: Match diacritics to latin alphabet equivalent How can I match lower case i and variants like í for example in ActionScript 3, please?
EDIT: The above is just an example, I am interested in matching all diacritics and special letters in general with a similar Latin Alphabet equivalent.
Thank you.

A: Unfortunately there is no relation (that I know of) behind the numeric character values of visually (and possibly audibly) similar characters. Hence, you will need to keep a lookup table between the regular 26 character alphabet and the diacritic versions of each character from that alphabet.


text:
Q: JS make element move by applying .css I wanted to make an element move on arrow press by applying .css() but its not working at all and I cant figure out why. The exactly same code is working perfectly with JQ animate(). Can you explain me why the .css is not working ? I know there are better ways to do this but I'm just curious why its not attaching the top property.Below is the code with animate
$(document).ready(function(){
    $('body').keydown(function() {
        if (event.which == 38)
        {
            $('div').animate({top:'-=10px'},'fast');
        }
        else if (event.which == 40)
        {
            $('div').animate({top:'+=10px'},'fast');
        }
        else if (event.which == 37)
        {
            $('div').animate({left:'-=10px'},'fast');
        }
        else if (event.which == 39)
        {
            $('div').animate({left:'+=10px'},'fast');
        }
    });
});

A: Moving div require space to move or you can use position:absolute
Demo

A: Using .css() to adjust a property requires that property to be explicitly set beforehand, whereas .animate() will adjust the calculated position of an element without it being specifically set.
In the below snippet, I have given the #movable element top and left properties, and left the other
 without them.  The selector that .css() is applied to affects both <divs>, but note that only the
 with the top and left properties moves.

$(document).ready(function(){
    $('body').keydown(function(event) {
        if (event.which == 38)
        {
            $('div').css({top:'-=10px'});
        }
        else if (event.which == 40)
        {
            $('div').css({top:'+=10px'});
        }
        else if (event.which == 37)
        {
            $('div').css({left:'-=10px'});
        }
        else if (event.which == 39)
        {
            $('div').css({left:'+=10px'});
        }

      //added to stop Stack Overflow scrolling
      event.preventDefault();
    });

});
div {
  position:relative;
}

/* Set top and left of the movable div explicitly */
#movable {
  top:0px;
  left:0px;
}

movable

immovable

A: Is the code in the post your real code? Because you're using an event variable, but you haven't defined any argument to the function passed to keydown. It needs to be $('body').keydown(function(event) {.


text:
Q: Spring sub state machine Exit point to parent machine I have successfully implemented a state machine and also a sub machine with a reference from the initial. Now I'm stuck at a point where I cannot think about any way of linking an exit point to it.
The links to my model is given.
https://drive.google.com/open?id=0B9PT7E5L1ac9LTZlZWV5bWx1V1U
https://drive.google.com/open?id=0B9PT7E5L1ac9RnR6UUtrMkRoZE0
If you look at it, I have referenced a sub-machine from "DirectQuery" State (marked in red in the parent machine- img2).
Now I have a problem in linking the exit point to the parent. If there are two exit points, how can I handle both of them?

A: Ok, currently not supported but I realised it's actually defined in spec and papyrus also have it(though a bit hidden in properties editor). Created gh-323 to implement this.


text:
Q: What happens if we define wrong flag for -mfpu? For example, if I have a chip -mcpu=cortex-a7 , I should define -mfpu=neon-vfpv4 , not -mfpu=neon . However, I'm wondering what will happen if I define -mfpu=neon on Cortex-A7? Will it just ignore the flag and don't do the SIMD, or what will it do with the wrong flag like that?

A: It will use an older set of NEON instructions (-mfpu=neon is for selecting the NEON instructions that are available on the Cortex-A8 core). For example, it will not include the VFMA instructions.
Note that from GCC 8 (still in development) you will be able to just use -mfpu=auto or leave out the -mfpu entirely and have the compiler pick the optimal FPU setting for the -mcpu option you selected

A: If you do this compiler won't use VFPv4 instructions and potentially generate suboptimal code.


text:
Q: Ununderstandable unit testing effects error using Jest I'm working on two nearly identical test cases where I should assert expect that two NgRx effects return a stream of booleans.
Everything works as expected in the first test case, and although doing the same for the second test case I can't make it to work as expected. Whatever I do, the received value is always an empty array:
expect(received).toEqual(expected) // deep equality
    - Expected
    + Received

    - Array [
    -   Object {
    -     "frame": 10,
    -     "notification": Notification {
    -       "error": undefined,
    -       "hasValue": true,
    -       "kind": "N",
    -       "value": true,
    -     },
    -   },
    - ]
    + Array []

Working test
logger.effects.spec.ts:
describe('LoggerEffects', () => {
    let actions$: Observable<ApiFailure>;
    let effects: LoggerEffects;
    const serviceMock = <AppLoggerServiceI>{ failure: ({ body, title }) => of(true) };
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [StoreModule.forRoot({})],
            providers: [
                LoggerEffects,
                provideMockActions(() => actions$),
                {
                    provide: 'appLoggerService',
                    useValue: serviceMock
                }
            ]
        });
        effects = TestBed.get(LoggerEffects);
    });
    const failure = new HttpErrorResponse({ error: 'HttpErrorResponse' });
    describe('logApiFailure$', () => {
        it('should return a stream of boolean if the dispatched action is ApiActions.searchFailure', () => {
            const action = ApiActions.searchFailure({ failure });
            actions$ = hot('-a--', { a: action });
            const expected = cold('-b--', { b: true });
            expect(effects.logApiFailure$).toBeObservable(expected);
        });
    });
});

logger.effects.ts:
logApiFailure$ = createEffect(
        () =>
            this.actions$.pipe(
                ofType(ApiActions.searchFailure),
                exhaustMap(({ failure: { body, title } }) =>
                    this.appLoggerService.failure({
                        body,
                        title
                    })
                )
            ),
        { dispatch: false }
    );

Failed test
router.effects.spec.ts:
describe('RouterEffects', () => {
    let actions$: Observable<boolean>;
    let effects: RouterEffects;

    const routerMock = <Partial<Router>>{ navigate: (commands: any[]) => Promise.resolve(true) };

    let router: Router;
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [StoreModule.forRoot({})],
            providers: [
                RouterEffects,
                provideMockActions(() => actions$),
                {
                    provide: Router,
                    useValue: routerMock
                }
            ]
        });
        effects = TestBed.get(RouterEffects);
    });
    describe('navigateTo$', () => {
        it('should return a stream of boolean if the dispatched action is RouterActions.navigateTo', () => {
            const action = RouterActions.navigateTo();
            actions$ = hot('-a--', { a: action });
            const expected = cold('-b--', { b: true });
            console.log('toto', effects.navigateTo$);
            expect(effects.navigateTo$).toBeObservable(expected);
        });
    });
});

router.effects.ts:
navigateTo$ = createEffect(
    () =>
        this.actions$.pipe(
            ofType(RouterActions.navigateTo),
            exhaustMap(() => this.router.navigate(['my-route', {}]))
        ),
    { dispatch: false }
);

At this point, I'm assuming there's something wrong with the Hot Observable in router.effects.spec.ts which prevents the effect to dispatch the navigateTo action. Do you have any thoughts about it?
The project's dependencies
{
    "dependencies": {
        "@angular/animations": "^8.0.0",
        "@angular/cdk": "^8.0.0",
        "@angular/common": "^8.0.0",
        "@angular/compiler": "^8.0.0",
        "@angular/core": "^8.0.0",
        "@angular/forms": "^8.0.0",
        "@angular/material": "^8.0.0",
        "@angular/material-moment-adapter": "^8.0.0",
        "@angular/platform-browser": "^8.0.0",
        "@angular/platform-browser-dynamic": "^8.0.0",
        "@angular/router": "^8.0.0",
        "@ngrx/effects": "^8.0.0",
        "@ngrx/router-store": "^8.0.0",
        "@ngrx/store": "^8.0.0",
        "core-js": "^2.5.4",
        "hammerjs": "^2.0.8",
        "moment": "^2.24.0",
        "rxjs": "^6.5.0",
        "tslib": "^1.9.0",
        "zone.js": "^0.9.1"
    },
    "devDependencies": {
        "jest-preset-angular": "7.0.0",
        "@angular-devkit/build-angular": "^0.800.0",
        "@angular-devkit/build-ng-packagr": "~0.800.0",
        "@angular-devkit/core": "^8.0.2",
        "@angular-devkit/schematics": "^8.0.2",
        "@angular/cli": "8.0.0",
        "@angular/compiler-cli": "^8.0.0",
        "@angular/language-service": "^8.0.0",
        "@ngrx/schematics": "^8.0.0",
        "@ngrx/store-devtools": "^8.0.0",
        "@nrwl/cypress": "8.1.0",
        "@nrwl/jest": "8.1.0",
        "@nrwl/workspace": "8.1.0",
        "@nrwl/schematics": "8.1.0",
        "@types/jest": "24.0.9",
        "@types/node": "^12.0.7",
        "codelyzer": "~5.0.1",
        "cypress": "~3.3.1",
        "dotenv": "6.2.0",
        "jest": "24.1.0",
        "ng-packagr": "^5.1.0",
        "prettier": "1.16.4",
        "ts-jest": "24.0.0",
        "ts-node": "^8.2.0",
        "tsickle": "^0.35.0",
        "tslib": "^1.9.0",
        "tslint": "~5.11.0",
        "typescript": "~3.4.5"
    }
}

A: I just spent some time tracking down a similar issue (empty expected array) and the problem turned out to be related to asynchronous code that was not managed by the TestScheduler. In my case I was using from([Promise]). To fix the issue I mocked the function returning a promise to return an observable of().
This issue helped me a lot and explains the problem clearly:
https://github.com/cartant/rxjs-marbles/issues/11
In your case I believe the problem is being caused by this.router.navigate(['my-route', {}]) which returns a promise, not an observable.
Try mocking router.navigate to return of(true).


text:
Q: How to stop a service from a service I am using location listerner in a service, and i have overriden onLocationChanged(Location) method. Now i want that whenever this method is called for the first time, i want to stop the service. So please tell me how to do it

A: Call stopSelf from the onLocationChanged method (assuming the Service itself implements that interface).


text:
Q: How can i make that in the timer my program will do something every second? In the top of MainActivity.java i added:
private Handler customHandler = new Handler();
long timeSwapBuff = 0L;

Then inside the onCreate i did:
@Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread,0);

        timerValue = (TextView) findViewById(R.id.timerValue);

        startButton = (Button) findViewById(R.id.startButton);

        startButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                startTime = SystemClock.uptimeMillis();
                customHandler.postDelayed(updateTimerThread, 0);

            }
        });

        pauseButton = (Button) findViewById(R.id.pauseButton);
        pauseButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                customHandler.removeCallbacks(updateTimerThread);

            }
        });

Then in the updateTimerThread:
private Runnable updateTimerThread = new Runnable() {

        public void run() {

            long updatedTime = 0L;
            long timeInMilliseconds = 0L;
            timeInMilliseconds = SystemClock.uptimeMillis() - startTime;//System.currentTimeMillis() - startTime;
            updatedTime = timeSwapBuff + timeInMilliseconds;

            int secs = (int) (updatedTime / 1000);
            int mins = secs / 60;
            secs = secs % 60;
            int milliseconds = (int) (updatedTime % 1000);
            timerValue.setText("" + mins + ":"
                    + String.format("%02d", secs) + ":"
                    + String.format("%03d", milliseconds));
            customHandler.postDelayed(this, 0);
        }

    };

Now each time i run my program from the start the timer will start from 00:00:00
Now i want to add somehow something that each second to do something.
Not to reset the timer not to pause or stop it to let it keep running but each second i want to do something else in my program.
The problem is how do i check every second to do something ?


text:
Q: How to send message to specific socket with Phoenix I have some socket with verification:
defmodule Test.UserSocket do
  use Phoenix.Socket

  ## Channels
  channel "user:*", Test.RoomChannel

  def connect(_params, socket) do
    case Phoenix.Token.verify(socket, "user",  _params["token"]) do
          {:ok, uid} ->
            {:ok, assign(socket, :user_id, uid)}
          {:error, _} ->
            :error
     end
  end

 def id(_socket), do: "user:#{_socket.assigns.user_id}"
end

And after connect socket named like user:#id
From the documentation I can send disconnect event
Test.Endpoint.broadcast("users_socket:" <> user.id, "disconnect", %{})
Question: How to send custom event to socket by user:#id, it should be like a push notification to specific socket.
I tried Test.Endpoint.broadcast "user:1", "new:msg", %{user: "SYSTEM", body: "iex"} but it's doesn't work, because i can't listen "new:msg" on socket.

A: Copying Chris McCord's answer down from the comment:
You do it on a channel like you described. You don't need to verify in join/3 if you've already verified and assigned a current user on the socket in connect. Just check socket.assigns.user_id against whatever room the user is trying to join. Then you broadcast to that room Endpoint.broadcast "rooms:1", "new_msg", %{user: "SYSTEM", body: "iex"}
(Marking answer as community wiki since I don't want the rep points if anyone decides to upvote this. It's not my answer :) )

A:
Thanks for the answer. So we works only on 'room' bases. And my
  sources will be like: def join("user:"<> _uid, message, socket) do if
  _uid == socket.assigns.user_id do {:ok, socket} else {:error, %{reason: "unauthorized"}} end end

you don't need to verify the userId again since you already have defined the logic in UserSocket#connect if the user is not authenticated he gets a message that he is not authorize, what you can do is use the userId to check if the user has permission to view a specific channel for instance
def join("rooms:some_private_room", message, socket) do
  if socket.assigns.user_id do
    {:ok, socket}
  else
    # kick him out he is not allowed here
    {:error, %{reason: "unauthorized"}}
  end
end


text:
Q: Is there the technical possibility in Gitlab that a custom adaption of the repository content is Dome during the merge? Is there the possibility that I can add e.g. a script which is executed during the merge Step in gitlab which can change some content of the repository?
Standard Workflow which is fully Supported with GitLab

*

*Create Merge Request in GitLab

*Add it to merge train to be merged

*Gitlab creates merge commit (temporary) if no conflicts are detected

*Pipeline runs to do some Integration steps

*Merge commit is pushed if pipeline execution was successful

What I Need additional:
I want to execute a Script after step 3 which might change again some files of the repository. These changes should be integrated in the merge commit.
Something like executing a cleaner Script which is executed after the git merge before the merge commit is done (and this on remote side in Gitlab as part of the merge process).
Does anyone have an idea with a technical Solution?
I would really appreciate it

A: It's possible, but it's not straightforward. What you are building is basically a bot, which will have to assume some kind of personality in order to modify the code, commit and push it to the repository (ideally - via a MR).
We're using such an approach for cases like:

*

*automated bumping of VERSION files

*automating merge requests in repo B, based on changes in repo A

*etc.

Solution
The solution is maybe a bit more generic than what you actually need, so you might need to simplify, but it works quite well.
You will need:

*

*A separate repo, where you will store the automation, let's call it bot repo

*An Access Token created in the target repo, with api, write_repository scopes, let's call it AUTO_MR_TOKEN

*A secret created in bot repo, with the contents of the AUTO_MR_TOKEN
In the bot repo you would create a gitlab-ci.yml which would have the following step:
add_mr:
  script:
    # SETUP THE ENVIRONMENT HERE
    - TARGET_REPO="https://oauth2:${AUTO_MR_TOKEN}@${CI_SERVER_HOST}/${TARGET_PROJECT}.git"
    # CLONE THE TARGET REPO
    - git clone -b $TARGET_BRANCH --single-branch $TARGET_REPO
    - git config user.email "${GIT_USER_EMAIL:-$GITLAB_USER_EMAIL}"
    - git config user.name "${GIT_USER_NAME:-$GITLAB_USER_NAME}"
    # MAKE CHANGES
    - echo "DO YOUR MAGIC HERE"
    - |
      git commit -m "commit from bot"
      git push origin master $TARGET_BRANCH \
        -o merge_request.create \
        -o merge_request.target=master

Then, in the target repo - you would trigger this bot job, depending on your workflow, in the appropriate step of your pipeline.


text:
Q: Errorjava sql.SQLException: Parameter index out of range (1 >) i have an error with my Code, but i don't know what is...
(Java + MySQL)
public void deleteClientes(int nit){
   sql = "DELETE FROM `clientes` WHERE `clientes`.`nit` =  ";
   delete(sql,nit);

}
Method that receives:
 public void delete(String sql,int id){
    final QueryRunner qr = new QueryRunner(true);
    try {
        qr.update(conexion(),sql,"%"+id+"%");
    } catch (SQLException ex) {
       System.err.println("Error"+ex);
    }
}

A: Your query doesn't have a placeholder ?. It should be:
"DELETE FROM `clientes` WHERE `clientes`.`nit` =  ?"

A: Need to add ? into sql statement where data will be placed based on parameter
sql = "DELETE FROM `clientes` WHERE `clientes`.`nit` =  ?";

and
 qr.update(conexion(),sql,id);


text:
Q: Python: How do I insert a string into a specific spot in a .txt file? I have a .txt file with a variable called id=
How can I write a script that will look into that .txt file, find id= and insert a string right after the =?
I do have a separate .py file called dictionary that contains a dictionary with the purpose of finding and replacing certain words in the .txt file.
Could I also use this dictionary as a way to find and insert?

A: Read the file line by line,  if line has 'id=' replace it with the builtin replace method of str and write the new line, else write the old line.
with open(path_to_file) as fp:
  with open(path_to_new_file, 'w') as nfp:
    string = "whatever"
      for line in fp:
        if "id=" in line:
          new_line = line.replace("id=", f"id={string}")
          print(f"replacing {line} with {new_line}")
          nfp.write(new_line)
        else:
          nfp.write(line)


text:
Q: Using JobQueue to continuously refresh a message I'm building a Telegram bot that uses ConversationHandler to prompt the user for a few parameters and settings about how the bot should behave. This information is stored in some global variables since it needs to be available and editable by different functions inside the program. Every global variable is a dictionary in which each user is associated with its own value. Here's an example:
language = {123456: 'English', 789012: 'Italian'}

where 123456 and 789012 are user ids obtained from update.message.from_user.id inside each function.
After all the required information has been received and stored, the bot should send a message containing a text fetched from a web page; the text on the web page is constantly refreshed, so I want the message to be edited every 60 seconds and updated with the new text, until the user sends the command /stop.
The first solution that came to my mind in order to achieve this was something like
info_message = bot.sendMessage(update.message.chat_id, text = "This message will be updated...")
...
def update_message(bot, update):
    while True:
        url = "http://example.com/etc/" + language[update.message.from_user.id]
        result = requests.get(url).content
        bot.editMessageText(result, chat_id = update.message.chat_id, message_id = info_message.message_id)
        time.sleep(60)

Of course that wouldn't work at all, and it is a really bad idea. I found out that the JobQueue extension would be what I need. However, there is something I can't figure out.
With JobQueue I would have to set up a callback function for my job. In my case, the function would be
def update_message(bot, job):
    url = "http://example.com/etc/" + language[update.message.from_user.id]
    result = requests.get(url).content
    bot.editMessageText(result, chat_id = update.message.chat_id, message_id = info_message.message_id)

and it would be called every 60 seconds. However this wouldn't work either. Indeed, the update parameter is needed inside the function in order to fetch the page according to the user settings and to send the message to the correct chat_id. I'd need to pass that parameter to the function along with bot, job, but that doesn't seem to be possible.
Otherwise I would have to make update a global variable, but I thought there must be a better solution. Any thoughts? Thanks.

A: I had the same issue. A little digging into the docs revealed that you can pass job objects a context parameter which can then be accessed by the callback function as job.context.

context (Optional[object]) – Additional data needed for the callback function. Can be accessed through job.context in the callback. Defaults to None

global language
language = {123456: 'English', 789012: 'Italian'}
j=updater.job_queue

context={"chat_id":456754, "from_user_id":123456, "message_id":111213}

update_job = job(update_message, 60, repeat=True, context=context)
j.put(update_job, next_t=0.0)

def update_message(bot, job):
    global language
    context=job.context
    url = "http://example.com/etc/" + language[context["from_user_id"]]
    result = requests.get(url).content
    bot.editMessageText(result,
                    chat_id = context["chat_id"],
                    message_id = context["message_id"])


text:
Q: How do I remove the Guest Session option from the shutdown menu? On the Indicator Shutdown menu in Ubuntu 10.04, there is a "Guest Session" option. How do I remove this?

A: One way is to remove the gdm-guest-session package:
Open software center and search for gdm-guest-session and uninstall it.
Or from the command line:
sudo apt-get remove gdm-guest-session


text:
Q: Operator == Overload for Derived Classes in C++ I am writing a program that has different shape classes
There is a base shape class similar to the following:
class Shape
    {
    public:
        Shape(int x, int y, int size, COLORREF colorRef);
        ~Shape();
        bool operator == (const Shape&) const;
        int x() const;
        int y() const;
        int size() const;

    protected:
        int xCoord;
        int yCoord;
        int shapeSize;
        COLORREF color;
    };

And then some derived classes similar to the following:
class Circle : public Shape
    {
    public:
        Circle(int x, int y, int size, COLORREF colorRef) : Shape(x, y, size, colorRef)
        {
            this->radius = (double)shapeSize / 2;
            this->xCenter = (double)xCoord + radius;
            this->yCenter = (double)yCoord - radius;
        }
        ~Circle() {}

    private:
        double radius;
        double xCenter;
        double yCenter;
    };

class Square : public Shape
    {
    public:
        Square(int x, int y, int size, COLORREF colorRef) : Shape(x, y, size, colorRef) {}
        ~Square() {}
    };

class Triangle : public Shape
    {
    public:
        Triangle(int x, int y, int size, COLORREF colorRef) : Shape(x, y, size, colorRef) {}
        ~Triangle() {}
    };

I would like to overload the == operator in the shape class so that I can determine if 2 shapes are identical. If I could assume both shapes being compared were of the same class then I know it would be fairly straight forward, but how do I go about testing whether 2 objects of the different derived classes are equal? For example, how do I determine that Triangle t != Circle c?

A: You have to determine which function to call based on type of two objects. This pattern in C++ is called double-dispatch (or Visitor pattern).
The most common implementation assumes that all derived classes (shapes in your example) are known - so you can list them in base class:
class Circle;
class Rectangle;
// all shapes here
class Shape {
public:
   virtual ~Shape() = default; // good habit is to add virtual destructor to all polymorphic classes (those with virtual methods)

   bool operator == (const Shape& other) const {
      return equalTo(other);
   }

   virtual bool equalTo(const Shape& other) const = 0;
   virtual bool doEqualTo(const Circle& other) const { return false; }
   virtual bool doEqualTo(const Rectangle& other) const { return false; }
   // etc.. for all other shapes

};

class Circle : public Shape {
  // ...
protected:
     virtual bool equalTo(const Shape& other) const
     {
         return other.doEqualTo(*this); // call doEqualTo(Circle) - first virtual dispatch
     }
     virtual bool doEqualTo(const Circle& other) const
     {
         return other.center == center && other.radius == radius; // second virtual dispatch
     }

};

As you can see - to perform action - you have to call 2 virtual functions (so double-dispatch)

A: Ok, here's an idea for using the curious recurring template pattern to make implementing derived classes easier while allowing the == operator to work as expected.  This maybe overkill, but it should work for your scenario.
Start by filling out your base Shape class.  Added to your basic definition is an implementation of operator== that invokes a helper called CompareTypesAndDimensions.  The function calls into two virtual methods, TypeCompare and Compare.
class Shape
{
public:
    Shape(int x, int y, int size, COLORREF colorRef) : xCoord(x), yCoord(y), shapeSize(size), color(colorRef) {}

    virtual ~Shape() {}; // need at least one virtual member for dynamic_cast

    int x() const { return xCoord; }
    int y() const { return yCoord; }
    int size() const { return shapeSize; }
    COLORREF col() const { return color; };

    bool operator == (const Shape& other) const
    {
        return CompareTypesAndDimensions(other);
    }

    bool BaseShapeCompare(const Shape& other) const
    {
        return ((other.xCoord == xCoord) && (other.yCoord == yCoord) && (other.shapeSize == shapeSize) && (other.color == color));
    }

    virtual bool TypeCompare(const Shape& other) const = 0;
    virtual bool Compare(const Shape& other) const = 0;

    bool CompareTypesAndDimensions(const Shape& other) const
    {
        // make sure the types checks are reciprocals
        // we don't accidently compare a "Square" with a "Rectangle" if they inherit from each other
        if (TypeCompare(other))
        {
            return Compare(other);
        }
        return false;
    }

protected:
    int xCoord;
    int yCoord;
    int shapeSize;
    COLORREF color;
};

The idea being with the above is that Circle, Triangle, and Square could just implement their own version of TypeCompare and Compare and be done with it. But wait!  What if we could save some typing by having a template base class do some work for us - especially for validating that both compared instances are of the same type.  And not having to a stock Compare function for the simpler types such as Square and Triangle.
Let's introduce a template class that inherits from Shape.  This class, ShapeComparable provides the implementations for Compare and TypeCompare. The only thing it needs the concrete class below it to deal with is a method to handle comparing its own methods.
template <typename T>
class ShapeComparable : public Shape
{
public:

    ShapeComparable(int x, int y, int size, COLORREF colorRef) : Shape(x, y,size,colorRef)
    {}

    bool TypeCompare(const Shape& other) const override
    {
        auto pOtherCastToDerived = dynamic_cast<const T*>(&other);
        return (pOtherCastToDerived != nullptr);
    }

    bool Compare(const Shape& other) const override
    {
        if (BaseShapeCompare(other))
        {
            auto pOtherCastToDerived = dynamic_cast<const T*>(&other);
            if (pOtherCastToDerived)
            {
                return this->CompareDerived(*pOtherCastToDerived);
            }
        }
        return false;
    }

    // derived classes that don't have members to compare will just inherit this member
    virtual bool CompareDerived(const T& other) const
    {
        return true;
    }
};

The magic with the above is that TypeCompare utilizes a dynamic_cast to validate if the two instances being compared are of the same type.  If you try to compare a Triangle to a Circle, the dynamic cast fails.  Hence, operator== will return false.
Now let's see what the rest of the classes look like. Start with Circle, it inherits from ShapeComparable and provides an implementation for CompareDerived.
class Circle : public ShapeComparable<Circle>
{
public:
    Circle(int x, int y, int size, COLORREF colorRef) : ShapeComparable(x,y,size,colorRef)
    {
        this->radius = (double)shapeSize / 2;
        this->xCenter = (double)xCoord + radius;
        this->yCenter = (double)yCoord - radius;
    }

    bool CompareDerived(const Circle& other) const
    {
        // BaseCompare has already been invoked by the time this method is invoked.
        return ((other.radius == radius) && (other.xCenter == xCenter) && (other.yCenter == yCenter));
    }

private:
    double radius;
    double xCenter;
    double yCenter;
};

But Triangle and Square are as simple as it gets.
class Triangle : public ShapeComparable<Triangle>
{
public:
    Triangle(int x, int y, int size, COLORREF colorRef) : ShapeComparable(x, y, size, colorRef) {}
};

class Square : public ShapeComparable<Square>
{
    Square(int x, int y, int size, COLORREF colorRef) : ShapeComparable(x, y, size, colorRef) {}
};

And if you ever need to introduce a new property to Triangle and Square, you just need to provide a CompareDerived method.
The above works with the assumption is that you wouldn't have additional shapes derived from another concrete shape class. Otherwise, the CompareType function won't be reciprocal when comparing a Square to a Rhombus.


text:
Q: How do you change color of lines drawn in d3 with svg? I'm using this tutorial, Making a cool Bitcoin price chart using D3.js and the CryptoCompare API and I am having trouble styling the lines that are drawn.
For example, I would like to be able to select and style the lines x and y to change their color to white. See this snippet from the tutorial:
var x = d3.scaleTime()
    .range([0, width])
I've tried adding .attr("fill", "#fff"), but this only breaks it. How do I change the colors of d3.scaleTime() and d3.scaleLinear()?
I have also tried the following as described in the d3-scale documentation:
var x = d3.scaleTime()
    .range([0, width])

x(20); // "#9a3439"

Here's the entire script:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

    <svg width="960" height="500"></svg>

Bitcoin Prices in U.S. Dollars

A: You can style the axes as shown below.
var xAxis = g.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

xAxis.select("path") //Axis
    .style("stroke","white");

xAxis.selectAll("line") //ticks
    .style("stroke","white");

var yAxis = g.append("g")
    .call(d3.axisLeft(y));

 yAxis.append("text")
    .attr("fill", "#000")
    .attr("transform", "rotate(-90)")
    .attr("y", 20)
    .attr("text-anchor", "end")
    .attr("font-size", "1.2em")
    .text("Price ($)");

yAxis.select("path") //Axis
    .style("stroke","white");

yAxis.selectAll("line") //ticks
    .style("stroke","white");

<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>

  <svg width="960" height="500"></svg>

Bitcoin Prices in U.S. Dollars

A: While Gilsha's answer seems like best practice and allows for more direct control over styling, the answer got from that was to use selectAll() to select and style each "path" (axes), "line" (ticks), and "text" (display of price and date).
Including the following in the end of the function d3.json(url).get(function(error, d) styles everything as white:
g.selectAll("path") //Axes
    .style("stroke","white");

g.selectAll("line") //Ticks
    .style("stroke","white");

g.selectAll("text") //Text displaying date and price
    .attr("fill", "white");

Note that this broad-stroke approach includes the path for the plotted data line as well. If you need to distinguish between them, you can define a variable for that and style it independently as Gilsha did for the axes.