text:
Q: Perform an os.walk through a zip compressed file using the zipfile module I would like to do an os.walk through a zipped file without extracting files. The zipfile module can provide the information needed. Does anyone have a script that will output the same list of tuples that os.walk outputs when looking through an uncompressed directory tree?
I have a partial solution. This only goes one level deep and outputs to a dictionary which can easily be converted to os.walk() output format:
import zipfile

def zipwalk(zfile):
    dlistdb = {'' : []}
    for info in zfile.infolist():
        ilist = info.filename.split('/')
        if '' in ilist:
            ilist.remove('')
        if info.is_dir():
            dlistdb[ilist[-1]] = []
        elif ilist[-2] in dlistdb:
            dlistdb[ilist[-2]].append(ilist[-1])
        else:
            dlistdb[''].append(ilist[-1])

    return dlistdb

A: Answered my own question. Here's the code I have:
#!/usr/bin/python3

import os
import zipfile

# Mimic os.walk() function for zipfiles
def zipwalk(zfile):
    # Initialize database
    dlistdb = {}

    # Walk through zip file information list
    for info in zfile.infolist():
        if info.is_dir():
            zpath = os.path.dirname(os.path.dirname(info.filename).rstrip('/'))
            zfile = os.path.basename(os.path.dirname(info.filename).rstrip('/'))
            if zpath in dlistdb:
                dlistdb[zpath][0].append(zfile)
            else:
                dlistdb[zpath] = [[zfile], []]
        else:
            zpath = os.path.dirname(info.filename)
            zfile = os.path.basename(info.filename)
            if zpath in dlistdb:
                dlistdb[zpath][1].append(zfile)
            else:
                dlistdb[zpath] = [[], [zfile]]

    # Convert to os.walk() output format
    dlist = []
    for key in dlistdb.keys():
        dlist.append((key, dlistdb[key][0], dlistdb[key][1]))

    return iter(dlist)

zfile = zipfile.ZipFile('data/test.zip')
db = zipwalk(zfile)

print(list(db))


text:
Q: Ignore null and get full result I have below linq select coding. The result become empty if db.actions.ACTC_DBID values are null. How to avoid that. I need to get the query result with null values.
var apList = (from r in db.components
                              join o in db.cmp_actionpanel on r.CMP_DBID equals o.CMP_DBID
                              join u in db.cmp_button on o.BTN_DBID equals u.BTN_DBID
                              join a in db.actions on o.ACTC_DBID equals a.ACTC_DBID
                              where (r.ORG_DBID == org && r.CMP_DBID == id)
                              orderby o.ORDER_IDX
                              select new
                              {
                                  AP_DBID = o.AP_DBID,
                                  CMP_NAME = r.CMP_NAME,
                                  CMP_DBID = r.CMP_DBID,
                                  BTN_NAME = u.BTN_NAME,
                                  BTN_DBID = u.BTN_DBID,
                                  ORDER_IDX = o.ORDER_IDX,
                                  ALWAYS_VISIBLE = o.ALWAYS_VISIBLE,
                                  ACTC_DBID = a.ACTC_DBID,
                                  ACTION_CODE = a.ACTION_CODE,
                                  ACTION_CMP_DBID = o.ACTION_CMP_DBID,
                                  STARTS_JOB_PROGRESSION = o.STARTS_JOB_PROGRESSION,
                                  VISIBLE_ON = o.VISIBLE_ON,
                                  CAPTURE_INFO = o.CAPTURE_INFO,
                                  COMMAND = o.COMMAND
                              }).ToList();

A:  var apList = (from r in db.components
                              join o in db.cmp_actionpanel on r.CMP_DBID equals o.CMP_DBID
                              join u in db.cmp_button on o.BTN_DBID equals u.BTN_DBID
                              join a in db.actions on o.ACTC_DBID equals a.ACTC_DBID into aGroup
                              where (r.ORG_DBID == org && r.CMP_DBID == id)
                              orderby o.ORDER_IDX
                              from ag in aGroup.DefaultIfEmpty()
                              select new
                              {
                                  AP_DBID = o.AP_DBID,
                                  CMP_NAME = r.CMP_NAME,
                                  CMP_DBID = r.CMP_DBID,
                                  BTN_NAME = u.BTN_NAME,
                                  BTN_DBID = u.BTN_DBID,
                                  ORDER_IDX = o.ORDER_IDX,
                                  ALWAYS_VISIBLE = o.ALWAYS_VISIBLE,
                                  ACTC_DBID = ag.ACTC_DBID == null ? (int?)null : ag.ACTC_DBID,
                                  ACTION_CODE = ag.ACTION_CODE,
                                  ACTION_CMP_DBID = o.ACTION_CMP_DBID,
                                  STARTS_JOB_PROGRESSION = o.STARTS_JOB_PROGRESSION,
                                  VISIBLE_ON = o.VISIBLE_ON,
                                  CAPTURE_INFO = o.CAPTURE_INFO,
                                  COMMAND = o.COMMAND
                              }).ToList();

redpajama_set_name: RedPajamaStackExchange


text:
Q: 'k' keybinding in ruby-mode in Emacs I am learning emacs and have started using it for ruby programming. As a newbie to emacs, I configured it based upon the Prelude package by bbatsov (https://github.com/bbatsov/emacs-prelude) which by and large is great.  I am using the Mac Emacs 24 pretest package from http://emacsformacosx.com/builds.
The problem I have is probably not related to that - not sure if it's a bug in the ruby-mode package.
When I'm in ruby-mode and I hit the "k" key, as if typing "knackered", the "k" key acts as a prefix key ("k" isn't inserted in the buffer but shows in the mini-buffer). The only way I can insert a "k" character in ruby-mode is C-q k, which is really annoying.
I've raked through all the documentation about keymaps and have been through all the config files (ELPA, modules, custom, init, etc) and can find nothing that switches this on, including in the ruby-mode config files. I am very confused and a bit frustrated.  Can anyone shine any light on this?

