text:
Q: My function is not defined properly, can anyone tell me why? I have a main function, and a getDogYears function that contains the variable dogYears. I have tried moving getDogYears above the main function, and I have tried initializing dogYears in the main function. I know dogYears is outside the scope of the main function, so can anyone tell me how I can make my main function be able to display information found in getDogYears? I'm sure it's something silly, but it would be a great lesson for me. Thank you!
The error: Traceback (most recent call last):
line 38, in
main()
line 21, in main
format(dogYears, ",.1f"), "in dog years.")
NameError: name 'dogYears' is not defined. Did you mean: 'getDogYears'?
FIRST_YEAR_EQUIV = 15
SECOND_YEAR_EQUIV = 9
THREE_PLUS_YEARS_MULTIPLIER = 5

def main():
    print("This program calculate's a dog's approximate age in \"dog years\" based on human years.\n")

    humanYears = float(input("Dog's age in human years? "))

    while humanYears < 0:
        print("\nHuman age must be a positive number.")
        humanYears = float(input("Dog's age in human years? "))
    else:
        getDogYears(humanYears)

        # end if
    print("\nA dog with a human age of", format(humanYears, ",.1f"), "years is",
    format(dogYears, ",.1f"), "in dog years.")

def getDogYears(humanYears):
    if humanYears <= 1:
        dogYears = FIRST_YEAR_EQUIV * humanYears
    elif humanYears <= 2:
        dogYears = FIRST_YEAR_EQUIV + SECOND_YEAR_EQUIV * (humanYears - 1)
    else:
        dogYears = FIRST_YEAR_EQUIV + SECOND_YEAR_EQUIV + THREE_PLUS_YEARS_MULTIPLIER * (humanYears - 2)

