text:
Q: How to fix this error on running a vbs script with Python? The VBScript I want to run through Python with Wscript.exe is a looping one type (when you press OK, it will pop up again). It is located in a folder called "extras", let's say on the Desktop folder. It CAN open the file with Wscript, but pressing OK won't work (causes an error). The Python script works, but the VBScript doesn't. I am very confused what causes the error (Error code: 80070002, cannot find file). Running it without Python works fine. Below is my Python code:
import os, subprocess

workingdir = os.getcwd()
programname = "wscript.exe"
filename = "runme.vbs"
fileloc = f"{workingdir}\extras\{filename}"

print(fileloc)
subprocess.Popen([programname, fileloc])

And maybe if you need the VBScript (named runme.vbs) code:
X = MsgBox("Hello world!", 64)
Set WSHShell = WScript.CreateObject("WScript.Shell")
WSHShell.Run "runme.vbs"
Set WSHShell = WScript.CreateObject("WScript.Shell")
WSHShell.Run "runme.vbs"


text:
Q: ¿Como crear un archivo de redireccion con destinos diferentes en PHP? Me explico, uso publicidad en mi pagina web. pero tengo 2 proveedores diferentes por cada publicidad, entonces lo que quiero es que cuando un usuario le de click en el barner, lo lleve a un archivo PHP que contenga los 2 destinos, si el usuario hace click la primera vez, que lo lleve al primero, si lo hace por una segunda vez que lo lleve al segundo, si lo hace por una tercera vez, entonces que empiece otra vez con el primero. que sea un ciclo. o en su defecto, que sea por segundos, es decir que el PHP, tenga una secuencia que cada tantos segundos, cambie entre 2 destinos diferentes. Tengo esto hasta ahora:
            if(){
                header ('Location: http://www.misitio1.com');

            }else{

                header ('Location: http://www.misitio2.com');
            }

A: Como te expuse en el comentario, por ejemplo puedes comprobar si el segundo o minuto es par o impar, o utilizar cualquier otra formula con numeros pseudo-aleatorios por ejemplo.
Ejemplos:
Puedes optener un numero variable con alguna de las siguientes formas:
// minutos
$numero = date('i');
// segundos
$numero = date('s');
// numeros pseudo-aleatorios
$numero = mt_rand();

Luego simplemente compruebas si es par o impar
if($numero%2==0){
    // PAR
    header ('Location: http://www.misitio1.com');
}else{
    // IMPAR
    header ('Location: http://www.misitio2.com');
}

Siguiendo la misma fórmula podemos crear un rango de segundos, de 0 a 30 a un sitio, de 31 a 60 otro, ejemplo:
if(date('s') <= 30){
    // segundo menor o igual a 30
    header ('Location: http://www.misitio1.com');
}else{
    // segundo mayor a 30
    header ('Location: http://www.misitio2.com');
}

A: Siguiendo la idea de Xerif , solo que lo lo haría con un contador almacenado en la session, ya que con el tiempo se puede repetir la redirección.
session_start();

if (!isset($_SESSION['clicks'])) {
    $_SESSION['clicks'] = 0;
}
$clicks = $_SESSION['clicks'];

$_SESSION['clicks'] = $clicks + 1;

if ($clicks % 2 == 0) {
    header ('Location: http://www.misitio1.com');
}else{
     header ('Location: http://www.misitio2.com');
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: When a value changes it then is transfered to another sheet but also retains each change So if N11 from sheet1 changes then it's posted to A2 in sheet2 but then next input from N11 would go to A3 and so on. I tried this code, I'm not to familiar with VBA and just trying out new things in excel for a personal project. This code was pulled from another forum that someone tried to help me with but haven't heard back yet. I'm using a formula in N11 and trying to get that number pasted to Sheet2 to A3 once that value changes, so I can record a range of data and make a chart from that.
Found from other forum I think it worked cause he said if it's a formula it might works with this Worksheet_calculate
Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = Me.Range("N11").Address Then
        With Worksheets("Sheet2")
            .Cells(.Rows.Count, 1).End(xlUp)(2, 1).Value = Target.Value
        End With
    End If
End Sub

A: If it is not working, did you make sure you placed the subroutine in the sheet's macro module? See image.
Private Sub Worksheet_Change(ByVal Target As Range)
   Dim lRow As Long
   MsgBox ("Hello")
   If Target.Address(0, 0) = "B2" Then
      lCol = Worksheets("Sheet2").Cells(1, Columns.Count).End(xlToLeft).Column
      Worksheets("Sheet2").Cells(1, lCol + 1).Value = Target.Value
   End If
End Sub


text:
Q: Feature Create Swift Virtual Network is not allowed for a free trial subscription I was trying to create Virtual Network (using #terraform), but this operation failed with error message "Feature Create Swift Virtual Network is not allowed for a free trial subscription".
Here is the complete Error: creating/updating App Service VNet association between "res-fnc-uat" (Resource Group "res-uat") and Virtual Network "res-vnet-uat": web.AppsClient#CreateOrUpdateSwiftVirtualNetworkConnectionWithCheck: Failure responding to request: StatusCode=400 — Original Error: autorest/azure: Service returned an error. Status=400 Code="BadRequest" Message="Feature Create Swift Virtual Network is not allowed for a free trial subscription." Details=[{"Message":"Feature Create Swift Virtual Network is not allowed for a free trial subscription."},{"Code":"BadRequest"},{"ErrorEntity":{"Code":"BadRequest","ExtendedCode":"52018","Message":"Feature Create Swift Virtual Network is not allowed for a free trial subscription.","MessageTemplate":"Feature {0} is not allowed for a free trial subscription.","Parameters":["Create Swift Virtual Network"]}}]
│with module.modules.azurerm_app_service_virtual_network_swift_connection.network-swiftcon,
│ on ../../modules/networking.tf line 51, in resource "azurerm_app_service_virtual_network_swift_connection" "network-swiftcon":
│ 51: resource "azurerm_app_service_virtual_network_swift_connection" "network-swiftcon" {
I was not aware about the solution.

A: There are limitations for trial subscriptions.
https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/azure-subscription-service-limits#app-service-limits
For App Services, you can't enable Vnet Integration, for any App Service SKU.

If you want to test this feature, you need a "Pay as you go" subscription.


text:
Q: Insert values for whole column in SQL Server Is there any way to insert different values for specific column, not whole row in SQL Server.
Classic UPDATE SET would set all to same value.

For example I want to set some int values to Ranking column for each of 3 rows, without dropping them and doing complete new insert into.

A: Use row_number()
  update a set ranking =rn from tablename a join
    (select id,name, row_number() over(order by id) as rn
        from tablename) b on a.id=b.id

A: do update
update tabale
  set ranking= your_va

   with cte as
   (
    select * ,row_number() over(order by id) rn
   ) update cte set ranking=rn where id<=3

A: What value do you want to set ranking to?
Just any value:
update mytable set ranking = id;

Certain values:
update mytable set ranking =
  case name
    when 'Positive' then 1
    when 'Neutral'  then 2
    when 'Negative' then 3
                    else 4
  end;


text:
Q: How do I save additional content into my UIManagedDocument file packages? I'm having a lot of trouble deciphering Apple's documentation around UIManagedDocument, specifically the following methods:

*

*- (id)additionalContentForURL:(NSURL *)absoluteURL error:(NSError **)error

*- (BOOL)readAdditionalContentFromURL:(NSURL *)absoluteURL error:(NSError **)error

*- (BOOL)writeAdditionalContent:(id)content toURL:(NSURL *)absoluteURL originalContentsURL:(NSURL *)absoluteOriginalContentsURL error:(NSError **)error
Has anyone successfully managed to save additional content into the "addition content" directory inside their UIManagedDocument packages? I'm looking to save straight images (PNGs, JPEGs, etc) and videos (m4v, etc) into this directory using UUIDs as the filenames (with the correct file extension), and storing references to these individual files as NSString file paths within my persistent store.

A: The documentation for -additionalContentForURL:error: indicates that returning a nil supposed to signal an error.
  A return value of nil indicates an error condition. To avoid generating
  an exception, you must return a value from this method. If it is not always
  the case that there will be additional content, you should return a sentinel value (for example, an NSNull instance) that you check for in
  writeAdditionalContent:toURL:originalContentsURL:error:.

I override -writeContents:andAttributes:safelyToURL:forSaveOperation:error: for another purpose (doing some stuff on first save of a new document), and calling super invokes the NSException gods because contents value is nil, not an NSDictionary as seemingly expected by UIManagedDocument. Hmm.
The more you know...
P.S. I guess it depends on the time of day with -writeContents:andAttributes:...  It once threw an exception complaining about expecting an NSDictionary, but later threw an exception complaining that I didn't pass it an NSData. My eyebrow could not be raised in a more Spock-like fashion than it is right now.

A: Credit goes to Apple DTS for helping me understand this class. I'm sharing some of the example they helped me with here (modified slightly).
OK, so basically it works like this: subclass UIManagedDocument, and implement the following methods (where the extraInfo property is just an NSDictionary implemented on our subclass):
- (BOOL)readAdditionalContentFromURL:(NSURL *)absoluteURL error:(NSError **)error
{
   NSURL *myURL = [absoluteURL URLByAppendingPathComponent:@"AdditionalInformation.plist"];
   self.extraInfo = [NSDictionary dictionaryWithContentsOfURL:myURL];
   return YES;
}

- (id)additionalContentForURL:(NSURL *)absoluteURL error:(NSError **)error
{
   if (!self.extraInfo) {
       return [NSDictionary dictionaryWithObjectsAndKeys: @"Picard", @"Captain", [[NSDate date] description], @"RightNow", nil];
   } else {
       NSMutableDictionary *updatedFriendInfo = [self.extraInfo mutableCopy];
       [updatedFriendInfo setObject:[[NSDate date] description] forKey:@"RightNow"];
       [updatedFriendInfo setObject:@"YES" forKey:@"Updated"];

       return updatedFriendInfo;
   }
}

- (BOOL)writeAdditionalContent:(id)content toURL:(NSURL *)absoluteURL originalContentsURL:(NSURL *)absoluteOriginalContentsURL error:(NSError **)error
{
   if (content) {
       NSURL *myURL = [absoluteURL URLByAppendingPathComponent:@"AdditionalInformation.plist"];
       [(NSDictionary *)content writeToURL:myURL atomically:NO];
   }

   return YES;
}

UIManagedDocument will call these methods when it needs to, automatically saving whatever you need to save to the document package inside an AdditionalContent directory.
If you need to force a save, simply call the following on your UIManagedDocument instance:
[self updateChangeCount:UIDocumentChangeDone];

At present, I'm not using this for images and videos — but the example should give you enough to go off.


text:
Q: Нужно ли использовать оператор lock при записи файла в .net 5 api??? c# (код ниже) public static async Task<string> SaveImageAsync(string base64)
{
    var normalizedBase64 = base64.Substring(base64.LastIndexOf(',') + 1);
    var bytes = Convert.FromBase64String(normalizedBase64);
    var newFileName = Guid.NewGuid() + GetFileExtension(normalizedBase64);
    await File.WriteAllBytesAsync(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", newFileName), bytes);
    return newFileName;
}

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

Если потребуется синхронизировать доступ к общим файлам, то можно так:

*

*Запись в файл из разных потоков


text:
Q: call tracker-search from php I try to run gnome tracker-search from php. For example like this:
<?php
   $result = shell_exec("/usr/bin/tracker-search -l 5 --disable-snippets --disable-color test");
   echo "<pre>$result</pre>";
?>

But the output is empty. When I run /usr/bin/tracker-search --help in php, I get the help output. I also try to put tracker-search in the visudo file, but it have also no effect.
Have anybody an Idea what's happen here?


text:
Q: What is the best way to backfill old database data to an existing Postgres database? A new docker image was recently stood up to replace an existing postgres database. A dump was taken of the database before the old instance was shut down using the following command:
pg_dump -h localhost -p 5432 -d *dbname* -U postgres > *dbname*.pgdump
We'd like to concatenate or append this data to the new database in order to "backfill" some older historical data. The database name and schema of the two databases is identical. What is the easiest, safest way to do this? Secondly, need postgres be shut down during the process?

A: If overlapping primary keys or unique columns have been assigned to the new data, then there will be no clean way to merge them without putting in some work to clean that up. Assuming that hasn't happened...
The current dump file will have create statements for all the objects that already exists.  If you replay that file into the current database, you will get a bunch of errors for all those objects.  If you don't have it all run in one transaction, then you could simply ignore those errors.  But, you might also load data in the wrong order and get foreign key violations.  Those errors will be mixed in with all the other ones about existing object, so might be easy to overlook.
So what I would do is stand up an empty database server, and replay your current dump into that.  Then retake the pg_dump, but with either -a or --section=data.  Then you should be able to load that dump into your new database.  This has two advantages, it will not dump out CREATE statements which are not needed and throw errors which would need to be ignored, and it should dump the tables in an order which will not cause foreign key violations.


text:
Q: Error: java.lang.ClassNotFoundException:com.mysql.jdbc.Driver I am trying to connect to mysql database. I am using MySQL workbench. These are my codes:
 Class.forName("com.mysql.jdbc.Driver");
 con =DriverManager.getConnection("jdbc:mysql://localhost/try?" +"user=jenny&password=perez");

 PreparedStatement ps=con.prepareStatement("SELECT * FROM address");
 ResultSet myRS=ps.executeQuery();

What's wrong with my codes?

A: Your codes are correct. You come up with that error because you have no mysql connector. Try to download mysql-connector-java-5.1.18-bin. Install it here C:\Program Files\Java\jre6\lib. Then, Go to the properties of your project, then follow these:
Go to Libraries, then Compile, click Add JAR/Folder, then search the mysql connector you installed. Then run your program. ^_^


text:
Q: something went wrong with your request. please try again later - Magento 2.3.4 I have installed the stripe payment. And after I fill the payment details and try to place the order then I can see this error "something went wrong with your request. please try again later" When I check in admin then order is placed.
Can anyone help me to resolve this?


text:
Q: How to handle orientation change using fragment? I now have 2 fragment, one fragment handle portrait mode then another handle landscape mode. But the problem is that when rotate from portrait to landscape then back to portrait. It will not show the same thing that show on the first portrait mode. Is there any code that can solve this problem?
This code is inside the fragment holder:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.frag_holder);

    FragmentManager fm = getSupportFragmentManager();

    final Fragment fragment = Frag.newInstance(); //Portrait layout
    final Fragment fragment2 = Frag2.newInstance(); //Landscape layout

    int orientation = getResources().getConfiguration().orientation; //check whether is it portrait or landscape

    if(orientation == Configuration.ORIENTATION_PORTRAIT){
        Fragment fragTAG = fm.findFragmentByTag(TAG_P);
        if(fragTAG == null){
            Log.i("test","test");
                fm.beginTransaction()
                        .replace(R.id.fragPlaceHolder, fragment, TAG_P)
                        .commit(); //Portrait
        }
        else{
            fm.beginTransaction().replace(R.id.fragPlaceHolder,fragTAG).commit();
        }

    }
    if(orientation == Configuration.ORIENTATION_LANDSCAPE){
        Fragment fragTAG = fm.findFragmentByTag(TAG_L);
        if(fragTAG == null){
                fm.beginTransaction()
                        .replace(R.id.fragPlaceHolder, fragment2, TAG_L)
                        .commit(); //Landscape
        }
        else{
            fm.beginTransaction().replace(R.id.fragPlaceHolder,fragTAG).commit();
        }
    }

}

}

A: Step 1:
Add Config changes in your activity
    <activity android:name=".ui.createtasks.CreateTaskActivity"
        android:configChanges="orientation|screenSize|keyboardHidden" > </activity>

Step 2:
   Add your edit text values to onSaveInstanceState
 @Override
public void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
     outState.putCharSequence(KEY_TITLE, et_text.getText().toString());
 }