A: I have no idea what switches that on, but you should be able to override it using something like:
(local-set-key (kbd "k") 'self-insert-command)

You can run this using M-:. You can also put this line in a ruby mode hook.

A: So, I'm an emacs noob myself and I had the same problem. I found that I had created a custom yasnippet and in the auto-generated template there was a directive to bind the snippet to a key: binding: "keybinding". Once I removed that, the problem went away.
TL;DR
I found it because when I typed C-h m to list the active modes, I saw some strange stuff about about a K E Y B I N D I N    Prefix Command. After I saw that, I hit C-h k keybinding (to show what command was bound to that set of keystrokes) and it came up with some error message that also included the snippet I remembered writing a day or so ago. I went to the yasnippet directory and edited the snippet, and my problem went away.
I know that you fixed your problem already, but for anyone else who might run into this issue, but doesn't want to just override the 'k' key to work as expected, you might try looking for a snippet with a binding: "keybinding" directive.


text:
Q: Node.js - getting a value from MySQL and assigning it to a variable My query:
pool.query("SELECT MAX(ID) FROM `games` WHERE status IN('0','1') LIMIT 1", (err, row) => {
    if(err) return console.log("err getting the game.");
    currentGame = row[0];
    console.log(currentGame);
});

Current Result:
RowDataPacket { 'MAX(ID)': 1 }

Desired Result:
1
How do I get just the value and not include the other stuff?

A: Try adding an alias to your count query, and then access it:
pool.query("SELECT MAX(ID) AS max_id FROM games WHERE status IN ('0','1')", (err, row) => {
    if(err) return console.log("err getting the game.");
    currentGame = row[0].max_id;
    console.log(currentGame);
});

Note: A max query by definition will always return only a single record result set (in the absence of GROUP BY), so there is no need for LIMIT 1.


text:
Q: ¿Cómo puedo generar un formulario y que se repita? Quiero generar un formulario un número de veces establecido por mí; yo ingreso en un input el número de veces que se va a repetir el formulario, pero cuando lo hago se repite de corrido. Yo quiero hacer para enviar uno, y que me salga el siguiente, y almacenar los datos en un array. ¿Cómo lo hago?

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

Dame el numero de alumnos registrados

        <input type="number" name="alum" id="alum">
        <input type="submit" value="enviar" name="uno">
    </form>

<?php
if(isset($_POST["uno"])){
    $alum = $_POST['alum'];
    $inicio = 1;
    while ($inicio <= $alum) {
    ?>
        <form action="practica3.php" method="post">
    <fieldset>
        <legend>Alumno Nº <?php echo "$inicio"; ?></legend>

¿Que edad tiene? <input type="number" name="edad">

¿Eres Chico o Chica? <select name="kesos" id="kesos">
            <option value="chico">chico</option>
            <option value="chica">chica</option>
        </select>

¿Publica o Privada? <select name="a" id="a">
            <option value="publica">publica</option>
            <option value="privadaca">privada</option>
        </select>

¿Cual fue tu promedio al terminar? <input type="number" name="pro">

    </fieldset>
    <?php
        $inicio++;
    }

?>

    <input type="submit" value="enviar" name="dos">
    </form>
    <?php
    }
    ?>

Este es mi código. Quiero hacer que no se ponga el formulario uno debajo de otro; quiero cargar el primero y que despues de llenarlo, y darle a enviar me salga el siguiente, así sucesivamente hasta llegar al número establecido antes.

A: Algo que debes saber: En PHP orientado a web (no php-cli), el script se ejecuta totalmente. O sea, procesa las órdenes, manda la salida HTML y muere. Si el script quedara esperando órdenes, el navegador se colgaría.
Hay varias formas de resolver tu problema: mandando un contador como input hidden, con sesiones, con una base de datos, etc.
Te voy a dejar un ejemplo usando hidden. En esta propuesta el contador $i se envía en el parámetro escondido 'idx'. Cuando se le da ENVIAR, nuevamente $i valdrá 0, pero no por mucho tiempo ya que entrará al primer if, captura el valor de idx y sobreescribe $i.
En el siguiente if/else se pregunta si $i es menor al $total, si es así, se intrementa ++$i y se dibuja el formulario (para ello usé una función, pero puedes prescindir de ella si quieres).

<?php
function generar_formulario($i) {
    ?>

Formulario <?php echo $i;?>

    <form action="" method="POST">
        - Aqui van los inputs -

        <input type="text" name="input1" value="">

        <input type="hidden" name="idx" value="<?php echo $i;?>">
        <input type="submit" value="ENVIAR">
    </form>
    <?php
}

$total = 3; // <-- Total de veces que se dibujará el formulario
$i = 0; // <-- Contador

if(isset($_POST['idx'])) {
    echo 'Valores capturados:
' . PHP_EOL;
    var_dump($_POST); // <-- Data cruda enviada
    $i = $_POST['idx']; // <-- sobreescribe $i
}

if ($i < $total) {
    generar_formulario(++$i); // <-- Dibujar formulario
} else {
    echo '
Ya fueron generados todos los formularios
';
}
?>


text:
Q: How do I create a file in a folder? I have an Apps Script that creates multiple files and moves them into a folder. Is there a way to place the a file directly in a folder or do I first have to get the file then copy it to the appropriate folder and then removing it from the root folder like this:
folder=DocsList.createFolder("MyFolder");
var file=DocsList.createFile(blob);
file.addToFolder(folder);
file.removeFromFolder(DocsList.getRootFolder());

The problem with this is that if you open up Drive you see the file is first placed in the root folder then moved to MyFolder. So there is a bit of a lag until the execution of removeFromFolder.

A: As of 2015, you should use the DriveApp service to manage files in Google Drive. DriveApp has a Folder class that allows you to create a file directly in a folder.
function createFilesInFolder() {
  //This creates the folder
  var folder = DriveApp.createFolder('My Folder');
  //This creates a file in the folder
  var file = folder.createFile('My File.txt',
                               'Lorem ipsum',
                               MimeType.PLAIN_TEXT);
}

A: The DocsList no longer works and has been replaced by the DriveAPI , Google App Services and Advanced Google services .
Here I leave my test code , this code creates folders - subfolders - google files - pdf - and stores them in folders and subfolders in various ways, and I hope will be helpful
function Drive_2015() {   //busca un folder, si no lo hay lo crea y crea 2 sub carpetas un google document copiado en cada una de ellas
  var name='folder de prueba';
  var carpeta = DriveApp.getRootFolder().searchFolders("title contains '"+name+"'");
  if (carpeta.hasNext()===true) {
      while (carpeta.hasNext()) {
      var folder = carpeta.next();
      Logger.log(folder.getName()+' '+folder.getId());
      }
  }else{
    var folder=DriveApp.getRootFolder().createFolder(name);

    var parent=DriveApp.getFolderById(folder.getId());   // get parent folder
    var folder2 =parent.createFolder('Subfolder');   // 1° way to create sub folder
    var folder3=folder.createFolder(name+1);// 2° way to create sub folder (and more easy)

    var doc = DocumentApp.create('Documento sta');
    var sheet = SpreadsheetApp.create('Spreadsheet sta');
    Utilities.sleep(300); // este retardo es para garantizar en el user-side la creacion del nuevo archivo
    var files = DriveApp.getFilesByName('Documento sta');// or Id var file = DriveApp.getFileById(doc.getId());
    while (files.hasNext()) {
      var file = files.next();
      Logger.log('ojo '+file.getName());
      file.makeCopy(folder3);
      file.makeCopy(folder2);
      var file2=file.makeCopy(folder);
      file2.setName('Acta individual del alumno')
      var blob = file2.getAs('application/pdf');
      var file2pdf = folder.createFile(blob);
      var file2pdf = DriveApp.getFileById(file2pdf.getId());
      var file2pdf=file2pdf.makeCopy(folder);
      Logger.log('se creó: '+file.getName()+' en la carpeta: '+folder.getName()+' el PDF es: '+file2pdf.getId());
      DriveApp.getFileById(file2pdf.getId()).setTrashed(true)
      DriveApp.getFileById(docid).setTrashed(true)
      }
  }
}

A: I just wanted to comment (but don't have the 50 reputation points).
The reason the answer above works when the original post didn't is that .createFolder applies to both DocsList.createFolder (which creates the folder in the root directory) and to Folder.createFolder which creates a sub-folder in the current folder.
It may be obvious to everyone but me - but it took me a good while to realise :-)

A: Just tested the following code
function Test() {
  DocsList.createFolder('Folder1').createFolder('Subfolder1').createFile('File1', 'Empty');
}

It works as expected, i.e. created a new File1 document in newly created folder My Drive\Folder1\Subfolder1.

A: GAS now allows a quicker method to move a file by using .moveTo
The assumption is that you want to build a document that you can edit.  This code allows you to create the folder, create the doc, move the doc, and finally, tap into the DocumentApp to edit the file.
Ex:
const saveTo = DriveApp.createFolder("FolderName").next().getId();
const newDoc = DocumentApp.create("New Doc"),
  newDocId = DriveApp.getFileById(newDoc.getId()).moveTo(saveTo);


text:
Q: Redirect to registration bootstrap model in Laravel 6 I am using the following code in my controller for redirecting to login page if a guest user clicks button for uploading a product. Now I have created bootstrap model for login and registration. I want to pop-up the modal if user click button.
public function __construct()
    {
        $this->middleware('auth')->except('index', 'show');
    }

Login and Register Button
@guest

     <button type="button" class="btn btn-primary btn-outline-light" data-toggle="modal" data-target="#signIn" href="{{ route('login') }}">{{ __('Login') }}</button>

   @if (Route::has('register'))

       <button type="button" class="btn btn-primary btn-outline-light" data-toggle="modal" data-target="#signUp" href="{{ route('register') }}">{{ __('Register') }} </button>

   @endif

Bootstrap Modal

SignIn

                <button type="button" class="close" data-dismiss="modal">
                    ×
                </button>

                <form method="POST" action="{{ route('login') }}">
                    @csrf

                        {{ __('E-Mail Address') }}
                        <input id="email" type="email" class="form-control" @error('email') is-invalid @enderror"
                            name="email" value="{{ old('email') }}" required autocomplete="email" autofocus />

                        @error('email')

                            {{ $message }}

                        @enderror

                        {{ __('Password') }}
                        <input id="password" type="password"
                            class="form-control @error('password') is-invalid @enderror" name="password" required
                            autocomplete="current-password">

                        @error('password')

                            {{ $message }}

                        @enderror

                        <button type="submit" class="btn btn-primary btn-block">
                            Sign In
                        </button>

                </form>


text:
Q: error connecting sequel pro to mysql on mac localhost i just installed mysql on my mac, with brew. I then started the service and made the secure installation to add a password.
now i can login into my sql from terminal but i'd like to connect also Sequel Pro to it.
i tried using standard connection but i get
"unable to connect to host 127.0.0.1 or the request timed out. be sure that the address is correct and that you have the necessary privileges, or try increasing the connection timeout"
MySQL said: Authentication plugin 'cachin_sha2_password' cannot be loaded: dlopen(/usr/local/lib/plugin/caching_sha2_password.so, 2): image not found
how to fix this? if i try connecting to other apps like table plus it works with no issues...


text:
Q: Nhibernate equal restriction on guid I have a class, Comapny, with userId as system.Guid, i want to filter that company (userId is not the primary key), but when I do it like this:
     List<Company> list =
            session.CreateCriteria<Company>().Add(Restrictions.Eq("UserId", userId))
            .List<Company>().ToList();

The list is returning empty even though there are rows in the db with that property.
I tried doing it like this:
        Company companyResult = null;

        list.ForEach(delegate (Company company)
                         {
                             if (company.UserId.Equals(userId))
                             {
                                 if (companyResult == null)
                                 {
                                     companyResult = company;
                                 }
                             }
                         });

        return companyResult;

and it works, is there a reason why Nhibernate eq won't work on this Guid?

A: Why not using the Query method?
var list = session.Query<Company>().Where(x => x.UserId == userId).ToList();

A: The best you can do to really investigate this, is to switch on show-sql, apparently you are retrieving something different from the database then you think?


text:
Q: Integrate product of x^s and log(x) Let
$$ f(x) = 1 - (1-c\log (F(x)))^s\\
g(x) = \log(\frac{a}{x})
$$
for some positive integers $s$, $c$, and some real-valued function $F(x)$. $\log$ denotes the natural logarithm. One can think about $f(x)$ as the minimum outcome of $s$ independent draws of a random variable with distribution $c\log (F(x))$.
I'm trying to get the expected value of $g(x)$, given the minimum of $s$ draws. That is, I need to integrate
$$ \int f'(x)g(x) dx$$
for some positive real number $a$. I know that $g'(x) = \frac{1}{x}$, and I am aware of the integral trick $\int u'v = uv - \int v'u$. However, I fail to see how I could use that. There's no substitution trick that I could think of that makes sense here.
How could I proceed? Note that this is not a homework assignment, so a closed form solution to the expression is not guaranteed.
I don't believe it is useful (because it doesn't have a nice structure), but here's F(x) for two real numbers $d,e$:
$$ F(x) = \frac{dx}{x-e}$$

A: FooBar.
We have: $ f(x) = 1 - \left( 1 - c \cdot \log(F(x)) \right)^s \Leftrightarrow f'(x) =-s \cdot (1 - c \cdot \log(F(x)))^{s-1} \cdot \left( - \frac{c}{F(x) \cdot \ln (10) } \right) \cdot F'(x)  $, assuming $ \log(F(x)) = \log_{10}( F(x)) $.
Then:
$ \int f'(x) \cdot g(x) dx = \frac{s}{\ln(10)}\int (1 - c \cdot \log(F(x)))^{s-1} \cdot \frac{c \cdot F'(x)}{F(x)} \cdot \log \left( \frac{a}{x} \right) dx $
Now: $ F(x) = \frac{dx}{x-e} \Leftrightarrow F'(x) = \frac{d \cdot (x-e) - dx \cdot 1}{(x-e)^2} = \frac{dx - de - dx}{(x-e)^2} = -\frac{de}{(x-e)^2} $
And thus we have:
$ \large{\frac{s}{\ln(10)} \cdot \int (1 - c \cdot \log \left( \frac{dx}{x-e} \right))^{s-1} \cdot -\frac{c \cdot \left( \frac{de}{(x-e)^2}\right)}{\frac{dx}{x-e}} \cdot \log \left( \frac{a}{x} \right) dx  \\\\ = -\frac{s \cdot c}{\ln(10)} \cdot \int \left(1 - c \cdot \log \left( \frac{dx}{x-e} \right)\right)^{s-1} \cdot \frac{e}{(x-e)^2 \cdot x}  \cdot \log \left( \frac{a}{x} \right) dx}$
I don't see how one can proceed from here on out without knowing the values of the variables.
Kind regards,
Pedro


text:
Q: Example of finite simply connected space Is there any space with such properties? If there is no such space, I would be very grateful if you could tell me proof of this fact.

A: The Sierpiński space is contractible, hence simply connected.