# DO NOT MODIFY CODE BELOW THIS LINE
if __name__ == "__main__":
    main() ```

A: Do a return dog years from getDogYears(), and do dogYears = getDogYears(humanYears) inside the main() function.
FIRST_YEAR_EQUIV = 15
SECOND_YEAR_EQUIV = 9
THREE_PLUS_YEARS_MULTIPLIER = 5

def main():
    print("This program calculate's a dog's approximate age in \"dog years\" based on human years.\n")

    humanYears = float(input("Dog's age in human years? "))

    while humanYears < 0:
        print("\nHuman age must be a positive number.")
        humanYears = float(input("Dog's age in human years? "))
    else:
        dogYears = getDogYears(humanYears)

        # end if
    print("\nA dog with a human age of", format(humanYears, ",.1f"), "years is",
    format(dogYears, ",.1f"), "in dog years.")

def getDogYears(humanYears):
    if humanYears <= 1:
        dogYears = FIRST_YEAR_EQUIV * humanYears
    elif humanYears <= 2:
        dogYears = FIRST_YEAR_EQUIV + SECOND_YEAR_EQUIV * (humanYears - 1)
    else:
        dogYears = FIRST_YEAR_EQUIV + SECOND_YEAR_EQUIV + THREE_PLUS_YEARS_MULTIPLIER * (humanYears - 2)
    return dogYears


text:
Q: Convergence of probability So I am getting ready for my first econometrics exam, and we have a lot of these plim (probability limits).  Looking at the definition, I have that as n goes to infinity,
$$P(|X_n-Q|>\epsilon)\rightarrow0 $$
And then there are a couple of theorems I get, including plim(A+B), plim(AB), but these require I know what plim(A) and plim(B) are.  One simple example that I did not understand was:
$$\frac{1}{n}plim(\sum X_i^2)$$
I thought that it would go to 0 in the limit that n gets really large.
What is the proper way to approach this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the recommended strategy for Git 'Master' branch in Salesforce? I want to know the recommended strategy for maintaining the Git 'Master' branch. I would like to share two scenarios:
Scenario 1: Our team is offered to work for a new client. The client has a pre-developed Salesforce environment. Our developed team requires adding some extra features. So, as usual, we created a new repo named 'SF-X.'
Question 1: So, the question is, what 'SF-X' repo's 'Master' branch will contain?
My assumption for 1: 'Master' branch will contain replicating the client's pre-developed codes.

Scenario 2: Our team is offered to work for a new client. The client wants us to develop some features from scratch in Salesforce. This means no code base exists. So, as usual, we created a new repo named 'SF-X.'
Question 2: So, the question is, what 'SF-X' repo's 'Master' branch will contain?
My assumption for 2: 'Master' branch will contain the Salesforce Development template (When we create a project using VSCode).
Please provide your valuable input for both of the questions. Thank you.

A:
So, the question is, what 'SF-X' repo's 'Master' branch will contain?

It depends. You have at least three choices.
First, you can choose to use git's "submodule" system, where the original repo is referenced by the new one. You can independently update both the SF-X repo and the parent repo independently and keep things in sync. This works well if your parent repo doesn't share a lot of similar file names (e.g, you're building an entirely new part of an application). The downside is that commits to the submodule will belong to the parent repo.
Second, you can choose to use the "fork" feature found in many git repos. This has the advantage that you can pull updates from the parent repo as if it were an upstream branch, and you can make "pull requests" to update from your repo to the parent repo. This has the advantage of being able to receive updates from the parent and also push things back to the parent if you want to.
Third, you can choose to just copy the repo. The easiest way to do this is to clone the repo, delete the .git folder entirely (rm -rf .git), then initialize a new git repository (git init). Note that if you do this, your clone loses all association to the parent repo. You can no longer make pull requests or receive fully merged updates from the parent repo. Consider this option carefully if you decide to go this route.

So, the question is, what 'SF-X' repo's 'Master' branch will contain?

It will initially just contain the boilerplate setup, but you'll likely want to customize it to suit your needs by adding whatever extensions, npm modules, etc that you use to make your work more efficient. You may also find features you find annoying, and may turn off some of them.
Note that because of changing US culture, you may want to consider not naming your "master" branch "master", but instead "main" or something like that. Using "master" risks offending your U.S. clients, but "main" should be perfectly neutral around the world.


text:
Q: Is there a simple way to find out if a boost::adjacency_list is empty? I'm using a LCCP from the Point Cloud Library, but I'm quite that I'm doing something wrong.
I think I narrowed the Error down and it has something to do with the SuperVoxelAdjacencyList sv_adjacency_list;
lccp.getSVAdjacencyList (sv_adjacency_list);
because I've implemented a other way to get the adjacency. The documentation states that

[out] adjacency_list_arg  The supervoxel adjacency list with classified
  (convex/concave) edges. On error the list is empty.

So now I'm wondering if there is a way find out if the list is emtpy.
Every help is appreciated.

A: I'd say if boost::num_vertices(sv_adjacency_list) == 0 you can conclude it's empty.
Of course, you could look at the number of edges instead.
See also: http://www.boost.org/doc/libs/1_61_0/libs/graph/doc/graph_concepts.html


text:
Q: How can I set the defaults for pictures in my document? I was wandering if there is a command that will let you define the size of graphics globally throughout then entire document. Most of my images are photos and should all be the same size and it would be good if I could change one thing that will affect the size of them all, rather than having to do it manually. For the odd picture here and there that has different dimensions I can adjust their size manually.
Question content copied with permission from a post on /r/latex.

A: Use graphicx's keyval group:
\setkeys{Gin}{width=25cm}

Stick that in your preamble after you load graphicx. If you're not loading it explicitly, put it right after \begin{document}.
After this, you shouldn't have to supply the width key at all when you use \includegraphics. Of course, if you do supply the width key, that value will take precedence.
\documentclass{article}
\usepackage{graphicx}

\setkeys{Gin}{width=.25\linewidth} % or whatever

\begin{document}
\includegraphics{example-image-a}
\end{document}


text:
Q: Codename One - Arabic text in the Simulator My app contains Arabic text. In Android and iOS devices the text is shown correctly, instead in the Simulator the text is replaced with strange characters. For example, the text "العربية" is shown similar to "[x][x][x][x]" (I cannot reproduce exactly how it is shown).
Platform: Windows 8
In the Netbeans logs generated by Log.p("...") calls, the Arabic text is shown correctly, the problem is only in the Simulator.

A: This is a problem with the Roboto Android fonts for the desktop that are shipped in the simulator skin. Google only provides some of the locales for those fonts but on the device they work as expected as we use the native builtin Roboto versions.


text:
Q: How to have autocompletion with thunderbird inside mail When I use vim, I have autocompletion with Ctrl+N, with netbeans, it's Ctrl+K.
I «want» this feature with Thunderbird. How can I do it?
Note. I don't speak about autocomplete addresses.

A: It is not perfect but if you like vim maybe it is ok for you:
use the extension External Editor
There you can define which editor is opened for editing your mails. In the properties of the Extension set
xterm -e vim

to use vim. Then you have your autocompletion just like always in vim.


text:
Q: git: Show index diff in commit message as comment When git commit open the message editor is shows a brief status, something like this:
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
# Your branch is ahead of 'origin/master' by 26 commits.
#
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   Showcase/src/com/gigantt/BorderArea.mxml
#   modified:   Showcase/src/com/gigantt/Client.mxml
#   modified:   Showcase/src/com/gigantt/GraphItem.mxml
#

How can I tweak git to show also the diff to be committed?
I'm aware that it may be a long diff, but still.. so useful.

A: If you want to always see the diff when you commit, you can add the following to your ~/.gitconfig file:
[alias]
commit = commit -v

A: Not enough reputation to post a reply to Alan's answer, but for Idan and anyone else I just tried it out and the diff lines in the commit message aren't explicitly commented out. However, they still don't show up in the final commit message, thank goodness.
$ git commit --verbose
In my editor:
Feeling a bit pessimistic now.

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   README
#
diff --git a/README b/README
index af5626b..c62237e 100644
--- a/README
+++ b/README
@@ -1 +1 @@
-Hello, world!
+Goodbye, world!

(note the lack of # preceding the diff lines)
And then the actual commit message:
$ git log -n 1
commit ad21a2655ef6d8173c2df08dc9893055b26bc068
Author: Tom Jakubowski <tom@crystae.net>
Date:   Thu Oct 27 19:12:54 2011 -0700

    Feeling a bit pessimistic now.

Obviously, git show will still show the diff, but that's because it always does for commits. :)

A: The simplest way to make sure this behavior is always present is to add this section to your git config file:
[commit]
  verbose = true

You may need to configure your editor to actually display in diff mode (for syntax highlighting).  I use Notepad2 as a Windows Notepad replacement, and -s diff sets the color scheme appropriately (red for deleted lines, etc.):
[core]
  editor = C:/Windows/system32/notepad.exe -s diff

A: The --verbose (or -v) flag for git commit will display the diff of what would be committed:
git commit --verbose

A: I've put the following lines in .git/hooks/prepare-commit-msg to get a commented out diff:
#!/bin/bash

if [ "$2" == "" ] ; then
    git diff --staged -p --stat 2> /dev/null | awk '{ printf "#"; print}' >> "$1"  2>/dev/null
fi

This way you can not only comment out the diff, but also add more info (like the stat option does).
Edit:
Also git commit --verbose does not include the diff to the commit message this way would do without the #s.


text:
Q: Order of convergence in a linear equation This is a general question about using the $\mathcal{O}$ idea to say something about the sign of coefficient. Suppose I have
$$x:=\frac{1}{b^2}\gamma(b)-\frac{1}{b^3}\beta(b)$$ and $b\in (b_0,+\infty)$ where $b_0 >1$.
$\gamma(b)$ and $\beta(b)$ are bounded continous functions . $\gamma(b)$  bounded above by $\bar{\gamma}>0$ and below by $\underline{\gamma}>0$. $\beta(b)$ is also bounded above by $\bar{\beta}>0$ and bounded below by $\underline{\beta}<0$ . Can i say that the sign of $x$ will be positive for large $b$ . Or more precisely, there exists a $\hat{b}$ such that for $b>\hat{b}$, the statement should hold?
My attempt:
Since $\underline{\gamma}>0$, there exists a $\hat{b}$, such that
$$\underline{\gamma}-\frac{\bar{\beta}}{\hat{b}}\ge0$$. Now for all $b>\hat{b}$, the expression will be positive. Is my reasoning okay?

A: You can't say anything about the sign of $x$. Consider $x=\frac{\sin(b)}{b^2}$ and $\gamma(b)=\frac{1}{b^2}$.


text:
Q: How to get traceback in http://locust.io/ How to get traceback in http://locust.io/
When i run
locust -f locustfile.py --host==http://www.test.com

output result displayed in localhost:8089 port
Now i am seeing the error message for failure requests. i also want to get the traceback when failures occurs in failures tab.
see screenshot for failure tab.
How can i see the traceback in failures tab.

A: I'm not sure if you can see error messages in the GUI. However you can see error messages in stderr or you can alternatively specify --logfile option to Locust to pump log messages into a file.  Set --loglevel to DEBUG for the highest verbosity.


text:
Q: primefaces single menuItem in panelmenu I'm trying to implement a menu with JSF 2.2 and Primefaces 5
I added PanelMenu of primefaces. Let's say I have a code snippet like this:
    <p:panelMenu>
      <p:menuitem value="Home" url="homee.xhtml" icon="ui-icon-home"/>
      <p:submenu label="User Operations">
        <p:menuitem value="ETC" actionListener="#{menuView.save}" icon="ui-icon-folder-open" />
        <p:menuitem value="New ETC" actionListener="#{menuView.update}"  icon="ui-icon-plusthick" />
      </p:submenu>
    </p:panelMenu>

The problem is, when I do this, that single menuItem which doesn't have a surrounding subMenu doesn't show up in the menu.
How can I overcome this?
Thanks.

A: you need to put the single menuitem inside a menu tag and outside the panelMenu :
<p:menu>
<p:menuitem value="Home" url="homee.xhtml" icon="ui-icon-home"/>
</p:menu>
<p:panelMenu>
<p:submenu label="User Operations">
<p:menuitem value="ETC" actionListener="#{menuView.save}" icon="ui-icon-folder-open" />
<p:menuitem value="New ETC" actionListener="#{menuView.update}"  icon="ui-icon-plusthick" />
</p:submenu>
</p:panelMenu>


text:
Q: TFS 2010 and MS Project 2010 refresh work item issue When choosing which work items to import (through the Get Work Items option) to my newly created MS Project file I've accidentally checked a work item that shouldn't be imported.
I've removed this work item from my project file, but every time I click "Refresh" the work item appears again???
Is this the correct behavior? I can NEVER bring a work item and later decide to remove it from the project file without it coming back?

A: Have you tried to publish the entire Project file (Team -> Publish) without canceling the operation? I've experienced that. For some unknown reason, the TFS plugin does not save the query information in the project file when some error occurrs, even when publishing some WorkItems got suceeded.


text:
Q: Monitor all user events in Android I would like to monitor all user generated events in an Android app. And I need to do it with as little modifications to the existing code as possible.
The "normal" way to achieve this would be use the activity's dispatchTouchEvent() and dispatchKeyEvent() method (from my understanding and experiments - I'm rather new to Android development). But this approach means subclassing the activity which is something I need to avoid.
Another thing I tried: registering a callback with setOnClickListener() on a view. But the behaviour I saw in my experiments is that if I register a callback on the content view, the callback is called for all clicks on views that do not handle clicks themselves like static text (TextView), but not for clicks on buttons, e.g. So in order to really monitor all events, I would need to register the callback not only on the content view, but on all views. This is also something I would like to avoid.
So is there a central place that all user generated events (touches and key events) pass that I can monitor without the need to subclass activities?

A: We developed the Android HCI Extractor some months ago. It was made to track and monitor the user and system interaction events in multimodal applications (e.g. touch, keypresses, scroll, number of elements provided by the system, etc.)
It is an open-source prototype. Our aim is to share its code for developers to use it, and also try to get some help to improve this tool to reach a 1.0 release. Thus, fell free to download, test, modify, etc. the application. You can send your suggestions, help, code, etc. to this email: pedromateo@um.es
It is very easy to integrate and to use. In the tutorials you can see that only a few lines of code are needed.
Here the links:
 - Android HCI Extractor code: http://code.google.com/p/android-hci-extractor/
 - MIM project (including tutorials about the tool integration and usage): http://www.catedrasaes.org/trac/wiki/MIM
I hope it helps you!!


text:
Q: Https get call results in 400 Bad Request in android So i have a webpage which i trying to access via a HttpsURLConnection. The certificate issued is by Digicert CA-3.However I always get a response as 400.The android developer website, wikipedia example works fine.This website also opens on chrome on the device.I want to know if this could a be a problem with how I am invoking the call.or what could be the issue
    URL url = new URL(strUrl);
    HttpsURLConnection urlConnection = (HttpsURLConnection) url
            .openConnection();
    SSLContext sslcontext = SSLContext.getDefault();
    CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();
    urlConnection.setDoOutput(false);
    urlConnection.setDoInput(true);
    urlConnection.setSSLSocketFactory(sslcontext.getSocketFactory());
    int code = urlConnection.getResponseCode(); //always 400 :(

A: Probably you should double check the URL you are using.. It is mostly because of client's Bad Request..


text:
Q: Как отобразить код элемента в виде форматированного текста Как с помощью JS, или JQuery можно отобразить в теге
 тег и содержимое тега

примерно так
$("pre").html($("#js").clone());

A: UPD. после комментария:
Пример на codepen, если так удобнее: ссылка

var elem = document.getElementById('script').outerHTML;
var pre = document.getElementById('pre');
pre.textContent = elem;

A: Что бы отобразить содержимое, надо отобразить содержимое.

output.textContent = test.outerHTML;
Output:


text:
Q: Change between displaying different controls in App widget I'm developing an App widget. I want the widget to alternate between displaying a image and, displaying some text.
The layout is designed using a RelativeLayout like this....
<RelativeLayout ....>

<Textview.... />
bla bla....

<TextView...... />   <!-- First I want to display these textviews -->
<TextView...... />   <!-- First I want to display these textviews -->
<TextView...... />   <!-- First I want to display these textviews -->

<ImageView...... />   <!-- After nest update I want to show this image instead -->

</RelativeLayout>

Can I group these controls and hide/show these groups or do I have to handle all of them?
Maybe there is a better to do this? Different layoutfiles?

A: It looks to me like you want to use a ViewFlipper.  You can check out the docs here: ViewFlipper


text:
Q: hash sign comments out code when using C in terminal I want to use #include header when writing C in linux terminal.
The hash sign comments out the code instead. Is there any way to go around this problem?

I use the terminal to write C code to the outer board and would need sentences like:

echo #include "analogout.h" > analogout.c

But the hash sign # comments my code out.

A: Quote the string to remove the special meaning of characters:
echo '#include "analogout.h"' > analogout.c

A: or you can also use this way to solve this problem:
echo \#include \"analogout.h\" > analogout.c


text:
Q: Model not generated on creating a table in database rails I created a table named products in postgresql
create table products ( id int,... )
    and restarted postgresql server
   How to generate its corresponding Model (Product.rb) in Rails? Is it possible ?
 PS : I am a beginner to Ruby on Rails

A: Don't create tables manually instead use ActiveRecord::Migration
For example:
rails generate model product name:string description:string price:integer
Rails automatically creates id, created_at and updated_at fields for you so you don't need to specify them while creating your model.
Then run rake db:migrate and your Products table will be created for you.

A: Models in rails are nothing but a subclass of ActiveRecord::Base, and by convention goes under app/models directory.
They are generally created using rails generate model command.
But you can also create them manually and place it under app/models directory.
Use the following in product.rb
class Product < ActiveRecord:: Base

end


text:
Q: how unzip many zip files found in many subdirectories, all in a certain different directory i have a list of zip files, which each zip file in it has also some other zip files, and so on. I need to extract them all, with an ubuntu shell command, and get only the files with the extension *.pdf, into a new empty directory.
This is where i managed to come, i have tried unzip -l "*.zip"

A: From
How do I recusively unzip nested ZIP files?
comes this one-liner :
while [ "`find . -type f -name '*.zip' | wc -l`" -gt 0 ]; do find -type f -name "*.zip" -exec unzip -- '{}' \; -exec rm -- '{}' \;; done

This removes all zip files that were done in order to avoid infinite loops.
If you want to conserve these files, take first a backup.


text:
Q: flattening json structure with arrays to multiple flat objects without arrays I'm not sure whether did I describe the problem in subject 100% correctly, but I believe that the examples will do the trick.
I have JSON structure like below (note: there is small chance that this might change, so i need to lean forward to generic solution)
One invoice with multiple line items:
{
    "contactName": "Company",
    "lineItems": [
     {
        "quantity": 7.0,
        "description": "Beer No* 45.5 DIN KEG"
     },
     {
        "quantity": 2.0,
        "description": "Beer Old 49.5 DIN KEG"
     }
     ],
    "invoiceNumber": "C6188372"
}

And this is the wanted result data structure (multiple invoices with duplicated data and different line item info):
[{
    "contactName": "Company",
    "quantity": 7.0,
    "description": "Beer No* 45.5 DIN KEG"
    "invoiceNumber": "C6188372"
},{
    "contactName": "Company",
    "quantity": 2.0,
    "description": "Beer Old 49.5 DIN KEG"
    "invoiceNumber": "C6188372"
}]

So each "line item" from "invoice" should "result" in new invoice with duplicated other elements.
Small variations around result data structure are accepted, i can adjust my code around it.
I've been spinning around using several similar questions such as:

*

*C# flattening json structure

*Flatten an array of objects that may contain arrays

*How can I flatten a collection of objects (which in turn contain collections)?

*Generically Flatten Json using c# (etc). i believe that this is the closest solution? but unsure if there is some better approach

For more background, i need this for CSV export. So result set should be two rows in generated CSV.
Any hints/tips are much appreciated. Thanks.

A: You could do it with a function like this:
//Pass in the name of the array property you want to flatten
public string FlattenJson(string input, string arrayProperty)
{
    //Convert it to a JObject
    var unflattened = JsonConvert.DeserializeObject<JObject>(input);

    //Return a new array of items made up of the inner properties
    //of the array and the outer properties
    var flattened = ((JArray)unflattened[arrayProperty])
        .Select(item => new JObject(
            unflattened.Properties().Where(p => p.Name != arrayProperty),
            ((JObject)item).Properties()));

    //Convert it back to Json
    return JsonConvert.SerializeObject(flattened);
}

And call it like this:
var flattenedJson = FlattenJson(inputJson, "lineItems");

A: You could use a custom JsonConverter if you are able to Deserialize/Serialize into a strongly typed class.
Invoice information I would imagine should be in some semi-structured object so this should be doable:
public class Invoice
{
    public string ContactName { get; set; }
    public List<Item> LineItems { get; set; } = new List<Item>();
    public string InvoiceNumber { get; set; }
}

public class Item
{
    public double Quantity { get; set; }
    public string Description { get; set; }
}

And then with the JsonConverter you can flatten it based upon the Items (Or any other property/properties you may want)
public class InvoiceFlattener : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var obj = value as Invoice;
        if (obj == null)
        {
            return;
        }

        writer.WriteStartArray();

        foreach (var item in obj.LineItems)
        {
            writer.WriteStartObject();
            writer.WritePropertyName(nameof(obj.ContactName));
            writer.WriteValue(obj.ContactName);
            writer.WritePropertyName(nameof(item.Quantity));
            writer.WriteValue(item.Quantity);
            writer.WritePropertyName(nameof(item.Description));
            writer.WriteValue(item.Description);
            writer.WritePropertyName(nameof(obj.InvoiceNumber));
            writer.WriteValue(obj.InvoiceNumber);
            writer.WriteEndObject();
        }

        writer.WriteEndArray();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Invoice);
    }
}

And to use this Converter you supply it when Serializing
        var invoice = JsonConvert.DeserializeObject<Invoice>(inputJson);
        var outputJson = JsonConvert.SerializeObject(invoice, new InvoiceFlattener());

As you have probably worked out this converter doesn't work when deserializing but if this is a requirement you can write the logic in the ReadJson converter method.
The downside to this is you will be required to maintain the converter should the structure of the Invoice class ever change. But it keeps us in a strongly typed world

A: With external lib Cinchoo ETL - an open source library, you can convert your JSON to expected CSV format with few lines of code
string json = @"{
    ""contactName"": ""Company"",
    ""lineItems"": [
     {
        ""quantity"": 7.0,
        ""description"": ""Beer No* 45.5 DIN KEG""
     },
     {
        ""quantity"": 2.0,
        ""description"": ""Beer Old 49.5 DIN KEG""
     }
     ],
    ""invoiceNumber"": ""C6188372""
}";

StringBuilder sb = new StringBuilder();
using (var p = ChoJSONReader.LoadText(json))
{
    using (var w = new ChoCSVWriter(sb)
        .WithFirstLineHeader()
        )
        w.Write(p
            .SelectMany(r1 => ((dynamic[])r1.lineItems).Select(r2 => new
            {
                r1.contactName,
                r2.quantity,
                r2.description,
                r1.invoiceNumber
            })));
}
Console.WriteLine(sb.ToString());

Output CSV:
contactName,quantity,description,invoiceNumber
Company,7,Beer No* 45.5 DIN KEG,C6188372
Company,2,Beer Old 49.5 DIN KEG,C6188372

Hope it helps.


text:
Q: Strange behavior with read() I discovered the function read(), but I don't understand everything.
Here is my code:
#include <unistd.h>
#include <stdio.h>

int     main(void)
{
    char array[10];
    int  ret;

    printf("read : ");
    fflush(stdout);

    array[sizeof(array) - 1] = '\0';
    ret = read(STDIN_FILENO, array, sizeof(array) - 1);

    printf("array = %s\n", array);
    printf("characters read = %d\n", ret);

    //getchar();

    return (0);
}

Here is an example of the running program :
$> ./a.out
read : hi guys how are you
array = hi guys h
characters read = 9
$> ow are you
zsh: command not found: ow
$>

Why is it launching a shell command after the end of the program?
I noticed that if I uncomment the getchar() line, this strange behavior disappears. I'd like to understand what is going on, if someone has an idea :)

A: Your call to read is reading in the first 9 characters of what you've type. Anything else will be left in the input buffer so that when you program exits, your shell will read it instead.
You should check the return value of read so you know how much has been read as it's not guaranteed that it'll be the amount you ask for and also the value returned is used to indicate an error.
The string read in won't be null-terminated either, so you also should use the return value (if positive) to put the NUL character in so that your string is valid.
If you want to read in the whole line, you'll need to put in a loop and identify when there is an end of line character (most likely '\n').

A: You typed about 20 characters, but you only read 9 characters with read(). Everything after that was left in the terminal driver's input buffer. So when the shell called read() after the program exited, it got the rest of the line, and tried to execute it as a command.
To prevent this, you should keep reading until you get to the end of the line.


text:
Q: Derivation of closed-form ROC expression under binormal assumptions It's a known result that, under binormality assumptions, the area under the ROC curve (AUC) for a binary classifier has the following closed form. Formally, define the class conditional mean and variance for class $y \in \{0, 1\}$:
$$\mu_y = \mathbb{E}[X \mid Y = y]$$
$$\sigma^2_y = Var[X \mid Y = y]$$
Further assume $\mu_1 \geq \mu_0$. Then the AUC is given by
$$AUC = \Phi\left(\frac{\mu_1 - \mu_0}{\sqrt{\sigma_1^2 + \sigma_0^2}}\right)$$
where $\Phi$ is the Normal CDF. I recently encountered this form in Fong et. al. (2021). A search turns up variations on this form as well, for example Pan and Metz (1997) or Bandos, Guo and Gur (2018).
I'm having trouble coming up with the derivation. Here's what I've tried. First, I know  false positive rate (FPR) and true positive rate (TPR), under the binormal assumption, are given at some threshold $\tau$ as
$$TPR(\tau) = 1 - \Phi\left(\frac{\tau - \mu_1}{\sigma_1}\right) = \Phi\left(\frac{\mu_1 - \tau}{\sigma_1}\right)$$
$$FPR(\tau) = 1 - \Phi\left(\frac{\tau - \mu_0}{\sigma_0}\right) = \Phi\left(\frac{\mu_0 - \tau}{\sigma_0}\right)$$
so that the AUC can be written as
$$\int_0^1 TPR(FPR^{-1}(x)) dx.$$
However, I'm getting stuck expanding that integral (or maybe this is not the right method to derive this). Substituting in the definition of TPR and FPR under our assumptions, I get something like
$$\int_0^1 TPR(FPR^{-1}(x)) dx= \int_0^1 \Phi\left(\frac{\mu_1 - FPR^{-1}(x)}{\sigma_1}\right) dx = \int_0^1 \Phi\left(\frac{\mu_1 - (\Phi^{-1}(1-x)\sigma_0 + \mu_0)}{\sigma_1}\right) dx.$$
At this point, I'm unsure how to proceed towards the expected closed form for the AUC. Any tips on how to proceed from here, or resources with the derivation (any form of the AUC will do)?

A: Found the issue. This comes directly from the derivation of the probabilistic interpretation of AUC. First, we know
$$AUC = \int_0^1 TPR(FPR^{-1}(x)) dx.$$
Through a change of variables $u := FPR(x)$, we have
$$AUC = \int_{FPR^{-1}(0)}^{FPR^{-1}(1)} TPR(u) FPR'(u) du = \int_{\infty}^{-\infty} \Phi\left(\frac{\mu_1 - u}{\sigma_1}\right)f_0(u) du,$$
where $f_0$ is the density of the negative class (i.e. pdf of $\mathcal{N}(\mu_0, \sigma_0^2)$). We'll later use the notation $f_1$ for the density of the positive class. To be rigorous, implicitly, there's another substitution at this phase as $FPR'(u) = f_0\left(\frac{u - \mu_0}{\sigma_0}\right)$, but the term inside $f_0$ has derivative one, so the effect is an identity multiplication.
Then, we can write the CDF (noting the flipped bounds this time) as
$$\int_{-\infty}^{\infty} \left(\int_{-\infty}^{\infty} \mathbf{1}[t < u] \cdot f_1(t) \;dt\right)\; f_0(u) du = \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} \mathbf{1}[t - u < 0] \cdot f_0(u)f_1(t) \;du \;dt$$
which is the CDF for a difference of normal distributions. This distribution has variance $\sigma_0^2 + \sigma_1^2$, and mean $\mu_1 - \mu_0$, which yields
$$AUC = \Phi\left( \frac{\mu_1 - \mu_0}{\sqrt{\sigma_0^2 + \sigma_1^2}}\right)$$
as needed.

A: About the probabilistic interpretation of the AUC...
Assume $X$ is a continuous measurement used to determine whether an individual has binary condition $D$ ($D = 0$ or $1$) and that higher values of $X$ are more suggestive of $D = 1$:
$$F_1(x) = P(X \le x|D=1)$$
$$F_0(x) = P(X \le x|D=0)$$
$$f_0(x) = \frac{dF_0}{dx} = \text{pdf of } x \text{ given } D=0$$
Define $TPR$ and $FPR$:
$$TPR(x) = 1- F_1(x) = P(X > x | D = 1) = P(X_1 > x)$$
$$FPR(x) =  1 - F_0(x) = P(X > x | D = 0) = P(X_0 > x)$$
$$dFPR(x) = -f_0(x)$$
The ROC curve is
$$ROC(\cdot) = \{(FPR(x), TPR(x)), x \in (\infty, -\infty) \}$$
I reversed the $\infty$ and $-\infty$ to remind myself that the ROC curve is traced out in the unit square from the left lower corner $(0, 0)$ to the right upper corner $(1, 1)$ as $x$ decreases from $\infty$ to $-\infty$.
The ROC curve has the following representation:
$$ROC(t) = TPR(FPR^{-1}(t))  \quad t = FPR(x) \quad t \in (0,1)$$
The area under the ROC curve is
\begin{align*}
AUROC = \int_0^1 ROC(t)dt &= \int_0^1 TPR(FPR^{-1}(t))dt \\
&= \int_{FPR^{-1}(0)}^{FPR^{-1}(1)} TPR(x)dFPR(x)\\
&= \int_{\infty}^{-\infty} TPR(x)dFPR(x)\\
&= \int_{\infty}^{-\infty} TPR(x)(-f_0(x))dx\\
&= \int_{-\infty}^{\infty}TPR(x)f_0(x) dx\\
&= \int_{-\infty}^{\infty}(1-F_1(x))f_0(x) dx\\
&= \int_{-\infty}^{\infty}P(X_1>x) f_0(x) dx
\end{align*}
This last expression leads to the interpretation of the AUROC as the probability that a random individual with the condition ($D=1$) will have a higher value of $X$ than a random individual without the condition ($D=0$).
Continuing from above:
\begin{align*}
AUROC &= \int_{-\infty}^{\infty}P(X_1 > x)f_0(x) dx \\
&= P(X_1 > X_0)
\end{align*}
Thus the AUROC is equal to the probability that $X_1$ and $X_0$ from a randomly selected pair of individuals with $D=1$ and $D=0$ will be correctly ordered, $P(X_1 > X_0)$.
I adapted this from Pepe page 78.
Once you accept that $AUROC = P(X_1 > X_0)$, then deriving a formula for the area under the binormal ROC curve is straightforward.
For the binormal ROC curve,
$$X_1 \sim N(\mu_1, \sigma_1^2)$$
$$X_0 \sim N(\mu_0, \sigma_0^2)$$
So,
\begin{align*}
AUROC &= P(X_1 > X_0)\\
&= P(X_1- X_0 > 0)\\
\end{align*}
The difference of two independent normal variables has a normal distribution:
$$X_1 - X_0 \sim N(\mu_1 - \mu_0, \sigma_1^2+\sigma_0^2)$$
So,
\begin{align*}
P(X_1- X_0 > 0) &= 1 - \Phi\left(\frac{0 - (\mu_1 -\mu_0)}{\sqrt{\sigma_1^2+\sigma_0^2}}\right)\\
&= \Phi\left(\frac{\mu_1-\mu_0}{\sqrt{\sigma_1^2+\sigma_0^2}} \right)
\end{align*}


text:
Q: C# Forms: Lock Main form and process another form I want to create something like this.

When the button clicks main form will lock/disable/inaccessible. Then the another form load and do some processing.
(actually when the button clicked, it will read some text from a file and write to db. I put progress bar to give a nice look)
As I said I want to lock/disable/inaccessible main form and load the another form.
How can I do this ?
Please Help
Yohan

A: new Form().ShowDialog() will do just that.

A: oldForm.Hide() and newForm().ShowDialog()

A: as J.N. mentioned, ShowDialog will work, but I think you will need to have your processing code in the new form you open up, as the program will only return and 'unlock' your main form after the new form has finished and closed.
Edit I just saw the comments below the original post, I guess this has been sorted, but I'll leave my comments above just in case


text:
Q: scroll bar to bottom after fetching from mysql I want to move the scroll  bar to bottom after appending/submission of a new text in both side. i.e the scroll bar should be moved to bottom at the user's side who is sending the text and also scroll bar should be moved in the user's side who is receiving the text.
    <?php
session_start();
?>

           <title>Live Table Data Edit</title>
           <link rel="stylesheet" href="css/bootstrap.min.css" />
           <link href="style.css" rel="stylesheet">

You Are : <?php echo $_SESSION['name']; ?>

                <textarea id="text" name="text"></textarea>
                <button type="submit" id="sub" name="sub">Send</button>

the problem is that whenever a new text is added the text goes down to bottom in both the side and the scroll br remain at its position(but should be moved along the new text).


text:
Q: Neural Network Inputs and Outputs to meaningful values I'm trying to determine how to transform my "meaningful input" into data for an Artificial Neural Network and how to turn the output into "meaningful output".
The way I can always see of doing it is by convering everything to categories with binary values.
For example, rather than outputting age, having a 0-1 for <10, a 0-1 for 10 - 19, etc.
Same with the inputs, where I might be using for example, hair colour. Is the only way to turn this into input to have Blonde 0-1, Brown 0-1, etc?
Am I missing some entire topic of ANNs? Most of the books and similar I read use theoretical examples.

A: Your example is spot-on, and is known as discretization. Another method would be to scale your continuous input/output into the 0-1 range. For your other example of hair color, that would be a nominal attribute, so the only real option there is to discretize it as separate inputs per color.


text:
Q: How to sort/order a list by date in dart/flutter? I have the following list, that I am trying to re-order/ sort by the DateTime.
import 'package:intl/intl.dart';
//don't forget to add under dependencies pubspec.yml "intl: ^0.15.8"

List products = [];

//adding into the new list from raw API list
for(final item in rawProducts){

   var parsedDate = DateTime.parse.(item['expiryDate']);
   tmpArray = {
     'id': item['id'],
     'name': item['name'],
     'price': item['price'],
     'expiry': parsedDate
   }
   products.add(tmpArray);
  }
}

List products = [

 {id: 1242, name: milk, price: $5, expiry: 2019-11-25 00:00:00:000},
 {id: 1242, name: egg, price: $2, expiry: 2019-11-22 00:00:00:000},
 {id: 1243, name: bread, price: $3, expiry: 2019-11-22 00:00:00:000},
 {id: 1244, name: butter, price: $7, expiry: 2019-11-24 00:00:00:000},
 {id: 1247, name: butter, price: $7, expiry: 2019-11-23 00:00:00:000},

]

I would like to re-order the list in a way that the farthest expiry date shows up first:
 25-11-2019
 24-11-2019
 23-11-2019
 22-11-2019
 22-11-2019

What I have tried (updated) -> SOLVED by changing a.expiry into a['expiry'] :
  products.sort((a,b) {
    var adate = a['expiry'] //before -> var adate = a.expiry;
     var bdate = b['expiry'] //var bdate = b.expiry;
     return -adate.compareTo(bdate);
  });

on the sort function I am receiving this error (SOLVED by above fix):
Unhandled Exception: NoSuchMethodError: Class
'_InternalLinkedHashMap<String, dynamic>'has no instance getter 'expiry'.

A: If you have something like:
{
"id": 100,
"timestamp": "2021-02-02T15:15:11Z",
"name": "Entry1"
}

Then do this:
List<Values> _myList = [];
_myList.sort((a,b)=> a["timestamp"].compareTo(b["timestamp"]));

Or like in my code:
task.sort((a,b) => a.createdAt.compareTo(b.createdAt));

Source

A: If you want to sort the objects by a property name without having to use DateTime assuming the date and time is a string, do this:
products.sort((a, b)=> a['expiry'].compareTo(b['expiry']));

A: I fixed it by changing  changing a.expiry into a['expiry'] and b.expiry into b['expiry']
products.sort((a,b) {
 var adate = a['expiry'] //before -> var adate = a.expiry;
 var bdate = b['expiry'] //before -> var bdate = b.expiry;
 return adate.compareTo(bdate); //to get the order other way just switch `adate & bdate`
});

A: convert to DateTime
import 'package:intl/intl.dart';

void main() {
  List products = [
    "2019-11-25 00:00:00.000",
    "2019-11-22 00:00:00.000",
    "2019-11-22 00:00:00.000",
    "2019-11-24 00:00:00.000",
    "2019-11-23 00:00:00.000"
  ];
  List<DateTime> newProducts = [];
  DateFormat format = DateFormat("yyyy-MM-dd");

  for (int i = 0; i < 5; i++) {
    newProducts.add(format.parse(products[i]));
  }
  newProducts.sort((a,b) => a.compareTo(b));

  for (int i = 0; i < 5; i++) {
    print(newProducts[i]);
  }
}

without convert to DateTime
import 'package:intl/intl.dart';

void main() {
  List products = [
    "2019-11-25 00:00:00.000",
    "2019-11-22 00:00:00.000",
    "2019-11-22 00:00:00.000",
    "2019-11-24 00:00:00.000",
    "2019-11-23 00:00:00.000"
  ];

  products.sort((a,b) => a.compareTo(b));

  for (int i = 0; i < 5; i++) {
    print(products[i]);
  }
}

A: In your example above, expiry is a String, not a DateTime object. You have a few options here, depending on what you want to achieve.
The easiest solution would be to use String's built in compareTo method, which allows sorting Strings. Those timestamps are already in a sortable format, so this would work:
products.sort((a,b) {
    return a.compareTo(b);
 });

Or more concise:
products.sort((a,b) => a.compareTo(b));

This is pretty basic. Like pskink mentioned in the comment, building on this you could convert the Strings to actual DateTime objects.
DateTime expiryAsDateTime = DateTime.parse(expiry);

DateTime also has a built in compareTo method, so the code snippet above would work with DateTimes as well as Strings.
If you want to reverse the order, just swap a and b.

A: If we get more specific then try like this one.
its worked perfectly for me

transactionList.sort((a, b) {
  int aDate = DateTime.parse(a.dateTime ?? '').microsecondsSinceEpoch;
  int bDate = DateTime.parse(b.dateTime ?? '').microsecondsSinceEpoch;
  return aDate.compareTo(bDate);
});

A: In my case, I needed to use DateTime.parse first before compareTo.
Source: https://www.fluttercampus.com/guide/169/how-to-sort-list-by-date-in-dart-flutter/


text:
Q: Finding nearest listed (array?) city from known location I'm looking to integrate the HTML5 geolocation functionality into a website.  The issue I have is getting the nearest city/town in a chosen list.  The site is only supported/marketed in a certain number of towns and cites so the idea is that the browser finds their location and chooses their nearest town or city.  Sounds simple enough but it's the 'finding the nearest' that I can get my head around.
I've found a thread that has helped me through the process of getting the long/lat from the browser and turning it into their Town/City name but this doesn't help finding the nearest listed one: Reverse Geocoding With Google Map API And PHP To Get Nearest Location Using Lat,Long coordinates
Are there any APIs (preferably in Google) that will find the nearest listed location?  I've had a look and can't find any of the sort.

A: You can find the nearest city using the Haversine formula. The following  functions are used to calculate the distance between the geolocated coordinates and the those of your array
function deg2rad(degrees){
radians = degrees * (Math.PI/180);
return radians;
}

function Haversine(lat1,lon1,lat2,lon2) {
  deltaLat = lat2 - lat1 ;
  deltaLon = lon2 - lon1 ;
  earthRadius = 3959; // in miles 6371 in meters.
  alpha    = deltaLat/2;
  beta     = deltaLon/2;
  a        = Math.sin(deg2rad(alpha)) * Math.sin(deg2rad(alpha)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(deg2rad(beta)) * Math.sin(deg2rad(beta)) ;
  c        = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  distance =  earthRadius * c;
  return distance.toFixed(2);
}

A: The simplest way is to compute the "as the crow flies" distance from the user's location to all your cities, using the haversine formula or the computeDistanceBetween method of the spherical geometry library, and pick the smallest one.
If you have less than 100 locations, you can use the Distance Matrix to determine the shortest driving distance, then pick the town with the shortest result.

A: I think the easiest solution is to store the lat lng coordinates of each town or city in a database and just do a radius based search around the users location and produce the closest result.
Have a look at the accepted answer given to this question.
Search database with lat and long by radius using php mysql


text:
Q: sp2-0667 message file sp2 lang .msb not found and sp2-0750 error is coming on windows While i am trying to connect with with database by the command
sqlplus /nolog
than the error message is coming
"sp2-0667 message file sp2 lang .msb not found and sp2-0750 error is coming on windows"
Earlier it was working fine i think some path issue is there so can any one tell me how to resolve the issue or how to set the path on windows machine

A: Setting the ORACLE_HOME environment variable incorrectly may cause these errors.
On Linux, you can set ORACLE_HOME as $ export ORACLE_HOME=path\to\oracle\home and on Windows you can set as C:\>set ORACLE_HOME=/path/to/oracle/home/.


text:
Q: typedef decltype function pointer not returning proper output (cout) I'm having a problem using decltype to create a typedef function pointer to "foo". printf works but with a warning: warning: format '%d' expects argument of type 'int', but argument 2 has type 'bar {aka int (*)(int)}' [-Wformat=] and cout displays "1". I'm sort of a newbie when it comes to function pointers so I don't really know what's going on. Can someone help me here?
#include <iostream>
int foo(int a) {
    return a;
}
int main() {
    typedef decltype(&foo) bar;
    printf("printf: %d\n", (*bar(70))); //work with a warning: format '%d' expects argument of type 'int', but argument 2 has type 'bar {aka int (*)(int)}' [-Wformat=]
    std::cout << "cout: " << (*bar(80));//displays "cout: 1" for some reason
    return 0;
}

A: You have to create variable of type bar and initialize it with foo address.
because () has higher precedence than *, you have to use parentheses (*var)(80) to dereference pointer to function, after that you can call it:
typedef decltype(&foo) bar;
bar b = &foo;
printf("printf: %d\n", ((*b)(70))); //work with a warning: format '%d' expects argument of type 'int', but argument 2 has type 'bar {aka int (*)(int)}' [-Wformat=]
std::cout << "cout: " << ((*b)(80));//displays "cout: 1" for some reason

or just:
b(80)

without explicit dereferencing.
Demo


text:
Q: Is there a way to open SublimeText 2 From Other Applications I loved the ability to open a file in textmate from other applications using the txmt://open/?url=file:// command.  I can't seem to find anything similar for SublimeText 2, does anybody know how I can do this?

A: subl-handler is an app that maps textmate's txmt url protocol to Sublime Text. I haven't tried it myself, but looks like it's what you're looking for.
Available here: https://github.com/hiddenbek/subl-handler
(Side note: for windows users, there's this: https://bitbucket.org/sublimator/sublimeprotocol/src/)

A: Which operating system are you using?
If you are on the Windows OS this is easy enough to do by registering the file extension with the Windows Shell and then using the ShellExecute WIN32 API.


text:
Q: Automatic layout when widget space is finite in Tkinter I am trying to achieve the following effect using a Tkinter python app:
The user can define a finite number of list elements, aka categories.
I then would like to present these categories next to each other, based on the following approach:
l=Label(self.body,text='Category: ')
l.pack(side=Left)
for i in range(0,len(self.categories)):
   l=Label(self.body,text=self.category[i])
   l.pack(side=LEFT)
self.body.pack(fill=BOTH)

Of course, this does not work. Is there an elegant way to "wrap" a whole label at the widget borders?
Thanks!

A: You have to know the size of the frame you are using to pack the labels into, and the width of the label.  You can set the width parameter for the label, but it uses a size that depends on the font used i.e. the same "width=" results in different label widths for different font sizes.  So it can not be done with the code you posted.  Link to label parameters http://effbot.org/tkinterbook/label.htm


text:
Q: jquery not work after async post back ocuur I use below code for toggling my main navigation :
    $(document).ready(function () {
    var body, click_event, content, nav, nav_toggler;
    nav_toggler = $("header .toggle-nav");
    nav = $("#main-nav");
    content = $("#content");
    body = $("body");
    click_event = (jQuery.support.touch ? "tap" : "click");
    $("#main-nav .dropdown-collapse").on(click_event, function (e) {
        var link, list;
        e.preventDefault();
        link = $(this);
        list = link.parent().find("> ul");
        if (list.is(":visible")) {
            if (body.hasClass("main-nav-closed") && link.parents("li").length === 1) {
                false;
            } else {
                link.removeClass("in");
                list.slideUp(300, function () {
                    return $(this).removeClass("in");
                });
            }
        } else {
            if (list.parents("ul.nav.nav-stacked").length === 1) {
                $(document).trigger("nav-open");
            }
            link.addClass("in");
            list.slideDown(300, function () {
                return $(this).addClass("in");
            });
        }
        return false;
    });

    if (jQuery.support.touch) {
        nav.on("swiperight", function (e) {
            return $(document).trigger("nav-open");
        });
        nav.on("swipeleft", function (e) {
            return $(document).trigger("nav-close");
        });
    }
    nav_toggler.on(click_event, function () {
        if (nav_open()) {
            $(document).trigger("nav-close");
        } else {
            $(document).trigger("nav-open");
        }
        return false;
    });

    $(document).bind("nav-close", function (event, params) {
        var nav_open;
        body.removeClass("main-nav-opened").addClass("main-nav-closed");
        return nav_open = false;
    });
    return $(document).bind("nav-open", function (event, params) {
        var nav_open;
        body.addClass("main-nav-opened").removeClass("main-nav-closed");
        return nav_open = true;
    });
});

this.nav_open = function () {
    return $("body").hasClass("main-nav-opened") || $("#main-nav").width() > 50;
};

but this code not worked after async post back occur in asp.net. please help me to know why this happen, and how I chnage this code to toggle menu after post back.
this is my menu before toggle :

and this is my menu after toggling :

and this is my asp.net codes:

<asp:UpdatePanel runat="server" ID="upExpander">
    <ContentTemplate>
        <asp:HiddenField ID="hfMenu" runat="server" Value="1" />

                        <%=Resources.Titles.ProjectList %>

                        <asp:HiddenField runat="server" ID="hfFolderID" />
                        <asp:ListView ID="lvProjects" runat="server" DataSourceID="odsProject" DataKeyNames="ID" OnItemDataBound="lvProjects_ItemDataBound">
                            <ItemTemplate>

                                    <asp:LinkButton ID="lbtnProject" runat="server" OnClick="lbtnProject_Click" data-expand="collapse">

                                        <%#System.Convert.ToString(Eval("Name").ToString().Length<30 ? Eval("Name") : Eval("Name").ToString().Substring(0,30) + "..." ) %>
                                    </asp:LinkButton>

                                        <asp:ListView ID="lvFolder" runat="server" DataKeyNames="ID" OnItemDataBound="lvFolder_ItemDataBound">
                                            <ItemTemplate>

                                                    <asp:LinkButton ID="lbtnFolder" runat="server" OnClick="lbtnFolder_Click">

                                                        <%#System.Convert.ToString(Eval("Name").ToString().Length<30 ? Eval("Name") : Eval("Name").ToString().Substring(0,30) + "..." ) %>
                                                    </asp:LinkButton>
                                                    <asp:LinkButton ID="lbtnAddDocument" runat="server" CssClass="addDocument" OnClientClick="ShowModalBox('modal_AddDocument');" OnClick="lbtnAddDocument_Click">
                                                        <i class="icon icomoon-icon-AddDocument hasTooltip" title="<%=Resources.Titles.AddDocument %>">
                                                    </asp:LinkButton>

                                            </ItemTemplate>
                                        </asp:ListView>

                                    <asp:LinkButton ID="lbtnAddFolder" runat="server" CssClass="addFolder" OnClientClick="ShowModalBox('AddFolderModal');" OnClick="lbtnAddFolder_Click">
                                <i class="icon icomoon-icon-AddFolder hasTooltip" title="<%=Resources.Titles.AddFolder %>">
                                    </asp:LinkButton>

                            </ItemTemplate>
                        </asp:ListView>
                        <asp:ObjectDataSource ID="odsProject" runat="server" TypeName="DMS.Data.ProjectProvider" SelectMethod="GetUserProjects" OnSelecting="odsProject_Selecting">
                            <SelectParameters>
                                <asp:Parameter Name="userID" Type="Int32" />
                            </SelectParameters>
                        </asp:ObjectDataSource>

                <%--

                        <%=Resources.Titles.MyFolders %>

                        <asp:HiddenField runat="server" ID="hfMyFolderID" />
                        <asp:ListView ID="lvMyFolders" runat="server" DataSourceID="odsMyFolders" DataKeyNames="ID" OnItemDataBound="">
                            <ItemTemplate>

                                    <asp:LinkButton ID="lbtnMyFolder" runat="server" OnClick="">

                                        <%#System.Convert.ToString(Eval("Name").ToString().Length<30 ? Eval("Name") : Eval("Name").ToString().Substring(0,30) + "..." ) %>
                                    </asp:LinkButton>

                                        <asp:Literal runat="server" ID="litSubfolders"/>

                                    <asp:LinkButton ID="lbtnAddFolder" runat="server" CssClass="addFolder" OnClientClick="ShowModalBox('AddFolderModal');" OnClick="lbtnAddFolder_Click">
                                <i class="icon icomoon-icon-AddFolder hasTooltip" title="<%=Resources.Titles.AddFolder %>">
                                    </asp:LinkButton>

                            </ItemTemplate>
                        </asp:ListView>
                        <asp:ObjectDataSource ID="odsMyFolders" runat="server" TypeName="DMS.Data.VirtualFolderProvider" SelectMethod="GetUserFolders" OnSelecting="">
                            <SelectParameters>
                                <asp:Parameter Name="userID" Type="Int32" />
                            </SelectParameters>
                        </asp:ObjectDataSource>

--%>

    </ContentTemplate>
</asp:UpdatePanel>

and this is generated html code :

        <input type="hidden" name="ctl00$ucExpander$hfMenu" id="ucExpander_hfMenu" value="ucExpander_lvProjects_lbtnProject_0">

                        لیست پروژه ها

                        <input type="hidden" name="ctl00$ucExpander$hfFolderID" id="ucExpander_hfFolderID">

                                        سامانه مدیریت اسناد

                                                        aa

                                                        bb

                                                        cc

                                                        dd

                                                        ee

                                        سامانه مدیریت و درج روزانه کار...

                                                        bbb

                                                        ff

                                        سامانه مدیریت هوشمند ماموریت

                                        سامانه مهر بندرعباس

please help me to solve this problem. thank you

A: You don't tell what the asynchronous postback does, but as there are not ASP.NET controls in the code that you show, I assume that it's all inside a control.
That means that the code is replaced by a new version of the same by the asynchronous call, so any events that you bound to the elements are gone as those elements doesn't exist any more.
You can use delegated events to bind the event outside the elements that are replaced by the asynchronous call. This will bind it to the body element, but you should use an element closer to the target elements if possible:
$("body").on(click_event, "#main-nav .dropdown-collapse", function (e) {

A: you can use this script


text:
Q: SQL - How can I exclude results without subselect? I stuck with sql query to list customer who bought product a but did not buy product b.
This is my table
Table customer
id_customer   customer_name
1             name1
2             name2
3             name3

Table order
id_order   id_customer  product
1          1            a
2          1            b
3          2            b
4          3            a

I try:
SELECT * FROM customer, order WHERE customer.id_customer = order.id_customer
AND (order.product='a' AND order.product<>'b')

SELECT * FROM customer, order WHERE customer.id_customer = order.id_customer
AND (order.product IN ('a') AND order.product NOT IN ('b'))
[AND (order.product = 'a' AND order.product <> 'b')]

SELECT table1.id_customer, table1.customer_name FROM customer INNER JOIN order ON customer.id_customer = order.id_customer
WHERE order.product IN ('a') AND order.product NOT IN ('b')
[WHERE order.product = 'a' AND order.product <> 'b']

but it did not the right answer because it return:
1          1            a
4          3            a

The answer should be:
4          3            a

Anyone help me please. Thank you so much

A: You can use joins to filter out whether customer has each of product a, b, and then query the join to implement your particular logic.  It would look something like this:
select distinct   -- pull only unique customer information
    C.*
from
    customer C
left join   -- orders of product a, which should exist
    order OA on OA.id_customer = C.id_customer and OA.product = 'a'
left join   -- orders of product b, which should not exist
    order OB on OB.id_customer = C.id_customer and OB.product = 'b'
where       -- orders of product a should exist
    OA.id_order is not null
and         -- orders of product b should not exist
    OB.id_order is null

A: I don;t think we have all the details so here is a query that uses subqueries (ignoring question title) and returns customers rather than orders (ignoring expected resultset):
SELECT *
  FROM customer AS c
 WHERE EXISTS (
               SELECT *
                 FROM order AS o
                WHERE o.id_customer = c.id_customer
                      AND product = 'a'
              )
       AND NOT EXISTS (
                       SELECT *
                         FROM order AS o
                        WHERE o.id_customer = c.id_customer
                              AND product = 'b'
                      );


text:
Q: a warning of type 'error' while in the json snippet below we see `"success": 1` On our wikibase server we see a cryptic message, a warning of type 'error' while in the json snippet below we see "success": 1
Warning: {"type":"error","message":"cirrussearch-backend-error","params":[]} [Called from Wikibase\Search\Elastic\EntitySearchElastic::getRankedSearchResults in /var/www/html/extensions/WikibaseCirrusSearch/src/EntitySearchElastic.php at line 318] in /var/www/html/includes/debug/MWDebug.php on line 333

{
    "searchinfo": {
        "search": "abc"
    },
    "search": [],
    "success": 1
}

http://api.kunstmuseum.nl/w/api.php?action=wbsearchentities&search=abc&language=en

A: The CirrusSearch README mentioned some steps that seem to have helped:
Now run this script to generate your elasticsearch index:
 php $MW_INSTALL_PATH/extensions/CirrusSearch/maintenance/UpdateSearchIndexConfig.php
Now remove $wgDisableSearchUpdate = true from LocalSettings.php.  Updates should start heading to Elasticsearch.
Next bootstrap the search index by running:
 php $MW_INSTALL_PATH/extensions/CirrusSearch/maintenance/ForceSearchIndex.php --skipLinks --indexOnSkip
 php $MW_INSTALL_PATH/extensions/CirrusSearch/maintenance/ForceSearchIndex.php --skipParse
Note that this can take some time.  For large wikis read "Bootstrapping large wikis" below.


text:
Q: getting my rails app to accept large files I'm developing a rails app where users will be able to upload files.
Currently I have my files on an online IDE called nitrous.io. When I upload a file above 17MB in size (or a combination of files like that). I get an error that says:
413 Request Entity Too Large
openresty/1.7.10.1

I did some reading and found out that this is a result of the
client_max_body_size needing to be set in nginx.conf to an appropriate size. I went on and found that nginx is part of openresty and so the nginx.conf file was located in /etc/nginx/, added the line
client_max_body_size = 50M;

To the file and now it looks as follows:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
        worker_connections 768;
        # multi_accept on;
}
http {
        ##
        # Basic Settings
        ##
        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        # server_tokens off;
        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;
# set client body size to 50MB #
client_max_body_size 50M;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;
        ##
        # SSL Settings
        ##
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;
        ##
        # Logging Settings
        ##
        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;
        ##
        # Gzip Settings
        ##
        gzip on;
        gzip_disable "msie6";
        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##
        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#       }
#
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}

I then reloaded the nginx webserver by typing:
sudo /etc/init.d/nginx reload

and got an [OK] status on that.
However, I still can't upload large files through my rails app. I know in PHP apps you need to change the PHP.ini file to allow large uploads in addition to webserver configurations, is there an equivalent in Rails?
EDIT: Put in the entire nginx.conf contents
EDIT#2: This just occurred to me; Since I can upload files between 1MB-17MB in size, does that mean that my client_max_body_size attribute is overridden somehow? according to the documentation, nginx's default max body size is 1MB


text:
Q: Python logging working on Windows but not Mac OS # Logging
cur_flname = os.path.splitext(os.path.basename(__file__))[0]
LOG_FILENAME = constants.log_dir + os.sep + 'Log_' + cur_flname + '.txt'
util.make_dir_if_missing(constants.log_dir)
logging.basicConfig(filename=LOG_FILENAME, level=logging.INFO, filemode='w',
                    format='%(asctime)s %(levelname)s %(module)s - %(funcName)s: %(message)s',
                    datefmt="%m-%d %H:%M")  # Logging levels are DEBUG, INFO, WARNING, ERROR, and CRITICAL
# Output to screen
logger = logging.getLogger(cur_flname)
logger.addHandler(logging.StreamHandler())

I use the code above to create a logger that I can use in my module to print messages to screen as well simultaneously to a text file.
On Windows, the messages get output to both file and screen. However, on Mac OS X 10.9.5, they only get output to file. I am using Python 2.7.
Any ideas on how to fix this?

A: From your question it is clear, you have no problem with creating logger name,
log file name and with logging to a file, so I will keep this part simplified to keep my code succinct.
First thing: To me your solution seems correct as logging.StreamHandler shall
send output to sys.stderr by default. You might have some code around (not
shown in your question), which is modifying sys.stderr, or you are running
your code on OSX in such a way, that output to stderr is not shown (but is
really output).
Solution with logging
Put following code into with_logging.py:
import logging
import sys

logformat = "%(asctime)s %(levelname)s %(module)s - %(funcName)s: %(message)s"
datefmt = "%m-%d %H:%M"

logging.basicConfig(filename="app.log", level=logging.INFO, filemode="w",
                    format=logformat, datefmt=datefmt)

stream_handler = logging.StreamHandler(sys.stderr)
stream_handler.setFormatter(logging.Formatter(fmt=logformat, datefmt=datefmt))

logger = logging.getLogger("app")
logger.addHandler(stream_handler)

logger.info("information")
logger.warning("warning")

def fun():
    logger.info(" fun inf")
    logger.warning("fun warn")

if __name__ == "__main__":
    fun()

Run it: $ python with_logging.py and you shall see expected log records (properly formatted)
in log file app.log and on stderr too.
Note, if you do not see it on stderr, something is hiding your stderr
output. To see something, change in StreamHandler the stream to sys.stdout.
Solution with logbook
logbook is python package providing alternative logging means. I am showing it here to show main
difference to stdlib logging: with logbook the use and configuration seems simpler to me.
Previous solution rewritten to with_logbook.py
import logbook
import sys

logformat = ("{record.time:%m-%d %H:%M} {record.level_name} {record.module} - "
             "{record.func_name}: {record.message}")
kwargs = {"level": logbook.INFO, "format_string": logformat, "bubble": True}

logbook.StreamHandler(sys.stderr, **kwargs).push_application()
logbook.FileHandler("app.log", **kwargs).push_application()

logger = logbook.Logger("app")

logger.info("information")
logger.warning("warning")

def fun():
    logger.info(" fun inf")
    logger.warning("fun warn")

if __name__ == "__main__":
    fun()

The main difference is, that you do not have to attach handlers to loggers, your loggers simply emit
some log records.
These records will be handled by handlers, if they are put in place. One method
is to create a handler and call push_application() on it. This will put the
handler into stack of handlers in use.
As before, we need two handlers, one for the file, another for stderr.
If you run this script $ python with_logbook.py, you shall see exactly the same results as
with logging.
Separate logging setup from module code: short_logbook.py
With stdlib logging I reall do not like the introductory dances to make the logger work. I want
simply emit some log records and want to do that as simply as possible.
Following example is modification of previous one. Instead of setting up
logging on very beginning of the module, I do it just before the code is run
- inside the if __name__ == "__main__" (you may do the same on any other
place).
For practical reasons, I separated the module and calling code to two files:
File funmodule.py
from logbook import Logger

log = Logger(__name__)

log.info("information")
log.warning("warning")

def fun():
    log.info(" fun inf")
    log.warning("fun warn")

You can notice, that there are really only two lines of code related to making
logging available.
Then, create the calling code, put into short_logbook.py:
import sys
import logbook

if __name__ == "__main__":
    logformat = ("{record.time:%m-%d %H:%M} {record.level_name} {record.module}"
                 "- {record.func_name}: {record.message}")
    kwargs = {"level": logbook.INFO, "format_string": logformat, "bubble": True}

    logbook.StreamHandler(sys.stderr, **kwargs).push_application()
    logbook.FileHandler("app.log", **kwargs).push_application()

    from funmodule import fun
    fun()

Running the code you will see it working the same way as before, only logger name will be funmodule.
Note, that I did the from funmodule import fun after the logging was set up. If I did it on the
top if the short_logbook.py file, the first two log records from funmodule.py would not be seen
as they happen during module import.
EDIT: added another logging solution to have fair comparison
One more stdlib logging solution
Trying to have fair comparison of logbook and logging I rewrote final logbook example to
logging.
funmodule_logging.py looks like:
import logging

log = logging.getLogger(__name__)

log.info("information")
log.warning("warning")

def fun():
    log.info(" fun inf")
    log.warning("fun warn")
    log.error("no fun at all")

and short_logging.py looks as follows:
import sys
import logging

if __name__ == "__main__":
    logformat = "%(asctime)s %(levelname)s %(module)s - %(funcName)s: %(message)s"
    datefmt = "%m-%d %H:%M"

    logging.basicConfig(filename="app.log", level=logging.INFO, filemode="w",
                        format=logformat, datefmt=datefmt)

    stream_handler = logging.StreamHandler(sys.stderr)
    stream_handler.setFormatter(logging.Formatter(fmt=logformat, datefmt=datefmt))

    logger = logging.getLogger("funmodule_logging")
    logger.addHandler(stream_handler)

    from funmodule_logging import fun
    fun()

Functionality is very similar.
I still strugle with logging. stdlib logging is not easy to grasp, but it is in stdlib and offers
some nice things like logging.config.dictConfig allowing to configure logging by a dictionary.
logbook was much simpler to start with, but is a bit slower at the moment and lacks the
dictConfig. Anyway, these differences are not relevant to your question.


text:
Q: Unsure of how to get the right evaluation order I'm not sure what the difference between these two pieces of code is (with respect to x), but the first one completes:
$ foldr (\x y -> if x == 4 then x else x + y) 0 [1,2 .. ]
10

and the second one doesn't (at least in GHCi):
$ foldr (\x (y, n) -> if x == 4 then (x, n) else (x + y, n + 1)) (0, 0) [1,2 .. ]
.......

What am I doing wrong that prevents the second example from completing when it hits x == 4, as in the first one?
I've tried adding bang-patterns to both the x and to the x == 4 (inside a let) but neither seems to make a difference.

A: Your second example has two related problems.
Recall that foldr produces a right-associative nesting, i.e., foldr f z [a, b, c] = f a (f b (f c z)). Thus, the second argument to the function you give foldr represents the final value of folding the entire remaining list. In the case of an infinite list, this is only possible if you either generate another lazy infinite data structure or, at some point, ignore the second parameter entirely, as your first example does.
Your second example always uses the second item in the input tuple to compute the second item of the result tuple, so when applied to an infinite list you end up with an infinite regress. Specifying 0 as the "starting" value doesn't help, because in foldr the starting value is placed at the end of the list, which an infinite list clearly doesn't have--it seems you want to pass the value along unchanged, but that requires having a value to begin (or perhaps "end") with!
That much only causes the second item in the result to be non-terminating. The first item of the result is well-defined, or at least could be. The problem here is that pattern matching forces evaluation, which prevents any result from being produced until the entire fold is finished. This can be avoided in several ways, but simply using fst and snd is easy enough: \x yn -> if x == 4 then (x, snd yn) else (x + fst yn, snd yn + 1) should give you a result consisting of a tuple whose first item is what you expect (but whose second item is undefined, as explained above).

A: The first one doesn't use the value from the "accumulator" (i.e. y), whereas the second one does, by using n.  Computing n requires folding the entire list, which is why it never terminates.  No amount of strictness will fix that.
In fact, your algorithm does not do what you think it does.  You are probably confusing foldr's behavior with foldl.  Even if you could somehow compute n, its value would be infinite.  The best way to think about foldr is that it replaces every (:) in the list with the first function and replaces the terminal [] with the second value.

A: It's the way the pattern matching/evaluation happens. If you let f = \x (y, n) -> ... as you've defined it, then
foldr f (0, 0) [1,2 .. ] =
   f 1 (foldr f (0,0) [2..]) =
   (\x (y, n) -> ...) 1 (foldr f (0,0) [2..])

and that (y,n) pattern is matched strictly, so to compute anything at all, the second argument (foldr .. [2..]) needs to be computed, which then requires foldr .. [3..] and so on forever.
One can make the pattern match non-strict, using ~ (called a "irrefutable pattern"), which changes the behaviour somewhat.
> foldr (\x ~(y,n) -> if x == 4 then (x,n) else (x+y,n+1)) (0,0) [1..]
(10,

(where as the refutable version can't compute even the first element of the tuple.)


text:
Q: Docker disconnect all containers from docker network I have docker network "my_network". I  want to remove this docker network with docker network rm my_network. Before it I should disconnect all my containers from this network. I can use docker network inspect and get output like
[
    {
        "Name": "my_network",
        "Id": "aaaaaa",
        "Scope": "some_value",
        "Driver": "another_value",
        "EnableIPv6": bool_value,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "10.0.0.0/1"
                }
            ]
        },
        "Internal": false,
        "Containers": {
            "bbb": {
                "Name": "my_container_1",
                "EndpointID": "ENDPOITID1",
                "MacAddress": "MacAddress1",
                "IPv4Address": "0.0.0.0/1",
                "IPv6Address": ""
            },
            "ccc": {
                "Name": "my_container_2",
                "EndpointID": "ENDPOINTID2",
                "MacAddress": "MacAddress2",
                "IPv4Address": "0.0.0.0/2",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]

It is okay to manual disconnect if  I have only several containers but if I have 50 containers I have problem.
How can I disconnect all containers from this network with single or several command?

A: docker network inspect has a format option.
That means you can list all Container names with:
docker network inspect -f '{{range .Containers}}{{.Name}}{{end}}' network_name

That should then be easy, by script, to read each name and call docker network disconnect.
wwerner proposes below in the comments the following command:
for i in ` docker network inspect -f '{{range .Containers}}{{.Name}} {{end}}' network_name`; do docker network disconnect -f network_name $i; done;

In multiple line for readability:
for i in ` docker network inspect -f '{{range .Containers}}{{.Name}} {{end}}' network_name`;\
  do \
     docker network disconnect -f network_name $i; \
  done;

Adding:

Note that there is a space in the format as opposed to the answer to split the names by a space.


text:
Q: How to fix this possibility of denial of service issue? Following security vulnerability has been reported on our application -

The call to readLine() at xyz.java line 119 might allow an attacker to
  crash the program or otherwise make it unavailable to legitimate
  users.

Code with vulnerability
Commented line reported -
BufferedReader reader = new BufferedReader(new InputStreamReader(
                        httpConnection.getInputStream()));
                String inputLine;
                StringBuffer okResponse = new StringBuffer();
                while ((inputLine = reader.readLine()) != null) { //readLine() on this line has been reported
                    okResponse.append(inputLine);
                }
                reader.close();
                return okResponse.toString();

The remediation for the same says -

Validate user input to ensure that it will not cause inappropriate
  resource utilization.

But, it is not clear what exactly can be validated. Any pointers?

A: In theory an attacker could send you an unlimited amount of data via the httpConnection. Since you try to consume all of it, it might crash your application (OutOfMemory).
I´d assume you have a certain format and length for the okResponse in mind,
so you would be better off checking that.

Make sure you read to read the answer from Subhas linked by Luis Muñoz (Most Robust way of reading a file or stream using Java (to prevent DoS attacks)),
that has some more implementation details for reading content from a stream.

Another issue might be that the attack just keeps the connection open without sending any data. I`d assume there should be a timeout in place to cut the connection at some point, else the thread might be blocked forever.
Edit:
Since you code does not have it explicitly, you also should add a try ... finally ... block to make sure that the resources are properly closed.