Step 3:
 Get your Saved edit text values through onViewStateRestored
    @Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
    super.onViewStateRestored(savedInstanceState);

    String savedTitle = null;
    if (savedInstanceState != null) {
        savedTitle = savedInstanceState.getString(KEY_TITLE);
        et_text.setText(savedTitle);

    }

}

A: You can either call setRetainInstance(True); in the onCreate() methods in both Fragments.
Or
to create a headless-Fragment(a Fragment with no UI) to cache data.
A third option will be to use onSaveInstanceState(Bundle outState) to cache data and re-display the data by using Bundle savedInstanceState in the onCreateView() method.

A: When there is activity rotation, the activity closed and reopen the onDestroy and onCreate are called.
if you want to save data and reload it in the other rotation you can do it with onSaveInstanceState method:
protected void onSaveInstanceState(Bundle outState)

for example:
@Override
public void onSaveInstanceState(Bundle outState)
{
    super.onSaveInstanceState(outState);
    outState.putString("name", "David");
    outState.putInt("age", 17);
}

and reload the data in the onCreate
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    …
    if(savedInstanceState != null)
    {
         savedInstanceState.getString("name");
         savedInstanceState.getInt("age");
    }
}

A: Add code in manifest file
<activity
        android:name=".file_name"//add your activity name
        android:label="label" //add label
        android:configChanges="orientation|screenSize|keyboardHidden"
        android:theme="@style/AppTheme.NoActionBar" />


text:
Q: Visualizar el contenido de una función php en Smarty Tengo el resultado de un carro de compra en una función que está dentro de una clase a la que llamo así:
$_SESSION["mycarrito"]->imprime_mycarrito();

la función definida se halla en un archivo funciones.php
Tengo mi archivo carro.php donde cargo toda la librería Smarty  y hago display en mi archivo carro.tpl
Hasta ahora llamo las variables así:
$smarty->assign("variable", $variable, true);

Y las imprimo en .tpl así {$variable}
Qué sintaxis debo utilizar para imprimir el contenido de la función imprime_mycarrito dentro del .tpl?
No se si estoy tomando el camino correcto al usar .tpl para mostrar el carrito, acepto consejos.
Muchas gracias!!

A: "Funciona pero me imprime la funcion desde el php, no responde desde {$print_carrito} y me coloca los datos por encima del  "
me suena a que tu función lo que hace es enviar el contenido directo al documento, algo como
echo 'alguna cosa';

si quieres capturar eso sin que salga al documento intercepta la salida con ob_start() y sus funciones asocidas, ob_get_clean así la puedes asignar a una variable y hacer lo que quieres
http://php.net/manual/es/ref.outcontrol.php

A: $_SESSION["mycarrito"]=imprime_mycarrito();
Asi le asignas el valor de la función, recuerda que esa función debe estar en el mismo documento en el que asignas el valor a la variable de sesión. Si no es así debes hacer un include_once de la clase que contiene esa función o llamarla de manera estática, eso depende de como lo hayas programado.
Por otro lado en el mismo documento en el que asignas ese valor a la variable de sesion debes hacer:
$smarty->assign("carrito", $_SESSION["mycarrito"]);
y tras inicializar todas tus variables de smarty desplegar el .tpl:
$smarty->display('../ruta/a/tu/plantilla.tpl');
despues en tu plantilla .tpl podras mostrar el contenido de {$carrito} pero la manera de hacerlo dependera del tipo que te devuelve la funcion imprime_mycarrito();
//por ejemplo si te devuelve un array de objetos con los atributos nombre y precio puedes hacer:

                Nombre
                precio

     {foreach $carrito as $indice=>$r}

                    {$r->nombre}
                    {$r->precio}

     {/foreach}

Si pones mas información acerca de la estructura que te devuelve tu función y como quieres mostrarlo te podría dar mas información.


text:
Q: in postgres, is it possible to optimize a VIEW of UNIONs in the database there are many identical schemas, cmp01..cmpa0
each schema has a users table
each schema's users table's primary key has its own unique range
for example, in cmp01.users the usr_id is between 0x01000000 and 0x01ffffffff.
is there any way I could define a VIEW global.users that is a union of each of the cmp*.union tables in such a way that, if querying by usr_id, the optimizer would head for the correct schema?
was thinking something like:
create view global.users as
select * from cmp01.users where usr_id between 0x01000000 and 0x01ffffffff
union all
select * from cmp02.users where usr_id between 0x02000000 and 0x02ffffffff
....

would this work?  NO.  EXPLAIN ANALYZE shows all schema used.
Is there an approach that might give good hints to the optimizer?

A: Why not create a table in a public schema that has all users in it, possibly with an extra column to store the source schema. Since the ids are globally unique, you could keep the id column unique:
create table all_users (
source_schema varchar(32),
usr_id int primary key,
-- other columns as per existing table(s)
);

Poluate the table by inserting all rows:
insert into all_users
select 'cmp01', * from cmp01.users union
select 'cmp02', * from cmp02.users union ...; -- etc

Use triggers to keep the table up to date.
It's not that hard to set up, and it will perform every well

A: What about creating a partitioned table? The master table would be created as global.users and it would be partitioned by the schema name.
That way you'd get the small user tables in each schema (including fast retrievals) provided you can create queries that PostgreSQL can optimize i.e. including the schema name in the where condition. You could also create a view in each schema that would hide the needed schema name to query the partitioned tables. I don't think it would work by specifying only the user_id. I fear that PostgreSQL's partitioning features are not smart enough for that.
Or use just one single table, and create views in each schema with an instead of trigger and limiting the result to that schema's users.

A: Try something like:
create view global.users as
select *
from (select 'cmp01' sel_schema, 0x01000000 usr_id_start, 0x01ffffffff usr_id_end
      union all
      select 'cmp02' sel_schema, 0x02000000 usr_id_start, 0x02ffffffff usr_id_end) s
join (select u1.*, 'cmp01' schema from cmp01.users u1
      union all
      select u2.*, 'cmp02' schema from cmp02.users u2) u
on s.sel_schema = u.schema

and include a condition like specified_usr_id between usr_id_start and usr_id_end when querying the view by a specified user ID.


text:
Q: Is it necessary to use throw keyword with Throwables.propagate(e)? In this code, do I need the throw keyword in order to propagate the exception?
try {
  //try something
} catch (Exception e) {
  throw Throwables.propagate(e);
}

The Throwables documentation says that this method always throws an exception - is adding the throw superfluous? Could I have written the following instead?
try {
  //try something
} catch (Exception e) {
  Throwables.propagate(e);
}