A: There is a construction which associates a topological space to any poset. Under this construction finite posets gives rise to finite topological spaces. It is known that the space is contractible if the poset has maximum (or minimum). This construction gives you a lot of examples. For instance the example of Arthur Fischer correspond with the poset with 2 (comparable) points.
EDIT: It is "easy" to construct examples of simply-connected non-contractible spaces. An easy one is the space associated to the poset $P=\{(a,b): a=0,1; b=0,1,2\}$ where $(a,b)<(a',b')$ if $b<b'$ (this is a model of $S^2$).


text:
Q: How to retrieve row and column data from table represented by div tags I am looking to retrieve data from rows and columns of the table represented by div tags. It is easier when tbody,tr,td tags are present but here the whole table, row and column is represented using div tags (UI grid view). Can someone help how can I proceed with fetching data using selenium webdriver. Any help appreciated.
Something like below code:

A: It's much easier as iteration of general table as below :-
WebElement table = driver.findElement(By.id("table_view"));

 //Now find all rows
List<WebElement> rows = table.findElements(By.xpath(".//div[@row]"));

for(WebElement row : rows)
{
    List<WebElement> cols = row.findElements(By.xpath(".//div[@col]"));
    for(WebElement col : cols)
    {
        System.out.println(col.getText());
    }
 }

Or you can directly iterate all columns only as below :-
List<WebElement> cols = driver.findElement(By.id("table_view")).findElements(By.xpath(".//div[@col]"));
 for(WebElement col : cols)
 {
     System.out.println(col.getText());
 }


text:
Q: Unable to update an item in CosmosDB using the replace method with JavaScript I am trying to create a basic REST API using Azure functions and the cosmosDB client for JavaScript. I have been successful with all the actions except the UPDATE. The cosmosDB client uses conainter.item(id,category).replace(newObject) I am unable to get the container.item().replace method to work. When I test the function in the portal or using Postman, I get a 500 error and in the portal, I get the error: Result: Failure Exception: Error: invalid input: input is not string Stack: Error: invalid input: input is not string at trimSlashFromLeftAndRight.
Example of my basic document/item properties

{
  id:002,
  project:"Skip rope",
  category:"task",
  completed: false
}

const config = require("../sharedCode/config");
const { CosmosClient } = require("@azure/cosmos");

module.exports = async function (context, req) {
  const endpoint = config.endpoint;
  const key = config.key;
  const client = new CosmosClient({ endpoint, key });

  const database = client.database(config.databaseId);
  const container = database.container(config.containerId);

  const theId = req.params.id;

  // I am retrieving the document/item that I want to update
  const { resource: docToUpdate } = await container.item(theId).read();

  // I am pulling the id and category properties from the retrieved document/item
  // they are used as part of the replace method
  const { id, category } = docToUpdate;

  // I am updating the project property of the docToUpdate document/item
  docToUpdate.project = "Go fly a kite";

  // I am replacing the item referred to with the ID with the updated docToUpdate object
  const { resource: updatedItem } = await container
    .item(id, category)
    .replace(docToUpdate);

  const responseMessage = {
    status: 200,
    message: res.message,
    data: updatedItem,
  };

  context.res = {
    // status: 200, /* Defaults to 200 */
    body: responseMessage,
  };

};
I Googled the heck out of this and been through the Microsoft Azure CosmosDB documents from top-to-bottom, but I can't figure out how to get this to work.  I can get the other CRUD operations to work based on the examples Microsoft docs provide, but not this. Any help would be greatly appreciated.

A: I believe the reason you're getting this error is because the data type of your "id" field is numeric. The data type of "id" field should be string.
UPDATE
So I tried your code and was able to run it successfully. There was one issue I noticed in your code though:
const { resource: docToUpdate } = await container.item(theId).read();

In the above line of code, you are not specifying the partition key value. If you don't specify the value, then your docToUpdate would come as undefined. In my code I used task as partition key value (I created a container with /category as the partition key).
This is the code I wrote:
const { CosmosClient } = require("@azure/cosmos");

const endpoint = 'https://account.documents.azure.com:443/';
const key = 'accountkey==';
const databaseId = 'database-name';
const containerId = 'container-name';

// const docToUpdate = {
//   'id':'e067cbae-1700-4016-bc56-eb609fa8189f',
//   'project':"Skip rope",
//   'category':"task",
//   'completed': false
// };

async function readAndUpdateDocument() {
  const client = new CosmosClient({ endpoint, key });

  const database = client.database(databaseId);
  const container = database.container(containerId);

  const theId = 'e067cbae-1700-4016-bc56-eb609fa8189f';

  const { resource: docToUpdate } = await container.item(theId, 'task').read();

  console.log(docToUpdate);
  console.log('==============================');
  const { id, category } = docToUpdate;
  docToUpdate.project = "Go fly a kite";

  console.log(docToUpdate);
  console.log('==============================');

  const { resource: updatedItem } = await container
      .item(id, category)
      .replace(docToUpdate);

  console.log(updatedItem);
  console.log('==============================');
}

readAndUpdateDocument();

Can you try by using this code?


text:
Q: LoadUserProfile not creating local user profile when it does not exist [C#] I have a tool which I use to programmatically create local user accounts as follows:
DirectoryEntry NewUser = dirEntryLocalMachine.Children.Add("UserName", "user");
NewUser.Invoke("SetPassword", new object[] { "Passsord" });
NewUser.Invoke("Put", new object[] { "Description", "Description" });
NewUser.CommitChanges();

The account is created fine but at at this point the User Profile does not exists (no HKEY CURRENT USER, no Documents & Settings, etc...), I was doing some research into this and found the following MSDN article that says calling LoadUserProfile(...) will actually create the profile if it does not exist:
How To Programmatically Cause the Creation of a User's Profile
So I added the code as follows:
IntPtr hToken = IntPtr.Zero;
bool bLogon = LogonUser(
        sName,
        sDomain,
        sPassword,
        LOGON32_LOGON_NETWORK,
        LOGON32_PROVIDER_DEFAULT,
        out hToken
        );

PROFILEINFO profileInfo = new PROFILEINFO();
profileInfo.dwSize = Marshal.SizeOf(profileInfo);
profileInfo.dwFlags = 1;
profileInfo.lpUserName = sName;
bool bLoad = LoadUserProfile(hToken, ref profileInfo);

Now, both bLogon and bLoad are true, no exceptions occur, everything "seems" to work fine ...
The contents of profileInfo are not updated (I would have assumed field like .lpProfilePath should have good values) and GetUserProfileDirectory() fails to find the path (obviously - it doesn't exist) - I also check manually and there is nothing under "documents & settings" for the new account.
Anyone have any clues as to what I am doing wrong?
Any help would be much appreciated.
Thanks,

A: I assume this is all done under admin - in reality it is a service running as LocalSystem performing the task - doesn't it have complete admin rights? And if I was lacking priveleges I assume I would get an error code of some sorts.
I have also tried running this as ADMINISTRATOR itself (logged on as interactive user) thinking it might have something to do with the Service, etc... But same results - no errors but the profile is not created.

A: I have the same problem. I run as an admin, then impersonate as a newly created non-admin and cannot LoadUserProfile, because of insufficient permissions. If you call Marshal.GetLastWin32Error() after calling to LoadUserProfile, you will get an error 1314: A required privilege is not held by the client.


text:
Q: how to aggregate only the numerical columns in a mixed dtypes dataframe I have a mixed pd.DataFrame:
import pandas as pd
import numpy as np
df = pd.DataFrame({ 'A' : 1.,
                     'B' : pd.Timestamp('20130102'),
                     'C' : pd.Timestamp('20180101'),
                     'D' : np.random.rand(10),
                     'F' : 'foo' })

df
Out[12]:
     A          B          C         D    F
0  1.0 2013-01-02 2018-01-01  0.592533  foo
1  1.0 2013-01-02 2018-01-01  0.819248  foo
2  1.0 2013-01-02 2018-01-01  0.298035  foo
3  1.0 2013-01-02 2018-01-01  0.330128  foo
4  1.0 2013-01-02 2018-01-01  0.371705  foo
5  1.0 2013-01-02 2018-01-01  0.541246  foo
6  1.0 2013-01-02 2018-01-01  0.976108  foo
7  1.0 2013-01-02 2018-01-01  0.423069  foo
8  1.0 2013-01-02 2018-01-01  0.863764  foo
9  1.0 2013-01-02 2018-01-01  0.037085  foo

I would like to aggregate my numerical columns, but keep also the non-numerical ones.
If I do a gropuby followed by agg.
I get:
df.groupby('B').agg(np.median)
Out[13]:
              A         D
B
2013-01-02  1.0  0.482157

which is fine, and I know is desired behavior as the other dtypes probably raise exceptions during np.median, but I would like to get also my original column F with value foo, as well as C with 2018-01-01
So far, I have solved with a custom wrapper to my numerical aggregation functions e.g. if I wanted to do a nanmean over my dataframe:
def my_nan_median(x):
    if isinstance(x.values[0], np.datetime64):
        return np.min(x) # let the first datetime pass!
    elif isinstance(x.values[0], str):
        return x.values[0] # let the strings pass!
    else:
        return np.nanmedian(x)

but it looks awful.
What is the right way to do so?

A: By using select_dtypes:
df.groupby(list(df.select_dtypes(exclude=[np.number]))).agg(np.median).reset_index()

Or something like this:
df1 = df.groupby('B',as_index=False).agg(np.median)
pd.concat([df1,df.drop_duplicates(['B']).drop(list(df1),1).reset_index(drop=True)],axis=1)

A: If 'C', 'F' are the same for each value of 'B', then you can include it in the groupby columns, like this:
df.groupby(['B','C','F']).agg(np.median).reset_index()

Or as @BradSolomn suggests:
df.groupby(['B','C','F'], as_index=False).agg(np.median)

Output:
           B          C    F    A         D
0 2013-01-02 2018-01-01  foo  1.0  0.392723

If not, then you'll need to aggregrate 'C', 'F' somehow for example get the get the first value from 'C', 'F'
df.groupby('B').agg({'D':np.median,'A':np.median,'C':'first','F':'last'}).reset_index()

           B          C    F    A         D
0 2013-01-02 2018-01-01  foo  1.0  0.392723


text:
Q: SQL Server: how to get data from lowest hierarchy in hierarchy table? I have a hierarchical table like this
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EX_TABLE](
    [PARENT_OBJ] [nvarchar](255) NOT NULL,
    [PARENT_OBJ_TYPE] [nvarchar](64) NOT NULL,
    [DESCEN_OBJ] [nvarchar](255) NOT NULL,
    [DESCEN_OBJ_TYPE] [nvarchar](64) NOT NULL,
    [DESCEN_OBJ_USAGE] [nvarchar](20) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'Batch_name_1', N'Batch', N'batch_name', N'Built In Function', NULL)
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'Batch_name_1', N'Batch', N'print', N'Built In Function', NULL)
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'Batch_name_1', N'Batch', N'batch_run_id', N'Built In Function', NULL)
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'Batch_name_1', N'Batch', N'db_name', N'Built In Function', NULL)
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'Batch_name_1', N'Batch', N'repo_name', N'Built In Function', NULL)
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'Batch_name_1', N'Batch', N'WF_Batch_name_1', N'WF', NULL)
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'Batch_name_1', N'Batch', N'table_attr', N'Built In Function', NULL)
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'WF_Batch_name_1', N'WF', N'DF_Batch_name_1', N'DF', NULL)
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'WF_Batch_name_1', N'WF', N'DF_Batch_name_1_2', N'DF', NULL)
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'DF_Batch_name_1', N'DF', N'TABLE_1', N'Table', N'Source')
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'DF_Batch_name_1', N'DF', N'Query', N'Transform', N'Transform')
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'DF_Batch_name_1', N'DF', N'sysdate', N'Built In Function', NULL)
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'DF_Batch_name_1', N'DF', N'TABLE_2', N'Table', N'Target')
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'DF_Batch_name_1', N'DF', N'TABLE_2', N'Table', N'Key')
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'DF_Batch_name_1', N'DF', N'DS_NAME', N'Ds', NULL)
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'DF_Batch_name_1', N'DF', N'Key', N'Trans', N'Trans')
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'DF_Batch_name_1_2', N'DF', N'TABLE_1', N'Table', N'Source')
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'DF_Batch_name_1_2', N'DF', N'sysdate', N'Built In Function', NULL)
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'DF_Batch_name_1_2', N'DF', N'TABLE_3', N'Table', N'Target')
INSERT [dbo].[EX_TABLE] ([PARENT_OBJ], [PARENT_OBJ_TYPE], [DESCEN_OBJ], [DESCEN_OBJ_TYPE], [DESCEN_OBJ_USAGE]) VALUES (N'DF_Batch_name_1_2', N'DF', N'Key', N'Trans', N'Trans')