text: Q: Powerpoint forward and backward action buttons in javascript Can anyone point me in the right direction or give me a clue on how to manipulate and control Powerpoint presentations which are embedded via an  iFrame link in your webpage using JavaScript ? Are there libraries available for this purpose as well, because I have been searching and couldn't find any. All I want for now is to get the back and forward functionalities and apply them on my own buttons to move back and forth. I would appreciate any help that comes for it.


text:
Q: Search DialogViewController elements by clicking a button I have a DialogViewController with EnableSearch = true.
This works fine and filters the elements as soon I type something in the search box. What I would like to do was override this behavior and filter the elements only when the user pressed a button or StringElement.
I've looked at the StartSearch, FinishSearch and PerformFilter methods but don't see how they can be used to prevent the filtering as the user is typing.
Can this be done?
Thanks.


text:
Q: Adding a google map image on page without touching the  section I´m trying to put a google maps image into my HTML page. I cannot touch the  section as the page is dynamically loaded using PHP code (this logic is not explained here).
So, I´ve build the following HTML test code, that doesn´t work - the maps does not appear on screen.
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta charset="UTF-8" />
        <title>TEST PAGE</title>

Maps test page.

";

The alerts are coming up, but no map is shown...
Help is appreciated to make is work.

A: The problem is that initialize() is getting executed before the Google Maps Javascript has been added to the page. You aren't importing the Google Maps JS until the DOM has finished loading, in your window.onload callback. Try this instead:

A: Asynchronously load the Google Maps Javascript API, use the callback parameter to run your initialize function.
working example

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta charset="UTF-8" />
        <title>TEST PAGE</title>

Maps test page.

";


text:
Q: Incomplete response JSON for looks from Looker API? I'm using https://developers.looker.com/api/explorer/4.0/methods/Query/query
Not entirely sure how some looks get a complete/incomplete response from the API, does anyone have experience working with looker API? want to understand what possible reasons could have led to this behaviour
incomplete response for look_id_1 : {"id":"1"}
complete response for look_id_2 : {"id":"2","view":"x","fields":["a"]}

Note - https://developers.looker.com/api/explorer/4.0/methods/Look/search_looks for the above looks retrieves complete information. I need the query response for the looks.


text:
Q: Accessing TimelineJS data structure I have a data structure that I transform into a format that TimelineJS can use. My data structure has the same number of slides as in the timeline, but it has more info than displayed in the timeline. Also, info in my data structure is not in the same order as how TimelineJS presents it as TimelineJS sorts the data by time before rendering the timeline.
For any given slide visible in the timeline, I want to access data from my original data structure. So, given http://example.com/timeline#22, I want to get some data out from my data structure which resulted in slide 22 in the timeline. Since the timeline has sorted my data structure, I don't know which element in my data array is what is showing up as #22 in the timeline. I have wracked my brains but can't figure out a solution.
One way would be to figure out where TimelineJS generates the final data structure that is rendered on the screen and make a copy of it so I can access it. Seems like the data are stored in VMM.Timeline.DataObj.data_template_obj.timeline but I can't figure out where to access it. Any guidance would be welcome.


