text:
Q: Fuzzy Matching for Duplicate Address Checks A good duplicate checker - for checking if the same address has already been entered - needs to take into account misspellings or spelling variations.
We have implemented our own APEX methods which transform each address field (name, street, city, postcode) into a phonetic code. These codes are then compared with other addresses to find possible duplicates. A fuzzy probability is assigned based on the type of match.
How are other users here approaching duplicate checks? Anyone employing the new String.getLevenshteinDistance()?
I'll post my own code below in the interests of knowledge sharing.

A: Phonetic Encoding Algorithm
/**
 * Encode a word phonetically
 * 'HeLLLL00 World!'
 *  -> 'HLWRLD'
 *    -> 'H40643'
 *       Which is the same code as 'Hello World!'
 */
public static string phonetic(string ip, integer max) {

    if (ip == null || ip == '') return '';

    string op = ip.toUpperCase();

    // Encode phonetically similar letters as same number
    op = op.replaceAll('[^BFPVCGJKQSXZDTLMNR]', '0');
    op = op.replaceAll('[BFPV]', '1');
    op = op.replaceAll('[CGJKQSXZ]', '2');
    op = op.replaceAll('[DT]', '3');
    op = op.replaceAll('[L]', '4');
    op = op.replaceAll('[MN]', '5');
    op = op.replaceAll('[R]', '6');

    // Remove double-letters
    string op2 = op.substring(0,1);
    for (integer i=1; i<op.length()-1; i++) {
        string c2 = op.substring(i,i+1);
        if (!op2.endsWith(c2)) op2 += c2;
        //system.debug('******'+op2);
    }

    // Limit length of code returned
    if (max > op2.length()) max = op2.length();

    // Keep first letter of original word
    op2 = ip.substring(0,1) + op2.substring(1, max);

    return op2;
}

Helper Functions
// Convert nulls to empty strings
private static string ops(string s) {
    return s == null?'':s;
}

Find Accounts Matching Address
/**
  * Return all accounts matching this address
  *  The field AnnualRevenue is misused to return the probability of match
  */
public static List<Account> AccountsByAddress(String Name1, String Street, String Postcode, String City, String Country) {

    List<Account> result = new List<Account>();

    List<Account> accs;
    Integer MAX = 50;

    // Find accounts with same postcode OR city
    accs = [SELECT Id, Name, BillingStreet, BillingPostalCode, BillingCity, BillingCountry
            FROM Account
            WHERE BillingCountry = :Country AND (BillingPostalCode = :Postcode OR BillingCity = :City)
            LIMIT :MAX];
    if (accs.size() == MAX) {
        // Too many, enforce same postcode
        accs = [SELECT Id, Name, BillingStreet, BillingPostalCode, BillingCity, BillingCountry
                FROM Account
                WHERE BillingCountry = :Country AND BillingPostalCode = :Postcode
                LIMIT :MAX];
    }
    if (accs.size() == 0) {
        // None, try same city
        system.debug('Fuzzy pre-selected none!');
        accs = [SELECT Id, Name, BillingStreet, BillingPostalCode, BillingCity, BillingCountry
            FROM Account
            WHERE BillingCountry = :Country AND BillingCity = :City
            LIMIT :MAX];
    } else if (accs.size() == MAX) {
        // Too many, enforce city
        system.debug('Fuzzy postcode pre-selected too many!');
        accs = [SELECT Id, Name, BillingStreet, BillingPostalCode, BillingCity, BillingCountry
                          FROM Account
                          WHERE BillingCountry = :Country AND BillingPostalCode = :Postcode AND BillingCity = :City
                          LIMIT :MAX];
    }
    system.debug('Fuzzy accounts Pre-selected '+accs.size());

    if (accs.size() == MAX) {
        // Too many, enforce name
        system.debug('Fuzzy postcode and city pre-selected too many(2)!');
        string Name4 = Name1.substring(0, 4)+'%';
        accs = [SELECT Id, Name, BillingStreet, BillingPostalCode, BillingCity, BillingCountry
                          FROM Account
                          WHERE BillingCountry = :Country AND BillingPostalCode = :Postcode AND BillingCity = :City
                            AND Name LIKE :Name4
                          LIMIT :MAX];
    }
    system.debug('Fuzzy accounts pre-selected '+accs.size());

    String Name10   = phonetic(Name1, 10);
    String Street10 = phonetic(Street, 10);
    String City10   = phonetic(City, 10);
    system.debug('Name10='+Name10+', Street10='+Street10+', City10='+City10);

    String Name4   = phonetic(Name1, 4);
    String Street4 = phonetic(Street, 4);
    String City4   = phonetic(City, 4);
    system.debug('Name4='+Name4+', Street4='+Street4+', City4='+City4);

    for (Account acc: accs) {
        system.debug(acc);
        Boolean SameName     = (acc.Name == Name1);
        // SF Street is multi-line, if SAP Street is in there somewhere it's a match
        Boolean SameStreet   = (acc.BillingStreet == Street || ops(acc.BillingStreet).indexOf(Street)>=0);
        Boolean SameCity     = (acc.BillingCity == City);
        Boolean SamePostcode = (acc.BillingPostalCode == Postcode);
        system.debug('SameName='+SameName+', SameStreet='+SameStreet+', SameCity='+SameCity+', SamePostcode='+SamePostcode);

        Boolean Like10Name   = (phonetic(acc.Name, 10) == Name10);
        Boolean Like10Street = (phonetic(acc.BillingStreet, 10) == Street10);
        Boolean Like10City   = (phonetic(acc.BillingCity, 10) == City10);
        system.debug('Like10Name='+Like10Name+', Like10Street='+Like10Street+', Like10City='+Like10City);

        Boolean Like4Name   = (phonetic(acc.Name, 4) == Name4);
        Boolean Like4Street = (phonetic(acc.BillingStreet, 4) == Street4);
        Boolean Like4City   = (phonetic(acc.BillingCity, 4) == City4);
        system.debug('Like4Name='+Like4Name+', Like4Street='+Like4Street+', Like4City='+Like4City);

        if (SameName && SameStreet && SameCity && SamePostcode)
          acc.AnnualRevenue = 99;
        else if (SameName && SameStreet && SameCity) acc.AnnualRevenue = 98;
        else if (SameName && SameStreet && ( SameCity || SamePostcode )) acc.AnnualRevenue = 97;
        else if (SameName && Like10Street && SameCity && SamePostcode)   acc.AnnualRevenue = 96;
        else if (Like10Name && SameStreet && SameCity)            acc.AnnualRevenue = 95;
        else if (SameName && SameCity && SamePostcode)            acc.AnnualRevenue = 94;
        else if (SameName && SameStreet && Like10City)            acc.AnnualRevenue = 94;
        else if (SameName && Like10Street && Like10City)          acc.AnnualRevenue = 93;
        else if (Like10Name && SameStreet && Like10City)          acc.AnnualRevenue = 92;
        else if (Like10Name && Like10Street && SameCity)          acc.AnnualRevenue = 91;
        else if (Like10Name && Like10Street && Like10City)        acc.AnnualRevenue = 90;
        else if (SameName && Like4Street && SameCity)             acc.AnnualRevenue = 86;
        else if (Like4Name && SameStreet && SameCity)             acc.AnnualRevenue = 85;
        else if (SameName && SameStreet && Like4City)             acc.AnnualRevenue = 84;
        else if (SameName && Like4Street && Like4City)            acc.AnnualRevenue = 83;
        else if (Like4Name && SameStreet && Like4City)            acc.AnnualRevenue = 82;
        else if (Like4Name && Like4Street && SameCity)            acc.AnnualRevenue = 81;
        else if (Like4Name && Like4Street && Like4City)           acc.AnnualRevenue = 80;
        else if (SamePostcode && Like4City && Like10Name && country != 'China' && country != 'Korea' && country != 'Japan')
          // Same postcode, similar city(4), similar name(10)
          acc.AnnualRevenue = 80;
        else if (SameName && SameCity)
          // Different postcode, same name, same city (postcode misspelled)
          acc.AnnualRevenue = 80;
        else if (SameCity && SameStreet)
          // Same postcode, city && street - name might be misspelled
          acc.AnnualRevenue = 79;
        else if (SameName && SameStreet)              acc.AnnualRevenue = 74;
        else if (Like4Name && Like4Street)            acc.AnnualRevenue = 73;
        else if (Like4Street && SameCity)             acc.AnnualRevenue = 72;
        else if (Like4Name && Like4City)              acc.AnnualRevenue = 71;
        else {
          // Probably not a duplicate
          system.debug('PROB=0');
          continue;
        }
        system.debug('PROB='+acc.AnnualRevenue);

        result.add(acc);
    }

    return result;
}

Use Case
// Check account newAcc against all Accounts
Account[] accs = Fuzzy.AccountsByAddress(
                   newAcc.Name,
                   ,newAcc.BillingStreet
                   ,newAcc.BillingPostalCode
                   ,newAcc.BillingCity
                   ,newAcc.BillingCountry
                 );


text:
Q: Let $ G $ be a group and $ a \in G $ an order element $ mn $, where $ m $ and $ n $ are relatively prime positive integers Let $ G $ be a group and $ a \in G $ an order element $ mn $, where $ m $ and $ n $ are relatively prime positive integers. Prove that there are $ x, y \in G $ such $ \vert x \vert = m $ and $ \vert y \vert = n $ and $ a = xy $.

A: Since $m$ and $n$ are relatively prime, we can write $1=mr+ns$ for some $r,s\in\mathbb{Z}$. Now, take $x=a^{ns}$ and $y=a^{mr}$ and show that this works...

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the pale greenish light in FOTR While Frodo is in the wight's barrow, during Chapter 8 of FOTR, what is the pale green-ish light that appears?

As he lay there, thinking and getting a hold of himself, he noticed all
  at once that the darkness was slowly giving way: a pale greenish light was
  growing round him.

It did not at first show him what kind of a place he was
  in, for the light seemed to be coming out of himself, and from the floor
  beside him, and had not yet reached the roof or wall.

I'm familiar with most of Tolkien's works that deal with Arda, but I've never understood what the pale-green light was supposed to be, or how it was produced.  Was it perhaps, a manifestation of the Ring's power or of Eru Ilúvatar's influence in behalf of the ring-bearer?

A: We don't know for certain.
Green light in Lord of the Rings is primarily associated with Gollum; particularly the colour his eyes take on when his evil side is in control:

Gollum was talking to himself. Smeagol was holding a debate with some other thought that used the same voice but made it squeak and hiss. A pale light and a green light alternated in his eyes as he spoke.

And:

Suddenly he turned back. A green light was flickering in his bulging eyes. 'Masster, masster!' he hissed. 'Wicked! Tricksy! False!' He spat and stretched out his long arms with white snapping fingers.