The idea is to traverse tree upwards from DF to WF and to Batch. In this example, Batch_name_1 has a many child objects (DESCEN_OBJ) but only WF child is interesting (WF_Batch_name_1). WF_Batch_name_1 has also child objects (DESCEN_OBJ), which are DF objects (DF_Batch_name_1, DF_Batch_name_1_2).
DF_Batch_name_1 and DF_Batch_name_1_2 have also child objects, but I'm only interested in table objects (from DESCEN_OBJ_TYPE) which have DESCEN_OBJ_USAGE as Target.
Batch is always the highest member in this tree and DF the lowest, but there can bee other members between these two. See that this is only the subset of real data.
So, how can I query distinct number of target (DESCEN_OBJ_USAGE) tables (DESCEN_OBJ_TYPE) for Batch_name_1 (PARENT_OBJ). The result should be 2 in this case (with real data this does not produce right result when I have many batches (highest member in hierarchy), so traversing upwards to batches is needed):
SELECT COUNT(distinct descen_obj) as dobj FROM EX_TABLE
WHERE DESCEN_OBJ_TYPE = 'Table' and DESCEN_OBJ_USAGE = 'Target'

Hierarchy is represented in DESCEN_OBJ field. Can this be achieved using single query (recursive CTE?) without temporary tables? Any advice regarding this would be most appreciated!

A: I am not sure I understand your question, but might you be looking for this?
with tree as (
   select parent_obj,
          parent_obj_type,
          descen_obj,
          descen_obj_usage,
          descen_obj_type,
          1 as level
   from ex_table
   where parent_obj = 'Batch_name_1'

   union all

   select e.parent_obj,
          e.parent_obj_type,
          e.descen_obj,
          e.descen_obj_usage,
          e.descen_obj_type,
          t.level + 1
   from ex_table e
      join tree t on e.parent_obj = t.descen_obj
)
select *
from tree
where descen_obj_type = 'Table'
  and descen_obj_usage = 'Target'

It would be very helpful if you could post the expected output from your sample data and a more detailed explanation on how that should be achieved.

A: If you want to get all DF-children of Batch_name_1 and these can be identified through [PARENT_OBJ_TYPE] = 'DF', and there are an unknown number of layers/members between then I might be suggesting using some temporary tables like this:
-- Creating a temporary table where we will store all found members from the lowest level
CREATE TABLE #DF (
    [DESCEN_OBJ_TYPE] [nvarchar](64) NOT NULL,
    [DESCEN_OBJ_USAGE] [nvarchar](20) NULL
)

CREATE TABLE #DESCEN (
    [DESCEN_OBJ] [nvarchar](255) NOT NULL
)

-- First we get the initial top layer
SELECT *
INTO #PARENTS
FROM [dbo].[EX_TABLE]
WHERE [PARENT_OBJ] = 'Batch_name_1'

-- Loop running as long as there are children
WHILE EXISTS (SELECT * FROM #PARENTS)
BEGIN

    -- Storing away the DF levelled members
    INSERT INTO #DF ([DESCEN_OBJ_TYPE],[DESCEN_OBJ_USAGE])
    SELECT [DESCEN_OBJ_TYPE],[DESCEN_OBJ_USAGE]
    FROM #PARENTS WHERE [PARENT_OBJ_TYPE] = 'DF'

    INSERT INTO #DESCEN ([DESCEN_OBJ])
    SELECT DISTINCT [DESCEN_OBJ]
    FROM #PARENT WHERE [PARENT_OBJ_TYPE] <> 'DF'

    -- Clearing the parents table since we are going to fill it with the next layer
    TRUNCATE TABLE #PARENTS
    INSERT INTO #PARENTS
    SELECT ex.*
    FROM #DESCEN de
    INNER JOIN [dbo].[EX_TABLE] ex ON ex.[PARENT_OBJ] = de.[DESCEN_OBJ]

    TRUNCATE TABLE #DESCEN

END

-- Finally outputting
SELECT DISTINCT * FROM #DF

DROP TABLE #PARENTS
DROP TABLE #DESCEN
DROP TABLE #DF

I might have misunderstood your problem. And also, if there is a set number of layers you can probably make it in a much simpler manner.
I haven't tested the code and there might be some bug in it, but I hope you understand the concept.
Also, be careful. If you have a hierarchy loop (a decendant having a higher level member as child), this will be stuck in an eternal loop.

A: Is this what you're talking about?
-- flatten hierarchy while keeping top-level ID
WITH all_descendants(top_parent_obj, middle_obj, descen_obj) AS (
    SELECT parent_obj, descen_obj, descen_obj
      FROM dbo.EX_TABLE
     WHERE PARENT_OBJ_TYPE = 'Batch'
     UNION ALL
    SELECT p.top_parent_obj, c.DESCEN_OBJ, c.DESCEN_OBJ
      FROM all_descendants p
     INNER JOIN dbo.EX_TABLE c
             ON p.middle_obj = c.PARENT_OBJ
)
-- show distinct usages by top-level ID
SELECT d.top_parent_obj, o.DESCEN_OBJ_USAGE
  FROM all_descendants d
 INNER JOIN dbo.EX_TABLE o
         ON d.descen_obj = o.DESCEN_OBJ
 GROUP BY d.top_parent_obj, o.DESCEN_OBJ_USAGE

The output is:
Batch_name_1    NULL
Batch_name_1    Key
Batch_name_1    Source
Batch_name_1    Target
Batch_name_1    Trans
Batch_name_1    Transform


text:
Q: Android: Fragment When frButton is clicked FragmentOne should open and MainActivity should be hidden but Components of MainActivity is still accessible in FragmentOne, which is unwanted.
How to fix it?
code for MainActivity:
public void gofag1(View v) {
    // TODO Auto-generated method stub
    FragmentOne frag = new FragmentOne();
    FragmentManager fm = getFragmentManager(); // import
    FragmentTransaction ftr = fm.beginTransaction(); // import
    ftr.add(R.id.mainlayout, frag, "keyFrag");
    ftr.addToBackStack(null);
    ftr.commit();
}

code for FragmentOne:
public class FragmentOne extends Fragment {

public FragmentOne() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_one, container,
            false);
    return v;
}
}

code for FragmentOne layout... R.layout.fragment_one
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.megavb.le.FragmentOne" >

<!-- TODO: Update blank fragment layout -->

<TextView
    android:id="@+id/tOnOff"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="22dp"
    android:text="@string/a1" />

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:onClick="reedToggleValue"
    android:text="ToggleButton"
    android:textSize="30sp" />

code for MainActivity layout.... R.id.mainlayout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical" >

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:onClick="gofag1"
    android:text="fOne" />

</RelativeLayout>

Please see the picture for better understanding...

A: So, you should be using ftr.replace instead of ftr.add
public void gofag1(View v) {
    // TODO Auto-generated method stub
    FragmentOne frag = new FragmentOne();
    FragmentManager fm = getFragmentManager(); // import
    FragmentTransaction ftr = fm.beginTransaction(); // import

    //Notice the change here
    ftr.replace(R.id.mainlayout, frag, "keyFrag");
    ftr.addToBackStack(null);
    ftr.commit();
}

Hope this helps!
EDIT: Well, without more information I'm going to take another stab at this.
In your mainlayout.xml you need to define a Fragment Container a simple method of doing this would be to use a layout file like the one that follows as a base for your Activity.
<?xml version="1.0" encoding="utf-8"?>

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/fragment_container">
</FrameLayout>

after defining this new fragment container you can programmatically add fragments to it by referencing it's ID.
The next step is to move your original MainActivty code into a new fragment!
This is the code for fragment_main
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:onClick="gofag1"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

Here we create a new layout that simply contains a button.
Next we create the actual fragment
public class FragmentMain extends Fragment {

    public FragmentMain() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_main, container,
                false);
}

From here we can change our Main activity OnCreate code to
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainlayout);
    FragmentMain frag = new FragmentMain();
    FragmentManager fm = getFragmentManager(); // import
    FragmentTransaction ftr = fm.beginTransaction(); // import
    ftr.add(R.id.fragment_container, frag, "keyFrag");
    ftr.addToBackStack(null);
    ftr.commit();

}