A: The javadoc also states

The RuntimeException return type is only for client code to make Java
  type system happy in case a return value is required by the enclosing
  method.

and then provides this example
T doSomething() {
  try {
    return someMethodThatCouldThrowAnything();
  } catch (IKnowWhatToDoWithThisException e) {
    return handle(e);
  } catch (Throwable t) {
    throw Throwables.propagate(t);
  }
}

In other words, the return type (RuntimeException) is necessary so you can use the method in return or throws statements.
In the above example, if you omitted the throw in the last catch block, then the Java compiler would report an error because it cannot guarantee that a value will be returned from that catch block. A return or throws instead indicate that the method completes at that point, abruptly.


text:
Q: Making a telegram app using cloudRail, how do I listen to the response from the user? I am making a little app for telegram using CloudRail. This is my node.js server. The node.js sends message to a telegram user when it receives a POST request of kind "sendMessage". But I also want to be able to receive the responses that users sends. How do I listen to the responses the user makes?
var express = require('express');
var router = express.Router();
var http = require('http');
var fs = require('fs');

const cloudrail = require("cloudrail-si");
cloudrail.Settings.setKey("pass");

const service = new cloudrail.services.Telegram(
    null,
    "botkey",
    "webhook"
);

function sendMessage(user,message){
    service.sendMessage(
    user,
    message,
        (error, result) => {
            if(error){ console.log("hubo un error");}
            // Check for potential error and use the result
        }
    );
}

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post("/",function(req,res,next){
    service.parseReceivedMessages(
        httpRequest: stream.Readable,
        (error, result) => {
            sendMessage("219148418","esta es mi respuesta");
            // Check for potential error and use the result
        }
    )
    if(req.method ==="POST" && req.body.kind != undefined && req.body.kind=="postMessage"){
        var user_id = req.body.user_id;
        var message = req.body.message;
        sendMessage(user_id, message);
    }
});

module.exports = router;

A: The parseReceivedMessages receieves type Message which is a response from the user.
See the example:
https://github.com/CloudRail/cloudrail-si-node-sdk/blob/master/examples/unified-messaging/index.js


text:
Q: why does not python3 for loop overwrite variables? for beginner type question but can somebody tell me why does python 3 dont overwrite the below variable
in this line output = output + s1/output = output + s2
in short can anyone tell inner workings of this==>output = output + s2
is it getting assign ref variable? or storing the value in it?
s=input("enter your string: ") #A132BC
S1=''
S2=''
output=''
for x in s:
    if x.isalpha():
        S1=S1 + x
    else:
        S2=S2 + x
for s1 in sorted(S1):
    output = output + s1 #output = '' + A==>  output = 'A'
for s2 in sorted(S2):
    output = output + s2
print(output)

A: In Python everything is an object that is treated as references.
S1 = "" creates the value "" and stores the reference into the name S1. If later you do S1 = "Hello, world!, the interpreter creates a new value an assigns this new reference to S1.
The same behaviour occurs for output, at first it stores a reference to "" and when you do output = output + s1 a new value that is the concatenation of output and s1 is created and the new reference is assigned to output.
Not that this can be written in a more concise way as output += s1.
This link contains useful stuff about Python types an assignment.

Note
As pointed out in the comments there is some subtleties with assignments, you can read [this](However, I'll update my answer concerning a missing note about mutable/immutable behaviour.) blog post for even more details.
An interesting and quite misleading behaviour for beginners pointed out is that there are differences in the use of operator +=.
For int, str or bool this operator effectively creates a new value from the old one, the original value is not mutated.
For sequences this operator behaves has a mutating operator.
For instance compare the output of those two functions:
def modify(int_value):
  int_value += 1  # Does not add 1 in-place

def modify(array):
  array += [1]  # Mutates the array in-place


text:
Q: Converting a list of strings of numbers to tuples with integers Python3 Example:
I have a file named data.txt saved on my system. This file contains information like:
'Noah,14,233,66,21,88,42'
'Robert,34,11,667,2,785,23'
'Jackson,85,22,73,12,662,5'

and so on,
My question is how can I make this a tuple with integers?, so this would be desired:
('Noah', [14,233,66,21,88,42] ),
('Robert', [34,11,667,2,785,23] )

I assume you must use a for loop for each line but I can't figure anything out.
Any help would be appreciated!

A: If you want exactly the same output you mentioned, you can split each line on , and store it in a tuple,
x = 'Noah,14,233,66,21,88,42'
# split string on ,
x = x.strip().split(',')
# x[0] is name, while x[1]....x[n] are numbers
y = (x[0], x[1:])
print(y)

Outputs,
('Noah', ['14', '233', '66', '21', '88', '42'])

Obviously you would need to read each line from file separately first, so,
with open("file_name", "r") as file:
    for line in file:
      line = line.strip().split(',')
      output = (line[0], line[1:])

will output,
('Noah', ['14', '233', '66', '21', '88', '42'])
('Robert', ['34', '11', '667', '2', '785', '23'])
('Jackson', ['85', '22', '73', '12', '662', '5'])

A: Agree with others that a dictionary might be best for this circumstance, but this should achieve your goal:
data= """Noah,14,233,66,21,88,42
Robert,34,11,667,2,785,23
Jackson,85,22,73,12,662,5"""

[(row.split(',')[0], row.split(',')[1:]) for row in data.split('\n')]

Output:
[('Noah', ['14', '233', '66', '21', '88', '42']),
('Robert', ['34', '11', '667', '2', '785', '23']),
('Jackson', ['85', '22', '73', '12', '662', '5'])]

A: Assuming the text is exactly as you have it in the question:
import re

input = """
'Noah,14,233,66,21,88,42'

'Robert,34,11,667,2,785,23'

'Jackson,85,22,73,12,662,5'
"""

lines = re.findall("'.*'", input) # Find lines which contain text between single quotes

tuples = []

for line in lines:
  line = line.replace("'", "").split(",") # Remove single quotes, split by comma
  tuples.append((line[0], line[1:])) # Add to tuple

print(tuples)

Which would print:
[
  ('Noah', ['14', '233', '66', '21', '88', '42']),
  ('Robert', ['34', '11', '667', '2', '785', '23']),
  ('Jackson', ['85', '22', '73', '12', '662', '5'])
]

First we grab all the lines which has something between two single quotes. Then take out the single quotes and create an array by splitting it by the commas. Finally create a tuple with the first element and the sub-array of the second to the last element.

A: You can try this:
   with open(data.txt, 'r') as f:
        lines = [(line.strip().split(',')[0], line.strip().split(',')[1:])for line in f]
   print(lines)

It will return a list of tuple in the format that you described.


text:
Q: Impersonate with username and password? WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();

 ...
context.Undo();

Where do i declare a administraotr UserName and Passowrd  ?
the accessToken param doesn't help me too much...
Do I have to import DLL'S for it ?

A: its exactly the accesstoken you have to use. to get it you need to call the LogonUser method:
oops didnt realise that i just have the VB.net code just here. imagine it in C# ;)
here in c#
external method declaration:
Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _
ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
ByRef phToken As IntPtr) As Boolean

and the execution:
_Token = New IntPtr(0)

Const LOGON32_PROVIDER_DEFAULT As Integer = 0
'This parameter causes LogonUser to create a primary token.
Const LOGON32_LOGON_INTERACTIVE As Integer = 2
Const LOGON32_LOGON_NEWCREDENTIALS As Integer = 9

_Token = IntPtr.Zero

' Call LogonUser to obtain a handle to an access token.
Dim returnValue As Boolean = LogonUser(_User, _Domain, _Password, LOGON32_LOGON_NEWCREDENTIALS, LOGON32_PROVIDER_DEFAULT, _Token)

If False = returnValue Then
     Dim ret As Integer = Marshal.GetLastWin32Error()
     Console.WriteLine("LogonUser failed with error code : {0}", ret)
     Throw New System.ComponentModel.Win32Exception(ret)
End If

_Identity = New WindowsIdentity(_Token)
_Context = _Identity.Impersonate()

A: You need to get the user's token. Use the p/invoke LogonUser from the advapi32.dll:
    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool LogonUser(
            string lpszUsername,
            string lpszDomain,
            string lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            out IntPtr phToken);

Example:
IntPtr userToken = IntPtr.Zero;

bool success = External.LogonUser(
  "john.doe",
  "domain.com",
  "MyPassword",
  (int) AdvApi32Utility.LogonType.LOGON32_LOGON_INTERACTIVE, //2
  (int) AdvApi32Utility.LogonProvider.LOGON32_PROVIDER_DEFAULT, //0
  out userToken);

if (!success)
{
  throw new SecurityException("Logon user failed");
}

using (WindowsIdentity.Impersonate(userToken))
{
  // do the stuff with john.doe's credentials
}

A: You need to P/invoke the LogonUser() API. That accepts username, domain and password and returns a token.


text:
Q: Docker can't connect to Container exposed port SCENARIO:
Hey there,I'm running a docker compose with containers.
This compose file works like charm on ma local docker desktop on windows 10.
I configured my own network with network driver bridge.
Now I want to run the docker compose on an external server with an ubuntu vm.
I have remote putty connection to the server. When I run docker-compose up all my services start successfully. I also have portainer running to have a gui control on that.
PROBLEM:
Lika I said, all my services are an running. The only difference to my local setup is that I startet portainer as a single container. I cann connect to portainer with my Browser and inspect the whole setup. But when I want to call my expose container, I can't get a connection and get a connection faild error.
When I have a look at the IP Adress Column in portainer in the Containers spec, I see that portainer has a different ip than my docker compose containers. So portainer has 172.17.xxx and all the other containers start with 172.20.xxx Obviosly my exposed ports in my private network are not exposed to the host bridge network.
What I expect
I want to have my exposed ports to be availble by the ip of my virtual machine like my portainer instance.
Thoughts
I'm pretty new to docker so I checked the docs and I thought because of the description:

Within a user-defined bridge network, linking is not supported. You
  can expose and publish container ports on containers in this network.
  This is useful if you want to make a portion of the bridge network
  available to an outside network.

..that bridge as the network driver would connect my network to the local host internet connection.
Question:
Is there something wrong when I run portainer seperate from my compose?
Is there something else to keep in mind when I run my compose on an external server and not on my localhost in point of networking?
compsose network cfg:
networks:
  my_net:
    driver: bridge

and my compose Version is 2.1
UPDATE:
Docker ps says all up and running
docker inpsect on a container I want to reach via Internet:
"NetworkSettings": {
            "Bridge": "",
            "SandboxID": "9e1e335ab30f1f4d3f690e8902e06523fa095e7d8bshddkdksis7d66s7sjdjd",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "7778/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "7778"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/9e1e386ttf56",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {
                "my_net": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": [
                        "3cb72e02c43b",
                        "usermanagement-service"
                    ],

                    "Gateway": "172.20.xx.x",
                    "IPAddress": "172.20.xx.xx",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "DriverOpts": null
                }
            }
        }
    }

A: In my case it was invalid order of arguments:
docker run myrazorapp -p 8080:80

when it should be:
docker run -p 8080:80 myrazorapp

Port args were simply ignored.