text:
Q: MISRA rule 18.3 preventing copying data to RAM MISRA has a problem with the following code:
extern uint32_t __etext;
extern uint32_t __data_start__, __data_end__;
uint32_t* src = (uint32_t*)&__etext;        // ROM location of code to be copied into ram
uint32_t* dst = (uint32_t*)&__data_start__; // Start of RAM data section

while (dst  < &__data_end__) // Loop until we reach the end of the data section
{
    *dst++ = *src++;
}

I am getting a violation for rule 18.3:
The relational operators >, >=, < and <= shall not be applied to objects of pointer type except when they point to the same object."
The rationale behind the rule is that attempting to make comparisons between pointers will produce undefined behavior if the two pointers do not point to the same object.
Why is this incorrect code? This seems like pretty generic boot code which is doing the right thing.

A: MISRA C:2012 required Rule 18.3 is undecidable because it is often impossible to determine, statically, whether two pointers are pointing to the same object.
In the example cited, as long as you can demonstrate that the two pointers are, indeed, pointing to the same object (or block of memory) and that __data_end__ is higher up the memory map than __data_start__ then this is an easy documentation task.
s3.4 of MISRA Compliance applies - this appears to fall within Category (2).  This is not the same as a formal deviation, but does still need appropiate review/signoff.
Whatever you do, do not change the code to try and create some clever mechanism that you claim is MISRA compliant!