text:
Q: How do I get a string from a registered Window message's lParam I am trying to decode a message I get back from qCollector.
http://www.mechtrading.com/developers/QCollectorDeveloperGuide_2.1.htm
In WndProc I appear to receive a message which should have lParam as a string, but it looks like an integer. Perhaps it is a pointer?
I have tried using Marshal.PtrToStringAnsi(m.LParam)) (See below) BUT no variation of it gives me a string that is NOT empty.
Output:
50483: QCOLLECTOR_CLIENT_PORTFOLIO_LIST_REQUEST
50484: QCOLLECTOR_PORTFOLIO_LIST_REQUEST_COMPLETE
50485: QCOLLECTOR_CLIENT_DATA_REQUEST
50486: QCOLLECTOR_DATA_REQUEST_COMPLETE
50487: QCOLLECTOR_CLIENT_REALTIME_SYMBOL_LIST_REQUEST
50488: QCOLLECTOR_REALTIME_SYMBOL_LIST_REQUEST_COMPLETE
50489: QCOLLECTOR_CLIENT_PORTFOLIO_ITEMS_REQUEST
50490: QCOLLECTOR_PORTFOLIO_ITEMS_REQUEST_COMPLETE
50491: QCOLLECTOR_CLIENT_REMOVE_REALTIME_SYMBOL_REQUEST
50492: QCOLLECTOR_CLIENT_CLEAR_REALTIME_SYMBOLS
50493: QCOLLECTOR_LAST_RECORD_UPDATE
50494: QCOLLECTOR_REGISTER_FOR_LAST_RECORD_UPDATE
50495: QCOLLECTOR_UNREGISTER_FOR_LAST_RECORD_UPDATE
50496: QCOLLECTOR_FILE_UPDATE
50497: QCOLLECTOR_ALL_FILES_UPDATED
50498: QCOLLECTOR_REGISTER_FOR_FILE_UPDATES
50499: QCOLLECTOR_UNREGISTER_FOR_FILE_UPDATES
50501: QCOLLECTOR_DELETE_PORTFOLIO_ITEM

SENT to: 13381044 From: 2438012  2438012
Ans: 1

Message:
HWnd: 2438012
LParam: 49440
WParam: 0
Msg: 50484
String:

If you create a simple forms App with a button then use this code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace ApiMessageTest2
{
    public partial class Form1 : Form
    {

        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private static extern int FindWindow(string sClass, string sWindow);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint RegisterWindowMessage(string lpString);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            TestQC();
        }

        int nWinHandle;
        bool msgSent = false;

        List<string> AtomsList = new List<string> {
            "QCOLLECTOR_CLIENT_DATA_REQUEST",
            "QCOLLECTOR_CLIENT_PORTFOLIO_LIST_REQUEST",
            "QCOLLECTOR_PORTFOLIO_LIST_REQUEST_COMPLETE",
            "QCOLLECTOR_CLIENT_PORTFOLIO_ITEMS_REQUEST",
            "QCOLLECTOR_PORTFOLIO_ITEMS_REQUEST_COMPLETE",
            "QCOLLECTOR_CLIENT_REALTIME_SYMBOL_LIST_REQUEST",
            "QCOLLECTOR_REALTIME_SYMBOL_LIST_REQUEST_COMPLETE",
            "QCOLLECTOR_DATA_REQUEST_COMPLETE",
            "QCOLLECTOR_CLIENT_REMOVE_REALTIME_SYMBOL_REQUEST",
            "QCOLLECTOR_DELETE_PORTFOLIO_ITEM",
            "QCOLLECTOR_CLIENT_CLEAR_REALTIME_SYMBOLS",
            "QCOLLECTOR_REGISTER_FOR_FILE_UPDATES",
            "QCOLLECTOR_UNREGISTER_FOR_FILE_UPDATES",
            "QCOLLECTOR_FILE_UPDATE",
            "QCOLLECTOR_ALL_FILES_UPDATED",
            "QCOLLECTOR_REGISTER_FOR_LAST_RECORD_UPDATE",
            "QCOLLECTOR_UNREGISTER_FOR_LAST_RECORD_UPDATE",
            "QCOLLECTOR_LAST_RECORD_UPDATE"};

        Dictionary<string, uint> Atoms = new Dictionary<string, uint>();

        public void RegisterAtoms()
        {
            foreach (var atom in AtomsList)
            {
                Atoms.Add(atom, RegisterWindowMessage(atom));
            }

        }

        public void ShowAtoms()
        {
            var sortedAtoms = Atoms.OrderBy(x => x.Value);

            foreach (var pair in sortedAtoms)
            {
                Console.WriteLine(pair.Value.ToString() + ": " + pair.Key);
            }
        }

        public void TestQC()
        {

            RegisterAtoms();
            ShowAtoms();
            System.Diagnostics.Process proc = Process.GetCurrentProcess();

            try
            {
                nWinHandle = FindWindow("QCDataInterfaceWndClass", null);
            }
            catch (Exception err)
            {
                throw;
            }

            if (nWinHandle == 0)
            {
                throw new Exception("Duff");
            }

            msgSent = true;
            int ans = SendMessage((IntPtr)nWinHandle, Atoms["QCOLLECTOR_CLIENT_PORTFOLIO_LIST_REQUEST"], IntPtr.Zero, this.Handle);
            Console.WriteLine("SENT to: " + nWinHandle + " From: " + proc.MainWindowHandle + "  " + this.Handle);
            Console.WriteLine("Ans: "+ans);
        }

        protected override void WndProc(ref Message m)
        {
            if (msgSent)
            {

                if (Atoms.ContainsValue((uint)m.Msg) || m.LParam == new IntPtr(nWinHandle))
                {
                    Console.WriteLine("HWnd: " + m.HWnd.ToString());
                    Console.WriteLine("LParam: " + m.LParam.ToString());
                    Console.WriteLine("WParam: " + m.WParam.ToString());
                    Console.WriteLine("Msg: " + m.Msg.ToString());
                    Console.WriteLine("String: " + Marshal.PtrToStringAnsi(m.LParam));

                }
            }
            base.WndProc(ref m);
        }
    }
}

A: Per the documentation you linked to:

The QCollector Data Interface relies on Windows messages and the Windows Global Atom Table to accept commands and exchange information with client programs. Atoms are references to text strings, managed by Windows, which can be used by Windows programs to share information.
...
QCOLLECTOR_PORTFOLIO_LIST_REQUEST_COMPLETE - After QCollector saves the portfolio list to a temp file, it will will send this message to the HWnd that requested the portfolio list. lParam is an Atom holding one string value which is the full path and file name for the portfolio list file. QCollector deletes the Atom when SendMessage returns. On receipt of this message the client application can read the file to get the list of current portfolios in QCollector.
...
QCOLLECTOR_PORTFOLIO_ITEMS_REQUEST_COMPLETE - QCollector sends this message to the window handle that requested the portfolio items list. lParam is an Atom holding one string value - the full path and file name for the portfolio item list text file created by QCollector. QCollector deletes the Atom when SendMessage returns.
...
QCOLLECTOR_REALTIME_SYMBOL_LIST_REQUEST_COMPLETE - QCollector sends this message to the window handle that requested the list. lParam is an Atom holding one string value - the full path and file name for the list text file. QCollector deletes the Atom when SendMessage returns. On receipt of this message your application can read the file to get information about all the items in the QCollector timed updates list.

And so on for all of the other messages that your app receives in reply to data requests.
Per MSDN documentation:
About Atom Tables:

String Atoms
When applications pass null-terminated strings to the GlobalAddAtom, AddAtom, GlobalFindAtom, and FindAtom functions, they receive string atoms (16-bit integers) in return. String atoms have the following properties:

*

*The values of string atoms are in the range 0xC000 (MAXINTATOM) through 0xFFFF.

*Case is not significant in searches for an atom name in an atom table. Also, the entire string must match in a search operation; no substring matching is performed.

*The string associated with a string atom can be no more than 255 bytes in size. This limitation applies to all atom functions.

*A reference count is associated with each atom name. The count is incremented each time the atom name is added to the table and decremented each time the atom name is deleted from it. This prevents different users of the same string atom from destroying each other's atom names. When the reference count for an atom name equals zero, the system removes the atom and the atom name from the table.
...
Atom-Table Queries
An application can determine whether a particular string is already in an atom table by using the FindAtom or GlobalFindAtom function. These functions search an atom table for the specified string and, if the string is there, return the corresponding atom.
An application can use the GetAtomName or GlobalGetAtomName function to retrieve an atom-name string from an atom table, provided the application has the atom corresponding to the string being sought. Both functions copy the atom-name string of the specified atom to a buffer and return the length of the string that was copied. GetAtomName retrieves an atom-name string from a local atom table, and GlobalGetAtomName retrieves an atom-name string from the global atom table.

So, in your case, given the atom handles being passed in the lParam values, you can use GlobalGetAtomName() to retrieve the string values:

Retrieves a copy of the character string associated with the specified global atom.