A: So the problem can be broken down to the following steps:

*

*Check the docker inspect or docker ps results to ensure that you have your port exposed correctly

*Try to connect to it using the public IP. If you got an error message for example

*

*Connection Refused: The reason could be because the application inside the container is not running as expected. for example you need to ensure that the application bind to 0.0.0.0 and not 127.0.0.1

*Connection Timeout: The reason could be a firewall outside the server like SecurityGroups in AWS or similar or maybe docker is not managing the server firewall (which is not the default setup)

A: Just recently we had similar problem with container to container connection and the problem was badly configured defaul ubuntu firewall ufw
So in our case solution was:
 sudo ufw disable

A: I had the problem that i specefied
RUN npm start
instead of
CMD npm start
Your Container will start but it will never get exposed. This did it for me


text:
Q: How to combine more then one collection in MongoDB I have three collections ("role", "permission", "role_permission"). In this case I want to list all permissions (collection->permission) but I also wanto to add role info and add a state field it's coming from role_permission.state. If role_permission is not exist for the role the state value has must to be 0. How can I solve this case?
Collections:
/* "role" collection */
{
    "_id" : 1,
    "name" : "Admin"
}

/* "permission" collection */
{
    "_id" : 1,
    "name" : "Add User"
}
{
    "_id" : 2,
    "name" : "Update User"
}
{
    "_id" : 3,
    "name" : "Delete User"
}
{
    "_id" : 4,
    "name" : "List User"
}

/* "role_permission" collection */
{
    "_id" : 1,
    "role_id" : 1,
    "permission_id" : 1,
    "state": 1
}
{
    "_id" : 2,
    "role_id" : 1,
    "permission_id" : 2,
    "state": 1
}
{
    "_id" : 4,
    "role_id" : 1,
    "permission_id" : 4,
    "state": 1
}

Expecting Result:
/* expecting result */
{
    "role_id": 1,
    "permission_id": 1,
    "permission_name": "Add User",
    "permission_state": 1 // if role_permission is exist for the role: use role_permission.state else: 0
}
{
    "role_id": 1,
    "permission_id": 2,
    "permission_name": "Update User",
    "permission_state": 1 // if role_permission is exist for the role: use role_permission.state else: 0
}
{
    "role_id": 1,
    "permission_id": 3,
    "permission_name": "Delete User",
    "permission_state": 0 // if role_permission is exist for the role: use role_permission.state else: 0
}
{
    "role_id": 1,
    "permission_id": 4,
    "permission_name": "List User",
    "permission_state": 1 // if role_permission is exist for the role: use role_permission.state else: 0
}

A: db.permission.aggregate
([
{ "$lookup" : { "from" : "role_permission", "localField" : "_id", "foreignField" : "permission_id", "as" : "JOIN_1" } },
{ "$lookup" : { "from" : "role", "localField" : "JOIN_1.role_id", "foreignField" : "_id", "as" : "JOIN_2" } },
{ "$unwind" : { "path" : "$JOIN_1", "preserveNullAndEmptyArrays" : true } },
{ "$unwind" : { "path" : "$JOIN_2", "preserveNullAndEmptyArrays" : true } },
{ "$project" :
    {   "_id" : 0,
        "p_id" : { "$ifNull" : ["$JOIN_1._id", 0] },
        "role_id" : { "$ifNull" : ["$JOIN_2._id", 1] },
        "permission_id" : "$_id",
        "permission_name" : "$name",
        "permission_state" : { "$ifNull" : ["$JOIN_1.state", 0] }
    }
}
])


text:
Q: How to write "where" clause in hive to filter out values in another table I have a table "mytable" contains several columns including one called "ip." There is another table called "bots" with only one column "bot", which is a list of several ip address values. I want to filter out all rows in mytable with "ip" value in table bots.
I wrote
select * from mytable
where ip not in (select bot from bots);

Apparently this is not the way to do it. I am wondering what is the correct syntax.
I googled around but the keywords here "where" and "in" are too common in the English language and hence hard to find any useful results.

A: select mytable.* from
mytable left outer join bots on mytable.id = bots.bot
where bots.bot is null


text:
Q: Sum, concatenate and merge data in several columns Need VBA macro to merge data in 4 columns. Tried to consolidate but it won't work.
Please see the picture for a better understanding. The red arrow explains what I need.
I need a working VBA to go from the 4 columns on the left to the 4 columns on the right:
Combine data (all the rows from row #2 down) by column a & c while consolidating values in column b and concatenating values in column d.
This code below is not working and is missing parts.
Sub CombineRows()
'This section combines and sum A and B but not C (1 to 6) and D and
'deletes rows that should not delete instead, because of the second
'part of the code
  Dim Rng As Range
  Dim InputRng As Range
  Dim nRng As Range
   Set InputRng = Application.Selection
   Set InputRng = Application.InputBox("Range :", xTitleId,
     InputRng.Address, Type:=8)
   Set InputRng = InputRng.Parent.Range(InputRng.Columns(1).Address)
     With CreateObject("scripting.dictionary")
     .CompareMode = vbTextCompare
   For Each Rng In InputRng
If Not .Exists(Rng.Value) Then
.Add Rng.Value, Rng.Offset(, 1)
   Else
.Item(Rng.Value).Value = .Item(Rng.Value).Value + Rng.Offset(, 1)
    If nRng Is Nothing Then
        Set nRng = Rng
    Else
        Set nRng = Union(nRng, Rng)
    End If
Next
    If Not nRng Is Nothing Then
    nRng.EntireRow.Delete
Next

'Second Part To combine A and D but it's not combining (maybe because
'of the large amount of data and I also need the comma between values
'in column D, not space but it doesn't work - deletes data
  Dim WorkRng As Range
  Dim Dic As Variant
  Dim arr As Variant
    On Error Resume Next
    xTitleId = "Combine"
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Range", xTitleId,
      WorkRng.Address, Type:=8)
    Set Dic = CreateObject("Scripting.Dictionary")
      arr = WorkRng.Value
    For i = 1 To UBound(arr, 1)
      xvalue = arr(i, 1)
    If Dic.Exists(xvalue) Then
      Dic(arr(i, 1)) = Dic(arr(i, 1)) & " " & arr(i, 2)
    Else
      Dic(arr(i, 1)) = arr(i, 2)
    End If
 Next
    Application.ScreenUpdating = False
      WorkRng.ClearContents
      WorkRng.Range("A1").Resize(Dic.Count, 1) =
    Application.WorksheetFunction.Transpose(Dic.keys)
      WorkRng.Range("D1").Resize(Dic.Count, 1) =
    Application.WorksheetFunction.Transpose(Dic.items)
    Application.ScreenUpdating = True
  End Sub

The "Set InputRng = Application.Selection and Set InputRng = Application.InputBox" can be deleted as the range is always the same.

A: I went for a different solution using a mix of VBA and formulas.  I think it's a bit more readable and certainly shorter.  Might not be a purist idea of VBA code but that's how I like to do things.  The code assumes that the input table is in columns A:D and the output will be in columns E:I - that can be changed of course.

Sub unique()
     Dim arr As New Collection, a
     Dim tmp() As Variant, var() As Variant
     Dim i As Long, j As Long, iRowCount As Long, iNewRowCount As Long
     Dim str As String
     Dim rng As Range

    iRowCount = Cells(Rows.Count, "A").End(xlUp).Row

    Set rng = Range("A2:C" & iRowCount)

     ' Columns 1 & 3 - create unique list
      tmp = rng
      For i = 1 To UBound(tmp, 1)
         ReDim Preserve var(i)
         var(i) = CStr(tmp(i, 1) & tmp(i, 3))
      Next

     On Error Resume Next
     For Each a In var
        arr.Add a, a
     Next
     On Error GoTo 0

      For i = 2 To arr.Count + 1
        Cells(i, 6) = Left(arr(i - 1), Len(arr(i - 1)) - 1)
        Cells(i, 8) = Right(arr(i - 1), 1)
     Next

     iNewRowCount = Cells(Rows.Count, "F").End(xlUp).Row

    ' Column 2 - sum based on columns 1 & 3
     Range("G2") = "=SUMIFS($B$2:$B$" & iRowCount & ",$A$2:$A$" & iRowCount & ",""=""&F2,$C$2:$C$" & iRowCount & ",""=""&H2)"
     Range("G2:G" & iNewRowCount).FillDown

     'Column 4 concatenate with comma
    For i = 2 To iNewRowCount
        For j = 2 To iRowCount
            If Cells(j, 1) & Cells(j, 3) = Cells(i, 6) & Cells(i, 8) Then
                str = str & Cells(j, 4) & ","
            End If
        Next
        Cells(i, 9) = Left(str, Len(str) - 1)
        str = ""
    Next

End Sub

Or just do it the lazy way, create a pivot table and use formulas to concatenate the strings:

A: Output goes to the same sheet in columns F:I. Workbook with code.
Sub DoConsolidation()
    Dim x, r, z, field_a, field_c, vsum, id, dic, k
    r = 2: z = 1: Set dic = CreateObject("Scripting.Dictionary")
    '// To make code work, we need to sort data
    Range("A1").CurrentRegion.Sort Key1:=Range("A1"), Key2:=Range("C1"), Header:=xlYes
    While Len(Cells(r, 1)) > 0
        field_a = Cells(r, "A"): field_c = Cells(r, "C")
        x = r: z = z + 1: vsum = 0: id = "": dic.RemoveAll
        Cells(z, "F") = field_a: Cells(z, "H") = field_c
        While (Cells(x, "A") = field_a) And (Cells(x, "C") = field_c)
            k = Cells(x, "D").Value: dic(k) = k
            vsum = vsum + Cells(x, "B")
            x = x + 1
        Wend
        For Each k In dic.Keys(): id = id & k & ",": Next
        Cells(z, "G") = vsum: Cells(z, "I") = Left(id, Len(id) - 1)
        r = x
    Wend
    MsgBox "Well done!", vbInformation
End Sub


text:
Q: Nested query sql hospital enter image description here
select Fname,Lname,salary,ssn
from Employee
where joptype='nurse' AND salary <= ALL (select salary
from Employee E,Nurses N
where E.Ssn=N.Ssn AND E.joptype='nurse' AND N.shift='morning')

I want to return a list of nurses name who works at morning and their salary is less than all nurses, or the opposite. I've tried both morning and night, also I've tried greater than all nurses. I think the problem is in the second where it seems like he ignores the shift condition.

A: You can use EXISTS to find the morning shifts and, from Oracle 12, you can use ORDER BY salary ASC FETCH FIRST ROW WITH TIES to find the matching employees with the lowest salary:
SELECT Fname,
       Lname,
       salary,
       ssn
FROM   Employee e
WHERE  jobtype='nurse'
AND    EXISTS( SELECT 1
               FROM   Nurses N
               WHERE  E.Ssn=N.Ssn
               AND    N.shift='morning' )
ORDER BY salary ASC
FETCH FIRST ROW WITH TIES;

or, if you want to check all nurses and find the minimum salary and then filter on morning shifts:
SELECT *
FROM   (
  SELECT Fname,
         Lname,
         salary,
         ssn
  FROM   Employee
  WHERE  jobtype='nurse'
  ORDER BY salary ASC
  FETCH FIRST ROW WITH TIES
) e
WHERE  EXISTS( SELECT 1
               FROM   Nurses N
               WHERE  E.Ssn=N.Ssn
               AND    N.shift='morning' )

If you want to use a JOIN, rather than EXISTS, then you can use:
SELECT e.Fname,
       e.Lname,
       e.salary,
       e.ssn
FROM   (
         SELECT Fname,
                Lname,
                salary,
                ssn
         FROM   Employee
         WHERE  jobtype='nurse'
         ORDER BY salary ASC
         FETCH FIRST ROW WITH TIES
       ) e
       INNER JOIN Nurses N
       ON E.Ssn=N.Ssn
WHERE  N.shift='morning'

(However, if there are multiple entries in Nurses for an Employee then you will get duplicates using a JOIN that you would not get using EXISTS)
Or for your code, you appear to have the filter for shifts in the wrong place:
SELECT e.Fname,
       e.Lname,
       e.salary,
       e.ssn
FROM   Employee e
       INNER JOIN Nurses n
       ON (e.Ssn = n.Ssn)
WHERE  e.jobtype='nurse'
AND    n.shift='morning'
AND    e.salary <= ALL ( SELECT salary
                         FROM   Employee
                         WHERE  jobtype='nurse' );

fiddle

A: This is how I understood it; what you said:

their salary is less than all nurses

probably means their average salary, so I used it in a subquery.
select e.fname, e.lname, e.salary, e.ssn
from employee e join nurse n on e.ssn = n.ssn
where e.joptype = 'nurse'
  and n.shift = 'morning'
  and salary < (select avg(salary)         --> average salary of all nurses
                from employee
                where joptype = 'nurse'
               );

(Just a remark: is it really joptype? Is it not a job?)

A: Maybe you could try it like here:
select
    Fname,  Lname,  salary,  ssn
from
    Employee
where
    joptype='nurse' AND
    salary <=   (   Select  MIN(salary)
                    From    Employee E
                    Inner join      Nurses N ON(E.Ssn=N.Ssn)
                    Where   E.joptype = 'nurse' AND
                            N.shift = 'morning'
                )

... this will give you the list of nurses with salary less than or equal to the minimum salary among morning nurses..


text:
Q: How is time_since_previous computed in featuretools? I am trying to reproduce the featuretools tutorial (See link below). I am using the mocking data provided in the package. They include a customers table and a sessions table. Every customer has many sessions. Every session has a session_start timestamp. I compute the mean of the primitive time_since_previous of the feature session_start a) using featuretools and b) manually. But I get different results, where am I wrong?
a) Calculation using featuretools:
import featuretools as ft