Howeve, Tolkien uses the very same green light to describe Treebeard, so we definitely shouldn't read anything significant into the choice of colour:

But at the moment the hobbits noted little but the eyes. These deep eyes were now surveying them, slow and solemn, but very penetrating. They were brown, shot with a green light.

One possible connection is in the following description of Minas Morgul, where it's glowing colour is likened to the green light in Gollum's eyes:

Then his eyes shone with a green-white light, reflecting the noisome Morgul-sheen perhaps...

As we know, the Barrow-wights were sent by the Witch-king, thus establishing the connection between Minas Morgul and the Barrow-downs:

It was at this time that an end came of the Dunedain of Cardolan, and evil spirits out of Angmar and Rhudaur entered into the deserted mounds and dwelt there.

And so the green light may be indicative of this connection, but there is really no other evidence to suggest anything.


text:
Q: error: unknown type name 'WebKitWebFrame' I'm attempting to build a browser with a url bar. The URL bar needs to reflect any navigational changes in the browser, and the docs recommend the use of navigation-policy-decision-requested; the callback takes 5 params, with types WebkitWebView, WebKitWebFrame, WebKitNetworkRequest, WebKitNavigationAction, webKitPolicyDecision, and gpointer.
When I try to compile, I get several errors of the variant "error: unknown type name ". This happens to all of the ones listed, except WebkitWebView. I know I included webkit2.h. I know I tried explicitly defining, by initializing a WebKitWebFrame, for example, but all it did was create more errors. Are the types not already defined? Or do I have to define them myself?
EDIT: My Wifi connection was really weak on the computer I was testing on before, so I was unable to provide code or compile output. Sorry.
main.c
static void uriUpdateCb(WebKitWebView* web_view, WebKitWebFrame* frame, WebkitNetworkRequest* request, WebkitWebNavigationAction* navigation_action, WebkitWebPolicyDecision* policy_decision, gpointer user_data){
  const gchar* uri = webkit_network_request_get_uri(request);
  char* file_type = strchr(uri, '.');
  if(file_type && (!strcmp(file_type, ".pdf") || !strcmp(file_type, ".db") || !strcmp(file_type, ".exe") || !strcmp(file_type, ".deb") || !strcmp(file_type, ".rpm") || !strcmp(file_type, ".dmg"))){
      // note to self: replace above if statement with a loop and a file that contains these extensions
      webkit_web_policy_decision_download(policy_decision);
  }
  else{
    webkit_web_policy_decision_use(policy_decision);
    gtk_entry_set_text(user_data, uri);
  }
}

window.h (controls webkitWebview)
g_signal_connect(webView, "navigation-policy-decision-requested", G_CALLBACK(uriUpdateCb), url_bar);

callbacks.h (definition)
static void uriUpdateCb(WebKitWebView* web_view, WebKitWebFrame* frame, WebkitNetworkRequest* request, WebkitWebNavigationAction* navigation_action, WebkitWebPolicyDecision* policy_decision, gpointer user_data);