For example:
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace ApiMessageTest2
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr FindWindow(string sClass, string sWindow);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint RegisterWindowMessage(string lpString);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint GlobalGetAtomName(ushort nAtom, StringBuilder lpBuffer, int nSize);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            TestQC();
        }

        IntPtr nWinHandle;

        Dictionary<string, uint> CommandMsgs = new Dictionary<string, uint>();
        Dictionary<uint, string> NotificationMsgs = new Dictionary<uint, string>();

        public void RegisterMessages()
        {
            List<string> Commands = new List<string> {
                "QCOLLECTOR_CLIENT_DATA_REQUEST",
                "QCOLLECTOR_CLIENT_PORTFOLIO_LIST_REQUEST",
                "QCOLLECTOR_CLIENT_PORTFOLIO_ITEMS_REQUEST",
                "QCOLLECTOR_CLIENT_REALTIME_SYMBOL_LIST_REQUEST",
                "QCOLLECTOR_CLIENT_REMOVE_REALTIME_SYMBOL_REQUEST",
                "QCOLLECTOR_DELETE_PORTFOLIO_ITEM",
                "QCOLLECTOR_CLIENT_CLEAR_REALTIME_SYMBOLS",
                "QCOLLECTOR_REGISTER_FOR_FILE_UPDATES",
                "QCOLLECTOR_UNREGISTER_FOR_FILE_UPDATES",
                "QCOLLECTOR_REGISTER_FOR_LAST_RECORD_UPDATE",
                "QCOLLECTOR_UNREGISTER_FOR_LAST_RECORD_UPDATE"};

            foreach (var MsgName in Commands)
            {
                uint msg = RegisterWindowMessage(MsgName);
                if (msg != 0)
                    CommandMsgs.Add(MsgName, msg);
            }

            List<string> Notifications = new List<string> {
                "QCOLLECTOR_PORTFOLIO_LIST_REQUEST_COMPLETE",
                "QCOLLECTOR_PORTFOLIO_ITEMS_REQUEST_COMPLETE",
                "QCOLLECTOR_REALTIME_SYMBOL_LIST_REQUEST_COMPLETE",
                "QCOLLECTOR_DATA_REQUEST_COMPLETE",
                "QCOLLECTOR_FILE_UPDATE",
                "QCOLLECTOR_ALL_FILES_UPDATED",
                "QCOLLECTOR_LAST_RECORD_UPDATE"};

            foreach (var MsgName in Notifications)
            {
                uint msg = RegisterWindowMessage(MsgName);
                if (msg != 0)
                    NotificationMsgs.Add(msg, MsgName);
            }
        }

        public void ShowMessages()
        {
            var sortedCommands = CommandMsgs.OrderBy(x => x.Value);

            foreach (var pair in sortedCommands)
            {
                Console.WriteLine($"{pair.Key}: {pair.Value}");
            }

            var sortedNotifications = NotificationMsgs.OrderBy(x => x.Key);

            foreach (var pair in sortedNotifications)
            {
                Console.WriteLine($"{pair.Value}: {pair.Key}");
            }
        }

        public void TestQC()
        {
            RegisterMessages();
            ShowMessages();

            System.Diagnostics.Process proc = Process.GetCurrentProcess();

            try
            {
                nWinHandle = FindWindow("QCDataInterfaceWndClass", null);
            }
            catch (Exception err)
            {
                throw;
            }

            if (nWinHandle == IntPtr.Zero)
            {
                throw new Exception("Duff");
            }

            int ans = SendMessage(nWinHandle, CommandMsgs["QCOLLECTOR_CLIENT_PORTFOLIO_LIST_REQUEST"], IntPtr.Zero, this.Handle);
            Console.WriteLine($"SENT to: {nWinHandle} From: {proc.MainWindowHandle} {this.Handle}");
            Console.WriteLine($"Ans: {ans}");
        }

        protected override void WndProc(ref Message m)
        {
            string MsgName;
            if (NotificationMsgs.TryGetValue((uint)m.Msg, MsgName))
            {
                Console.WriteLine($"HWnd: {m.HWnd}");
                Console.WriteLine($"Msg: {m.Msg} ({MsgName})");
                Console.WriteLine($"WParam: {m.WParam}");
                Console.WriteLine($"LParam: {m.LParam}");

                if ((MsgName == "QCOLLECTOR_PORTFOLIO_LIST_REQUEST_COMPLETE") ||
                    (MsgName == "QCOLLECTOR_PORTFOLIO_ITEMS_REQUEST_COMPLETE") ||
                    (MsgName == "QCOLLECTOR_REALTIME_SYMBOL_LIST_REQUEST_COMPLETE") ||
                    (MsgName == "QCOLLECTOR_DATA_REQUEST_COMPLETE") ||
                    (MsgName == "QCOLLECTOR_FILE_UPDATE") ||
                    (MsgName == "QCOLLECTOR_LAST_RECORD_UPDATE"))
                {
                    StringBuilder sb = new StringBuilder(514);
                    GlobalGetAtomName((ushort)Msg.LParam, sb, sb.Capacity);
                    Console.WriteLine($"String: {sb.ToString()}");
                }
                else if (MsgName == "QCOLLECTOR_ALL_FILES_UPDATED")
                {
                    Console.WriteLine($"# Updated: {Msg.LParam}");
                }
            }
            base.WndProc(ref m);
        }
    }
}


text:
Q: How to retain the state of inflated layout in android Can anybody tell me how to retain the state of inflated layout while configuration changes, in android?
Can anybody provide some sample code?
Thanks

A: Activity.onSaveInstanceState - save current state
Activity.onRestoreInstanceState - restore from saved state
More reading: http://developer.android.com/reference/android/app/Activity.html#SavingPersistentState

A: It's not cleat which part you have problem with. But anyway, take a good read of:

*

*Activity Lifecycle: Saving Activity state

*Handling Runtime [Configuration] Changes
Also, all views with assigned id's usually save their state themself.

A: This is one trick I've learned to retain the current layout when configuration changes:
http://xjaphx.wordpress.com/2011/09/19/the-less-known-over-screen-orientation/


text:
Q: HDF4Error: SD (59): HDF Internal error I am trying to download a hdf file and read it python as follows
from pyhdf import SD

file = open("temp.hdf", 'w')
ftp.retrbinary('RETR '+ filename, file.write)
file.close()

hdf=SD.SD('temp.hdf')

It works but soon after the I am getting the following Error:
Traceback (most recent call last):

  File "<ipython-input-46-55805a9d569b>", line 6, in <module>
    hdf=SD.SD('temp.hdf')

  File "/usr/local/lib/python2.7/dist-packages/pyhdf/SD.py", line 1444, in __init__
    _checkErr('SD', id, "cannot open %s" % path)

  File "/usr/local/lib/python2.7/dist-packages/pyhdf/error.py", line 23, in _checkErr
    raise HDF4Error(err)

HDF4Error: SD (59): HDF Internal error

A: You need to open the output file in binary mode:
file = open("temp.hdf", 'wb') # was 'w'

Better would be to use with to automatically close the file:
with open("temp.hdf", 'wb') as out:
    ftp.retrbinary('RETR '+ filename, out.write)


text:
Q: Android studio looses connection to device saying IGmsServiceBroker.getService failed My flutter android application seems to quit soon after loading with following error message. I am using google maps in my application and this happens soon after the maps load. I can see the map but can't seem to press +/- zoom button on the map. So, I am not sure if the map is loading completely with success. But because I see the map, I believe API keys are set up correctly. I have spent days trying to figure this out. So, any help appreciated. Following is error message and configuration file for my project.
[+4906 ms] W/GmsClient(30295): IGmsServiceBroker.getService failed
[        ] W/GmsClient(30295): android.os.DeadObjectException
[        ] W/GmsClient(30295):  at android.os.BinderProxy.transactNative(Native Method)
[        ] W/GmsClient(30295):  at android.os.BinderProxy.transact(Binder.java:1127)
[        ] W/GmsClient(30295):  at com.google.android.gms.common.internal.IGmsServiceBroker$Stub$zza.getService(com.google.android.gms:play-services-basement@@17.2.1:13)
[        ] W/GmsClient(30295):  at com.google.android.gms.common.internal.BaseGmsClient.getRemoteService(com.google.android.gms:play-services-basement@@17.2.1:257)
[        ] W/GmsClient(30295):  at com.google.android.gms.common.api.internal.zabn.run(com.google.android.gms:play-services-base@@17.2.1:11)
[        ] W/GmsClient(30295):  at android.os.Handler.handleCallback(Handler.java:873)
[        ] W/GmsClient(30295):  at android.os.Handler.dispatchMessage(Handler.java:99)
[        ] W/GmsClient(30295):  at com.google.android.gms.internal.base.zap.dispatchMessage(com.google.android.gms:play-services-base@@17.2.1:8)
[        ] W/GmsClient(30295):  at android.os.Looper.loop(Looper.java:193)
[        ] W/GmsClient(30295):  at android.os.HandlerThread.run(HandlerThread.java:65)

App level build.gradle
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.fair.riderapp"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    //-> implementation 'com.google.firebase:firebase-core:16.0.1'
    // Add the SDK for Firebase Cloud Messaging
    //-> implementation 'com.google.firebase:firebase-messaging:17.0.3'
    //implementation 'com.google.firebase:firebase-analytics:17.4.4'
    implementation 'com.google.firebase:firebase-auth:19.3.2'
    //implementation 'com.android.support:support-core-utils:28.0.0'
    // <-
    //implementation 'com.google.firebase:firebase-analytics:17.4.4'
    implementation 'com.google.firebase:firebase-messaging:20.2.3'
}

apply plugin: 'com.google.gms.google-services'
//apply plugin: 'com.android.application'

Project level build graddle
buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        //->classpath 'com.android.tools.build:gradle:3.3.0'
        //->classpath 'com.google.gms:google-services:4.0.1'
        //classpath 'com.google.gms:google-services:4.3.3'
        //<-
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath 'com.google.gms:google-services:4.3.3'
    }

    subprojects {
        project.configurations.all {
            resolutionStrategy.eachDependency { details ->
                if (details.requested.group == 'com.android.support'
                        && !details.requested.name.contains('multidex') ) {
                    details.useVersion "27.1.1"
                }
                if (details.requested.group == 'androidx.core'
                        && !details.requested.name.contains('androidx') ) {
                    details.useVersion "1.0.1"
                }
                if (details.requested.group == 'androidx.localbroadcastmanager' &&
                        !details.requested.name.contains('androidx')) {
                    details.useVersion "1.0.0"
                }
            }
        }
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

project level gradle.properties
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
android.enableR8=true

My pubspec.yaml
name: abc_xyz_app
description: A new Flutter application.

version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cloud_firestore: ^0.13.7 #any
  firebase_auth: ^0.16.1 #^0.8.4+5
  google_maps_flutter: ^0.5.28+1 #any
  flutter_map: ^0.10.1 #any
#  geoflutterfire: ^2.0.3+2
  location: ^3.0.2 #^2.3.5
  google_maps_webservice: ^0.0.17 #^0.0.14
  http: ^0.12.2 #^0.12.0+2
  uuid: ^2.2.0 #^2.0.1
  geolocator: ^5.3.2+2 #^5.1.0
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  provider: ^4.3.1 #^3.0.0+1
  geocoder: ^0.2.1 #^0.1.2
  flutter_google_places: ^0.2.4 #^0.2.3
  geoflutterfire: ^2.1.0 #any
  get_it: ^4.0.2 #^1.0.3+2
  shared_preferences: ^0.5.8 #^0.5.3+4
  flutter_spinkit: ^4.1.2+1 #^4.0.0
  firebase_messaging: ^6.0.16 #^4.0.0+1
  flutter_mapbox_autocomplete: ^1.0.4 #^1.0.3

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.3 #^0.1.2

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:

  uses-material-design: true

  assets:
    - assets/FAYR_logo.png
    - assets/greencar.png
    - assets/loading.gif

A: I have the same problem. Started today. service was working just fine. Could it be an update on gooogl  services
Google Maps Android API(12315): Google Play services package version: 202414019
D/AbsListView(12315): Get MotionRecognitionManager
W/GmsClient(12315): IGmsServiceBroker.getService failed
W/GmsClient(12315): android.os.DeadObjectException


text:
Q: Erro ao customizar o InfoWindowAdapter no Google Map? Tenho este arquivo XML:
?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:src="@drawable/ic_carro"
        android:layout_alignBottom="@+id/mmarker_snippet"
        android:layout_alignParentTop="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/marker_titulo"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/imageView"
        android:layout_toEndOf="@+id/imageView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/mmarker_snippet"
        android:layout_below="@+id/marker_titulo"
        android:layout_alignLeft="@+id/marker_titulo"
        android:layout_alignStart="@+id/marker_titulo" />
</RelativeLayout>

E o código para:
mapa.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

                @Override
                public View getInfoContents(Marker marker) {

                    if (janela == null) {

                        janela = getLayoutInflater().inflate(R.layout.info_window, null);

                        janela.setLayoutParams(new RelativeLayout.LayoutParams(200, RelativeLayout.LayoutParams.WRAP_CONTENT));

                        TextView markerTitulo = (TextView) findViewById(R.id.marker_titulo);
                        markerTitulo.setText(marker.getTitle());

                        TextView markerSnippet = (TextView) findViewById(R.id.mmarker_snippet);
                        markerSnippet.setText(marker.getSnippet());

                    }

                    return janela;
                }

                @Override
                public View getInfoWindow(Marker marker) {

                    return null;
                }

            });