es = ft.demo.load_mock_customer(return_entityset=True)
feature_matrix, features_defs = ft.dfs(
    entityset=es,
    target_entity='customers',
    agg_primitives=['mean'],
    trans_primitives=['time_since_previous'])

The MEAN(sessions.TIME_SINCE_PREVIOUS(session_start)) for customer 3 is 888.333333
b) Manual calculation:
time_since_previous(sessions[sessions.customer_id == 3].session_start).tolist()
[nan, 10075.0, 3900.0, 1625.0, 8710.0, 1170.0]
statistics.mean([ 10075.0, 3900.0, 1625.0, 8710.0, 1170.0])
5096.0

Snapshot1
Snapshot2
https://docs.featuretools.com/en/stable/automated_feature_engineering/primitives.html

A: To apply time_since_previous for each customer, you can use groupby_trans_primitives in DFS.
fm, fd = ft.dfs(
    entityset=es,
    target_entity='customers',
    agg_primitives=['mean'],
    groupby_trans_primitives=['time_since_previous'],
)

fm.filter(regex='sessions.TIME_SINCE_PREVIOUS')

             MEAN(sessions.TIME_SINCE_PREVIOUS(session_start) by customer_id)
customer_id
5                                                  5577.000000
4                                                  2516.428571
1                                                  3305.714286
3                                                  5096.000000
2                                                  4907.500000

Let me know if this helps.


text:
Q: How I can split long equation with over-brace and color box? I have long equation with over-brace and color box. how it is possible split equation like picture or better way?
\documentclass{article}
\usepackage{amsmath}
\usepackage{mathtools}
\usepackage{tikz}
\begin{document}

\begin{equation}
\begin{split}
&\sum_{p=1}^{n} \overbrace{\tikz[baseline]{
            \node[fill=blue!30,anchor=base] (t1)
            {$ \left[ \frac{\left(EI \right)_i}{EI_0}\bar{D}_{ip} +\frac{\left(EI \right)_i}{EI_0}\bar{D}_{ip}+ \frac{\left(EI \right)_i}{EI_0}\bar{D}_{ip} \frac{2}{EI_0}\left( \frac{dEI}{d \xi }\right)_i\bar{C}_{ip}
\left. +\frac{1}{EI_0}\left(\frac{d^2EI}{d \xi ^2} \right)_i B_{ip} +\frac{P_0L^2}{EI_0}B_{ip}  +\frac{k_wL^4}{EI_0} \delta _{ip} \right]$};
        }                  \rule[-12pt]{0pt}{5pt}}^{\mbox{$A$}}
\bar{w}_p \\
&+\overbrace{\tikz[baseline]{
            \node[fill=green!30,anchor=base] (t1)
            {$[0]$};
        }                  \rule[-12pt]{0pt}{5pt}}^{\mbox{$B$}} \kappa _{\bar{i}}=\overbrace{\tikz[baseline]{
            \node[fill=yellow!50,anchor=base] (t1)
            {${\frac{w_0}{L}}$};
        }                  \rule[-12pt]{0pt}{5pt}}^{\mbox{$C$}}
\end{split}
\end{equation}

How I can break large equation

\end{document}

A: You can place the long expression in an aligned:

\documentclass{article}

\usepackage{mathtools}
\usepackage{tikz}

\begin{document}

\begin{equation}
  \begin{split}
    &\sum_{p=1}^{n}
      \overbrace{\tikz[baseline]{
      \node[fill=blue!30,anchor=base] (t1)
      {$\displaystyle
      \left[
          \begin{aligned}
            &\frac{(EI)_i}{EI_0}\bar{D}_{ip}
            + \frac{(EI)_i}{EI_0}\bar{D}_{ip}
            + \frac{(EI)_i}{EI_0}\bar{D}_{ip}
            \frac{2}{EI_0}
            \biggl( \frac{dEI}{d \xi}\biggr)_i
            \bar{C}_{ip}\\
            &\qquad
            + \frac{1}{EI_0}
            \biggl(\frac{d^2EI}{d \xi ^2} \biggr)_i
            B_{ip}
            + \frac{P_0L^2}{EI_0}B_{ip}
            + \frac{k_wL^4}{EI_0} \delta _{ip}
          \end{aligned}
        \right]
        $};
        }
        }^{\displaystyle A}
          \bar{w}_p \\
    &+ \overbrace{\tikz[baseline]{
      \node[fill=green!30,anchor=base] (t1)
      {$[0]$};
      }}^{\displaystyle B}
      \kappa _{\bar{i}}
      = \overbrace{\tikz[baseline]{
      \node[fill=yellow!50,anchor=base] (t1)
      {${\frac{w_0}{L}}$};
      }}^{\displaystyle C}
  \end{split}
\end{equation}

\end{document}

A: Here, three different approaches to this problem.

\documentclass{article}
\usepackage{amsmath}
\usepackage{mathtools}
\usepackage{tikz}
    \usetikzlibrary{decorations.pathreplacing}
\usepackage[customcolors]{hf-tikz}

\begin{document}

% #1 With separated braces

\begin{equation}
    \begin{split}
\sum_{p=1}^{n}  &
    \overbrace{\tikz[baseline]{%
            \node[fill=blue!30,anchor=base] (t1)
            {%
            $\left[\frac{\left(EI\right)_i}{EI_0}\bar{D}_{ip} +\frac{\left(EI \right)_i}{EI_0}\bar{D}_{ip}+ \frac{\left(EI \right)_i}{EI_0}\bar{D}_{ip} \frac{2}{EI_0}\left( \frac{dEI}{d \xi }\right)_i\bar{C}_{ip}\right.$};
} \rule[-12pt]{0pt}{5pt}}^{\mbox{$A$}} \\
    & \underbrace{\tikz[baseline]{%
            \node[fill=blue!30,anchor=base] (t1)
            {$\left. +\frac{1}{EI_0}\left(\frac{d^2EI}{d \xi ^2} \right)_i B_{ip} +\frac{P_0L^2}{EI_0}B_{ip}+\frac{k_wL^4}{EI_0} \delta _{ip} \right]$};
    } \rule[-12pt]{0pt}{5pt}}_{\mbox{$A$}} \bar{w}_p \\
    &+\overbrace{\tikz[baseline]{%
            \node[fill=green!30,anchor=base] (t1)
            {$[0]$};
    } \rule[-12pt]{0pt}{5pt}}^{\mbox{$B$}} \kappa _{\bar{i}}=\overbrace{\tikz[baseline]{
            \node[fill=yellow!50,anchor=base] (t1)
            {${\frac{w_0}{L}}$};
    } \rule[-12pt]{0pt}{5pt}}^{\mbox{$C$}}
    \end{split}
\end{equation}

\bigskip

% #2 By colouring each section
% Ideas from https://tex.stackexchange.com/questions/75129/boxed-tikz-and-colored-equation-background

\hfsetfillcolor{blue!30}
\hfsetbordercolor{blue!30}
\begin{equation}
    \begin{split}
\sum_{p=1}^{n}  &
    \tikzmarkin[disable rounded corners=true]{a}(0.05,-0.5)(0.1,0.65)
            \left[\frac{\left(EI\right)_i}{EI_0}\bar{D}_{ip} +\frac{\left(EI \right)_i}{EI_0}\bar{D}_{ip}+ \frac{\left(EI \right)_i}{EI_0}\bar{D}_{ip} \frac{2}{EI_0}\left( \frac{dEI}{d \xi }\right)_i\bar{C}_{ip}\right.\tikzmarkend{a} \\
    & \left.\tikzmarkin[disable rounded corners=true]{b}(0.03,-0.5)(0,0.75) +\frac{1}{EI_0}\left(\frac{d^2EI}{d \xi ^2} \right)_i B_{ip} +\frac{P_0L^2}{EI_0}B_{ip}+\frac{k_wL^4}{EI_0} \delta _{ip} \right] \tikzmarkend{b} \cdot\,\bar{w}_p  \\[2ex]
    &+\tikz[baseline]{\node[fill=green!30,anchor=base] (t1)
            {$[0]$};} \kappa _{\bar{i}}= \tikz[baseline]{%
            \node[fill=yellow!50,anchor=base] (t1)
            {${\frac{w_0}{L}}$};}%
    \end{split}
\end{equation}

\begin{center}
\tikz{\node (A) at (0,0) [draw=blue!30, fill=blue!30] {$A$};}
\tikz{\node (B) at (A.east) [draw=green!30, fill=green!30] {$B$};}
\tikz{\node (C) at (B.east) [draw=yellow!50, fill=yellow!50] {$C$};}
\end{center}

\bigskip

% #3 With coloured braces