Compile Errors
In file included from main.c:35:0:
callbacks.h:4:50: error: unknown type name 'WebKitWebFrame'
 static void uriUpdateCb(WebKitWebView* web_view, WebKitWebFrame* frame, WebkitNet
                                                  ^
callbacks.h:4:73: error: unknown type name 'WebkitNetworkRequest'
 atic void uriUpdateCb(WebKitWebView* web_view, WebKitWebFrame* frame, WebkitNetwo
                                                                       ^
callbacks.h:4:104: error: unknown type name 'WebkitWebNavigationAction'
 View* web_view, WebKitWebFrame* frame, WebkitNetworkRequest* request, WebkitWebNa
                                                                       ^
In file included from main.c:35:0:
callbacks.h:4:150: error: unknown type name 'WebkitWebPolicyDecision'
 etworkRequest* request, WebkitWebNavigationAction* navigation_action, WebkitWebPo
                                                                       ^
In file included from /usr/include/glib-2.0/gobject/gobject.h:28:0,
                 from /usr/include/glib-2.0/gobject/gbinding.h:29,
                 from /usr/include/glib-2.0/glib-object.h:23,
                 from /usr/include/glib-2.0/gio/gioenums.h:28,
                 from /usr/include/glib-2.0/gio/giotypes.h:28,
                 from /usr/include/glib-2.0/gio/gio.h:26,
                 from /usr/include/gtk-3.0/gdk/gdkapplaunchcontext.h:28,
                 from /usr/include/gtk-3.0/gdk/gdk.h:32,
                 from /usr/include/gtk-3.0/gtk/gtk.h:30,
                 from main.c:29:
window.h: In function 'create_window':
window.h:56:81: error: 'uriUpdateCb' undeclared (first use in this function)
 l_connect(webView, "navigation-policy-decision-requested", G_CALLBACK(uriUpdateCb
                                                                       ^
/usr/include/glib-2.0/gobject/gsignal.h:475:60: note: in definition of macro 'g_signal_connect'
     g_signal_connect_data ((instance), (detailed_signal), (c_handler), (data), NU
                                                            ^
window.h:56:70: note: in expansion of macro 'G_CALLBACK'
    g_signal_connect(webView, "navigation-policy-decision-requested", G_CALLBACK(u
                                                                      ^
window.h:56:81: note: each undeclared identifier is reported only once for each function it appears in
 l_connect(webView, "navigation-policy-decision-requested", G_CALLBACK(uriUpdateCb
                                                                       ^
/usr/include/glib-2.0/gobject/gsignal.h:475:60: note: in definition of macro 'g_signal_connect'
     g_signal_connect_data ((instance), (detailed_signal), (c_handler), (data), NU
#include <gtk/gtk.h>
#include <string.h>
#include <gtk/gtk.h>
#include <string.h>
#include <stdio.h>
#include <webkit2/webkit2.h>

// window.h
int create_window(){

  // Create an 800x600 window that will contain the browser instance
  GtkWidget *main_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_default_size(GTK_WINDOW(main_window), 800, 600);

  // create the tab manager
  GtkWidget *notebook = gtk_notebook_new();

  GtkWidget *label = gtk_label_new ("test");

  // create the gtk box that'll set the layout and put box in window
  GtkWidget *box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);

  gtk_notebook_append_page(GTK_NOTEBOOK (notebook), box, label);

  gtk_container_add(GTK_CONTAINER(main_window), GTK_WIDGET(notebook));

  GtkWidget *grid = gtk_grid_new();
  gtk_container_add(GTK_CONTAINER(box), GTK_WIDGET(grid));

  // create url_bar and add to grid

  GtkWidget *back_button = gtk_button_new_with_label("Back");
  GtkWidget *forward_button = gtk_button_new_with_label("Forward");
  GtkWidget *stop_connection_button = gtk_button_new_with_label("Stop");

  GtkEntryBuffer *buf = gtk_entry_buffer_new("about:blank", 12);
  GtkWidget *url_bar = gtk_entry_new_with_buffer(buf);

  gtk_grid_attach(GTK_GRID(grid), back_button, 0, 0, 1, 1);
  gtk_grid_attach(GTK_GRID(grid), forward_button, 1, 0, 1, 1);
                                                            ^
window.h:56:70: note: in expansion of macro 'G_CALLBACK'
    g_signal_connect(webView, "navigation-policy-decision-requested", G_CALLBACK(u
                                                                      ^
main.c: At top level:
main.c:107:50: error: unknown type name 'WebKitWebFrame'
 static void uriUpdateCb(WebKitWebView* web_view, WebKitWebFrame* frame, WebkitNet
                                                  ^
main.c:107:73: error: unknown type name 'WebkitNetworkRequest'
 atic void uriUpdateCb(WebKitWebView* web_view, WebKitWebFrame* frame, WebkitNetwo
                                                                       ^
main.c:107:104: error: unknown type name 'WebkitWebNavigationAction'
 View* web_view, WebKitWebFrame* frame, WebkitNetworkRequest* request, WebkitWebNa
                                                                       ^
main.c:107:150: error: unknown type name 'WebkitWebPolicyDecision'
 etworkRequest* request, WebkitWebNavigationAction* navigation_action, WebkitWebPo

A: WebKitWebFrame and WebKitNetworkRequest are types from the obsolete webkitgtk-1.0 and webkitgtk-3.0 APIs, but since you are including webkit2.h it is clear that you are trying to use the modern webkit2gtk-4.0 API (as you should be). You're probably looking at documentation for the old APIs. Here is the modern documentation.
You don't need to listen to navigation policy decisions to get the URL. Just look for property changes to WebKitWebView::uri by connecting to the notify::uri signal. Look up the documentation of g_signal_connect() if you're not sure how to do this.


text:
Q: Direct binding deployment with Kafka as message bus I am trying to use direct binding on the following stream.
stream create --definition "time | log" --name ticktock
stream deploy ticktock --properties module.*.count=0

Deployment fails with this exception on both the admin and container node:
java.lang.IllegalArgumentException: Module count cannot be zero
    at org.springframework.xd.dirt.integration.kafka.KafkaMessageBus$KafkaPropertiesAccessor.getNumberOfKafkaPartitionsForProducer(KafkaMessageBus.java:799)
    at org.springframework.xd.dirt.integration.kafka.KafkaMessageBus.bindProducer(KafkaMessageBus.java:500)
    at org.springframework.xd.dirt.plugins.AbstractMessageBusBinderPlugin.bindMessageProducer(AbstractMessageBusBinderPlugin.java:287)
    at org.springframework.xd.dirt.plugins.AbstractMessageBusBinderPlugin.bindConsumerAndProducers(AbstractMessageBusBinderPlugin.java:143)
    at org.springframework.xd.dirt.plugins.stream.StreamPlugin.postProcessModule(StreamPlugin.java:73)
    at org.springframework.xd.dirt.module.ModuleDeployer.postProcessModule(ModuleDeployer.java:238)
    at org.springframework.xd.dirt.module.ModuleDeployer.doDeploy(ModuleDeployer.java:218)
    at org.springframework.xd.dirt.module.ModuleDeployer.deploy(ModuleDeployer.java:200)
    at org.springframework.xd.dirt.server.container.DeploymentListener.deployModule(DeploymentListener.java:365)
    at org.springframework.xd.dirt.server.container.DeploymentListener.deployStreamModule(DeploymentListener.java:334)
    at org.springframework.xd.dirt.server.container.DeploymentListener.onChildAdded(DeploymentListener.java:181)
    at org.springframework.xd.dirt.server.container.DeploymentListener.childEvent(DeploymentListener.java:149)
    at org.apache.curator.framework.recipes.cache.PathChildrenCache$5.apply(PathChildrenCache.java:509)
    at org.apache.curator.framework.recipes.cache.PathChildrenCache$5.apply(PathChildrenCache.java:503)
    at org.apache.curator.framework.listen.ListenerContainer$1.run(ListenerContainer.java:92)
    at com.google.common.util.concurrent.MoreExecutors$SameThreadExecutorService.execute(MoreExecutors.java:297)
    at org.apache.curator.framework.listen.ListenerContainer.forEach(ListenerContainer.java:83)
    at org.apache.curator.framework.recipes.cache.PathChildrenCache.callListeners(PathChildrenCache.java:500)
    at org.apache.curator.framework.recipes.cache.EventOperation.invoke(EventOperation.java:35)
    at org.apache.curator.framework.recipes.cache.PathChildrenCache$10.run(PathChildrenCache.java:762)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

I have a Spring-XD(1.2.0) cluster with one admin and two container nodes using Kafka as a message bus.
Am I doing something wrong? Or is there a problem with direct binding and the Kafka message bus?

A: Per the documentation, the XD KafkaMessageBus does not currently support direct binding...

NOTE: The Kafka message bus does not support count=0 for module deployments, and therefore, it does not support direct binding of modules. This feature will be available in a future release. In the meantime, if direct communication between modules is necessary for Kafka deployments, composite modules should be used instead.


text:
Q: How does one convert a CGImageRef to a CGDataProviderRef? I am using a library that needs a CGDataProviderRef however I know how to get a CGImageRef from an image.
NSData* data = ... get raw image data from somewhere (PNG, JPEG, etc.) ...;
UIImage* image = [UIImage imageWithData: data];
CGImageRef imageRef = image.CGImage;

How do I convert imageRef to a CGDataProviderRef

A: You don't.
You use the CGDataProvider functions to create a CGDataProviderRef, then pass that to the library.
See the CGDataProvider reference, and in particular:
CGDataProviderCreateWithCFData,
CGDataProviderCreateWithData,
CGDataProviderCreateWithFilename,
CGDataProviderCreateWithURL

A: Have you tried not converting it to a `CGImageRef first? From the docs
CGDataProviderRef CGDataProviderCreateWithData (
    void *info,
    const void *data,
    size_t size,
    CGDataProviderReleaseDataCallback releaseData
);

If this method does not work for your situation, there are several other CGDataProviderCreateWithXXXXX methods pointed out in the docs which may.


text:
Q: Как выбрать string из БД, и отобразить его, без цикла? У меня есть БД, где написан путь к папке. Мне надо выбрать его, и отобразить в echo.
Я бы не писал сюда, но везде в интернете показаны примеры с циклом while.
Мне нужно просто выбрать один string из БД.
Вот сам БД:

Выделено красным на скрине. Вот этот текст мне надо отобразить в echo.
Я имею такой запрос SQL: SELECT user_image FROM users WHERE login = '$login', но он нихера не работает.
Как мне получить результат, состоящий из одного пользователя, без использования цикла while.

A: Если вы используете PDO для подключения к СУБД, тогда следующий код для вас.
Обратите внимание на то что в вашем запросе есть проблема c безопасностью.
Лучше написать так:
$sth = $dbConnection->prepare("SELECT user_image FROM users WHERE login = ?");
$sth->execute([$login]);

$result = $sth->fetch(PDO::FETCH_ASSOC);
if ($result !== false){
 echo $result['user_image'];
}else{
  echo "Not found";
}

A: SELECT user_image FROM users WHERE login = '$login'
Не совсем понимаю зачем вам переменная?
Вы знаете конкретный логин?
Если вам необходимо первую строчку выбрать например,то там логин obitoihom, его используйте при составлении запроса.
SELECT user_image FROM users WHERE login = 'obitoihom'
Переменные тут не нужны.


text:
Q: Confusion about adjunct and complement In my recently concluded test, I was asked to identify the sentence pattern of this sentence:

It stands tall

I split it as:
It | stands | tall

S      V       A

For me, "tall" is an additional information and if removed, the sentence still makes sense to me.
However, my teacher marked it wrong and said that it should instead be C (complement)
Can anyone help me out? Was I wrong or was she?
Also please be simple as I don't know many technical terms except the basic ones. I say this because I went through the link that StoneyB provided, and wasn't able to understand terms like "secondary complement", "sentence-constituent". I know I may be the noobest person around here, so please explain those terms if you use it.

A: You are both right, and you are both wrong!

*

*You are right in that the word tall does not play a syntactic role which cannot be omitted. It stands is a complete sentence; stand does not require a following adjective or adjectival to complete its meaning, which is what the grammatical term complement ordinarily means.

*Your teacher is right in that the word tall is not used either as an attributive adjective directly modifying it or as an adverb modifying stand, which are the traditional roles played by adjuncts: it is a predicate adjective describing the subject, exactly as in the sentence It is tall. Grammarians therefore often find it useful to describe uses of this sort as secondary predication or secondary complementation, as if the verb were behaving like a linking verb like BE or BECOME.

*You are both wrong in that the collocation stand tall is an idiom: it has, or can have, a meaning which is not entirely understandable as the sum of its components. Stand tall in many contexts has the figurative meaning "to exhibit pride or defiance"; for instance, in this headline from The Guardian:

On the day of his release, Nelson Mandela stood tall ... and the story goes on to speak of the "iconic image of that moment – a lean, beaming Mandela in a dark suit emerging from Victor Verster prison holding hands with Winnie, both raising triumphant clenched fist salutes".

From this perspective stand tall is a single entity which cannot be analyzed into different parts with different roles.
The lesson to be drawn from this is not that you guys are wrong and I am right; it is that all of us are right.

*

*You have brought a sophisticated understanding of the term adjunct to the discussion—perhaps more sophisticated than your teacher expected!

*Your teacher, on the other hand, is concerned that you gain a more sophisticated understanding of the term complement, and is trying to ascertain whether you have mastered that.

*And I am bringing an entirely different perspective into the discussion with the term idiom, for the sake of completeness.

The point is that grammatical terms like adjunct and complement and idiom are not real "things" but tools for talking about language and understanding how it works. Which tool you use depends on what you want to talk about, just as you use a screwdriver for some jobs and a chisel for others.


text:
Q: Query params for nested objects with python requests module like QS.stringify When creating a Strapi client in Python using the requests module I came across a problem.
When using the params argument for the requests.get method with a nested dictionary it doesn't translate to a querystring like the npm package qs does.
I wanted a qs.stringify in python but found the answer nowhere on Stack Overflow.

A: I found this package:
https://github.com/cine-io/nested-query-string
   def _get(self, path, params=None, **kwargs):
        url = self.__construct_url(path)
        headers = self.__get_request_headers()

        if params is not None:
            #see line here!!
            from nested_query_string import NestedQueryString
            params = NestedQueryString.encode(params)

        response = requests.get(url, params=params, headers=headers, **kwargs)
        assert response.status_code == 200
        return self.__parse_strapi_response(response)


text:
Q: Equivalent of Akka but for .NET (Concurrency Framework) Is there something equivalent of Akka but for .NET?
http://doc.akka.io/use-cases

A: This is an (/my) ongoing port of Akka actors for .NET
[EDIT]
The project have evolved into a direct port of real Akka: https://github.com/akkadotnet
It is in large a class by class, line by line port.

A: You may take a look at https://github.com/phatboyg/Stact
It falls into the 'something equivalent' category.


text:
Q: An application of Zorn's lemma. Suppose that $R$ is a commutative ring, an $R$-module $M$ is said to be finitely embedded if $M$ has a finitely generated essential socle. Now Let $M$ be finitely embedded and not
artinian, let $S$ be the set of all submodules $N$ of $M$ such that $M/N$ is not finitely
embedded. Is it true that $S$ has a minimal element by Zorn's lemma?

A: Call $\mathcal F$ the family of all the submodules $N\subseteq M$ such that $M/N$ is not f.e.
How could you prove that given a chain $N_1 \subseteq N_2\subseteq\dots\subseteq N_n\subseteq \dots$ of elements of $\mathcal F$ then $N=\bigcup_n N_n$ is in $\mathcal F$? It seems not to be true by I cannot actually see counter examples now...
A characterization of f.e. modules can be obtained using Zorn's lemma, that is:
Theorem.
E is f.e. iff any inverse system of non-zero submodules is bounded (from below) by a non-zero submodule.
(the above theorem is due to prof. Vamos and the proof is essentially a dualization of an analogous property for f.g. modules)
So finally the answer is, could you prove that $\mathcal F$ is an inverse system?


text:
Q: A* Pathfinding in a hexagonal grid Can anyone point me to a simple example that implements A* path-finding algorithm on a hexagonal grid (in JS). I have made it working on a square grid, however all my attempts to make it work on a hexagonal grid have failed.
This is how my grid looks like:

I'm using the same technique to both draw the grid and generate coordinates as seen in this topic.
Here's the grid coords data along with the start, end coords:
        [0, 0] , [0, 1],  [0, 2],
    [1, 0],  [1, 1],  [1, 2],  [1, 3],
 [2, 0],  [2, 1],  [2, 2],  [2, 3],  [2, 4],
    [3, 0],  [3, 1], [3, 2],  [3, 3],
        [4, 0], [4, 1],  [4, 2]

start_point: [0,2]
end_point: [4.0]

After updating the manhattan distance calculation to:
var dx = pos1[0] - pos0[0];
    var dy = pos1[1] - pos0[1];

    var dist;
    if ( Math.sign(dx) == Math.sign(dy) ){
        dist = Math.abs (dx + dy);
    }else{
        dist = Math.max(Math.abs(dx), Math.abs(dy))
    }

return dist;

I get this result:

and also the way I'm calculating the shortest path:

if (!Array.prototype.remove) {
    Array.prototype.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
    };
}

var astar = {
    init: function(grid) {
        for(var x = 0; x < grid.length; x++) {
            for(var y = 0; y < grid[x].length; y++) {
                grid[x][y].f = 0;
                grid[x][y].g = 0;
                grid[x][y].h = 0;
    //grid[x][y].content = false;
                grid[x][y].visited = false;
                grid[x][y].closed = false;
                grid[x][y].debug = "";
                grid[x][y].parent = null;
    console.log([grid[x][y].coords[0],grid[x][y].coords[1]])
            }
        }
    },
    search: function(grid, start, end, heuristic) {
        this.init(grid);
        heuristic = heuristic || this.manhattan;

        var openList = [];

  //// find the start and end points in the grid ////
  start = grid[start.pos[0]][start.pos[1]];
  end =  grid[end.pos[0]][end.pos[1]];

  console.log( start, end )

        openList.push(start);

        while(openList.length > 0) {

            // Grab the lowest f(x) to process next
            var lowInd = 0;
            for(var i=0; i<openList.length; i++) {
                if(openList[i].f < openList[lowInd].f) { lowInd = i; }
            }
            var currentNode = openList[lowInd];

            // End case -- result has been found, return the traced path
            if( currentNode == end ) {
                var curr = currentNode;
                var ret = [];
                while(curr.parent) {
                    ret.push(curr);
                    curr = curr.parent;
                }
                return ret.reverse();
            }

            // Normal case -- move currentNode from open to closed, process each of its neighbors
            openList.remove( lowInd );
            currentNode.closed = true;

            var neighbors = this.neighbors(grid, currentNode);
            for(var i=0; i<neighbors.length;i++) {
                var neighbor = neighbors[i];

                if( neighbor.closed || neighbor.content == 2 ) { // not a valid node to process, skip to next neighbor
                    continue;
                }

                // g score is the shortest distance from start to current node, we need to check if
                //   the path we have arrived at this neighbor is the shortest one we have seen yet
                var gScore = currentNode.g + 1; // 1 is the distance from a node to it's neighbor
                var gScoreIsBest = false;

                if(!neighbor.visited) {
                    // This the the first time we have arrived at this node, it must be the best
                    // Also, we need to take the h (heuristic) score since we haven't done so yet
                    gScoreIsBest = true;
                    neighbor.h = heuristic(neighbor.coords, end.coords);
                    neighbor.visited = true;
                    openList.push(neighbor);
                }
                else if(gScore < neighbor.g) {
                    // We have already seen the node, but last time it had a worse g (distance from start)
                    gScoreIsBest = true;
                }

                if(gScoreIsBest) {
                    // Found an optimal (so far) path to this node.  Store info on how we got here and just how good it really is. ////
                    neighbor.parent = currentNode;
                    neighbor.g = gScore;
                    neighbor.f = neighbor.g + neighbor.h;
                    neighbor.debug = "F: " + neighbor.f + "
G: " + neighbor.g + "
H: " + neighbor.h;
                }
            }
        }

        // No result was found -- empty array signifies failure to find path
        return [];
    },
    manhattan: function(pos0, pos1) { //// heuristics : use manhattan distances  ////
        var dx = pos1[0] - pos0[0];
        var dy = pos1[1] - pos0[1];

        return  Math.abs (dx + dy);
    },
    neighbors: function(grid, node) {
        var ret = [];
        var x = node.coords[0];
        var y = node.coords[1];

        if(grid[x-1] && grid[x-1][y] ) {
            ret.push(grid[x-1][y]);
        }
        if( grid[x+1] && grid[x+1][y] ) {
            ret.push(grid[x+1][y]);
        }
        if( grid[x][y-1] && grid[x][y-1] ) {
            ret.push(grid[x][y-1]);
        }
        if( grid[x][y+1] && grid[x][y+1] ) {
            ret.push(grid[x][y+1]);
        }
        return ret;
    }
};

Tried looking around for some good examples or documents on the internet but couldn't really find anything of use.

A: As already mentioned by someone here, the way I was generating the grid, and also the coordinates were incorrect.
I have another read through Amit Patel's implementation guide and I used his way to generate the grid and also the coordinates system including the coord. conversions.
generate: function(){
        var n_hex = null;
        var row = 0, col = 0;
        for (var q = -this.grid_r; q <= this.grid_r; q++) {
            var r1 = Math.max(-this.grid_r, -q - this.grid_r);
            var r2 = Math.min(this.grid_r, -q + this.grid_r);
            col = q + this.grid_r;
            this.hexes[ col ] = [];
            for (var r = r1; r <= r2; r++) {
                row = r - r1;
                n_hex = new Hex( [q, r], [col, row], this.layout );
                this.hexes[ col ][ row ] = n_hex;
            }
        }
    },

As I started using the cube coordinates , the only thing I had to change in the a* pathfinding algorithm was the distance calculation:
return Math.max(Math.abs(a.x - b.x), Math.abs(a.y - b.y), Math.abs(a.z - b.z))

now the path-finding is working on both "pointy" and "flat" layouts :

A: This is a solved problem, with much literature to back it up. The best resource I know is on Red Blob Games: https://www.redblobgames.com/grids/hexagons/.
In brief, the most likely reason is that you chose the wrong coordinate system. Using a Cube coordinate system implementing the A* algorithm is quite simple. See the live demo on the above link.
If you really want to use some other system, then convert to and from when needed.

A: The problem resides in your neighbors method: although a hexagon has six neighbors (6), you only push four (4) onto ret. The following figure highlights the issue. The light grey hex represents the current node (i.e. neighbor). The green hexagons are added to ret, but the red hexagons are not.

To fix this, add the following two (2) cases to your neighbors method:
    if( grid[x+1][y-1] && grid[x+1][y-1] ) {
        ret.push(grid[x][y-1]);
    }
    if( grid[x-1][y+1] && grid[x-1][y+1] ) {
        ret.push(grid[x][y+1]);
    }

Regarding your updated manhattan method: it is correct. The following figure uses colors to show the distance from the current central hex (at [0:0] in red) to every other hex. For example, the orange hex tiles are one (1) move from the red. The yellow are two (2) moves from the red. And so on.

You may notice the pattern: If the x- and y-coordinates share the same sign, the distance is equal to the magnitude of the largest coordinate. Otherwise, the distance is the sum of their absolute values. This is exactly the way you've calculated distance in your updated manhattan method. So you're good there.
Regarding heuristic search in general: Here's a simple way to check if a suboptimal solution is the result of a bug in the heuristic implementation or else because of a bug in the algorithm implementation. Just use the heuristic value zero (0) for all values, i.e. use the trivial heuristic. If, while using the trivial heuristic, the path is not optimal, then you know it's not a heuristic problem---it's an algorithm problem.

A: The "classic" path finding algorithm works as follows:

*

*Initialize all cells with zero.

*Start at the starting point and mark this point with the number 1.

*Loop start with n = 1:

*Take all cells with number n and mark all adjacent cells, which contains a zero, with number (n+1). If any of these adjacent cells is the exit, leave loop. If no adjacent cell with number zero found, there's no path to exit.

*Increment n and goto loop

If exit found then:

*

*Start loop at exit:

*Search adjacent cell with number n and remember this cell.

*Decrement n and goto loop

All remembered cells builds up the result path (in reverse order).
Cheerz
Hennes


text:
Q: Pageview controller with webview crashing I am using a webview in my contentviewcontroller, when I slide between pages my app crashes.
Below is my code:
contentviewcontroller.m

#import "ContentViewController.h"

@interface ContentViewController ()

@end

@implementation ContentViewController
@synthesize m_CtrlWebview,DocumentPath;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    m_CtrlWebview.scrollView.pagingEnabled=YES;
    m_CtrlWebview.scrollView.bounces=NO;
    m_CtrlWebview.scalesPageToFit=YES;
    m_CtrlWebview.backgroundColor=[UIColor clearColor];
    //m_CtrlWebview.scrollView.zooming=NO;
    m_CtrlWebview.scrollView.zoomScale=1.0;

    NSURL *url = [NSURL fileURLWithPath:DocumentPath isDirectory:NO];

    [m_CtrlWebview loadRequest:[NSURLRequest requestWithURL:url]];
}

-(void)dealloc
{
    [super dealloc];
}
- (void)viewDidUnload
{
    //[m_CtrlWebview stopLoading];
    [m_CtrlWebview release];
    [super viewDidUnload];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

In rootviewcontroller:
  #pragma mark - UIPageViewControllerDataSource Methods

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
      viewControllerBeforeViewController:(UIViewController *)viewController
{
    NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)viewController DocumentPath]];
    if(currentIndex == 0)
    {
        return nil;
    }

    ContentViewController *firstViewController = [self viewControllerAtIndex:currentIndex - 1];
    // ContentViewController *secondViewController = [self viewControllerAtIndex:x+1 ];

    return firstViewController;

}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
       viewControllerAfterViewController:(UIViewController *)viewController
{
    NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)viewController DocumentPath]];
    if(currentIndex == self.modelArray.count-1)
    {
        return nil;
    }
    NSString *Path=[self.modelArray objectAtIndex:currentIndex + 1];
     if  (![[NSFileManager defaultManager] fileExistsAtPath:Path])
     {
        return nil;
     }
    else
    {
        ContentViewController *firstViewController = [self viewControllerAtIndex:currentIndex + 1];

        return firstViewController;
    }

}

- (ContentViewController *)viewControllerAtIndex:(NSUInteger)index {

    if (([self.modelArray count] == 0) || (index >= [self.modelArray count])) {
        return nil;
    }
    ContentViewController *dataViewController;
    dataViewController = [[ContentViewController alloc]initWithNibName:@"ContentViewController" bundle:nil];

    dataViewController.DocumentPath = [self.modelArray objectAtIndex:index];
    return dataViewController;

}

How can I solve this issue? Also how to disable the zooming of the web view? Any help, Thanks in advance.

A: return [dataViewController autorelease];

The above line in - (ContentViewController *)viewControllerAtIndex:(NSUInteger)index solved my issue.

A: From this code it is not really sure why the app crashes.
To be more specific to catch the error, add an exception breakpoint in Xcode.
Steps to do that for Xcode 4.5

*

*Select the "Breakpoint Navigator" in left pane.

*Tap "+" button at bottom left.

*From the popped-up menu, select "Add exception breakpoint"

*When app crashes after doing this setting, check your stack trace to see if any of your function is in the stack trace.
Also enable Zombie objects and log exceptions:

*

*Go to Product -> Edit Scheme

*Select Run YourApp.app from left pane.

*Select Diagnostics in Right pane.

*Check boxes for "Enable Zombie Objects" and "Log Exceptions". This may print some useful information on console when app crashes.

Hope this may help you resolve your problem.


text:
Q: Change values row from mysql database instead of adding I want to change the properties of a user when they edit them in a form.
This is my view:
@using (Html.BeginForm("Manage", "Account")) {
@Html.AntiForgeryToken()
@Html.ValidationSummary()

<fieldset>
    <legend>Change Password Form</legend>

            @Html.LabelFor(m => m.UserName)

            @Html.LabelFor(m => m.Email)
            @Html.TextBoxFor(m => m.Email, new { @Value = ViewBag.Email })

            @Html.LabelFor(m => m.Adress)
            @Html.TextBoxFor(m => m.Adress, new { @Value = ViewBag.Adress })

            @Html.LabelFor(m => m.Description)
            @Html.TextBoxFor(m => m.Description, new { @Value = ViewBag.Description })

            @Html.LabelFor(m => m.Skills)
            @Html.TextBoxFor(m => m.Skills, new { @Value = ViewBag.Skills })

    <input type="submit" value="Change password" />
</fieldset>

}
As you can see I fill the text boxes with the value if it's already in the database.
When they click on "Submit" I want to save the changes in my repository.
This is my Action method in my Controller:
public ActionResult Manage(ChangeSettingsModel model)
{
    if (ModelState.IsValid)
    {
        try
        {
            string username = User.Identity.Name;

            // Get user
            users user = userrepo.FindByUsername(username);

            long userid = user.user_id;

            userrepo.ChangeSettings(userid, model.Name, model.SurName, model.Email, model.Adress, model.Description, model.Skills, model.Website);
        }
        catch (ArgumentException ae)
        {
                ModelState.AddModelError("", ae.Message);
        }
   }

   return View(model);

}

In my repository:
public void ChangeSettings(long userid, string name, string surname, string email, string adress, string description, string skills, string website)
    {
        //users user = entities.users.SingleOrDefault(u => u.user_id.Equals(userid));

        try
        {

        }

        catch (ArgumentException ae)
        {
            throw ae;
        }
        catch (Exception)
        {
            throw new ArgumentException("The authentication provider returned an error. Please verify your entry and try again. " +
                "If the problem persists, please contact your system administrator.");
        }

        Save();
    }

Normally I add something in try but now I don't want to add a user but change the properties. How can I do this?

A: something like below would help.
var query = (from u in entities.users
                         where u.user_id== UID
                         select u).First();

            query.Address = u.Address;
            query.Company = u.Company;
            query.Fax = u.Fax;
            query.Mobile = u.Mobile;
            query.Name = u.Name;
            query.Telephone = u.Telephone;
entites.SubmitChanges();


text:
Q: Removing specific pattern from a string using regex in python I am trying to remove the pattern  using following code
x = "mr<u+092d><u+093e><u+0935><u+0941><u+0915>"
pattern = '[<u+0-9de>]'
re.sub(pattern,'', x)

Output
mr

This output is actually correct for the given sample string but when I am running this code to the corpus, it removing all the occurrences of 'de' as well as digits etc. I want these things are replaced only when < > is used.

A: You need to put the <> outside, as the structure will always be

*

*start with <

*following by u\+

*4 chars in hexa [0-9a-f]{4} as from Unicode definition

*end with >
pattern = '<u\+[0-9a-f]{4}>'
re.sub(pattern,'', x)

                                   REGEX DEMO ★ CODE DEMO


text:
Q: Building and Compiling Error Im having a problem compiling my project, below is the screenshot of the error where am I having a problem, I tried adding the needed frameworks and used CLEAN function, but still not working.

Thanks for the help. Any help would be much appreciated.

A: It looks like that ScratchableView is not included in the link list.

*

*Press project-target in file list   (your APP project name in the file list)

*Targets set to: Photoslot      (your APP name)

*The Tab: Build Phases

*Open: Copy Bundle Resources
Your file should be included here. If not press + to add.
When the file is listed in red, it is missing/wrong. Remove it (-) and add again

A: You're encountering a referece error. Check your class OneSlotViewController.h/m for the include of ScratchableView.h which seems to be missing from your project. Another problem could be that ScratchableView class is not added to your target.


text:
Q: URL not updating with latest page changes I have a problem that is very similar to this one: How to navigate in JSF? How to make URL reflect current page (and not previous one)
It is actually the same very problem but happens in different situations, and it is when I use a <jsp:forward> tag
To put you in situation, I have a form that asks for an user and pass to perform login. This redirects to a new page (checklogin.jsp) that performs the checking, updates the session and if everything is ok then it goes like this:
  if (con.comprobarUserPass(passmd5)) { // We check everything is OK
           sesion.setAttribute("conexion", con);
           sesion.setAttribute("pass", passmd5);
  %>
  <jsp:forward page="index.jsp"/> //forwards to the index
  <%
  } else {
  %>
  <jsp:forward page="login.jsp"> // user/pass error, goes back to the login.jsp page
     <jsp:param name="error" value="Usuario y/o clave incorrectos.
Vuelve a intentarlo."/>
  </jsp:forward>
  <%               }
  } catch (userPassIncorrectoException e) {
  %>
  <jsp:forward page="login.jsp">
     <jsp:param name="error" value="Usuario y/o clave incorrectos.
Vuelve a intentarlo."/>
  </jsp:forward>
  <%                       }
  %>

Well, the problem appears here, even if I'm redirected to the index.jsp page or to the login.jsp page my url is:
http://localhost:8084/myContext/checklogin.jsp
Any ideas why this is happening? It's making the debug process realy harder than it should be.

A: Solved my problem by using response.sendRedirect("pageToGo"); and inserting a page between the form submit and the actual page I need to go after submitting.
This way the form will call the intermediary web that only redirects to the page the user has to see after submitting the form.


text:
Q: Google OAuth 2.0 server side access to Google Drive I have created a user with access to a specific google drive. Through a Spring Boot application (jhipster) I connect with this user to the G-Drive.
My problem is the authentication. I use this code in order to authenticate (as in the samples that Google provides for web applications):
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
    HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
    .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(".")))
    .setApprovalPrompt("auto")
    .build();
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");

The first time the application starts it tries to find the StoredCredential file.
If it does not then Google provides a link for the user to open it in his browser:

Please open the following address in your browser:
https://accounts.google.com/o/oauth2/auth?...

Since I am not able to do this from the EC2 instance I do this on my local computer and I upload the file on the expected location from the server. Finally a restart makes the web server to work for a while until the token expires.
After that I have to do the same procedure.
Obviously I am doing something wrong here. What is the correct procedure for a web application to connect on the G-Drive every few minutes?
UPDATE:
I found (https://cloud.google.com/storage/docs/authentication) that I must use a service account as the link suggests for the cloud storage. Unfortunately I have downloaded the json for the service account, set the env variable but this seems that it does not work for the google drive rest api (v3).
Thank you

A: thank you for the input but I finally found my answer.
I used from the samples the code for the installed applications (Standalone applications).
What I should have used instead is a "service account".
This can be easily created from a normal Google user account.
You will receive a JSON and you must set the full path to this json file in an environmental variable GOOGLE_APPLICATION_CREDENTIALS
More information can be found here: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
As soon as you have a GoogleCredential object the rest of the sample code remains the same.
EDIT:
The use of the solution that I described before "Installed Application"/"Standalone application" is ok for demonstration purposes where there is a user to actually press the link that will pop up and in order to refresh the expired token every 60 minutes or so.
The correct solution is indeed to use a service account and impersonate the parent account (the one with who you created the service account).
Here is a sample:

    GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(HTTP_TRANSPORT)
        .setJsonFactory(GCredentials.JSON_FACTORY)
        .setServiceAccountId("xxxxxx@xyz.iam.gserviceaccount.com")
        .setServiceAccountUser("This is the email of the real user that you want to impersonate")
        .setServiceAccountProjectId("The project ID")
        .setServiceAccountPrivateKeyFromP12File(p12File)
        .setServiceAccountScopes(SCOPES)
        .build();

The administrator must give you the appropriate rights (SCOPES) as the ones that you declare and this must be done with the use of the CLIENT ID on the admin console.
Also you must make sure that the account that you impersonate is a member of the g-drive folder. This is not required for the service account.
The Project name must be correct as well when you create the DriveService instance.
I hope this will help many people and avoid wasting a lot of time trying to connect successfully.


text:
Q: Request ajax per button jquery, twitter bootstrap How to get an ajax response for a clicked button?
The HTML part:
<button type="button" class="btn btn-success ccomment" rel="popover" data-original-title="Comment" value="12">click</button>
<button type="button" class="btn btn-success ccomment" rel="popover" data-original-title="Comment" value="460">click</button>

and the jquery script:
<script type='text/javascript' language='javascript'>
$('.ccomment').click(function(){

    var ccomment_val = $(this).val();

    $.ajax({
        url: '/getcomment/'+ccomment_val,
        type:'POST',
        dataType: 'json',
        success: function(output){

            $('.ccomment').popover({
                content: output,
                html: true,
                placement: 'right',
                trigger: 'click'
            });
        }
    });

});

</script>

I just want to bind a valid ajax response with a specific button. Right now, the output is related to the button clicked as first.
Thank you

A: Not 100% sure what your trying to achieve as your explanation isn't great. But i have spotted what i believe to be a potential issue in the script, assuming it does what i think it does. So here's the solution (i hope).
underneath the line var ccoment_val.... add:
var self = $(this);
this will add a reference to the clicked button that you can then use in the ajax response. So once you have added that line, change: $('.ccomment').popover( in the ajax success function to: self.popover(
That should solve what i think is what your trying to say is the problem, if not, i apologise.

A: $('button[value="'+ccomment_val+'"]').popover({
    content: output,
    html: true,
    placement: 'right',
    trigger: 'click'

  });

you can change your popover binding like this. hope it will work


text:
Q: Import config from sphinx subfolder I've created a sphinx project in a subfolder ("docs") inside my project root. When I run the make file autodoc  it cannot find the config file and raises errors.
Is there a way to resolve this?
project structure
conf.py
Makefile
myreplicator.py
myreplicator.rst
This is the error:
/vagrant/python/mymongo/doc/myreplicator.rst:4: WARNING: autodoc: failed to import module 'myreplicator'; the following exception was raised:
Traceback (most recent call last):
  File "/var/venv/mymongo/lib/python3.5/site-packages/sphinx    /ext/autodoc.py", line 518, in import_object
    __import__(self.modname)
  File "/vagrant/python/mymongo/myreplicator.py", line 20, in <module>
logging.config.fileConfig('conf/logging.conf')
  File "/opt/py35/lib/python3.5/logging/config.py", line 76, in fileConfig
    formatters = _create_formatters(cp)
  File "/opt/py35/lib/python3.5/logging/config.py", line 109, in _create_formatters
    flist = cp["formatters"]["keys"]
  File "/opt/py35/lib/python3.5/configparser.py", line 956, in __getitem__
    raise KeyError(key)
KeyError: 'formatters'

Thanks,
Giovanni

A: I have to your folder structure diagram looks very messy.
Well, so from what I can see, there are two possible reasons.
1. System PATH
You didn't put the directory of myreplicator.py into the sys.path so that the sphinx.autodoc.py cannot locate your module (since it will only search the module in system path. Therefore you need to insert your project folder into the sys.path first). Which can be done by including the following in conf.py
import os
import sys
sys.path.insert(0, os.path.abspath('../')) # based on what I see in your structure, the myrepicator.py is in the parent directory of conf.py

2. Third-party Pacakge
Inside the myreplicator.py, there are some third-party modules cannot be loaded, most likely some C type libs (like .pyd). In this case, you can mock those third-party modules which cannot be imported by using below codes
from mock import MagicMock, Mock  # if you are using python2
# from unittest.mock import MagicMock, Mock # if you are using python3

class Mock(MagicMock):
    @classmethod
    def __getattr__(cls, name):
            return Mock()

MOCK_MODULES = ['mymongolib ', 'numpy', 'pandas'] # packages you want to mock
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)

However, from the exception you post, the chance of this error is small.
Overall, I think most likely the error is due to the first reason.


text:
Q: How to get all children of several nodes in tree structure? I have a table with hierarchical structure like this:
 Create Table tbl1
 (
     AccountID  NVARCHAR(100),
     ID int,
     ParentID int
 );

 INSERT INTO tbl1
 VALUES ('11', 1, Null), ('12', 2, Null), ('13', 3, Null),
        ('11/11', 4, 1), ('11/12', 5, 1), ('11/111', 6, 1),
        ('11/11/001', 7, 4), ('11/11/002', 8, 4), ('12/111', 9, 2),
        ('12/112', 10, 2);

How to get all children of some nodes from tbl1 in tree structure, according to an other table (FilteringTbl) like this:
 AccountID
 ---------
 11/11
 12
 13

In other words I want to create a SQL query to get all children of nodes 11/11 and 12 and 13 from my first table (tbl1) in SQL Server 2008.
Main tables have more than 5000 records. (tbl1 5400 records and filteringtbl 1500 records)
Please help me. Thanks.

A: ;with C
as (
    select  AccountID,
            ID,
            ParentID,
            0 as [level]
    from    tbl1
    where   ID IN (SELECT ID FROM Filteringtbl)
    union all
    select  I.AccountID,
            I.ID,
            I.ParentID,
            C.[level] + 1 as [level]
    from    tbl1 as I
            inner join C on
                C.ID = I.ParentID
)
select  *
from    C


text:
Q: Android: Changing Views visibility on Activity start | Hide Notification panel on Notification Button click My app has a Notification that holds a Button.
When the user clicks the Button, the app should open (if it was closed) and show a custom dialog, which I've created by a bunch of views.
Showing the dialog means setting its Visibility to View.VISIBLE.
I use a BroadcastReceiver to receive the Notifications Button click, and it works (I've used Toast messages to check it, and it does - the Receiver is getting called when the Button is clicked, and it reaches to the function that changes the dialogs Visibility to View.VISIBLE)
When I click the Button, the app does open, but the dialog won't show.
Also, I've noticed that when I click the Button, the Notification panel does not hide (unlike when clicking the Notification itself), and I thought maybe it has something to do with it.
So I found this answer, but it didn't work for me (below there's another answer, much newer, but I didn't understand what he did there or how can I do it).
I also checked using Toast messages whether the Visibility parameter of the dialog is changing or not, and it is changing to View.VISIBLE (0), and still, the dialog is not shown.
If I'm in the app and trying to show the dialog, it works, the dialog shows on an in-app button click, the issue occurs when trying to show the dialog as soon as opening the app using the Notifications Button click
Is the Notification Panel the problem?
If it is, why is it happening and how can I hide the notification panel?
If it's not, what is it, and how can I solve this?
Edit
I was asked for the code that inits and shows the notification, so here it is:
@RequiresApi(api = Build.VERSION_CODES.M)
private void updateNotification() {
    isBatteryOptimizationActive = App.isBatteryOptimizationActive();

    clearAllTimerNotificationActionButtons();

    if (isBatteryOptimizationActive) {
        initBatteryOptimizationActiveNotification();
    } else {
        if (notificationJustStarted) {
            initNotificationBase();
        }
        initAndStartPomodoroTimerNotification();
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.notify(TIMER_NOTIFICATION_ID, pomodoroNotificationBuilder.build());
    }

}
private void initNotificationBase() {
    pomodoroNotificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);

    pomodoroNotificationBuilder
            .setContentTitle(getString(R.string.timer_notification_background_allowed_title))
            .setOngoing(true)
            .setAutoCancel(false)
            .setSmallIcon(R.drawable.tomato)
            .setContentIntent(pendingIntent)
            .setNotificationSilent()
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);
    notificationJustStarted = false;
}

@RequiresApi(api = Build.VERSION_CODES.M)
private void initAndStartTimerNotification() {
    String enableScreenOverlayText = "",
            actionButtonTitle;
    PendingIntent pendingIntent;
    if (!Settings.canDrawOverlays(this)) {
        /** Initialize the notification in case "draw over other apps" setting is disabled */
        Intent notificationIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
        actionButtonTitle = "Enable";
        enableScreenOverlayText = String.format("To be able stopping the timer from the notification:\nClick Enable -> Search for %s -> Allow Display over other apps", getString(R.string.app_name));
    } else {
        /** Initialize the notification in case "draw over other apps" setting is enabled */
        Intent stopActionIntent = new Intent(this, PomodoroService.class);
        stopActionIntent.setAction(ACTION_STOP_SERVICE);
        stopActionIntent.putExtra(POMODORO_SERVICE_STOP_FOR_REAL_EXTRA_NAME, false);
        pendingIntent = PendingIntent.getService(this, 1, stopActionIntent, PendingIntent.FLAG_IMMUTABLE);
        actionButtonTitle = "Stop";
    }

    pomodoroNotificationBuilder
            .setContentText(String.format("%s is in progress\nThis session remains: %s until finished", goalName, PublicMethods.formatStopWatchTime(millisRemaining)))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(enableScreenOverlayText))
            .addAction(R.drawable.stop, actionButtonTitle, pendingIntent);
}

A:
How can I hide the notification panel?

I see that you are receiving the action button click in the Receiver. So, then it becomes an easy task to dismiss it. In the receiver, add this line:
NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
manager.cancel(TIMER_NOTIFICATION_ID);

When I click the Button, the app does open, but the dialog won't show.

You need to pass an intent extra that you are wanting to show the dialog. Then, you can, in the onCreate() get that extra and then show the dialog accordingly.


text:
Q: Embedding C compiler to a webpage I am developing a site for online C coding competition. The coding will be done in an editor that will be embedded in the webpage, and this must also be able to compile the program online. Is there any available compiler that can be embedded in the webpage? The server can be either linux or windows server. If anyone has any idea please share.

A: Well, you can always write a script that invokes an installed compiler through system() commands. Although you want to be very, very careful as this can be very dangerous. For example if you do not sanitize your input, then someone could inject commands which intentionally crash/damage your system.


text:
Q: "Cannot access private field" despite @:access, but only outside FlxState subclass? Running Haxe 3.2.1.
I was building something special that needed access to HaxeFlixel's internals, so I added this above the function that needed it:
@:access(flixel.FlxG.keys)

This worked, in the context of override update() in a FlxState subclass.
Then I wanted to move this code to a higher level[1].  So I made a new class (not a subclass of anything), put the code in a function in the new class instead, and moved the @:access to above the new function.
The new class won't compile, saying Cannot access private field playback.  Why is this, when I have the same @:access metadata I had working before?
[1] I.e. to be called via FlxG.signals.preUpdate so that it would also run if my FlxState subclass opened a substate, which normally pauses the parent state's update() (which I still want it to do.)

A: For the "I'm not sure how it was working before" department:
Don't use the member directly in @:access(), instead use the class' type.  In this case, FlxG.keys is a FlxKeyboard, so the following works:
@:access(flixel.input.keyboard.FlxKeyboard)


text:
Q: How to add active class dynamically **I use this code but not working **

                        <?php
                            $feuted_post_slider = new WP_Query( array(
                                'post_type'         => 'post',
                                'posts_per_page'    => 5,
                                'order'             => 'ASC',
                                // 'meta_key'          => 'featured_post',
                                // 'meta_value'        => 'on'
                            ) );
                            // need a variable for active class
                            $i = 1;
                        ?>
                        <?php if( $feuted_post_slider->have_posts() ) : ?>
                            <?php while( $feuted_post_slider->have_posts() ) : $feuted_post_slider->the_post();

                            $featured_img_id    = get_post_thumbnail_id( get_the_ID() );
                            $featured_img       = wp_get_attachment_image_src( $featured_img_id , 'full' );
                            ?>
                                <div class="carousel-item <?php if ( $i == 1 ) : echo 'active'; endif; ?> bg-img" style="background-image: url(<?php echo $featured_img[0]; ?>)">

<?php the_time( 'M d, Y' ); ?> /
                                            <?php
                                                $categoris = get_the_category();
                                                $separator = ', ';
                                                $output    = '';

                                                if( $categoris ){
                                                    foreach( $categoris as $category ){
                                                        $output .= 'term_id ) . '">' . $category->cat_name .'' . $separator;
                                                    }
                                                    echo trim( $output , $separator );
                                                }
                                            ?>

                                        <a href="<?php the_permalink(); ?>" class="post-title">

<?php the_title(); ?>

                            <?php endwhile; ?>
                        <?php endif; wp_reset_postdata(); ?>

                        <?php
                        $post_num = 1;
                        $slider_data_value = 0;
                        $count = 0;
                        if( $feuted_post_slider->have_posts() ) : ?>
                            <?php while( $feuted_post_slider->have_posts() ) : $feuted_post_slider->the_post(); ?>
                                <li data-target="#featured-post-slides" data-slide-to="<?php echo $slider_data_value++; ?>" class="<?php
                                    if($count==0){
                                        echo "active";
                                      }
                                      else{
                                          echo " ";
                                      }
                                ?>">

<?php echo $post_num++; ?>

                                    <a href="<?php the_permalink(); ?>" class="post-title">

<?php the_title(); ?>

                            <?php endwhile; ?>
                        <?php endif; wp_reset_postdata(); ?>

A: You should change $i == 1 to $i++ == 1


text:
Q: Javascript dropdown options 0-100 increment by .5 I have a javascript function that is creating the values for a dropdown on my page. I am currently incrementing by 5, (0-100).
I am trying to change this to increment by .5 instead but it keeps just returning 0-100 with no increment.
My expected output is 0,.5,1,1.5,2,2.5 ... 100.
Here is my function so far:
/**
 * Generate our possible error scores
 */
function generateErrorScores() {

    var min = 0,
        max = 100,
        multiplier = 5, // Tried .5 here
        list = [];

    // Loop between min and max, increment by multiplier
    for (var i = min; i <= max; i++) {
        if (i % multiplier === 0) {
            list.push(i);
        }
    }

    return list;
}

console.log(generateErrorScores())

Fiddle: http://jsfiddle.net/3y451jga/
I have a feeling its if (i % multiplier === 0) { causing the problem but I am not sure how to adapt it to the .5 increments.

A: If all you want is the list [0, 0.5, 1, 1.5, ..., 100] you could do:

/**
 * Generate our possible error scores
 */
function generateErrorScores() {
  const multiplier = 0.5
  return [...Array((100 / multiplier) + 1)].map((x, i) => i * multiplier)
}

console.log(generateErrorScores())

A: I think it would be easier to just do this
for (var i = min; i <= max; i+=0.5) {
    list.push(i);
}

A: The if (i % multiplier === 0) serves no purpose. That works if you need multipliers off a list, but in this case you need fractions.
Interestingly, your comment is correct ("increment by multiplier") but the code is not doing that. A valid solution would be something like this:
function generateErrorScores() {

    var min = 0,
        max = 100,
        segment = .5,
        list = [];

    // Loop between min and max, increment by segment
    for (var i = min; i <= max; i += segment) {
        list.push(i);
    }

    return list;
}

console.log(generateErrorScores())

A: You can just increment the i by 0.5 and you will get your expected output, there is no need for extra check here.
 for (var i = min; i <= max; i+=0.5) {

/**
 * Generate our possible error scores
 */
function generateErrorScores() {
  var min = 0,
    max = 100,
    multiplier = 0.5,
    list = [];
  // Loop between min and max, increment by multiplier
  for (var i = min; i <= max; i += 0.5) {
    list.push(i);
  }
  return list;
}
console.log(generateErrorScores())

A:

function generateErrorScores() {

 var min = 0,
  max = 100,
  increment = 0.5,
  list = [];

 // Loop between min and max, increment by multiplier
 for (var i = min; i <= max; i = i + increment) {
  list.push(i);
 }

 return list;

}

console.log(generateErrorScores());


text:
Q: Run a custom function on a WordPress page I have a function in my WordPress theme functions.php file with the following code:
function locations() {
    $locations_list = array();
    query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'post_type' => 'location'));
    while(have_posts()) {
      $locations_list[the_slug()] = the_title();
    }
    wp_reset_query();
    return $locations_list;
}

The idea is that I can run this function anywhere on my site and it will store all my posts in an array.
However, I have no idea how I run this at the public end :'(
Perfect world, I'd like to run this in my footer.php script.
Any help would be greatly appreciated.

A:
Perfect world, I'd like to run this in my footer.php script.

Then simply run the function in the footer.php template from your theme.
Also, avoid using query_posts() for custom queries because that function alters the main query. Use the WP_Query class directly instead:
$query = new WP_Query(array(...));
while($query->have_posts()) {
  $query->the_post();
  // $locations...
}

FYI the_title() prints the post title on the screen, so you don't need to assign it to a variable because it returns nothing.


text:
Q: Highlight first element with condition in XSLT I am looking for a function that can highlight only a line from an XML.
For example:
<DatabaseResult Result='Database transaction completed successfully.'>
<root>
<row Name='ABC1' Description='General 1' Quantity='1.000' UOM='ea' ID='1' Added='0'/>
<row Name='ABC2' Description='General 2' Quantity='1.000' UOM='ea' ID='2' Added='0'/>
<row Name='ABC3' Description='General 3' Quantity='1.000' UOM='ea' ID='3' Added='0'/>
</root>
</DatabaseResult>

I have the above mentioned XML and i need to display this information in a table. First, I need to highlight only the first line.
After the first line has been highlighted and action will be taken, the " Added " property will be updated from value 0 with value 1
The XML file will be updated with the new value/
After this the workflow re-enter to this XML using XSLT and shows table, now with with line 2 highlighted.
I tought about using an XSL function that use for example the following:
Will highlight only the first value that has Added = '0' and the value is greater than the first one.

      <xsl:if test="(@Added= '0') and (@ID= DatabaseResult/root/row/ID[not(. > /DatabaseResult/root/row/ID)][1])">

      <xsl:attribute name="style">background-color: green</xsl:attribute>

          <xsl:value-of select = "@Name" />
          <xsl:value-of select = "@Description" />
          <xsl:value-of select = "@Quantity" />
          <xsl:value-of select = "@UOM" />
          <xsl:value-of select = "@ID" />
          <xsl:value-of select = "@Added" />

        </xsl:if>
        </xsl:for-each>

Can you please advise what would be the best condition to use for the above mentioned case?
Thanks in advance


text:
Q: Set transparency in sns.pointplot I am trying to figure out to add transparency or alpha to sns.pointplot. I have a plot that looks like this:

I am trying to add the transparency or alpha to it, but no luck. I know I can set alpha in sns.kdeplot but not sure how to do it on sns.pointplot.
plt.rcParams['figure.autolayout'] = True
fig, ax = plt.subplots()
q1 = sns.pointplot(df1['Q53Val'][0:191], color='#22b584', dodge = True, errwidth=50, scale = 7.5, plot_kws=dict(alpha=0.3)).set(xlim=0)
q2 = sns.pointplot(df1['Q53Val'][192:], color='#f77f2f', dodge = True , errwidth=50, scale = 7.5, plot_kws=dict(alpha=0.3)).set(xlim=0)
ax.set(ylabel=None)
ax.set(xlabel=None)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
plt.xticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])
plt.xticks([])
plt.yticks([])


text:
Q: How to test which addon makes Firefox unstable? I have installed a lot of addons and recently I find that Firefox keeps increasing memory usage and sometimes hangs after 30 minutes running.
It's hard to test them one by one. Is there a better way to test them?

A: Remove half of them (32/2=16). Still unstable: the next half, else, the other half.
32-16-8-4-2-1 => 6 steps.

A: Does not seem to be possible. If you want something that will show firefox memory usage in firefox, see here.

A: In my experience, anytime I add more than a few add-ons to Firefox, the chances for conflicts and crashes are multiplied greatly. I would say pick the add-ons that are the most useful to you, and if you must, add on one at a time and give it time to see if the browser becomes unstable.
Another possibility is that it is time to do a fresh install of your OS. Any pc slows down to a crawl and browsers crash frequently when the system has not been restored for a maximum of say, a year, sometimes six months. This is a not-advertised dirty little secret of the Windows OS. It is full of leaky code which will fill up your hard drive even though you have ALL your files stored in the cloud on a service like Dropbox. A disk clean up will do NOTHING to free up space or solve this problem. Your pc will only become slower and slower, prompting many to think it's time for a new pc, when all you need is a fresh install.
Research elsewhere for how to save all your add-ons and settings in one nifty file for transfer to a clean OS.
As well, your multiple add-ons are bound to have pieces of conflicting code, which may operate fairly well together for a time, but by the same token, will build up detritus in your system and start to cause you more and more problems. So you MAY be able to start over with a fresh install, cannot guarantee.


text:
Q: "The Willis Tower is taller" or "the Willis Tower is the taller" I have a question about a sentence with the comparative form of an adjective.
When you say "Between A and B, A is better, larger, taller, etc.", should there be an article before the adjective?

Between the Willis Tower and the Empire State Building, the Willis
Tower is the taller.
Between the Willis Tower and the Empire State Building, the Willis
Tower is taller.

Which of the two sentences above can you use?

A: When comparing two or more things using than, you use a comparative, for example better or more dangerous:

The Burj Khalifa is taller than any other building. -many things,
The Willis Tower is taller than the Empire State Building. -two things

When comparing more than two things and you don't use than, you use the definite article followed by the superlative, for example best or most dangerous.

The Burj Khalifa is the tallest building.

When comparing just two things and you don't use the word than, you use the definite article followed by the comparative, for example better or more dangerous.

Between the Willis Tower and the Empire State Building, the Willis Tower is the taller.

In informal English, it is not unusual to omit the definite article in sentences without than.

A: Your sentence is correct in grammar and meaning both with and without "the", but the structure is different.
In both cases, there are some missing words that are understood by the listener:

"... the Willis Tower is taller (than the Empire State Building)."
"... the Willis Tower is the taller (one of these two buildings)."


text:
Q: I can't properly select an XML node in a SOAP header in C#.Net I have an XML document wrapped in a SOAP header but I can't select a single node. I think I am just misunderstanding how to repsresent the tree when nodes are prepended with text.  e.g. wsu:Timestamp, wsu:Created
Here is the top part of my XML:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:itk="urn:nhs-itk:ns:201005">
    <soap:Header>
        <wsa:MessageID>39c6f52b-1be0-42a9-a219-5d6ececd1695</wsa:MessageID>
        <wsa:Action>urn:nhs-itk:services:201005:SendCDADocument-v2-0</wsa:Action>
        <wsa:To>http://127.0.0.1:4000/syncsoap</wsa:To>
        <wsa:From>
            <wsa:Address>http://localhost</wsa:Address>
        </wsa:From>
        <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
            <wsu:Timestamp xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="D6CD5232-14CF-11DF-9423-1F9A910D4703">
                <wsu:Created>2015-01-30T19:40:00</wsu:Created>
                <wsu:Expires>2015-01-30T19:50:00</wsu:Expires>
            </wsu:Timestamp>
            <wsse:UsernameToken>
                <wsse:Username>TKS Server test</wsse:Username>
            </wsse:UsernameToken>
        </wsse:Security>
    </soap:Header>

Here is my code, which throws a null pointer exception on the Select Single Node because it doesn't return a match.
private static XmlDocument CreateSoapEnvelope()
{
    XmlDocument soapEnvelop = new XmlDocument();
    DateTime myCreatedDate = DateTime.UtcNow;

    soapEnvelop.Load(@"c:\myFile.xml");
    soapEnvelop.SelectSingleNode("/soap/Envelope/Header/wsse/Security/wsu/Timestamp/Created").InnerText = myCreatedDate.ToString("yyyy-MM-ddTHH:mm:ssZ");
    return soapEnvelop;
}

I triple checked for case sensitivity and I don't see a mistake there.  And when I put a breakpoint in I can see the XML is loaded into the soapEnvelop object fine.
I implemented the suggestion of using a Namespace Manager and I could select several nodes fine. However, I have an issue with matching the Id value in wsu:Timestamp.  I tried the following but all couldn't match:
soapEnvelop.SelectSingleNode("//soap:Envelope/soap:Header/wsse:Security/wsu:Timestamp/Id", ns).InnerText = Guid.NewGuid().ToString();
soapEnvelop.SelectSingleNode("//soap:Envelope/soap:Header/wsse:Security/wsu:Timestamp/wsu:Id", ns).InnerText = Guid.NewGuid().ToString();
soapEnvelop.SelectSingleNode("//soap:Envelope/soap:Header/wsse:Security/wsu:Timestamp", ns).Attributes["Id"].Value = Guid.NewGuid().ToString();

I figured out my last problem.  If you have an attribute that is empty then the Value() call must "fail". I had modified my xml doc I was working with when I added in the code suggested below and took out the existing ID and replaced it with "", which is what I was doing with Created and Expires.  The issue must be you can have an InnerText for a node that is an empty string but you can't have that for an attribute. Maybe that is considered invalid XML so .Net says "no go dude".
What is odd is that when I changed my code to do this call before my initial setting of Id.
XmlNode myNode = soapEnvelop.SelectSingleNode("//soap:Envelope/soap:Header/wsse:Security/wsu:Timestamp", ns);
myNode.Attributes["wsu:Id"].Value = Guid.NewGuid().ToString();

It set the value fine even if Id was "" in my xml file.  That is how I stumbled onto my solution because I left my original call still in the code and it didn't throw an exception so it got me thinking the only difference is Id has a value.
Thanks,
Dan

A: This is a namespace issue. The nodes that you are selecting don't all belong to the same namespace so effectively does not have access to them. You need to use an XmlNameSpaceManager to store your namespaces and specify which namespace each element belongs to.
Such as:
    private static XmlDocument CreateSoapEnvelope()
    {
        XmlDocument soapEnvelop = new XmlDocument();
        DateTime myCreatedDate = DateTime.UtcNow;

        soapEnvelop.Load(@"c:\myFile.xml");

        XmlNamespaceManager ns = new XmlNamespaceManager(soapEnvelop.NameTable);
        ns.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
        ns.AddNamespace("wsa", "http://www.w3.org/2005/08/addressing");
        ns.AddNamespace("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
        ns.AddNamespace("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

        soapEnvelop.SelectSingleNode("//soap:Envelope/soap:Header/wsse:Security/wsu:Timestamp/wsu:Created", ns).InnerText = myCreatedDate.ToString("yyyy-MM-ddTHH:mm:ssZ");

    }

There are more elegant ways of performing this task but this at least will allow you to proceed.


text:
Q: How to properly configure CodeCov for a C++ w/ CMake project in TravisCI? I was trying to configure CodeCov on my GitHub repo with TravisCI. Since my repo is in C++ and I used CMake already, I essentially copy-pasted the after_success label of this example into my .travis.yml file:
after_success:
    # Creating report
  - cd ${TRAVIS_BUILD_DIR}
  - lcov --directory . --capture --output-file coverage.info coverage info
  - lcov --remove coverage.info '/usr/*' --output-file coverage.info
  - lcov --list coverage.info
  # Uploading report to CodeCov
  - bash <(curl -s https://codecov.io/bash) || echo "Codecov did not collect coverage reports"

I pushed a custom .codecov.yml file to provide my token and notification settings, but the after_success is just the one suggested in the example. I'm really not familiar with lcov, so I have no idea whether something else is missing or what those calls are for.
Looking at CodeCov's documentation I couldn't find what I might be missing but my coverage reports are empty because lcov can't find some mysterious .gcda file (I guess). CodeCov's docs don't mention that anywhere so I guess I'm missing an important step in my configuration (or perhaps the file can't be found for some reason...?)
This is the output of TravisCI's after_success stage:
$ lcov --directory . --capture --output-file coverage.info
Capturing coverage data from .
Found gcov version: 4.8.4
Scanning . for .gcda files ...
geninfo: ERROR: no .gcda files found in .!

$ lcov --remove coverage.info '/usr/*' --output-file coverage.info
Reading tracefile coverage.info
lcov: ERROR: no valid records found in tracefile coverage.info

$ lcov --list coverage.info
Reading tracefile coverage.info
lcov: ERROR: no valid records found in tracefile coverage.info

$ bash <(curl -s https://codecov.io/bash) || \
  echo "Codecov did not collect coverage reports"
  _____          _
 / ____|        | |
| |     ___   __| | ___  ___ _____   __
| |    / _ \ / _` |/ _ \/ __/ _ \ \ / /
| |___| (_) | (_| |  __/ (_| (_) \ V /
 \_____\___/ \__,_|\___|\___\___/ \_/
                              Bash-8fda091
==> Travis CI detected.
    project root: .
--> token set from env
    ...
==> Running gcov in . (disable via -X gcov)
==> Python coveragepy not found
==> Searching for coverage reports in:
    + .
    -> Found 3 reports
==> Detecting git/mercurial file structure
==> Appending build variables
    + TRAVIS_OS_NAME
==> Reading reports
    - Skipping empty file ./coverage.info
    + ./doc/****.zip bytes=337165           -----> That's not a report.
    + ./doc/****.pdf bytes=353614           -----> That's not a report.
==> Appending adjustments
    http://docs.codecov.io/docs/fixing-reports
    + Found adjustments
==> Uploading reports
    url: https://codecov.io
    query: branch=codecov&commit=*****...
    -> Pinging Codecov
    -> Uploading to S3 https://codecov.s3.amazonaws.com
    -> View reports at https://codecov.io/github/********

A: The problem was with Cmake compiler and linker flags. In order for GCov (part of GCC, and used by lcov) to provide profiling information and coverage tests some flags have to be set.
From Code Coverage for C Unit Tests:

Specifically, you need the compiler to add profiling information to the object code, which is done by adding the flags -fprofile-arcs and -ftest-coverage to your compile command.
The first flag adds logic to the object code to generate generic profiling information. This is information about how often each basic block is executed. When your program is run, all of this information will be saved to a new file with the extension .da, next to the .o file. The data in this file isn't coverage specific, but it will be used by gcov.
The second flag that you passed to GCC, -ftest-coverage, is also going to add logic to your object files. This time, the goal is to output the coverage-specific information. There are two files that will be generated, a .bb and a .bbg. The .bb file is a simple mapping file from basic blocks to line numbers. The .bbg file lists each of the arcs in the corresponding source file that were run when executing the application. This data is used by gcov to reconstruct the actual program flow graph, from which all basic block and arc execution counts can be computed.

Also, the sources need to be linked with -lgcov --coverage. In my case, since I'm using Cmake I needed to specify these with the  set_target_properties function:
add_executable(dss-sim dss-sim.cpp)
target_link_libraries(dss-sim
    list
    of
    my
    static
    libs
)
# The libs above also need to be compiled with the same flags.
set_target_properties(dss-sim
    PROPERTIES
    COMPILE_FLAGS "-ftest-coverage -fprofile-arcs"
    LINK_FLAGS    "-lgcov --coverage"
)

Finally, since you normally don't want to include your unit tests in your coverage report, you will not define the compiler flags for them. Note, however, that if you link your unit tests with libraries that were compiled with gcov options, you'll still need to add the linker flags.


text:
Q: How can I show a modal window saying 'Exporting", while exporting Telerik RadGrid to Excel and then close it when exporting is done I'm exporting Telerik Grid to Excel.
How can I display a Modal window notifying a user that a data is being exported.
And after it's done exporting, just close the window and open the file.
Probably I can change the text on the 'Export" button to 'Exporting..." and then after export is finished, show the default text again.
I have the following code exporting grid:
public void ExcelExport()
{

    grdMyGrid.ExportSettings.IgnorePaging = true;
    grdMyGrid.ExportSettings.FileName = "Moss2 Merchants_" + DateTime.Now.ToString("yyyyMMdd");
    grdMyGrid.Rebind();
    grdMyGrid.ExportToExcel();
}

And I have a button, that when clicked, the data is being exported:

        <telerik:RadButton ID="btnExport" runat="server" OnClick = "btnExportClick" Text="Export To Excel" CausesValidation="false" SingleClick="false" SingleClickText="Fetching Data..."/>

What is the best way to accomplish something that I need?


text:
Q: How to share worlds between platforms with Minecraft Better Together I have read that with the new "Better Together Update" (BTU) it is now possible to create a world on one platform and then continue playing it on a different platform.  However, I am having trouble finding details of how this is supposed to work to determine if it would do what I am hoping it would and therefore whether it is worth my time/money.
I have some saved worlds on Minecraft for XBox One, all done in creative mode.  I am able to import them into what is now just called "Minecraft" which as of the BTU is what is being used to mean the cross-platform version.   Can I now play this same world on my Windows 10 PC?   If I go to the Minecraft web site it offers to sell me the "Java Edition" with the addendum "includes edition for Windows 10".   But from what I have read, anything that has the word "edition" in it isn't the cross platform version.   It's very unclear to me what I would actually be buying here.
If it is possible to open the same world on different platforms, exactly how would I go about doing this?  On the XBox I have to sign in with an outlook.com e-mail address to access my worlds, or my kids' sign-ins to access their worlds, is it the same from the PC? And where would my world be saved?   I have read that XBox saves will be in the cloud, but PC saves will be local, so how can I get a cloud save onto my PC?  And then how can I get it back to the cloud when I am done so I can play it on the console again?  Will there be two copies floating around, making it possible for me to make a backup on my PC?
How will this interact with world editors?  At some point will I be able to start a game on XBox, transfer it to the PC, open it in a world editor, make some changes, and then transfer it back to the XBox?

A: There is a way to transfer worlds from the Xbox to windows 10 and back using Minecraft Realms, but it will cost some money and availability may depend on your country.
You sign up for the Realms service in the game (on either platform) and then the realm appears on the list of worlds you can log into. A pencil button next to the realm name opens the Edit dialog, and that screen has two buttons you will use. First use "Replace World" which allows you to upload a world file from your local gaming platform to the realm. You'll do this on the Xbox, or the one that has the world you're trying to transfer. Then, on the other platform, used the "Download World" button to import the world.

I've just tried this and it works fine, but it does require a subscription to the Minecraft Realm service. I think you can sign up for this service through multiple different stores, like Google Play or the Microsoft Store. Tonight it was $3.99 / month for the "You + 2" monthly subscription, I'm sure that will eventually change.
You can cancel after transferring the world if you want but if you plan to play on both platforms you will probably want to just leave it subscribed, then you don't even have to mess with downloading the realm. You could still download the world as a backup, but the service will also create backups periodically. These appear in the in-game menu and the world can be restored from them, but I'm not sure what schedule they are created on and there doesn't seem to be a way make it take a backup.

A: There is a program called UFO Transfer that can be used to access your MC folder on Xbox one and other devices. To transfer them using a NTFS formatted USB stick, they can be copied to the win10 folder and played, or edited with the universal MC Editor from OprizeLP! I've looked, and the only method anyone talks about is using Realms.
Finally, a real way to transfer free. I ran across this program seeing tutorials on adding Mods (Behavior/texture Packs) to Xbox one.

A: All console editions (other than the PlayStation edition) of Minecraft (this includes Xbox) + Windows 10 edition + Pocket edition are now the cross-platform "Minecraft Bedrock Edition". You can transfer your world from and to any of these devices and play on that world via these devices. Please do keep in mind that Minecraft Java Edition (formerly PC edition) and Windows 10 edition are NOT the same edition of Minecraft! You will also be able to start a game on XBox, transfer it to the PC, open it in a world editor, make some changes, and then transfer it back to the XBox, as long as you are using a world editor compatible with Minecraft Bedrock Edition. About the Cloud saves, I am quite sure you can just get onto Cloud using your PC and download the saves from then on, and I suppose you can also insert saves back in again.

A: So I was reading you guys answers and I didn't want to delet my saved data so I Radomly went to settings on my switch and and I went to profile and there is a option that says "Clear Account sign in data" so I clicked it and went back to the home screen and it will now let me sign into my account and I still have all my worlds and Resource packs I hope this helps you!!!