NB: janela refer-se à uma View que declarei na mesma classe.
Mas quando executo a app, sempre que clico no marcador, recebo um NullPointerException e não entendo porquê.

A: O método findViewById() que está a chamar é do objecto Activity.
Ele encontra views que estejam no layout passado ao método setContentView().
No código postado as views markerTitulo e markerSnippet encontram-se na view janela, que foi criada na linha
janela = getLayoutInflater().inflate(R.layout.info_window, null);

Para obter a referência a essas views deve usar o método findViewById() do objecto janela, que é do tipo View.
em vez de
TextView markerTitulo = (TextView) findViewById(R.id.marker_titulo);
markerTitulo.setText(marker.getTitle());

TextView markerSnippet = (TextView) findViewById(R.id.mmarker_snippet);
markerSnippet.setText(marker.getSnippet());

use
TextView markerTitulo = (TextView) janela.findViewById(R.id.marker_titulo);
markerTitulo.setText(marker.getTitle());

TextView markerSnippet = (TextView) janela.findViewById(R.id.mmarker_snippet);
markerSnippet.setText(marker.getSnippet());


text:
Q: How to make upper bound predictions and lower bound predictions not far from predictions on fbprophet or Silverkite forecasting? How to make upper bound predictions and lower bound predictions not far from predictions on fbprophet or Silverkite forecasting?
I've done a lot of methods and research but haven't found it yet, does anyone know how to do it, thanks.
enter image description here


text:
Q: Dismiss Spinner on Server Side Validation Error Performed extensive searches - could not find a solution.
When a user selects "submit" on a form, I'd like to display a spinner.  If there exists a validation error I'd like to dismiss the spinner so that the user can correct the errors on the form.  I know how to hook this when validating on the client.  But there are instances where I have to validate on the server.
In cases where there is a server side validation error is there a way to hook  @Html.ValidationSummary to call out a jQuery function?
I have to imagine this is a common scenario - just can't figure out how to do this.


text:
Q: How to automatic insert blank rows depend on 1 column? I have table same there

and I want automatic insert blank rows depend on the cell in first column,

Anyone can help me? I tried many methods but none of it does exactly I need.
Sorry for my English.

A: You can add 1 index column as primary key. Then insert only index column and your PK with all blank fields.

A: Create button and assign to the following macro
Sub BRow()
    Dim WorkRng As Range
    Dim FirstRow As Integer
    Dim lngRows As Integer
    Dim lngCols As Integer

    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Select Range", WorkRng.Address, Type:=8)
    FirstRow = WorkRng.Row
    lngRows = WorkRng.Rows.Count
    lngCols = WorkRng.Columns.Count
    WorkRng.Cells(lngRows, 1).Resize(1, lngCols).Select

    Do Until Selection.Row = FirstRow
        Selection.Insert shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        Selection.Offset(-1, 0).Select
    Loop
End Sub

See Examples here


text:
Q: Does utf-8 encoding need character length? From what I understand, casual binary serialization implementations of non-static structures (like an array or a vector) would usually state the structure's "length" as the first word (usually a 64bit uint), then proceed to encode each entity's value, without separators (given the serialized subject data in each cell of the array is deterministic, so the binary parser doesn't need any lookahead or backtracking).
Would this behavior be the same, traditionally, for utf-8 strings? I can't see any other way for implementing a binary serialization for "unbounded" utf-8 strings, such that the parser wouldn't need backtracking (which can be really inefficient) or lookahead (which would also need excessive testing against various possibilities, also inefficient). My guess is that the "length" value would denote the number of characters, not the number of bytes, as the utf-8 encoding ranges from 1 to 4 bytes for each character, although the encoding itself denotes how many bytes exist in the character based on the first byte (eliminating backtracking and lookahead, per-character).
As an example, the octet stream for the string abc would be
[0,0,0,0,0,0,0,3,97,98,99]

where 0,0,0,0,0,0,0,3 denotes the uint64 length of the input string, abc.
Is my intuition correct, or is there something I'm missing?

A: In UTF-8, the Unicode code point U+0000 (NUL) is encoded as a single byte of value zero.  It does not occur in the encoding of any other code point in UTF-8, so a null-terminated byte string can be used without a preceding length as long as embedded NUL is not allowed in the sequence; Otherwise, a preceding length can also be used as you have shown in the question.
For example, the Unicode string "abcdéfg一二三四" is encoding as the hexadecimal bytes:
61 62 63 64 c3 a9 66 67 e4 b8 80 e4 ba 8c e4 b8 89 e5 9b 9b 00
a  b  c  d  é     f  g  一       二       三       四        ␀

UTF-8 doesn't need backtracking or lookahead since the lead byte of a sequence indicates the number of trailing bytes required for the code point:

61hex = 01100001bin (one-byte sequence)
  c3hex = 11000011bin (two-byte sequence)
  e4hex = 11100100bin (three-byte sequence)

Trailing bytes all begin with 10xxxxxxbin:

a9hex = 10101001bin (trailing byte)
  b8hex = 10111000bin (trailing byte)
  80hex = 10000000bin (trailing byte)


text:
Q: try websphere portal in cloud does exist a websphere portal version to try in cloud?
i can't find nothing about "web sphere portal" that i can sign up and play
i've found something about other ibm products like "bpm" but nothing about portal.
I've found nothing in bluemix as well
do you know more?

A: no there is not a cloud trial version,  Portal on cloud is known as DX on cloud https://www.ibm.com/us-en/marketplace/web-content-management-software . and is quite expensive


text:
Q: How to custom tabs with fragment? I just want to customize the tabs on my app to a picturs with selector or something where i need to begin? here is my code.
now my app is with the regular black and blue tabs but i want to make it custom
what should i do?
    here is my code:
Class a
  public class ListFragment extends Fragment{

        basAdapterCustom adapter;
        ListView lv;
        ArrayList<Clock> list;
        private DbHandler hand;
        Context context;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.list_fragment, container, false);
            context = getActivity();

            Log.d(TAG, "onCreateView");

            hand = new DbHandler(context);
            list = new ArrayList<Clock>();

            lv = (ListView) v.findViewById(R.id.listOfShifts);
            adapter = new basAdapterCustom(list, getActivity());
            lv.setAdapter(adapter);
            refreshList();
            return v;
        }

        //like on "resume":
        @Override
        public void setUserVisibleHint(boolean isVisibleToUser) {
            super.setUserVisibleHint(isVisibleToUser);
            // Make sure that we are currently visible
            if (this.isVisible()) {
                refreshList();
                if (!isVisibleToUser) {
                    // TODO stop
                }
            }
        }

        private void refreshList() {

            list = hand.getByWorkName();
            adapter = new basAdapterCustom(list,getActivity());

            lv.setAdapter(adapter);
        }

class b:
public class ClockFragment extends Fragment{

    DbHandler hand;

    Context context;
    @Override
    public View onCreateView(LayoutInflater inflater,
            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.clock, container,false);

        context = getActivity();

        hand = new DbHandler(context);

        return v;
    }

    // ADD to .Db
    public void addToDb(View v){
        hand.add(new Clock(0, dateDay));

    }

}

class mainActivity:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener, OnPageChangeListener{

    public static final String TAG = "myClock";

    String[] tabMenu = {"FRAG A","FRAG B","FRAG C"};

    private ViewPager viewPager;
    private TabPagerAdapter mAdapter;
    private ActionBar actionBar;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d(MainActivity.TAG, "OnCreate = MainActivity (Pager");
        viewPager = (ViewPager) findViewById(R.id.pager );
        actionBar = getActionBar();
        mAdapter = new TabPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        for (String tabsNames : tabMenu) {
            actionBar.addTab(actionBar.newTab().setText(tabsNames).setTabListener(this));
        }
        viewPager.setOnPageChangeListener(this);

    }

    //  public void transDialog(){
    //      Dialog mDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
    //  }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {

    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int position) {
        actionBar.setSelectedNavigationItem(position);
    }

}

PagetAdapter.class
public class TabPagerAdapter extends FragmentPagerAdapter {

    private static final String TAG = "myClock";

    public TabPagerAdapter(FragmentManager fm) {
        super(fm);
        // TODO Auto-generated constructor stub
    }

    @Override
    public Fragment getItem(int index) {
        Log.d(TAG, " CLASS : TabPagerAdapter");
        switch (index) {
        case 0:

            return new ListFragment();
        case 1:
            return new ClockFragment();
        case 2:
            return new SettingFragment();

        default:
            break;
        }
        Log.d(TAG, " CLASS : TabPagerAdapter = "+index);
        return null;
    }

    @Override
    public int getCount() {
        return 3;
    }

}

A: for (String tabsNames : tabMenu) {
    actionBar.addTab(actionBar.newTab().setText(tabsNames).setTabListener(this));
}

Change this to:
for (String tabsNames : tabMenu) {
    actionBar.addTab(actionBar.newTab().setText(tabsNames).setTabListener(this).setIcon(resources.getDrawable(<drawable_id>));
}

Maybe, you should first create an array with drawable id's, then in 'for' loop take id with something like .setIcon(resources.getDrawable(icons[i])
If you have already put the drawables for icons into corresponding folders, you can give me their names and I'll show you the full code.


text:
Q: Java app: Connect to PostgreSQL database I am attempting to connect to a postgres SQL database. Normally, I can connect by simply going to the link:
test.ischool.testU.edu

Where I connect to phpPgAdmin by entering my credentials, and then I can connect to my database, testDB, by selecting it from the side.
Here is my relevant Java code:
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    }

    String url = "jdbc:postgresql://test.ischool.testU.edu:5432/testDB";
    String user = "testuser";
    String pass = "testpassword";
    Connection db = null;
    try {
        db = DriverManager.getConnection(url,user,pass);
    } catch (SQLException e1) {
        e1.printStackTrace();
    }