\hfsetfillcolor{blue!30}
\hfsetbordercolor{blue!30}
\begin{equation}
    \begin{split}
\sum_{p=1}^{n}  &
    \tikzmarkin[disable rounded corners=true]{c}(0.05,-0.5)(0.1,0.65)
            \left[\frac{\left(EI\right)_i}{EI_0}\bar{D}_{ip} +\frac{\left(EI \right)_i}{EI_0}\bar{D}_{ip}+ \frac{\left(EI \right)_i}{EI_0}\bar{D}_{ip} \frac{2}{EI_0}\left( \frac{dEI}{d \xi }\right)_i\bar{C}_{ip}\right.\tikzmarkend{c} \\
    & \left.\tikzmarkin[disable rounded corners=true]{d}(0.03,-0.5)(0,0.75) +\frac{1}{EI_0}\left(\frac{d^2EI}{d \xi ^2} \right)_i B_{ip} +\frac{P_0L^2}{EI_0}B_{ip}+\frac{k_wL^4}{EI_0} \delta _{ip} \right] \tikzmarkend{d} \cdot\,\bar{w}_p  \\[2ex]
    &+\color{green!30}\overbrace{\tikz[baseline]{%
            \node[fill=green!30,anchor=base] (t1)
            {$\color{black}[0]$};
    } \rule[-12pt]{0pt}{5pt}}^{\mbox{$B$}} \color{black}\kappa _{\bar{i}}=\color{yellow!60}\overbrace{\tikz[baseline]{
            \node[fill=yellow!50,anchor=base] (t1)
            {${\color{black}\frac{w_0}{L}}$};
    } \rule[-12pt]{0pt}{5pt}}^{\mbox{$C$}}
    \end{split}
\begin{tikzpicture}[%
        decoration = {brace,
        amplitude=5pt}]
\draw [rotate = 180, ultra thick, blue!40, decorate, transform canvas={xshift = 1em, yshift= -1em}]
    (1,-1) -- node [right=7pt]
    {\text{$A$}} (1,1.5);
\end{tikzpicture}
\end{equation}

\end{document}


text:
Q: I'm getting a null exception in c# while creating a web api I am receiving an error and my code is highlighting this function to be faulty
public string GetConnectionString(string name)
{
    return ConfigurationManager.ConnectionStrings[name].ConnectionString;
}

the exact error is:
System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null.
I'm trying to access the "product" data on the api by going api/product, and this error pops up for me. This is the error on the web page
<ExceptionMessage>
Object reference not set to an instance of an object.
</ExceptionMessage>

The whole error message on the webpage is this
<StackTrace>
at RMPwebapi.Library.Internal.DataAccess.SqlDataAccess.GetConnectionString(String name) in C:\Users\Gamer\Desktop\The mighty project\retail-manager-project\RMPwebapi.Library\Internal\DataAccess\SqlDataAccess.cs:line 17 at RMPwebapi.Library.Internal.DataAccess.SqlDataAccess.LoadData[T,U](String storedProcedure, U parameters, String connectionStringName) in C:\Users\Gamer\Desktop\The mighty project\retail-manager-project\RMPwebapi.Library\Internal\DataAccess\SqlDataAccess.cs:line 23 at RMPwebapi.Library.DataAccess.ProductData.GetProducts() in C:\Users\Gamer\Desktop\The mighty project\retail-manager-project\RMPwebapi.Library\DataAccess\ProductData.cs:line 16 at RMPwebapi.Controllers.ProductController.Get() in C:\Users\Gamer\Desktop\The mighty project\retail-manager-project\RMPwebapi\Controllers\ProductController.cs:line 19 at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.<GetExecutor>b__2(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()
</StackTrace>

I tried to check the difference classes and identify where I could be going wrong because I suspect I'm passing on an object that is null. At the moment I'm analysing this function in my ProductData.cs file:
public List<ProductModel> GetProducts()
{
    SqlDataAccess sql = new SqlDataAccess();
    var output = sql.LoadData<ProductModel, dynamic>("dbo.spProduct_GetAll",
         new { }, "RMPdatabase");
    return output;
}

I'm also investigating this function within my ProductController.cs file:
public List<ProductModel > Get()
{
    ProductData data = new ProductData();

    return data.GetProducts();
}

What can I do guys, please help. I would like to say I am a beginner so I won't understand everything


text:
Q: SAP HANA connectivity from .Net Core application What I'm trying to do:

*

*Connecting HANA db from .Net Core application. (Windows environment)

What I did:

*

*Downloaded and installed HANA Client for windows. Installed using "hdbinst.exe" from the folder "hdb_client_windows_x86_64" I got it.

*Created a NuGet package for the file - "Sap.Data.Hana.Core.v2.1.dll" from the path: C:\Program Files\sap\hdbclient\dotnetcore\v2.1

*Installed this file in to my sample .Net Core 2.1 project thru NuGet package manager.

What I'm experiencing:

*

*Warning 1 -->
Warning NU1701. Package 'SAP.HANADBClient.NetCore 2.1.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.1'. This package may not be fully compatible with your project.

*Warning 2  --> Warning   MSB3270.    There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "C:\Users\XXXXX.nuget\packages\sap.hanadbclient.netcore\2.1.0\lib\Sap.Data.Hana.Core.v2.1.dll", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.

*Similar case for .Net Core 2.2 project

What I looked around:

*

*I did a search in the web and saw few members had already shared this kind of issue (.Net core with HANA integration). But saw this post saying that the issue got resolved. But was it good? not sure.

*Even this post says HANA supports .Net Core.

*Did search in the web, but could not find the solution.

What I'm looking for:

*

*Why am I getting these two warnings?

*Will it give any issues later on - (prod runtime..)

*Particularly - 2nd warning - why it's looking for "Processor architecture", and how to resolve this.

Can I request any one of you to help me out on this effort.
Please let me know still additional details are needed.
Thanks in advance.

A: To narrow down the issue, try adding the Sap.Data.Hana.Core.v2.1.dll library to your .NET Core 2.1 project directly (not through NuGet) and see if you get the compilation warnings.
If you don't get the warnings, then it's likely your NuGet package that's causing the issue.
If so, how did you create your package?  If you created it using the SDK-style, check the  TargetFramework to make sure it's set to the correct TFM or TxM as described here.
Also, according to this answer make sure you are using the correct version of the DLL, either x86 or x64.


text:
Q: Primefaces 6.1 SelectOneMenu pick itemLabel as value I am using PrimeFaces 6.1 SelectOneMenu to render a editable/filtered dropdown menu with itemLabel/value as selectItems. Unfortunately, selectOneMenu pick itemLabel as value put it in my selectOneMenu value field. This is very annoying issue and maybe it is a bug.
There is my snippet code:
I am using Map to hold ID/Name pair as selectItems:
Map<String,String> hm = new HashMap<String, String>();
hm.put("Cust001","John Dow");
hm.put("Cust002","Mark Polo");
hm.put("Cust003","Noel Max");

then I put it in my selectOneMenu as:
<p:selectOneMenu id="selectCustomerId" value="#{paymentControlBean.selectedCustomerId}" effect="fold" editable="true" filter="true" filterMatchMode="startsWith">
   <p:ajax update="paymentListToolbar"/>
   <f:selectItems value="#{hm.entrySet()}" var="entry" itemValue="#{entry.key}" itemLabel="#{entry.value}"/>
</p:selectOneMenu>

Dropdown list rendering works fine, but when I pick one from the dropdown list and then press process it. My backing bean paymentControlBean.selectedCustomerId shows up "John Dow", which means, selectOneMenu pick my itemLabel into my selectOneMenu's value field.
I tried to change the PrimeFaces element to p:selectOneListBox and keep everything no change, repeat the processing, my backing bean shows up "Cust001", which is working fine.
From this comparison I found out, there must a serious bug exists in PrimeFaces 6.1, and it is same bug existing in PrimeFaces 5.2 as well.
SelectOneMenu is very popular in dropdown list selection, especially when we have to handle key/value pairs by using Map.
If it is not a bug, what I can do or have an other work around to make it pick up right value in my selectItems?
Please advise>

A: I have fixed it with this PR: https://github.com/primefaces/primefaces/pull/2870
It will be in PrimeFaces 6.2 release coming out in November 2017.


text:
Q: svg circle not being drawn with javascript I have been trying to do a hello world for svg manipulation using javascript in HTML. I have written the below code and although it generates the correct html, I don't see any output in the browser, nor do I see any error.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var svg1 = document.createElement("svg");
svg1.setAttribute("height",200);
svg1.setAttribute("width",500);
document.body.appendChild(svg1);
var circles = document.createElement("circle");
circles.setAttribute("cx",20);
circles.setAttribute("cy",20);
circles.setAttribute("r",20);
svg1.appendChild(circles);
</script>
</body>
</html>

Where am I going wrong? thanks in advance.

A: SVG elements need to be created with the SVG XML namespace. You can do that using createElementNS and using the http://www.w3.org/2000/svg namespace:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var svg1 = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg1.setAttribute("height",200);
svg1.setAttribute("width",500);
document.body.appendChild(svg1);
var circles = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circles.setAttribute("cx",20);
circles.setAttribute("cy",20);
circles.setAttribute("r",20);
svg1.appendChild(circles);
</script>
</body>
</html>


text:
Q: Linker error on compile time?  error: unable to open executable '/Users/mac2/Library/Developer/Xcode/DerivedData/ProjectName-hftpysylqrrbjoanrgzctdxelpxr/Build/Products/Debug-iphonesimulator/ProjectName.app/ProjectName'

What i have to do in this situation,As per the answer of the same question ,I cleared the derived data and then deleted the app from the device after that its not working still problem arising.


text:
Q: Summarizing log file to unique entries only I have been using this script for years at work to summarize log files.
 #!/usr/bin/perl

 $logf = '/var/log/messages.log';

 @logf=( `cat $logf` );
 foreach $line ( @logf ) {
      $line=~s/\d+/#/g;
      $count{$line}++;
 }

 @alpha=sort @logf;
 $prev = 'null';
 @uniq = grep($_ ne $prev && ($prev = $_), @alpha);
 foreach $line (@uniq) {
      print "$count{$line}: ";
      print "$line";
 }

I have wanted to rewrite it in Python but I do not fully understand certain portions of it, such as:
 @alpha=sort @logf;
 $prev = 'null';
 @uniq = grep($_ ne $prev && ($prev = $_), @alpha);

Does anyone know of a Python module that would negate the need to rewrite this?  I haven't had any luck find something similar.  Thanks in advance!

A: As the name of the var implies,
@alpha=sort @logf;
$prev = 'null';
@uniq = grep($_ ne $prev && ($prev = $_), @alpha);

is finding unique elements (i.e. removing duplicate lines), ignoring numbers in the line since they were previously replaced with #. Those three lines could have been written
@uniq = sort keys(%count);

or maybe even
@uniq = keys(%count);

Another way of writing the program in Perl:
my $log_qfn = '/var/log/messages.log';
open(my $fh, '<', $log_qfn)
   or die("Can't open $log_qfn: $!\n");

my %counts;
while (<$fh>) {
   s/\d+/#/g;
   ++$counts{$_};
}

#for (sort keys(%counts)) {
for (keys(%counts)) {
   print "$counts{$_}: $_";
}

This should be easier to translate into Python.

A:  @alpha=sort @logf;
 $prev = 'null';
 @uniq = grep($_ ne $prev && ($prev = $_), @alpha);

would be equivalent to
uniq = sorted(set(logf))

if logf were a list of lines.
However, since you are counting the freqency of lines,
you could use a collections.Counter to both count the lines and collect the unique lines (as keys) (thus removing the need to compute uniq at all):
count = collections.Counter()
for line in f:
    count[line] += 1

import sys
import re
import collections

logf = '/var/log/messages.log'
count = collections.Counter()
write = sys.stdout.write

with open(logf, 'r') as f:
    for line in f:
        line = re.sub(r'\d+','#',line)
        count[line] += 1

for line in sorted(count):
     write("{c}: {l}".format(c = count[line], l = line))

A: I have to say I often encountered with people trying to do stuff in python perl can be done in one line on shell or bash:
I don't care for downvotes, since people should know there is no reason to do stuff in 20 lines of python if it can be done on shell
< my_file.txt | sort | uniq > uniq_my_file.txt


text:
Q: How to restart stack trace when rethrowing an exception? Is there a way to restart stack trace given a caught exception? Problem is that when I await a future and it fails, stack trace does not tell which await failed.
For example, stack trace tells that doSomethingMayFail failed:
def doSomethingMayFail() = Future { throw new RuntimeException("test") }
Await.result(doSomethingMayFail(), 1.seconds)
Await.result(doSomethingMayFail(), 1.seconds)

java.lang.RuntimeException: test
    at RandomSpec$$anon$7.$anonfun$doSomethingThatFails$1(RandomSpec.scala:79)
    at scala.concurrent.Future$.$anonfun$apply$1(Future.scala:672)
    at scala.concurrent.impl.Promise$Transformation.run(Promise.scala:431)
    at java.base/java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1426)
    at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
    at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
    at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
    at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
    at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)