A:
Why is this incorrect code? This seems like pretty generic boot code which is doing the right thing.

Because the code invokes undefined behavior, as specified by the C standard (additive operators 6.5.6/8), MISRA or no MISRA. For this reason, the compiler might generate incorrect code.
Possible work-arounds:

*

*Create a big array or struct object covering the whole area to copy from and the area to copy into.

*Use a compiler with a known and documented non-standard extension which allows you address absolute addresses regardless of what happens to be stored there. Then document it yourself in turn, in your MISRA documentation. (Most embedded compilers should support this. gcc might, but I don't know how without looking it up.)

*Use integers instead of pointers and deviate from the MISRA rule regarding casting between integers and pointers. Which is an impossible rule to follow in embedded systems anyway.

Other problems:

*

*(Severe) You have missing volatile bugs all over the code, which could result in incorrect code generation.

*(Severe) You aren't using const correctness for variables stored in ROM which is surely a bug.

*(Severe) Using extern in a safety/mission-critical application is highly questionable practice.

*(Minor) Identifiers starting with double underscore are reserved by the compiler. If this code is from your home-made CRT it might be ok, but not if this code is from some generic bootloader.

*(Minor) *dst++ = *src++; violates MISRA C 13.3. You need to do *dst = *src; dst++; src++;.

A: With linker defined symbols like this, the only way to satisfy this rule (without breaking 18.2 instead) is to cast the pointers to integers before comparing them.  I don't think this change would help readability, so I would suggest making an exemption (called a "deviation record" in MISRA) and disabling the rule for this line of code.


text:
Q: jquery function not registering changes I have a jquery script in my django project that reads checkboxes and then submits them to a function when clicked. My problem is that this only works when I reload my page. is it possible to have the jquery script "listening" allt the time to the checkboxes?
$(document).ready(function() {
  var vals = [];
  $.each($("input[name='checkb']:checked"), function() {
    vals.push($(this).attr('id'));
  });
  console.log('calling function:', vals)

  $('.print').click(function() {
    console.log('print:', vals)
    $.get('eprint/ticked/', {
      marked: vals
    })
  })

  $('.delete').click(function() {
    console.log('delete:', vals)
    $.get('edelete/ticked/', {
      marked: vals
    })
  });
});

{% for l in object_list %}

      <form>
        <input type="checkbox" id={{l.pk}} name="checkb">
        <form>

A: One way to achieve what you require would be to add a change event handler to the checkboxes so that you can update the vals variable whenever the user checks or unchecks a box.
However, I'd suggest instead that you simply create a function which reads the values at the point they are required in the .print and .delete click handlers. This avoids any unnecessary global variables, and avoids the need to maintain an array as you're reading the DOM exactly at the point the action occurs. Try this:
let getValues = () => $("input[name='checkb']:checked").map((i, el) => el.value.trim()).get();

$(document).ready(function() {
  $('.print').on('click', () => {
    $.get('eprint/ticked/', {
      marked: getValues()
    });
  });

  $('.delete').on('click', () => {
    $.get('edelete/ticked/', {
      marked: getValues()
    });
  });
});


text:
Q: Corda gradle install fail on Windows: "Could not resolve net.i2p.crypto:eddsa:0.2.0" When setting up https://github.com/roger3cev/corda-training-template on Windows I get the following stack trace. It appears to be an issue a file name ending in .crypto
What went wrong:
Could not resolve all files for configuration ':java-source:compileClasspath'.
Could not resolve net.i2p.crypto:eddsa:0.2.0.
Required by:
project :java-source > net.corda:corda-core:1.0.0
Could not resolve net.i2p.crypto:eddsa:0.2.0.
Could not get resource 'https://jcenter.bintray.com/net/i2p/crypto/eddsa/0.2.0/eddsa-0.2.0.pom'.
Failed to move file 'C:\Users\A57C\AppData\Local\Temp\gradle_download2832834655657514563bin' into filestore at 'C:\Users\A57C\.gradle\caches\modules-2\files-2.1\net.i2p.crypto\eddsa\0.2.0\d2905a940ee7c59e1636e1c3541069ccbbcdf227\eddsa-0.2.0.pom'
Failed to create parent directory 'C:\Users\A57C\.gradle\caches\modules-2\files-2.1\net.i2p.crypto' when creating directory 'C:\Users\A57C\.gradle\caches\modules-2\files-2.1\net.i2p.crypto\eddsa\0.2.0\d2905a940ee7c59e1636e1c3541069ccbbcdf227'
Could not resolve net.i2p.crypto:eddsa:0.2.0.

How can I successfully import this dependency?

A: A direct download of eddsa 0.2.0 from MVNRepository resolved the issue: https://mvnrepository.com/artifact/net.i2p.crypto/eddsa/0.2.0
mvn install:install-file "-Dfile=eddsa-0.2.0.jar" "-DgroupId=net.i2p.crypto" "-DartifactId=eddsa" "-Dversion=0.2.0" "-Dpackaging=jar"

AddcordaCompile "net.i2p.crypto:eddsa:0.2.0" to the build.gradle in kotlin-source and java-source to import the artifact.


text:
Q: Selenium IDE javascript strip last character I am wanting to strip the last letter of a variable in selenium IDE and store in a variable.
I've tried
${projectName}.slice(0, -4)
${projectName}.slice(0, -1)

Looking to get ksGHMOP from ksGHMOPW

A: Close!
Give this bit a go:
var projectNameLess = ${projectName}.substr(0, ${projectName}.length-1);

A: Here is an example that takes variable x and slices off the last element and stores it in variable a.

    store
    ksGHMOPW
    x

    echo
    ${x}

    storeEval
    storedVars['x'].slice(0,-1);
    a

    echo
    ${a}

You need to do the slicing in javascript, so you need to use storedVars to access the selenium variables in javascript.
Let me know if you need further explanation.


text:
Q: Numpy, creating 1D array in C++ segfaults I am trying to create a 1D array for numpy in c++:
PyObject* foo()
{
   npy_intp length[1];
   length[0] = 10;
   PyObject* my_array = PyArray_SimpleNew(1, length, NPY_DOUBLE);
   return boost::python::incref(my_array);
}

Then I make a python module:
BOOST_PYTHON_MODULE(pyMod)
{
    using namespace boost::python;

    import_array();

    def("foo", foo);
}

When I run this in python, calling foo(), it segfaults when executing the call to PyArray_SimpleNew, even though I have called import_array, which seems to be the common cause to this segfaulting. If I make a 2D array of dimensions [10, 1], it works well, i.e:
PyObject* foo()
{
   npy_intp length[2] = {10, 1};
   PyObject* my_array = PyArray_SimpleNew(2, length, NPY_DOUBLE);
   return boost::python::incref(my_array);
}

In python it is used like this
import numpy as np
import pyMod

if __name__ == "__main__":
    v = pyMod.foo()

Any ideas of why this segfaults?

A: I'm not sure how you exposed the PyObject* to Python, but I think the right way is to expose it by means of boost::python::object.
Another point is that you are calling boost::python::object using a PyObject. Altough it's possible, it's not recommended (see the guidelines written by David Abrahams). So boost::python::handle should be used to address this situation.
boost::python::object foo()
{
   npy_intp dims[1] = {10};
   PyObject* p_array = PyArray_SimpleNew(boost::size(dims), dims, NPY_FLOAT);
   boost::python::handle<> handle(boost::python::borrowed(p_array));
   return boost::python::object(handle);
}


text:
Q: Graphing Quadratic Functions I need help with $f(x)=(x-3)^2$. My teacher said the $x$ intercept is $3$. I don't understand how it   can be positive $3$ when it is negative $3$ in the parenthesis.

A: The $x$-intercepts are the points where $f(x)=0$, i.e., where the graph touches the $x$-axis. You have $f(3)=(3-3)^2=0$, so you have an $x$-intercept at $x=3$.

A: Lets graph it and see what happens.

Do you see why $f(x) = 0$ at $x=3$ now?

A: $x$-interscepts are when the function intersects the $x$ axis, i.e. when $f(x)=0$.  Thus
$$0=(x-3)^2 \implies 0=x-3\implies {x=3}$$

A: The x-intercept is the value that you can plug in for x and have f(x) come out to 0. Try evaluating f(3), and see what happens.
Since f(3)=0, that means the point (3,0) is on the graph, so it is an x-intercept.
Seeing the minus sign inside the parentheses can be confusing, because it makes you think of a negative number, but remember to ask, "what value of x would make this equal 0?"

A: The $x$ intercepts are the abscissa of intersection points of the curve with the $x$ axis. When the curve intersects the $x$ axis, the ordinate is always equal to 0.

The code to generate the graph can be found here.
Therefore, we have the following equation:
$$
(x-3)^2=0
$$
We have a theorem as follows.

The solution of  $$ A \times B =0 $$
is $A=0$ with any $B$ OR any $A$ with $B=0$.

Thus, the solution of $(x-3)^2=(x-3)(x-3)=$ is $x-3=0$ or $x=3$.


text:
Q: Add header to message with Graph API I'm currently using Graph API to download messages and then move them to a different mail folder. This all works perfectly. As part of this process though we need to add a custom header to the email and then we can track it easier to see where it ends up. We used to do all of this using Mime/MailKit, however, this does not yet support the Graph API and so non-interactive OAuth2.0.
I tried adding headers to the message, uploading that to the new mail folder and then deleting the original message. However, it looks like doing it this way means we lose information (attachments, other body types, headers, etc.).
var messageHeaders = new System.Collections.Generic.List<InternetMessageHeader>();
if (message.InternetMessageHeaders != null)
{
    messageHeaders.AddRange(message.InternetMessageHeaders);
}

InternetMessageHeader header = messageHeaders.FirstOrDefault(h => h.Name.Equals(HEADER_ID));
if (header != null)
{
    header.Value = headerValue;
}
else
{
    messageHeaders.Add(new InternetMessageHeader()
    {
        Name = HEADER_ID,
        Value = headerValue
    });
}

message.InternetMessageHeaders = messageHeaders;

Message uploadedMessage = await UploadMessageAsync(graphServiceClient, user, destinationMailFolder, message);

await DeleteMessageAsync(graphServiceClient, user, message);

static async Task<Message> UploadMessageAsync(GraphServiceClient graphServiceClient, User user, MailFolder mailFolder, Message message)
    => await graphServiceClient.Users[user.Id].MailFolders[mailFolder.Id].Messages.Request().AddAsync(message);

static async Task DeleteMessageAsync(GraphServiceClient graphServiceClient, User user, Message message)
{
    await graphServiceClient.Users[user.Id].Messages[message.Id].Request().DeleteAsync();
}

I then wanted to try doing it a different way where I would download the MIME content of the message, add the header and then re-upload the message. I was able to easily do the first part of this. However, I can't work out a way to upload a message from file/stream using the Graph API.
Lastly, I thought updating the message might be the way to go here but according to the documentation it doesn't look like you can alter/add headers this way.
How can I do this?

A: I believe the MIME support is read-only currently.  To move emails, I suggest using the move action:
GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var destinationId = "deleteditems";

await graphClient.Me.Messages["{message-id}"]
    .Move(destinationId)
    .Request()
    .PostAsync();

https://learn.microsoft.com/en-us/graph/api/message-move?view=graph-rest-1.0&tabs=http
Unfortunately, the internetMessageHeader property is currently readOnly.  I would recommend filing a request aka.ms/graphrequest to add support for writing these headers.


text:
Q: Why my shuffle partition is not 200(default) during group by operation? (Spark 2.4.5) I am new to spark and trying to understand the internals of it. So,
I am reading a small 50MB parquet file from s3 and performing a group by and then saving back to s3.
When I observe the Spark UI, I can see 3 stages created for this,
stage 0 : load (1 tasks)
stage 1 : shufflequerystage for grouping (12 tasks)
stage 2:  save (coalescedshufflereader) (26 tasks)
Code Sample:
df = spark.read.format("parquet").load(src_loc)
df_agg = df.groupby(grp_attribute)\
 .agg(F.sum("no_of_launches").alias("no_of_launchesGroup")
df_agg.write.mode("overwrite").parquet(target_loc)

I am using EMR instance with 1 master, 3 core nodes(each with 4vcores). So, default parallelism is 12. I am not changing any config in runtime. But I am not able to understand why 26 tasks are created in the final stage? As I understand by default the shuffle partition should be 200. Screenshot of the UI attached.

A: I tried a similar logic on Databricks with Spark 2.4.5.
I observe that with spark.conf.set('spark.sql.adaptive.enabled', 'true'), the final number of my partitions is 2.
I observe that with spark.conf.set('spark.sql.adaptive.enabled', 'false') and spark.conf.set('spark.sql.shuffle.partitions', 75), the final number of my partitions is 75.
Using print(df_agg.rdd.getNumPartitions()) reveals this.
So, the job output on Spark UI does not reflect this. May be a repartition occurs at the end. Interesting, but not really an issue.

A: In Spark sql, number of shuffle partitions are set using spark.sql.shuffle.partitions which defaults to 200. In most of the cases, this number is too high for smaller data and too small for bigger data. Selecting right value becomes always tricky for the developer.
So we need an ability to coalesce the shuffle partitions by looking at the mapper output. If the mapping generates small number of partitions, we want to reduce the overall shuffle partitions so it will improve the performance.
In the lastet version , Spark3.0 with Adaptive Query Execution , this feature of reducing the tasks  is automated.
http://blog.madhukaraphatak.com/spark-aqe-part-2/
Considering this in Spark2.4.5 also catalist opimiser or EMR might have enabled this feature to reduce the tasks insternally rather 200 tasks.