I receive the following error:
org.postgresql.util.PSQLException: Connection refused. Check that the hostname and port             are correct and that the postmaster is accepting TCP/IP connections.

I'm pretty sure I am doing something wrong. Assuming that my code is correct (which I'm sure is not the case), to connect to the database, do I need to have my .jar file inside the remote directory, or can I run it locally? Does it make a difference?
I have successfully connected to my database using the following python code (this code was inserted into the remote directly and run from there):
    conn = psycopg2.connect("dbname=testDB user=testuser password=testpassword")

A: The JDBC URL you are using is for MySQL:
jdbc:mysql://test.ischool.testU.edu:5432/testDB

use one for PostgreSQL:
jdbc:postgresql://test.ischool.testU.edu:5432/testDB

If changing this doesn't help please post the exact error you are getting.

A: try this piece of code:
String url = "jdbc:postgresql://localhost/YOURSCHEMA?user=YOURUSER&password=YOURPWD";

Class.forName("org.postgresql.Driver");

Connection con = DriverManager.getConnection(url);`


text:
Q: How to fetch connection string from web.config file? I am calling a function of ClassA of Project A from ClassB of Project B but in this case i am getting connection string null from my web.config file.
Main issue may be i am calling from another project. so how to solve this.
I googled but no luck. give some suggestion for try.

A: Lets see you have two projects in same solution.
Project A
and
project B
Your connection string is declared in projectA and you want to access this connectionstring from projectB
there are two possibilities.

*

*Better if you declare <connectionStrings> for projectB its a simple
or

*You need to create one static variable  which will return a connection string  in projectA
public static string DBConnection()
        {
            try
            {
                return System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
            }
        catch (Exception ce)
        {
            throw new ApplicationException("Unable to get DB Connection string from Config File. Contact Administrator" + ce);
        }
    }


text:
Q: How do I select a PostgreSQL system column using SQLAlchemy? Postgresql implicitly defines several columns on every table, such as xmax and ctid (see docs).
Assuming my SQLALchemy table definition does not specify these columns, is there a way to select them using the core sql functionality (i.e. not the ORM part of SA)?
The following does not work as xmax is not explicitly defined in the table definition.
table = sa.Table(
    "mytable",
    metadata,
    sa.Column("col_a", sa.BIGINT),
    sa.Column("date", sa.DATE),
)

s = sa.select([table.c.xmax])
result = engine.execute(s)

Specifically my requirement is to reference xmax in the returning clause of an upsert.
insert(mytable).returning((mytable.c.xmax == 0).label("inserted"))

A: If you don't want to change your existing table declarations, you can use the sqlalchemy.column() function (note the lowercase c in column):
xmax = sa.column('xmax')
sa.insert(mytable).returning((xmax == 0).label("inserted"))

However, if your SQL statement selects from more than one table (e.g. in a join) then PostgreSQL will complain it doesn't know which xmax column you're talking about:
ProgrammingError: (psycopg2.ProgrammingError) column "xmax" does not exist

In this case you can use the (unfortunately undocumented) _selectable parameter:
xmax = sa.column('xmax', _selectable=mytable)
sa.insert(mytable).returning((xmax == 0).label("inserted"))

Which works in a joined tables query just as well as in the case where you're selecting only from one table, so you can always use it if you want.

A: One option is to declare xmax in your SA table definition as a system column:
table = sa.Table(
    # ...,
    sa.Column("xmax", sa.TEXT, system=True),
)

This will allow you to access table.c.xmax like any other column (so your proposed table.c.xmax == 0 should then work). The system=True flag tells SA not to attempt to create the xmax column explicitly when emitting CREATE TABLE.
(I've used sa.TEXT as a bit of a workaround here because sqlalchemy.dialects.postgresql doesn't provide an XID datatype, and apparently xid cannot be casted to a numeric type.)


text: Q: Why isn't stackexchange.com using the same mobile layout as other SE sites in my browser? I can see most SE sites and pages mobile friendly, including this one. But for just stackexchange.com it displays full desktop on mobile chrome and safari. Is there something I need to change on my end? See screenshot.


text:
Q: How to count occurrences of parts of datetime2 I have been trying to find out how to group and count just the years in datetime2. The rest of the date does not matter, for as long as it has the same year I want it to be counted and grouped. This is the query I have so far. I tried to get the year of the date in an integer and try my luck using the count method, but it will only count it if the date values are exactly the same.
DECLARE @user_id [int] =12
SELECT [date],user_id, COUNT(YEAR([date])) as yearCount
from table
where table.user_id = @user_id
group by date,user_id

What the query shows:
date                          user_id   yearCount
-------                       -------   -----------
2020-11-12 00:00:00.0000000     12          1
2020-05-23 00:00:00.0000000     12          1
2021-06-01 00:00:00.0000000     12          1
2021-04-15 00:00:00.0000000     12          1
2022-02-20 00:00:00.0000000     12          1
2022-01-20 00:00:00.0000000     12          1

What I would like it to look like:
date                          user_id   yearCount
-------                       -------   -----------
2020-11-12 00:00:00.0000000     12          2
2020-05-23 00:00:00.0000000     12          2
2021-06-01 00:00:00.0000000     12          2
2021-04-15 00:00:00.0000000     12          2
2022-02-20 00:00:00.0000000     12          2
2022-01-20 00:00:00.0000000     12          2

A: You can use the windowed version of count() and partition by the year (and optional the user ID -- you can also omit this, if you really only ever include exactly one user ID in the result).
SELECT date,
       user_id,
       count(*) OVER (PARTITION BY year(date),
                                   user_id) yearcount
       FROM elbat
       WHERE user_id = @user_id;


text:
Q: Registering an achivement I'm trying to learn about facbeook achievements, so i made the achivement URL but now when i'm trying to register it i'm getting :
"(#15) This method is not supported for native apps",
i comlpetely removed the native iOS section from my app's definition on facebook but it still won't let me register.  any ideas?
Oded

A: See the following links:
creating test users - method is not supported for native application
http://forum.developers.facebook.net/viewtopic.php?id=90782
Also ensure your app is registered as a "game".


text:
Q: How can I log in (WNetAddConnection) to a file share programatically using Qt, C++? I wanted to access a file share remotely and I found this post. I haven't tried it, but I think it will work. But I would like to know that is there any way to do this with Qt in C++ (using Visual Studio 2012) ? I copied to here the relevant code from the other post:
public static void CopyFile( string from,
                             string shareName,
                             string username,
                             string password )
{
    NETRESOURCE nr = new NETRESOURCE();
    nr.dwType = ResourceType.RESOURCETYPE_DISK;
    nr.lpLocalName = null;
    nr.lpRemoteName = shareName;
    nr.lpProvider = null;

    int result = WNetAddConnection2( nr,  password,  username, 0 );

    System.IO.File.Copy( from,
                         System.IO.Path.Combine( shareName,
                                                 System.IO.Path.GetFileName( from ) ) );
}

Note, that I do not want to copy, just log on. So I need a function like this or an equivalent code:
public static void CopyFile( const std::string& shareName,
                             const std::string& username,
                             const std::string& password )
{
    /*
    NETRESOURCE nr = new NETRESOURCE();
    nr.dwType = ResourceType.RESOURCETYPE_DISK;
    nr.lpLocalName = null;
    nr.lpRemoteName = shareName;
    nr.lpProvider = null;

    int result = WNetAddConnection2( nr,  password,  username, 0 );
    */
}


text:
Q: Programatically install .apk file located in /res/raw I have stored a .apk file for another app in my /res/raw directory and wish to give the user a prompt to install it. Here's my current code:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("android.resource://" + getPackageName() + "/res/raw/myapk.apk")), "application/vnd.android.package-archive");
startActivity(intent);

However, when the intent runs, I get a Parse error: There is a problem parsing the package.
The .apk file is the one created by eclipse in the /bin directory when I run the other application.
How would I accomplish this programmatic local install correctly?

A: I figured it out. I ended up putting my .apk file in the /assets directory and copying it programatically to the sd card where I installed it from. Here's my code:
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
try {
    in = assetManager.open("myapk.apk");
    out = new FileOutputStream("/sdcard/myapk.apk");
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
        out.write(buffer, 0, read);
    }
    in.close();
    in = null;
    out.flush();
    out.close();
    out = null;
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(new File("/sdcard/myapk.apk")), "application/vnd.android.package-archive");
    startActivity(intent);
}catch(Exception e){
    // deal with copying problem
}

Hopefully this will help someone else with a similar question!

A: String path = "file:///android_asset/raw/myapk.apk";

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
startActivity(intent);

A: also add one permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

otherwise "permission denied" error occur.


text:
Q: How can I improve this piece of code? Shark tells me that this is a hotspot for bad performance:
double distanceA = fabsf(target - current);

target is CGFloat
current is CGFloat
the rest of my calculations rely on double. Maybe there's some smarter way to do this anyways?

A: Unless you have a need for double precision in your distance, change distance to a float.  CGFloat is defined as a float on the iPhone, and fabsf() takes a float value and returns a float value.  The iPhone can be significantly slower at handling double-precision values than standard floats.
In fact, there's no point in using double precision for your distance variable, because you have already lost precision by running your calculation through fabsf(), which only returns a float.

A: Not near Xcode right now, but try:
double distanceA = (double) fabsf(target - current);


text:
Q: IntelliJ - Constants show up as unused if accessed via aliases Since webpack 3 (and older versions using plugins, I believe) it is possible to add aliases to folder paths, so as to replace highly nested and complicated paths such as '../../../../Some/File' with 'Some/File'.
Inside IntelliJ, everything works as it should one way (ctrl+click on an aliased absolute path navigates to the correct path), but in the destination file, the usage check that grays out unused constants does not see that constant is used, albeit from an aliased path.
Is there a way to tell IntelliJ to inspect more closely and to resolve these links both ways?

A: Since the wording is quite different from this other question which answers it I do not think that it should be considered as a duplicate.
However the answer from this question worked for me.
TL;DR: no plugin needed, file -> project settings -> modules and mark your source folders as 'resources', then apply and IntelliJ will re-index your project and resolve the aliased links between files.