A: One way to is to catch, fillInStackTrace and rethrow the exception.
try {
  Await.result(doSomethingThatFails(), 1.seconds)
} catch {
  e => throw e.fillInStackTrace()
}


text:
Q: Google Speech-to-text on Amazon Kinesis stream: io.grpc.StatusRuntimeException: CANCELLED: The operation was cancelled I want to use Google speech-to-text using Kinesis stream as part of voicebot service using Amazon Connect, Amazon Lex and Amazon SQS (I used code from https://cloud.google.com/speech-to-text/docs/streaming-recognize#speech-streaming-mic-recognize-java and I changes reference type from AudioInputStream to InputStream).
I use Amazon Transcribe speech-to-text service but I want to replace it with Google as Google supports more languages. However, Google Speech can't accept InputStream object created by Amazon SDK.
I use the code below. Instead of changing AudioInputStream to InputStream, I also tried getAudioInputStream() method (also with creating BufferedInputStream).
String streamName = streamARN.substring(streamARN.indexOf("/") + 1, streamARN.lastIndexOf("/"));
InputStream kvsInputStream = KVSUtils.getInputStreamFromKVS(streamName, REGION, startFragmentNum, getAWSCredentials());
//InputStream bufferedIn = new BufferedInputStream(kvsInputStream); //to solve 'no reset/mark support in stream' error
//AudioInputStream audioStream = AudioSystem.getAudioInputStream(bufferedIn); //to solve 'no reset/mark support in stream' error
streamingMicRecognize(kvsInputStream);

In current state I get the error
com.google.api.gax.rpc.CancelledException: io.grpc.StatusRuntimeException: CANCELLED: The operation was cancelled.

When I used two commented lines (I found this solution on SO), the error was
java.lang.ClassCastException: com.amazonaws.util.ServiceClientHolderInputStream cannot be cast to javax.sound.sampled.AudioInputStream

Can you please suggest any solution? For English voicebot Connect offers a special block which lets me connect phone call voice with Lex, but Lex supports only US English and I need other languages as well. I know Google Dialogflow ("Google's Lex") can process many languages and offers integration with phone gateway, but the phone gateway supports English only (which is ridiculous).
Thanks in advance.

UPDATE
I solved this problem with the following code:
    InputStream kvsInputStream = KVSUtils.getInputStreamFromKVS(input.getStreamName(), Regions.US_EAST_1, input.getStartFragmentNum(), new SystemPropertiesCredentialsProvider());
    StreamingMkvReader streamingMkvReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(kvsInputStream));
    FragmentMetadataVisitor.BasicMkvTagProcessor tagProcessor = new FragmentMetadataVisitor.BasicMkvTagProcessor();
    FragmentMetadataVisitor fragmentVisitor = FragmentMetadataVisitor.create(Optional.of(tagProcessor));
    ByteBuffer audioBuffer = KVSUtils.getByteBufferFromStream(streamingMkvReader, fragmentVisitor, tagProcessor, input.getConnectContactId());
    SpeechClient client = SpeechClient.create();
    clientStream = client.streamingRecognizeCallable().splitCall(responseObserver); //responseObserver is an instance of ResponseObserver<StreamingRecognizeResponse>() with onXXX methods defined by user -- see Google Speech-To-Text examples
    byte[] audioBytes;
    int counter = 0;
    do {
        audioBytes = new byte[audioBuffer.remaining()];
        audioBuffer.get(audioBytes);
        request = StreamingRecognizeRequest.newBuilder()
                            .setAudioContent(ByteString.copyFrom(audioBytes))
                            .build();
        clientStream.send(request);
        audioBuffer = KVSUtils.getByteBufferFromStream(streamingMkvReader, fragmentVisitor, tagProcessor, input.getConnectContactId());
                        counter++;
    } while (audioBytes.length > 0);

The solution is to go to the lowest possible level in stream handling, i.e. to get simply a byte array instead of stream objects


text:
Q: Possible to replace all occurrences of a lower case character in either SSIS or SQL? For some particular fields, I need to add an underscore after any lower case character. UPPER/LOWER are of no help in this case, but the fact that these functions can pin down which characters are of the wrong case suggests that this should be possible.
Note that I am using SQL Server.

A: Assuming you don't have underscores except for after lowercase letters
SELECT REPLACE(fieldName, '_', '')
SELECT REPLACE(fieldName COLLATE SQL_Latin1_General_CP1_CS_AS, 'a', 'a_')
SELECT REPLACE(fieldName COLLATE SQL_Latin1_General_CP1_CS_AS, 'b', 'b_')

A: Since the question is tagged with ssis, then I will provide a SSIS solution.
You can simply use a Script Component within a data flow task and use C# regex.replace() function to achieve that, as example:
Note that you have to import System.Text.RegularExpressions assembly in the Script.
var regex = new Regex("[a-z]", RegexOptions.None);
row.outputcolumn = regex.Replace(row.inputcolumn, m => m + "_");

If you need to achieve this using SQL, you can use CLR functions similar to:

*

*RegEx in SQL Server for replacing text


text:
Q: R Shiny. "Error: no applicable method for 'xtable' applied to an object of class "c('double', 'numeric')" I am trying to create an interactive data set and I need to subset it for calculations. When I try to extract certain rows and columns I get this error message about xtable being applied object of class "C('double','numeric')". Here is my code.
ui.r
library(shiny)
require(ggplot2)

shinyUI(fluidPage(

  titlePanel("Vasicek Model Example"),

  sidebarLayout(
    sidebarPanel(
      numericInput("sim", "Simulations", value = 100),
      numericInput("loans", "Loans", value = 10),
      numericInput("M", "Systemic Risk Factor", value = 0),
      numericInput("rho", "Firm Correlation", value = 0),
      sliderInput("bins", "Number of Bins:", min = 1, max = 50, value = 30),
      submitButton("Submit")
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Debug", tableOutput("probs"), tableOutput("dftable")),
        tabPanel(plotOutput("distPlot"), tableOutput("sumtable"),
                 tableOutput("tabs"))
    )
  )
)))

server.r
library(shiny)
require(ggplot2)

shinyServer(function(input,output){

  TMo <- reactive({
         matrix(c(.90, .05, .04, .01,
                  .05, .80, .10, .05,
                  .05, .25, .60, .10,
                  .00, .00, .00, 1.0), nrow=4, ncol=4, byrow=T)
     })
   Pprob <- reactive({
     TMo()[1:3, 4]
   })

   output$probs <- renderTable({
     Pprob()
   })
   plotdata <- reactive({
     R <- vector()
     c <- vector()
     DefRate <- vector()
     groups <- vector()
     ctr <- 0

     for(group in 1:3){
       c[group] <- qnorm(Pprob()[group])
       for(i in 1:input$sim){
         e <- matrix(data = rnorm(n = input$loans, mean = 0, sd = 1))
         ctr <- ctr + 1
         default <- 0
         for(j in 1:input$loans){
           R[j] <- sqrt(input$rho) * M + sqrt(1 - input$rho) * e[j]
           if(R[j] <= c[group]){
             default + 1
           }
           if(j == input$loans){
             DefRate[ctr] <- default/input$loans
             if(group == 1){
               groups[ctr] = 'A'
             }
             else if(group == 2){
               groups[ctr] = 'B'
             }
             else{
               groups[ctr] = 'C'
             }
           }
           if(group == 3 & i == input$sims & j == input$loans){
             DefData <- cbind(DefRate,groups)
             as.data.frame(DefData)
           }
         }
       }
     }
   })
   output$dftable <- renderTable({
     head(plotdata())
   })

  #output$distPlot <- renderPlot({
    #bins <- seq(min(x), max(x), length.out = input$bins + 1)
    #DR_plots <- ggplot(DData, aes(x=DData$Default_Rate, fill=DData$Credit_Rating))
    #DR_Hist_options <- geom_histogram(binwidth = .01, alpha=.5, position = "identity")
    #DR_Hist <- DR_plots + DR_Hist_options
    #DR_Hist
    #hist(x, breaks = bins, col = 'darkgray', border = 'white',
         #main = "Default Rate Distribution", xlab = "Default Rates",
         #ylab = "Frequency")
  #})

  #output$tabs <- renderTable({
    #x <- DR_Data
    #head(x)
  #})

})

excuse the commented out sections. I'm was debugging to try to figure out the source of the problem. Thank you for the help.


text:
Q: Delay privilege separation in openSSH This question is about delaying the privilege separation in openSSH.
This is what I have learned from: Privilege Separated OpenSSH
Monitor process spawns unprivileged process for network processing (key exchange and authentication) and if user is authenticated, monitor spawns user privilege process after which pty will be allocated and user specific shell is spawned.
In my case, I need to spawn a shell (custom script) which first enters into a particular namespace and then call the script to spawn the shell. Since at this stage, user privilege process is spawning custom script, it is not able to enter into a particular namespace.
What I have seen from code that following lines of code in dropping the privilege (in privsep_postauth) to user.
-
668     -
669     /* Demote the private keys to public keys. */   -
670     demote_sensitive_data();    -
671     -
672     reseed_prngs(); -
673     -
674     /* Drop privileges */   -
675     do_setusercontext(authctxt->pw);

Can you guys guide me whether is it safe to do so and also how we can delay this privilege separation until shell is spawned. ?


text:
Q: How could I access java Runtime.getRuntime() if the project already have a Runtime Class? I have a code running inside Sinalgo Distributed Algorithm simulator. Sinalgo main thread is named Runtime and it needs to be imported inside all projects to run properly. I also use Sinalgo´s Runtime class. So I have:
import sinalgo.runtime.Global;
import sinalgo.runtime.Runtime;

However, I also need to access java´s Runtime.getRuntime() and I can´t because it is linked as Sinalgo´s runtime.
How could I access java Runtime.getRuntime()?
ps.: I tried to do the import java.lang.Runtime; but do not works.

A: Just specify the package name also if you're using the class which has package other than imported just like "user2478398" has mentioned.
java.lang.Runtime.getRuntime()


text:
Q: Two threads use same method despite using lock() in Java code? I have a simple code in Java. The purpose is to test entranceLock() of Java. There's a class named Bank (code below), which contains an array of Account objects (code for Account class is below).
Bank class can transfer money from one Account to another Account, using methods of Account objects named withdraw end deposit. (One of the data members is an array of Accounts named accounts).
AccountThread extends Thread which will run each Account as a Thread. It contains a reference to "Bank" object.
TestBank has the (public static void main(String args[]) method and will run the objects.
It will initialize a Bank object, make 10 AccountThread objects, pass reference to that Bank object to these AccountThread objects. Then it will start running all these 10 threads (running the AccountThread objects).
These 10 accounts transfer money only to each other. Each thread will run its own account.
These threads will in an infinite loop, randomly pick an account (one of the other 9 accounts) and transfer a random amount to that account.
After each 10 000 transaction the program will print some data, one of them is the "sum balance" (sum of the balance of all these 10 accounts).
That sum should never change, since the accounts only transfer money to each other.
I used lock.lock() and lock.unlock() in "deposit" and "withdraw" methods so that while there's a deposit or withdrawing in one account, other threads should not access those methods.
But there are some problems:
But the problem is, I do get some deviations from the sum, I don't understand what causes that.
I tried using "AccountThread" as class implements Runnable, but the results are the same.
There's what I tried:
1)
And I suspected the devitaion maybe is caused by that threads are still running when printing the data (which  may cause inconsistent data). So I changed something on the transfer method in Bank class, made a code to stop all threads from running before test() (and unlock all after running test()).
for (Account account: accounts) {account.getLock().lock();} before calling test() and toString()
and after test() and toString() I did call
for (Account account: accounts) {account.getLock().unlock();}

But the results are the same.
2)
I only locked the two accounts that just used in transfer before runing test(), so that other threads don't use these to accounts. But it doesn't work either.
I have tried other combinations too, but the results are not the desired results.
Ohter two problems are:

*

*Another problem is, while the toString() and test() methods are
called after each other, when running the program these methods get
called in random order**

*A thirdy problem is the test() results show not after each 10 000
transactions but often more than 10 000 transactions
Can multiple threads do access same deposit() or withdraw() method from same class at the same time despite the the methods use "lock.lock() and "lock.unlock()" methods?
Why is there some devitaion here ? How can I make sure the total-balance is always the same ?
Here's Account class:
import java.util.concurrent.locks.*;

class Account {
  private int balance;
  private int accountNumber;
  private Lock lock;
  private Condition lockCondition;

  public Account(int accountNumber, int balance) {
    this.accountNumber = accountNumber;
    this.balance = balance;
    this.lock = new ReentrantLock();
    this.lockCondition = lock.newCondition();
  }

/* HERE IS THE WITHDRAW AND DEPOSIT METHODS THAT ARE LOCKED */
  void withdraw(int amount) {
      lock.lock(); // Acquire the lock
      try {
        while (balance < amount) {
          lockCondition.await();
        }
        balance -= amount;
      }
      catch (InterruptedException ex) {
        ex.printStackTrace();
      }
      finally {
        lock.unlock(); // Release the lock
      }
  }

  void deposit(int amount) {
      lock.lock(); // Acquire the lock
      try {
        balance += amount;
        // Signal thread waiting on the condition
        lockCondition.signalAll();
      }
      finally {
        lock.unlock(); // Release the lock
      }
  }

  int getAccountNumber() {
    return accountNumber;
  }

  public int getBalance() {
    return balance;
  }

  Lock getLock() {
      return lock;
  }
}

Here's AccountThread class:
import java.util.Random;

class AccountThread extends Thread {
  private Bank bank;
  private boolean debug;
  private int accountIndex;
  private int maxTransferAmount;
  private Random random;

  public AccountThread(Bank b, int index, int max, boolean debug) {
    this.bank = b;
    this.accountIndex = index;
    this.maxTransferAmount = max;
    this.debug = debug;
    this.random = new Random();
  }

  public void run() {
    try {
      while (!interrupted()) {
        for (int i = 0; i < maxTransferAmount; i++) {
            int toAccount = random.nextInt(bank.nrOfAccounts());
            int amount = random.nextInt(maxTransferAmount);
            bank.transfer(accountIndex, toAccount, amount);
            sleep(2);
        }
      }
    } catch (InterruptedException ignored) {
    }
  }
}

Here's Bank class:
import java.util.concurrent.locks.*;

class Bank {
  private static final int TEST_FREQUENCY = 10000;
  private static final int TO_STRING_FREQUENCY = 10000;
  private Lock lock;
  private int deviationCount;
  private int initialBalance;
  private Account[] accounts;
  private long transactionCount;
  private boolean debug;
  private int testCount;

  public Bank(int accountAmount, int initialBalance, boolean debug) {
    accounts = new Account[accountAmount];
    this.initialBalance = initialBalance;
    this.debug = debug;
    int i;
    for (i = 0; i < accounts.length; i++)
      accounts[i] = new Account(i, initialBalance);
    this.transactionCount = 0;
    this.deviationCount = 0;
    this.lock = new ReentrantLock();
  }

  public void transfer(int fromAccount, int toAccount, int amount) {
      accounts[fromAccount].withdraw(amount);
      accounts[toAccount].deposit(amount);
      this.transactionCount++;
//    accounts[fromAccount].getLock().lock();
//    accounts[toAccount].getLock().lock();
    //  for (Account account: accounts) {account.getLock().lock();}
      lock.lock();
      try {
          if (transactionCount % TEST_FREQUENCY == 0) {
              test();
          }
          if (transactionCount % TO_STRING_FREQUENCY == 0) {
              System.out.println(toString());
          }

    //    accounts[fromAccount].getLock().unlock();
//        accounts[toAccount].getLock().unlock();
      } finally {
          lock.unlock();
      }
//    for (Account account: accounts) {account.getLock().unlock();}
  }

  public void test() {
    int sum = 0;
    for (Account account : accounts) {sum += account.getBalance(); }

    if (sum != nrOfAccounts()*initialBalance) {deviationCount++; }

    System.out.println("Transactions:" + getTransactionCount() + " Balance: " + sum
            + " Deviation count: " + getDeviationCount());
    testCount++;
  }

  @Override
  public String toString() {
      String string = String.format("\nTransactions; %d%n"
            + "Initial balance: %d%nNumber of accounts: %d%n"
            + "Deviation count: %d%nTestCount: %d%n"
            + "Error percentage: %.2f%n",
            getTransactionCount(), initialBalance, nrOfAccounts(),
            getDeviationCount(), testCount, getErrorPercentage());
      if (debug) {
          for (Account account :accounts) {
              string = string.concat(String.format("Account nr.: %d, Balance: %d%n",
                      account.getAccountNumber(), account.getBalance()));
          }
      }
      return string;
  }

  int nrOfAccounts() {
    return accounts.length;
  }

  private long getTransactionCount() {
      return transactionCount;
  }

  private int getDeviationCount() {
      return deviationCount;
  }

  private double getErrorPercentage() {
      double dividend = getDeviationCount();
      double divisor = testCount;
      double result = dividend / divisor;
      return result;
  }
}

Here's the BankTest class:
    public class BankTest {
    private static final boolean DEBUG = true;
    private static final int ACCOUNT_AMOUNT = 10;
    private static final int INITIAL_BALANCE = 100000;

    public BankTest() {};

    public static void main(String[] args) {
        Bank b = new Bank(ACCOUNT_AMOUNT, INITIAL_BALANCE, DEBUG);
        int i;
        for (i = 0; i < ACCOUNT_AMOUNT; i++) {
            AccountThread t = new AccountThread(b, i,
                    INITIAL_BALANCE, DEBUG);
            t.setPriority(Thread.NORM_PRIORITY + i % 2);
            t.start();
        }
    }
}

A: Q: What happens when there's a test() in progress, and some other AccountThread deducts money from one account that the test already has sampled, and transfers it to an account that the test has not sampled yet?
A: The money that was moved will be counted twice.
You have the opposite problem if money is transferred from an account that has not been sampled yet to an account that already has been sampled. That money will not be counted at all.
The locking that you've tried so far ensures that the total in the bank always will be correct at any single instant in time, but your test() can't be completed in a single instant.  You need to shut down the bank—prevent any and all transfers—during the counting.
IMO: The best way to do that would be to use a ReadWriteLock.  The normal use-case for a ReadWriteLock is a shared data structure that threads frequently want to examine, but seldom want to update. It will allows any number of simultaneous "readers" to access the structure *OR* it will allow one "writer" to access it, but not both.
In your application, the threads that want to transfer funds are the "readers." This may sound strange because those threads want to actually change the bank structure, but the point is, you want to allow any number of them to do their thing at the same time. On the other hand, a thread that wants to call test(), even though it modifies nothing, must play the "writer" role because it must have exclusive access to the bank. No transfers must be allowed to happen while a test() is in progress.


text:
Q: Чётные числа в массиве Не могу разобраться, как в консоли вывести элементы массива: все чётные числа от 1 до 20. Помогите, пожалуйста.
public static void main(String[] args) {
    int [] a = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};

    for (int i = 0; i < a.length; i++) {
        a[i] = (i+1)*2;

        System.out.println(Arrays.toString(a));
    }
}

A:
как в консоли вывести элементы массива: все чётные числа от 1 до 20

Вот так:
public static void main(String[] args) {
    int [] a = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};

    for (int i = 0; i < a.length; i++) {
        System.out.printf( "%d\n", a[i] );
    }
}

Или у вас что-то не так либо с задачей, либо с входными данными.

A: Отвечаю с планшета по этому за синтаксис не ручаюсь
For(int=0;i<a.length();i++){
   If(a[i]%2==0)
      System.out.println(a[i]);
}

A: Если нужно вывести все четные числа массива в котором могут быть нечетные числа, можно использовать данный подход:
 int [] array = {2, 3, 5, 8, 10, 11, 14, 15, 18, 20};

    for(int i=0;i<array.length;i++)
    {
        if(array[i]%2==0)
        {
            System.out.println("Index: "+i+"; Number: "+array[i]);
        }
    }

Если нужно вывести только числа, то и foreach'ем можно обойтись
for (int number : array)
        if (number % 2 == 0)
            System.out.println(number);

Вывод:
Index: 0; Number: 2
Index: 3; Number: 8
Index: 4; Number: 10
Index: 6; Number: 14
Index: 8; Number: 18
Index: 9; Number: 20