text:
Q: Stack Exchange API returns an empty array for tags on methods that return a list of answers I was trying this filter to get the answers of a Stack Overflow user.
But the tags array "tags": [], is always empty when questions have at least one mandatory tag (for example, see this documentation demo).
How can I get the tags along with the answer?
{
  "items": [
    {
      "tags": [],
      "owner": {
        "account_id": 10812562,
        "reputation": 171,
        "user_id": 7952738,
        "user_type": "registered",
        "profile_image": "https://i.stack.imgur.com/lVbQp.png?s=128&g=1",
        "display_name": "DevDengChao",
        "link": "https://stackoverflow.com/users/7952738/devdengchao"
      },
      "down_vote_count": 1,
      "up_vote_count": 0,
      "is_accepted": false,
      "score": -1,
      "last_activity_date": 1632710580,
      "last_edit_date": 1632710580,
      "creation_date": 1632710104,
      "answer_id": 69340594,
      "question_id": 69340570,
      "content_license": "CC BY-SA 4.0",
      "link": "https://stackoverflow.com/questions/69340570/calculate-the-sum-in-array-with-condition/69340594#69340594",
      "title": "Calculate the sum in array with condition",
      "body": "
Maybe you are looking for a reduce or groupBy function.
\n
Btw, it's clear and it works, man, why troubleing yourself and making it a little bit harder to maintain.
\n"
    },
    {
      "tags": [],
      "owner": {
        "account_id": 18052725,
        "reputation": 11,
        "user_id": 13122002,
        "user_type": "registered",
        "profile_image": "https://lh3.googleusercontent.com/a-/AOh14Gg8PdwxNmPOSKuMqrpKi4vseiljtsjMRQLnXS5I=k-s128",
        "display_name": "Let's L.C.E",
        "link": "https://stackoverflow.com/users/13122002/lets-l-c-e"
      },
      "down_vote_count": 0,
      "up_vote_count": 0,
      "is_accepted": false,
      "score": 0,
      "last_activity_date": 1632710574,
      "last_edit_date": 1632710574,
      "creation_date": 1612824636,
      "answer_id": 66110503,
      "question_id": 53218570,
      "content_license": "CC BY-SA 4.0",
      "link": "https://stackoverflow.com/questions/53218570/how-to-convert-number-1-to-a-boolean-in-python/66110503#66110503",
      "title": "How to convert number 1 to a Boolean in python",
      "body": "
To convert 1 to boolean type:
\n
print(bool(1))\n
\n
Which returns True.
\n"
    },
    {
      "tags": [],
      "owner": {
        "account_id": 448551,
        "reputation": 1574,
        "user_id": 842808,
        "user_type": "registered",
        "accept_rate": 79,
        "profile_image": "https://www.gravatar.com/avatar/86bc1885f9caab6706e51fab0601e307?s=128&d=identicon&r=PG",
        "display_name": "Abhinav",
        "link": "https://stackoverflow.com/users/842808/abhinav"
      },
      "down_vote_count": 0,
      "up_vote_count": 0,
      "is_accepted": false,
      "score": 0,
      "last_activity_date": 1632710562,
      "creation_date": 1632710562,
      "answer_id": 69340637,
      "question_id": 2459851,
      "content_license": "CC BY-SA 4.0",
      "link": "https://stackoverflow.com/questions/2459851/octave-matlab-extend-a-vector-making-it-repeat-itself/69340637#69340637",
      "title": "Octave / Matlab: Extend a vector making it repeat itself?",
      "body": "
Although late, I am posting this because this turned out to be the most popular answer to a similar question here.
\n
This is a Faster Method Than repmat or reshape by an Order of Magnitude
\n
One of the best methods for doing such things is Using Tony's Trick. I came across this trick in one of the Electrical Engineering course lectures notes of Columbia University. Repmat and Reshape are usually found to be slower than Tony's trick as it directly uses Matlabs inherent indexing. To answer you question,
\n
Lets say, you want to tile the row vector r=[1 2 3] N times like r=[1 2 3 1 2 3 1 2 3...], then,
\n
c=r'\ncc=c(:,ones(N,1));\nr_tiled = cc(:)';\n
\n
This method has significant time savings against reshape or repmat for large N's.
\n
I conducted a small Matlab test to check the speed differential between repmat and tony's trick. Using the code mentioned below, I calculated the times for constructing the same tiled vector from a base vector A=[1:N]. The results show that YES, Tony's-Trick is FASTER BY AN ORDER of MAGNITUDE, especially for larger N. People are welcome to try it themselves. This much time differential can be critical if such an operation has to be performed in loops. Here is the small script I used;
\n
N= 10 ;% ASLO Try for values N= 10, 100, 1000, 10000\n\n% time for tony_trick\ntic;\nA=(1:N)';\nB=A(:,ones(N,1));\nC=B(:)';\nt_tony=toc;\nclearvars -except t_tony N\n\n% time for repmat\ntic;\nA=(1:N);\nB=repmat(A,1,N);\nt_repmat=toc;\nclearvars -except t_tony t_repmat N\n
\n
The Times (in seconds) for both methods are given below;
\n
\n
N=10,     time_repmat = 8e-5 ,   time_tony = 3e-5
\n
N=100,    time_repmat = 2.9e-4 , time_tony = 6e-5
\n
N=1000,   time_repmat = 0.0302 , time_tony = 0.0058
\n
N=10000,  time_repmat = 2.9199 , time_tony = 0.5292
\n
\n
My RAM didn't permit me to go beyond N=10000. I am sure, the time difference between the two methods will be even more significant for N=100000. I know, these times might be different for different machines, but the relative difference in order-of-magnitude of times will stand. Also, I know, the avg of times could have been a better metric, but I just wanted to show the order of magnitude difference in time consumption between the two approaches. My machine/os details are given below :
\n
Relevant Machine/OS/Matlab Details : Athlon i686 Arch, Ubuntu 11.04 32 bit, 3gb ram, Matlab 2011b
\n"
    },
    {
      "tags": [],
      "owner": {
        "account_id": 13125518,
        "reputation": 742,
        "user_id": 9481613,
        "user_type": "registered",
        "profile_image": "https://lh3.googleusercontent.com/a-/AOh14GjFWZ7udq84X5Ysni5L9gmx-8sykZfNRCy4IvUv=k-s128",
        "display_name": "mLstudent33",
        "link": "https://stackoverflow.com/users/9481613/mlstudent33"
      },
      "down_vote_count": 0,
      "up_vote_count": 0,
      "is_accepted": false,
      "score": 0,
      "last_activity_date": 1632710552,
      "creation_date": 1632710552,
      "answer_id": 69340635,
      "question_id": 43877288,
      "content_license": "CC BY-SA 4.0",
      "link": "https://stackoverflow.com/questions/43877288/how-to-hide-android-statusbar-in-flutter/69340635#69340635",
      "title": "How to hide Android StatusBar in Flutter",
      "body": "
Some of the above is deprecated in favor of:
\n
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,\n        overlays: [SystemUiOverlay.bottom]);\n
\n
What I am finding strange is that I placed this in initState of my second screen rather than in void main of the app but it is applied to all my screens nonetheless.
\n
https://api.flutter.dev/flutter/services/SystemChrome/setEnabledSystemUIMode.html
\n"
    },
    {
      "tags": [],
      "owner": {
        "account_id": 6768404,
        "reputation": 16484,
        "user_id": 5212614,
        "user_type": "registered",
        "accept_rate": 32,
        "profile_image": "https://i.stack.imgur.com/2qaHz.jpg?s=128&g=1",
        "display_name": "ASH",
        "link": "https://stackoverflow.com/users/5212614/ash"
      },
      "down_vote_count": 0,
      "up_vote_count": 0,
      "is_accepted": false,
      "score": 0,
      "last_activity_date": 1632710538,
      "creation_date": 1632710538,
      "answer_id": 69340634,
      "question_id": 69321407,
      "content_license": "CC BY-SA 4.0",
      "link": "https://stackoverflow.com/questions/69321407/converting-lists-of-categorical-data-to-numeric-vectors-with-unlabeled-data/69340634#69340634",
      "title": "Converting lists of categorical data to numeric vectors with unlabeled data",
      "body": "
You can easily convert all columns in dataframe into categories. Here is a simple code sample.
\n
import pandas as pd\n \n# Intitialise data of lists\ndata = [{'Year': 2020, 'Airport':2000, 'Casino':5000, 'Stadium':9000, 'Size':'Small'}, \n       {'Year': 2019, 'Airport':3000, 'Casino':4000, 'Stadium':12000, 'Size':'Medium'},\n       {'Year': 2018, 'Airport':5000, 'Casino':9000, 'Stadium':10000, 'Size':'Medium'},\n       {'Year': 2017, 'Airport':5000, 'Casino':10000, 'Stadium':15000, 'Size':'Large'}]\ndf = pd.DataFrame(data)\n\n\ndf = df.set_index(['Year'])\ndf\n
\n
Result:
\n

\n
df_fin = pd.DataFrame({col: df[col].astype('category').cat.codes for col in df}, index=df.index)\ndf_fin\n
\n
Result:
\n

\n"
    },
    {
      "tags": [],
      "owner": {
        "account_id": 8252,
        "reputation": 35823,
        "user_id": 14768,
        "user_type": "registered",
        "accept_rate": 82,
        "profile_image": "https://i.stack.imgur.com/b6aMa.png?s=128&g=1",
        "display_name": "Joshua",
        "link": "https://stackoverflow.com/users/14768/joshua"
      },
      "down_vote_count": 0,
      "up_vote_count": 0,
      "is_accepted": false,
      "score": 0,
      "last_activity_date": 1632710534,
      "creation_date": 1632710534,
      "answer_id": 69340633,
      "question_id": 69340108,
      "content_license": "CC BY-SA 4.0",
      "link": "https://stackoverflow.com/questions/69340108/how-to-check-if-character-read-in-through-read-system-call-is-a-backspace/69340633#69340633",
      "title": "How to check if character read in through read system call is a backspace?",
      "body": "
You can check if it's a backspace by looking for character number 8 (ASCII). It's written in C as '\\b'.
\n
However did you forget to put your terminal in RAW mode?
\n"
    },
    {
      "tags": [],
      "owner": {
        "account_id": 16805054,
        "reputation": 6295,
        "user_id": 12149471,
        "user_type": "registered",
        "profile_image": "https://www.gravatar.com/avatar/5bb9107b3d75e1de3585ba0f14e9d632?s=128&d=identicon&r=PG&f=1",
        "display_name": "Andreas Wenzel",
        "link": "https://stackoverflow.com/users/12149471/andreas-wenzel"
      },
      "down_vote_count": 0,
      "up_vote_count": 0,
      "is_accepted": false,
      "score": 0,
      "last_activity_date": 1632710528,
      "last_edit_date": 1632710528,
      "creation_date": 1632709543,
      "answer_id": 69340554,
      "question_id": 69340407,
      "content_license": "CC BY-SA 4.0",
      "link": "https://stackoverflow.com/questions/69340407/how-do-you-write-a-program-that-tests-if-a-users-inputs-are-integers-and-return/69340554#69340554",
      "title": "How do you write a program that tests if a user's inputs are integers and returns a message if they enter characters?",
      "body": "
The function std::isdigit expects an int with the value of a character code. However, you are not passing it a character code. If you want to pass a character code, you must read the input as a string or as individual characters, not as a number. Otherwise, you will have no character codes to pass to std::isdigit.
\n
However, unless the task description explicitly requires you to check that every single character is a digit, you don't have to call std::isdigit. This would also not be meaningful in some cases. For example, when the user enters negative numbers such as -34, the first character is not a digit. With this specific task, where the user is supposed to enter numbers between 0 and 100, there should be no negative numbers, but the user may want to enter +34 for the number 34, which should also be valid (unless the task description explicitly says otherwise).
\n
You have two options to solve this problem. You can either
\n
\n
rely on the stream extraction operator >> and check whether an error occurred by checking cin.fail, or
\n
read one line of input using std::getline and use std::stoi to attempt to convert the string into to a number. The function std::stoi will tell you whether the input was valid or not, i.e. whether it was possible to convert the string to a number.
\n
\n
The first option may be easier to use, but the second option is generally recommended for line-based user input.
\n
However, both options do have one problem: They will accept input such as 6sdfh4q as valid input for the number 6. Therefore, if you want perfect input validation, you should also check the part of the input that was not converted to a number, to check whether it is acceptable. In that case, all whitespace characters are probably harmless, but all other characters are not, so I recommend that you use std::isspace for this purpose.
\n"
    },
    {
      "tags": [],
      "owner": {
        "account_id": 9913598,
        "reputation": 11,
        "user_id": 7339346,
        "user_type": "registered",
        "profile_image": "https://www.gravatar.com/avatar/b4b434c2e36e180e1b413183a755d1ae?s=128&d=identicon&r=PG&f=1",
        "display_name": "Tejas Narayanan",
        "link": "https://stackoverflow.com/users/7339346/tejas-narayanan"
      },
      "down_vote_count": 0,
      "up_vote_count": 0,
      "is_accepted": false,
      "score": 0,
      "last_activity_date": 1632710526,
      "creation_date": 1632710526,
      "answer_id": 69340631,
      "question_id": 69340545,
      "content_license": "CC BY-SA 4.0",
      "link": "https://stackoverflow.com/questions/69340545/k-means-algorithm-in-python-returning-typeerror-list-object-is-not-callable/69340631#69340631",
      "title": "K-Means Algorithm In Python returning TypeError: 'list' object is not callable",
      "body": "
It seems that you haven't posted the snippet of code where the error actually occurred. But based on the error message, you might have created a list called kmeans_cluster, which conflicts with your function name. That might be why it's trying to "call" your list, because even though you intend for it to be using the kmeans_cluster function, it's actually using the kmeans_cluster list (which can't be called).
\n
Again, this is mostly speculation based on the error message, since you haven't posted the code preceding the error message. But inspect your code for conflicting variable and function names.
\n"
    },
    {
      "tags": [],
      "owner": {
        "account_id": 22118428,
        "reputation": 812,
        "user_id": 16372109,
        "user_type": "registered",
        "profile_image": "https://i.stack.imgur.com/nzydo.jpg?s=128&g=1",
        "display_name": "HatLess",
        "link": "https://stackoverflow.com/users/16372109/hatless"
      },
      "down_vote_count": 0,
      "up_vote_count": 0,
      "is_accepted": false,
      "score": 0,
      "last_activity_date": 1632710521,
      "last_edit_date": 1632710521,
      "creation_date": 1632709598,
      "answer_id": 69340559,
      "question_id": 69340094,
      "content_license": "CC BY-SA 4.0",
      "link": "https://stackoverflow.com/questions/69340094/keep-current-and-previous-line-only-if-current-line-fulfills-a-given-condition/69340559#69340559",
      "title": "Keep current and previous line only if current line fulfills a given condition",
      "body": "
Is perl an option?
\n
perl -nle '$prev && print if length() >50 and length() < 800 && print $prev; $prev = $_' input_file\n
\n
$prev - Create a variable which will hold every line. When the length condition is met, and there has been a previous line $prev, then it prints the condition matched in $prev and prints the last line.
\n
$prev = $_ Assigns the current line to the prev line variable
\n
\n
If the upper limit 800 is not essential, could sed be an option?
\n
$ sed -En '/>/ {N;/[a-zA-Z0-9]{50,}/p}' input_file\n
\n
/>/ - Match > and read into the pattern space
\n
N; Run the condition on the next line after the match and append that to the pattern space also:
\n
{50,} - If the length is 50 or more
\n
\\1/p - Return it and print
\n
\n
Output
\n
>4RYF_2\nMNLIPTVIEQTSRGERAYDIYSRLLKDRIIMLGSAIDDNVANSIVSQLLFLDAQDPEKDIFLYINSPGGSISAGMAIYDTMNFVKADVQTIGMGMAASMGSFLLTAGANGKRFALPNAEIMIHQPLGGAQGQATEIEIAARHILKIKERMNTIMAEKTGQPYEVIARDTDRDNFMTAQEAKDYGLIDDIIINKSGLKGHHHHHH\n
\n"
    }
  ],
  "has_more": true,
  "quota_max": 10000,
  "quota_remaining": 9952
}

A: This is a bug and has been reported on StackApps. It appears to affect all methods that return a list of answers.
Basically, the tags property will only be empty if certain properties exist (no idea which, though). It is not linked just to body_markdown, though, but to up_vote_count and down_vote_count as well (and possibly some other properties).
Make sure to limit the requests to just the properties you need using appropriate filters. If you're still unlucky, then you'd probably need to make two requests.


text:
Q: How to get the children of specific parent? There are several HTML segments like that. I want to check the "check_item" which belong to    this "shopcart-con" class when "check_all" clicked. But when I click the "check_all", all "check_item" was checked. How to fix it? Thanks
HTML:

<input type="checkbox" class="check_all" name="select"/>fruit shop A

<input type="checkbox" class="check_item" name="aihao" />

apple

                        <input type="button" name="" class="inp-reduce">
                        <input type="text"  name="" class="num" value="5">
                        <input type="button" name="" class="inp-add">

                    ¥8.00

<s> $12.00</s>

x5

                    <input class="delbtn" name="">

<input type="checkbox" class="check_item" name="aihao" />

                        <input type="button" name="" class="inp-reduce">
                        <input type="text"  name="" class="num" value="5">
                        <input type="button" name="" class="inp-add">

                    ¥8.00

x5

                    <input class="delbtn" name="">

共计10  sum:$80

JS:
$('.check_all').click(function(){
        var checked_items = $('.check_all').closest('.shopcart-con').find('.check_item')
        console.log(checked_items.length)
        if($(this).prop('checked')){
            $.each(checked_items, function(i,val){
                val.checked = true;
            });
        }else{
            $.each(checked_items, function(i,val){
                val.checked = false;
            });
        }
    });

A: Try this : you are using $('.check_all').closest this will find shopcart-con under all check_all. But you need to find shopcart-con for clicked check_all, hence use $(this) like  $(this).closest
$('.check_all').click(function(){
        var checked_items = $(this).closest('.shopcart-con').find('.check_item')
        console.log(checked_items.length)
        if($(this).prop('checked')){
            $.each(checked_items, function(i,val){
                val.checked = true;
            });
        }else{
            $.each(checked_items, function(i,val){
                val.checked = false;
            });
        }
    });

DEMO
You can make your code even shorter, you need not to iterate all checkbox and set its property, see below code
$('.check_all').click(function(){
        var checked_items = $(this).closest('.shopcart-con').find('.check_item')
        console.log(checked_items.length)
        $(checked_items).prop('checked',this.checked);
    });

DEMO

redpajama_set_name: RedPajamaStackExchange


text:
Q: Axes3D.text() Annotate 3D Scatter Plot Can't get the 3D text working to annotate the scatter plot points.
Tried Axes3D.text, plt.text but keep getting 'missing required positional argument 's'. How do you annotate in 3D in a loop?
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
import pandas as pd
import numpy as np

df = pd.read_csv (r'J:\Temp\Michael\Python\9785.csv')

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

#Scatter plot
for i in df.index:
    x = df.at[i,'x']
    y = df.at[i,'y']
    z = df.at[i,'h']
    ax.scatter(xs=x, ys=y, zs=z, s=20,color='red',marker='^')
    label = df.at[i,'to']
    Axes3D.text(x+0.8,y+0.8,z+0.8, label, zdir=x)

TypeError: text() missing 1 required positional argument: 's'

A: Changing: ax = fig.add_subplot(111, projection='3d')
to: ax = fig.gca(projection='3d')
solved the problem. Used ax.text.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
import pandas as pd
import numpy as np

df = pd.read_csv (r'J:\Temp\Michael\Python\9785.csv')

fig = plt.figure()
ax = fig.gca(projection='3d')

#Scatter plot
for i in df.index:
    df.set_index('to')
    x = df.at[i,'x']
    y = df.at[i,'y']
    z = df.at[i,'h']
    ax.scatter(xs=x, ys=y, zs=z, s=20,color='red',marker='^')
    ax.text(x+0.8,y+0.8,z+0.8, df.at[i,'to'], size=10, zorder=1)


text:
Q: My static (CSS) files are loading for my Django website, but they are not being displayed. What am I missing or doing wrong? EDIT:
I figured out that the CSS file was not being displayed because I copied the link tag pointing to the CSS file from Microsoft Word, so the quotations marks around rel="stylesheet" were not the right type of quotations marks!!
The settings.py file in the project folder defines the STATIC_URL variable as '/static/'
The CSS file is inside the app folder: DjangoProject/shop/static/shop/style.css
The {% load static %} is at the top of the HTML template (if I use "staticfiles" instead of "static", I get an error)
The CSS file is linked using href="{% static 'shop/style.css' %}"
The CSS file loads and is visible when I analyze the "view page source", but the actual CSS is not displayed on the webpage.
What am I doing wrong? I'm using Django version 3.0.7
EDIT:
I've also tried defining the STATICFILES_DIRS in the settings.py file, but that doesn't do anything. Nor does adding the additional code below to the project urls.py file.
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

.
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    #your url patterns
]
urlpatterns += staticfiles_urlpatterns()

A: you have to add
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

in your settings.py file below STATIC_URL
add bolew code in main urls.py
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    #your url patterns
]
urlpatterns += staticfiles_urlpatterns()

and make sure you are hard refreshing the webpage and try restarting server


text:
Q: Open folder in Explorer from VS Code Say I have a project/folder open in VS Code and I want to open the folder in Windows Explorer, is there keyboard shortcut or a VS Code Extension for that? Sometimes I also need to go to the project folder in command prompt.
In Visual Studio 2017, there's a menu option to open the folder and an extension for quickly getting to the project folder in command prompt -- see below:

How do I handle these in VS Code?

A: Right click on a file or folder from the left side explorer of VSCode, then select "Reveal in Explorer".  Now you can see the folder in windows explorer.


text:
Q: Is it possible to switch between two UI form in one class in qt? I have following two classes with their UI forms.

*

*loginWindow

*mainWindow

Now when I need to go to the mainWindow I click on the push button in loginWindow and a new window pops up that is the mainWindow.
void LoginWindow::on_pbLogin_clicked()
{
    MainWindow *mainW = new MainWindow;
    mainW->show();
}

What I am trying to have is to get the contents of mainWindow in the loginWindow.
I could switch/move to mainWindow from LoginWindow in the same window, without mainWindow creating its own window to show its content and I don't want to use qstackedwidget
Is it possible? if yes, how can I achieve this?

A: If we assume that LoginWindow and MainWindow are both derived from QMainWindow (otherwise it wouldn't just be a content switch), then one option other than using a QStackedWidget would be to have the two form classes derive from QWidget and use either as the centralWidget of a single QMainWindow instance.


text:
Q: Varnish 3 ignore the req.backend directive Varnish3 is ignoring the req.backend directive.
As explained on the documentation (here), I've set two backends, and the regex for redirecting the request to the correct one. By the way, seems liks Varnish is just ignoring
the directive, obviously I'm missing something :-)
I want to catch awesomedomain.it as well as awesomedomain.it/whatever, while all the others domain just should point to default backend.
Any help is appreciated.
backend local {
    .host = "127.0.0.1";
    .port = "8000";
}

backend default {
    .host = "10.8.0.2";
    .port = "80";
}

sub vcl_recv {

if (req.http.host ~ "/awesomedomain\.it/") {
    set req.backend = local;
    }
}

A: The first backend is the default backend. The name of the backend doesn't matter


text:
Q: In a RESTful HTTP request for search results, if there are no results, should I return an empty array or a 404 error code? In a RESTful HTTP request for search results, if there are no results, should I return an empty array or a an error code?

A: You should return an empty array, because the resource (result collection) exists, but it is empty.


text:
Q: How to download a PDF file with selenium python webdriver? Website: http://mbct.com/wp-content/uploads/Eisendrath-Jan-2016.pdf
Error: unable to locate the element
Maybe this is because the download icon will disappear when I don't do something?
This is my code:
# coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time
import os
site = 'http://mbct.com/wp-content/uploads/Eisendrath-Jan-2016.pdf'
br = webdriver.Chrome()
br.get(site)
br.find_element_by_xpath('//*[@id="icon"]').click()

A: Transferred from comment to answer:
You appear to be trying to find an XML element in a PDF. PDF, unlike HTML, does not overlap with XML, so that's not going to work.
The download icon that shows up if you visit a PDF in your browser is not a part of the webpage, so even if a PDF was XML, that wouldn't work. Also, there's a decent chance that there's more than one icon, in which case you'd probably be clicking on the wrong thing, and it might not be clickable (if you were using this for some non-PDF thing with a download button on the actual webpage).
To download a PDF from a website... you shouldn't need to use a webdriver (or any Python at all). Just load it with curl in a shell script, if you're on UNIX. There's probably a simple Windows equivalent but I don't know it. If you do want to use Python for whatever reason, urllib.request (Python 3) or urllib2 (Python 2) can do it.
Or, if it really is just that website, you don't need to run an automatic program at all - just right-click the link and choose "Save link as..." or equivalent in most browsers.


text:
Q: Fetch only Live Photos using Photos Framework dosen't work I'm trying to fetch only Live Photos out of the device albums.
I found this Objective C code, but for some reason when converting it to Swift to doesn't compile.
PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.predicate = [NSPredicate predicateWithFormat: @"(mediaSubtype == %ld)", PHAssetMediaSubtypePhotoLive];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey: @"creationDate" ascending: NO]];
PHFetchResult<PHAsset *> *assetsFetchResults = [PHAsset fetchAssetsWithMediaType: PHAssetMediaTypeImage options: options];

Swift:
 fetchOptions.predicate = NSPredicate(format: "mediaSubtype == %ld", PHAssetMediaSubtype.PhotoLive)

throws compile error :
 Argument type 'PHAssetMediaSubtype' does not conform to expected type 'CVarArgType'

Any suggestions?

A: You can't supply a Swift enumeration value to that method - it needs a long (as is implied by the %ld format string), so use
fetchOptions.predicate = NSPredicate(format: "mediaSubtype == %ld", PHAssetMediaSubtype.PhotoLive.rawValue)

to access the underlying integer value of the enumeration value


text:
Q: Passing $_SESSION through an iframe - PHP For the record, I DID see this entry - Passing sessions variables through an iframe, php which is asking the exact same question, but the answer (even when I followed it to a T) still isn't working for me.
I have two pages - one is the landing page, the other is the page pulled in to the landing page via iframe. I start the session on the landing page and assigned $_SESSION a value, and I want that value pulled in to the iframe.
Here's my code for the landing page:
<?php
session_start();
    $_SESSION['vendorname'] = $this->getVendorId(); // store session vendor name data
    echo "Vendor = ". $_SESSION['vendorname']; // test to see if the vendor name was properly set
session_write_close();
?>

    ....blah blah...

Here's the code from the page within the iframe:
<?php
session_start();
?>

    <link href="css/something.css" type="text/css" rel="stylesheet" />

  <?php
     if(isset($_SESSION['vendorname']) && is_array($_SESSION['vendorname'])) {
       echo "vendor = ". $_SESSION['vendorname']; }
     else {
       echo "Meh, back to the drawing board"; }?>

On the landing page, the $_SESSION displays correctly. It retrieves the vendor's name via our database and spits it out on the screen. In the iframe however, it only displays my failure message ("Meh, back to the drawing board"). I am missing something. :(
EDIT:
Per Marc B's suggestion, I'm now checking the session_id(). So for this code (on landing page):
<?php
session_start();
    echo session_id();
    echo "
";
    $_SESSION['vendorname'] = $this->getVendorId(); // store session vendor name data
    echo "Vendor = ". $_SESSION['vendorname']; //test to see if the vendorname was properly set
    echo "
";
    echo session_id();
session_write_close();
?>

I'm getting the following output:
0lq5gb79p52plgd9mcknpife60
Vendor = SUPERVEND
0lq5gb79p52plgd9mcknpife60
On the iframe page, for this code:
<?php
session_start();
echo session_id();
?>

        <link href="css/something.css" type="text/css" rel="stylesheet" />

<?php
echo session_id();
if(isset($_SESSION['vendorname'])) {
    echo "vendor = ". $_SESSION['vendorname']; }
else {
    echo "vendor = ". $_SESSION['vendorname']; }
?>

I'm getting the following output:
0lq5gb79p52plgd9mcknpife60
0lq5gb79p52plgd9mcknpife60
vendor =

A: Start the iframe with the following:
header('P3P: CP="CAO PSA OUR"');
session_start();

you should then be able to access the session variables in the normal fashion.


text:
Q: BODMAS calculation in c Hi i m trying to write a code in C to solve the mathematical equation based on BODMAS rule,any suggestion?
for eg:
the program should give the output as:
(8+8)/2+4=12

A: #include <stdio.h>

int calc(char *exp_str){
    FILE *fp;
    int ret;
    fp=fopen("calc_aux.c","w");
    fprintf(fp, "int main(){ return %s; }", exp_str);
    fclose(fp);
    system("gcc calc_aux.c -o calc_aux.exe");
    ret=system("calc_aux.exe");
    remove("calc_aux.c");
    remove("calc_aux.exe");
    return ret;
}

int main(){
    char exp[]="(8+8)/2+4";
    printf("%s=%d\n", exp, calc(exp));
}
//result:(8+8)/2+4=12


text:
Q: What's a word for something you do, but you don't like to mention it? For instance, a business man might be cold and hard in his demeanor, but really enjoys watching childish cartoons. Or an exercise buff might also really enjoy deep fried chicken. It also might be a two word phrase, but I'm not entirely sure.

A: That's a guilty pleasure. Anything you're half-ashamed of liking, especially because it seems incongruous with the rest of your life (as those examples), or because society as a whole sort of disapproves (like eating a lot of chocolate ice cream).

A: Taboo ta·boo /təˈbo͞o,taˈbo͞o/ –Google
noun:

a social or religious custom prohibiting or forbidding discussion of a particular practice or forbidding association with a particular person, place, or thing.
"the taboo against healing on the Sabbath"
a social practice that is prohibited or restricted.
"speaking about sex is a taboo in his country"

adjective:

prohibited or restricted by social custom.
"sex was a taboo subject"

It is taboo to ask people of which debaucheries they partake.
Edit: In my haste, I didn't even mention the word embarrassment, which I skipped over to go right to the cause of it. Some people think knowledge of their vices might "ostracize [them] from society" so they'd rather not "mention them" and therefore (personally) consider the topic taboo.


text:
Q: JavaScript EMV TLV Parser I am trying to parse the card data for EMV TLV transactions. Are there any parsers for decoding EMV TLV card data for JavaScript that do not use node.js?

A: My favourite application that partially does this is TVR Decoder. It actually does a little more than just decode TVR. Its source code is on Github if you want to contribute to the project.
Alternatively, I also liked the EMV Data Viewer proprietary software from the Ingenico SDK. I strongly doubt it is coded in JS thought.

A: You would have to read the specifications from the EMVCo page https://www.emvco.com/specifications.aspx?id=223
It depends on the exact command / response you want to decode.
Responses have different Tags which may occur in templates. You need to know what tag you have, and then using the template you would know exactly what is expected as value. The length always comes after the tag. The value itself can also be a TLV of a different Tag.
Check this video
https://youtu.be/iWg8EBhsfjY
It explains how to decode using some examples responses.

A: Check this out. It has most of the things you do in emv processing. Can give you a better idea even if does not match your exact requirement. Quite understandable coding.
But I can say, a little effort, you can do it on your own.

*

*Get the list of mandatory and optional tags from EMVCo books.

*Get the length of the data which follows

*Get the data( note that some R-APDU come in templates, these details are also there in EMVCo books).


text:
Q: Using websockets in classic asp.net forms application I need to add websocket functionality to legacy asp.net webforms application (just one simple long time workflow converted from old applet functionality).
I naively tried to just add websocket handler to aspx page:
        public override void ProcessRequest(HttpContext context)
        {
            if (context.IsWebSocketRequest)
            {
                context.AcceptWebSocketRequest(HandleWebSocket);
            } else
            {
                base.ProcessRequest(context);
            }
        }

and enable websocket on the IIS:

Then try: var ws = new WebSocket("ws://localhost/APP/Page.aspx");
but this does not seam to work.
Not sure if this is at all possible?
Do I miss something about configuration or implementation?
I could put websocket on separate application/server but would prefer to keep it in one place with access to same session object.

A: It should be possible to handle a web socket connect in a classic ASP.NET Forms application. The tools are available on HttpContext and you basically have the correct idea.
I think the issue is that you are trying to invoke it from an aspx page and not just using a generic IHttpHandler. IIS runs specific processing pipelines based upon the file extension. Aspx is rather specialized to trying to render an HTML page, so while it might be possible to reconfigure IIS to allow websockets to interact with ASPX pages, it is much easier to just use a generic ashx handler.
You can create a handler by going to the "Add Item" dialog in Visual Studio

At this point, you would just implement your websocket logic in your handler code. I'm putting in a simple echo from this aspnet sample just to demonstrate.
public class MyHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        if (context.IsWebSocketRequest)
        {
            context.AcceptWebSocketRequest(EchoWebSocket);
        }
    }

    private async Task EchoWebSocket(AspNetWebSocketContext socketContext)
    {
        var buffer = new byte[1024 * 4];
        var result = await socketContext.WebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

        while (!result.CloseStatus.HasValue)
        {
            await socketContext.WebSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
            result = await socketContext.WebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        }

        await socketContext.WebSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

You should now be able to connect to the websocket. Note the usage of wss rather than ws. The setup I tested with requires the secure version (wss). Use whatever is relevant for the application you are working on.
// Replace with port/path to your handler.
var ws = new WebSocket("wss://localhost:44336/MyHandler.ashx");

ws.onmessage = function(evt) {
    console.log(evt);
};

ws.send("Hello, World!");

And you should see output similar to this:

Note: I generally wouldn't recommend trying to access Session data from the websocket handler. Your session may expire outside the timeframe of the websocket's lifespan. You would probably want to use some other mechanism to persist state between the socket and the rest of the pages (potentially a database or the application-level cache, which you can access from socketContext.Cache in the example above.
Edit: Added an example of using session value on socket initialization.
Per your comment, if you want to use session values during the initialization of a websocket (which should be a safe operation), then your handler just needs to implement IRequiresSessionState and needs to add a little extra syntax to pass the session value into the accept handler.
public class MyHandler : IHttpHandler, IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
        if (context.IsWebSocketRequest)
        {
            var sessionValue = context.Session["session_key"] as string;

            context.AcceptWebSocketRequest(async (socketContext) =>
            {
                await SetupWebSocket(socketContext, sessionValue);
            });
        }
    }

    private async Task SetupWebSocket(AspNetWebSocketContext socketContext, string sessionValue)
    {
        // Handle socket as before, but 'sessionValue' is now available for use.
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}


text:
Q: Laravel 5.2 foreign key constraint fails I am getting the following error when I try to save a new property:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (lightning.residentials, CONSTRAINT residentials_residential_type_id_foreign FOREIGN KEY (residential_type_id) REFERENCES residential_types (id)) (SQL: insert into residentials (furnished, rooms, rent, property_id, updated_at, created_at) values (1, 1, 100, 17, 2016-07-06 23:32:59, 2016-07-06 23:32:59))
I cant see why.
Db schema
The Property model:
   protected $table = 'properties';
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'user_id', 'is_for_sale','available','title', 'description','price'
];

public function user()
{
    return $this->belongsTo('App\User');
}

public function Residential()
{
    return $this->hasOne('App\Residential');
}

/**
 * The Addresses that belong to the properties.
 */
public function addresses()
{
    return $this->belongsToMany('App\Address');
}

address model
 /**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'building_name', 'street_number', 'street_name', 'town', 'county', 'postcode','is_deleted'
];

/**
 * The Users that belong to the Address.
 */
public function user()
{
    return $this->belongsToMany('App\User');
}

/**
 * The Users that belong to the Address.
 */
public function organisation()
{
    return $this->belongsToMany('App\Organisation');
}

/**
 * The Users that belong to the Address.
 */
public function Property()
{
    return $this->belongsToMany('App\Properties');
}

The residential model:
protected $table = 'residentials';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'property_id', 'residential_type_id','furnished','rooms','rent'
];

public function Property()
{
    return $this->belongsTo('App\Property');
}

public function Residential_Type()
{
    return $this->belongsTo('App\Residential_types');
}

The residential_type model
 // Define table name
protected $table = 'residential_types';

protected $fillable = [
    'residential_type'
];

/**
 *
 */
public function Residential()
{
    return $this->hasMany('App\Residential', 'residential_type_id');
}

My controller function where I try to save a property along with the fields in the related residential table but I get the error above. The property and address saves correctly just fails when it comes to the residential.
  $property = new Property([
        'user_id' => $user->id,
        'is_for_sale' => $request['listing_type'],
        'available' => $request['available'],
        'title' => $request['title'],
        'description' => $request['description'],
        'price' => $request['price'],
    ]);

    $property->save();

    //save address and related to property
    $address = new Address([
        'building_name' => $request['building_name'],
        'street_number' => $request['street_number'],
        'street_name' => $request['street_name'],
        'town' => $request['town'],
        'county' => $request['county'],
        'postcode' => $request['postcode'],
    ]);
    $property->addresses()->save($address);

    //save property and related to residential
    $residential = new Residential([
        'furnished' => $request['furnished'],
        'rooms' => $request['bedrooms'],
        'rent' => $request['price'],
    ]);

    $residential_type = new Residential_Types([
        'residential_type' => $request['property_type'],
    ]);

    $residential_type->save();

    $property->Residential()->save($residential);

    $residential->Residential_Type()->save($residential_type);

    return view('renting');


text:
Q: my Realme device is not connect as adb devices on mac but connecting on windows fluently device is connecting perfectly on windows but not on mac devices is not asking permission to trust this device and showing offline while running adb devices command my phone is realme 9 pro speed addition,
i have tried on multiple macbook but still not connecting , also tried on diffrent windows laptops connected succesfully on each windows device. tried changing the cable , resarting server, downloaded latest platform-tools..

A: I had similar issue on Realme Master GT and in my case solution was connecting wirelessly by adb. This feature was announced in android 11.

*

*Developer options > Wireless debugging > Pair device with pairing code

*Take ip, port, pairing code from phone - example: ip:port = 192.168.150.120:37181 pairing_code = 188231

*Your phone and computer have to be connected to the same wifi network

*On mac: adb pair [ip:port] [pairing_code] - example: adb pair 192.168.150.120:37181 188231

*On mac: adb connect 192.168.150.120:37181

*On mac: adb devices
After last command your device should be properly listed and ready to run npm react-native run-android :)


text:
Q: Methods for development wordpress themes Analyzing the code from WordPress themes, both free and paid for, and realized that there is no standard for the development of themes. Some themes use CPT for all other widgets, other Visual Composer (and dirty code) and so on.
I know WordPress, studying hard and already making my themes and I am honestly confused as to which way I should build my themes. What is the best or "worst" method.
Some may say that "the best method is what solves your problem," but I believe it is not because it solves my problem, which is the best method. Not because it is running that is good!
My question is, is there some way "more appropriate / better / less worse" to develop a theme? CPT, Widgets, VisualComposer and so on...?

A: The way you are asking your question doesn't follow WPSE guidelines. You will get a lot of opinionated answers which is not what we look for here.
Try to come up with more context with your question.

*

*What are you building your theme for?

*Who's your users (single client or public/masses)?

*What problems are you trying to solve?

*What tools are you considering to use to solve the issue?

*Are you planning to build extensions/modules for your theme

*Do you wish to separate some core functionalities from design or offer your client to modify design without affecting core functionalities (parent/child designs)

*etc.

The worst method to build any program is to not be structured in your program logic and have functions all over the places (which would be a problem not specific to WP theme dev), repeating yourself, etc.
If you came up with a question like "I need to do so and so, is it better to use CPT or custom field to solve my issue" then it would be easier and more productive to answer that kind of question. We could then provide the pros and cons of either solutions.
There is all kind of situations, problems, clients, contexts that can affect the way you build your software. Sometimes, because it works it IS the better solution. But generally speaking you try to be as structured and concise as possible keeping your stuff readable/understandable for other devs and you (would you still understand your code if you came back to it, 6-12 months from now?)


text:
Q: ASP.NET Core MVC. Как реализовать систему диалогов? Имеется приложение ASP.NET Core MVC в связке с MS SQL Server. Стоит задача реализовать систему диалогов (сообщений) между пользователями, наподобие как в любом мессенджере (Telegram, Skype, ВКонтакте и т.д.). То есть чтобы история сообщений сохранялась в БД и диалог можно было продолжить.
Подскажите, кто сталкивался с подобной задачей как решали. Какие подводные камни, может что почитать. Пока что на ум приходит поверх SignalR писать свою инфраструктуру.

A: Использовали SignalR, очень удобен и разработка заняла не так много времени. Если количество сообщений будет очень большим, то можно задуматься о брокерах сообщений(RabbitMQ).
Основную сложность в создании чата заняла его архитектура, но это из-за особенностей создаваемой системы, если у вас все открыто, то будет проще.


text:
Q: (C#) Class member initializing thread-safety issue Comparing 2 ways of class property defenition (A & B):
// implemention A
public class Cache {
    private object m_syncRoot = null;
    public object SyncRoot {
        get {
            if (m_syncRoot == null) {
                Interlocked.CompareExchange(ref m_syncRoot, new object(), null);
            }
            return m_syncRoot;
        }
    }
}

AND
// implemention B.
public class Cache {
    public object SyncRoot { get; } = new object(); // in C# 6.0
}

And finally some where uses cache:
static Cache MyCache = new Cache(); //  I don't know if this kind of declaration is thread-safe either
lock (MyCache.SyncRoot) {
    ....
}

Question:
Since "Cache" will be used as static instance, are both "SyncRoot" creations in [A] & [B] thread-safe ?

A: Yes, both of the two creation are thread-safe. The difference is in implementation B, the SyncRoot object is created when the Cache instance is created. And in A, SyncRoot is created when it is accessed.


text:
Q: How to Install Ubuntu 14.04 with RAID 1 using desktop installer? Many people claim that it is impossible to install Ubuntu onto RAID 1 with the Desktop CD. Is this really true? If not, how can it be done?

A: Edit: This guide does not take UEFI boot into account. Additional or different steps may be required if UEFI boot is desired. This guide assumes legacy boot!
It is true, that the ubiquity installer does not know about mdadm software raid devices. Also it is true, that the live-cd is missing the mdadm raid administration tool. However, doing some work by hand, it is very much possible to install Ubuntu on RAID1.
In the following I will assume two identical hard disks (/dev/sd[ab]) which will be used completely for our new install. To simplify the recovery if one drive fails, there will be only one mdadm-volume /dev/md0 which will then be partitioned for /, swap and data storage, e.g. /home.
After booting up the live-cd and (if necessary) configuring network access, open up a terminal and assume root access sudo -s
apt-get install mdadm

Now we create a single primary partition each of /dev/sda and /dev/sdb from sector 2048 to the end of the disk, for example using sudo fdisk. I also like to already set the partition type to fd for linux raid autodetection. The keystroke-sequence in fdisk (if the disk is emptyin the beginning, meaning no partitions) is n <return> p <return> 1 <return> 2048 <return> <return> t <return> fd <return> w <return>.
Now we create the mdadm volume:
mdadm --create /dev/md0 --bitmap=internal --level=1 -n 2 /dev/sd[ab]1

I noticed, that the ubiquity installer also does not quite manage to create partitions inside this /dev/md0, so I also did this by hand - again using fdisk. So on /dev/md0 create the following partitions:

*

*/dev/md0p1 for your root filesystem, the size of course depending upon how much software you are going to install.

*/dev/md0p2 for swap, the size of course also depending on what you use the machine for and how much ram it's got

*/dev/md0p3 for /home, all the space that's left

After that we can begin the Installation. Make sure to start the installer from the terminal with the -b option, because installing the bootloader will fail anyway:
ubiquity -b

Make sure to go for manual partitioning and "use" the 3 partitions you just created and tick the format checkbox for / and /home so a filesystem will be created.
After the installation the system is not yet bootable, so do not restart the box right away. We need to chroot into the installed system and fixup some stuff:
sudo -s
mount /dev/md0p1 /mnt
mount -o bind /dev /mnt/dev
mount -o bind /dev/pts /mnt/dev/pts
mount -o bind /sys /mnt/sys
mount -o bind /proc /mnt/proc
cat /etc/resolv.conf >> /mnt/etc/resolv.conf
chroot /mnt
apt-get install mdadm
nano /etc/grub.d/10_linux  # change quick_boot to 0
grub-install /dev/sda
grub-install /dev/sdb
update-grub
exit

Now the newly installed system is ready to boot. Have fun!

A: Do not install Ubuntu Desktop CD with RAID 1. My advice:

*

*Use the Ubuntu Server CD to have a guided RAID 1 install. The manual for this is here (ignore the LVM part, not needed) :
https://help.ubuntu.com/lts/serverguide/advanced-installation.html

*After that install the Ubuntu desktop environment with
sudo apt-get install ubuntu-desktop

*Reboot and you have a Ubuntu desktop (installed with the server cd).

A: I haven't tried, but just came accross http://www.salamander-linux.com/.
Salamander is a modified version of the default installer for Ubuntu Linux, Ubiquity. This modified installer allows users to easily install Ubuntu Linux onto a Software RAID array. No special hardware is required -- the Salamander installer can be used on any system with multiple hard disks.


text:
Q: Optimizing Quicksort in JAVA (checking earlier if sorted) I want to check the array if it's sorted or not, before sorting the array with quicksort.
I'm always getting a stackoverflow in line 77, or an array index out of bounds error in line 65.
My basic idea was to check the first two numbers if they are sorted, then second and third, and so on. If they are not sorted, the whole while loop should cancel and start sorting with quicksort using the last correct sorted value as comperative value.
public class customQuickSort
{
    Runtime runtime = new Runtime();

    private int[] a;
    private int n;
    boolean isSorted = true;
    int arraySortCount = 0;
    int x = 0;

    public customQuickSort(int[] unsorted)
    {
        sort(unsorted);
    }
    @Override
    public void sort(int[] a)
    {
        this.a=a;
        n=a.length;
        runtime.start();
        quicksort(0, n-1);
        runtime.end(getCounter());
    }

    private void quicksort (int lo, int hi)
    {
        int i=lo, j=hi;
        while(isSorted = true && arraySortCount < a.length-1)
        {
            if(a[arraySortCount] <= a[(arraySortCount+1)])
            {
                if(arraySortCount == a.length-2)
                {
                    System.out.println("array sorted ascending");
                }
            }
            else if(a[arraySortCount] >= a[(arraySortCount+1)])
            {
                if(arraySortCount == a.length-2)
                {
                    System.out.println("array sorted descending");
                }
            }
            else
            {
                isSorted = false;
                x=a[c(arraySortCount)];
                System.out.println("unsorted");
            }
            arraySortCount++;
        }
        if(isSorted == false)
        {

            while (i<=j)
            {
                while (a[i]<x)
                {
                    i++;
                }
                while (a[j]>x)
                {
                    j--;
                }
                if (i<=j)
                {
                    exchange(i, j);
                    i++; j--;
                }
            }

            if (lo<j) quicksort(lo, j);
            if (i<hi) quicksort(i, hi);
        }
    }

    private void exchange(int i, int j)
    {
        int t=a[i];
        a[i]=a[j];
        a[j]=t;
    }
}

A: Just use
Arrays.sort(T[], Comparator<? super T> c)

it uses a highly optimized sorting algorithm

Implementation note: This implementation is a stable, adaptive,
  iterative mergesort that requires far fewer than n lg(n) comparisons
  when the input array is partially sorted, while offering the
  performance of a traditional mergesort when the input array is
  randomly ordered. If the input array is nearly sorted, the
  implementation requires approximately n comparisons. Temporary storage
  requirements vary from a small constant for nearly sorted input arrays
  to n/2 object references for randomly ordered input arrays.
The implementation takes equal advantage of ascending and descending
  order in its input array, and can take advantage of ascending and
  descending order in different parts of the the same input array. It is
  well-suited to merging two or more sorted arrays: simply concatenate
  the arrays and sort the resulting array.
The implementation was adapted from Tim Peters's list sort for Python
  ( TimSort). It uses techiques from Peter McIlroy's "Optimistic Sorting
  and Information Theoretic Complexity", in Proceedings of the Fourth
  Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January
  1993.

read more here


text:
Q: Can a Page.PrePrender event be fired before Page.Load event handler called return? A Page.PreRender event is guaranteed to be fired after Page.Load event is fired. But is it guaranteed to be fired after Load event handler returned?
A more general question is if event lifecycle of ASP.Net page guarantees that each event is fired only after previous has returned or events can be fired while previous is still executing?
How does answer change if previous event fires some custom event such as DataBound? Can such event be executed in parallel with another event in page lifecycle?

A: Yes, the events run synchronous after each other. The events are handled in a single thread, so there can't be two events for the same page running at the same time (except of course if an event calls "sub-events", but then the code calling the "sub-event" doesn't continue to run until it returns).


text:
Q: Keyboard shortcut to select the address bar for the current page in Safari? When I want to navigate to a new page using the address bar in Safari without taking my hands off the keyboard, I use the keyboard shortcut Command + T, which opens a new tab and places the cursor in its address bar.
This is fine when I want to keep the original page open in another tab. But sometimes I want to replace it with the new page. Sometimes I can get back to the address bar by pressing Tab or Shift + Tab several times, but the number of times depends on the amount of tab-selectable fields on the page.
Is there a keyboard shortcut to select the address bar for the current page in Safari?

A: Command + L is the keyboard shortcut you are looking for.
This shortcut is corresponding to Open Location... command which can be found under File → Open Location... in Safari Menu bar.


text:
Q: Understanding fourier coefficients In my text book it says that if $c_n$ are fourier coefficients of $f$ and $f_n$ is an orthonormal set then
$\bigg( \sum_{n=1}^N c_n f_n, f - \sum_{n=1}^N c_n f_n\bigg) = 0$
This is not immediately obvious to me and I am wondering if someone has a proof of this?

A: We have:
$$\left( \sum_{n=1}^N c_n f_n, f - \sum_{n=1}^N c_n f_n\right) = \left(\sum_{n=1}^N c_nf_n, f\right) - \left(\sum_{n=1}^N c_n f_n , \sum_{m=1}^N c_m f_m\right) \\ = \sum_{n=1}^N c_n (f_n,f) - \sum_{n=1}^N\sum_{m=1}^Nc_n c_m \underbrace{(f_n,f_m)}_{= \delta_{nm}} \\ = \sum_{n=1}^N c_n^2 - \sum_{n=1}^Nc_n^2 = 0$$

A: This is a slightly stronger result from which the other follows. It says that the error in approximating $f$ by $\sum_n c_n f_n$ is perpendicular to the linear subspace spanned by the $f_n$.
If $c_n = \langle f, f_n \rangle$, and $k \le n$, then
$\langle f-\sum_n c_n f_n , f_k \rangle = \langle f, f_k \rangle - \langle \sum_n c_n f_n , f_k \rangle = c_k - c_k = 0$


text:
Q: Error #1034: cannot convert XMLList@c093fd1 to mx.collections.ArrayCollection         protected function initView(event:ViewNavigatorEvent):void
            {
                // Api Call
                NFLScore.url="http://api.nfldata.apiphany.com/trial/XML/ScoresByWeek/2013REG/14" +
                    "?key=BDAE4263-4522-45B9-96FF-01F0DFB0F610";
                NFLScore.send();
            }
            protected function NFLScore_resultHandler(event:ResultEvent):void
            {
                // Alle items en Labels value geven

                myData=event.result.ArrayOfScore.Score;

            }
            protected function NFLScore_faultHandler(event:FaultEvent):void
            {
                // TODO Auto-generated method stub
                printUit.text = "foute zoek opdracht";
            }

                                //////// End ////////
            ///////////////////////// API CALL /////////////////////////

        ]]>
    </fx:Script>

    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
        <s:HTTPService id="NFLScore" fault="NFLScore_faultHandler(event)"
                       result="NFLScore_resultHandler(event)" resultFormat="e4x" />
    </fx:Declarations>
    <s:actionContent>
        <s:Button id="Score" icon="assets/Score.png" click="Score_clickHandler(event)" />
    </s:actionContent>

    <s:Label id="printUit"/>
    <s:TextArea height="100%" width="100%" id="txtResult" text="{NFLScore.lastResult.Score.AwayScore}"/>

</s:View>

Result:

<AwayScore xmlns:i="http://www.w3.org/2001/XMLSchema-instance">20</AwayScore>
<AwayScore xmlns:i="http://www.w3.org/2001/XMLSchema-instance">26</AwayScore>
<AwayScore xmlns:i="http://www.w3.org/2001/XMLSchema-instance">21</AwayScore>

Want:
output:
20
26
21
Situation: I'm calling on API that gives me result (XML) as main node ArrayOfScore after that Score where the date is that i want. But i keep getting error "TypeError: Error #1034: Type Coercion failed: cannot convert XMLList@c1e1fd1 to mx.collections.ArrayCollection. "

A: You have to rewrite the code as specified below
protected function NFLScore_resultHandler(event:ResultEvent):void
            {
                var obj:SomeObject = null;//someobject is any class that stores the xml data that is returned from the server.
                for(XML item:event.result.ArrayOfScore.Score){
                      obj = new SomeObject();
                      obj.someProperty = item.toString();
                      myData.additem(obj);
                }
            }

Basically what you are doing is, converting one object(xmllist) type into arraycollection object by the above iteration. This may not be perfect but, shoudl give you an idea to start working on it.


text:
Q: Using blur.js with angularjs I'm trying to make a blurred background efect with angular on a div, something like the image above, for this i'm using blur.js and everything work fine with jquery but the real question is this posible with angularjs, and what is the best way?
I'm really newbie with angular
thanks in advance
here another example of using blurjs http://www.designedbyaturtle.co.uk/2013/blur-a-background-image/
SOLVED (with help of gtramontina):
you can download the code here demo-blurjs-angular
The result (with my images)

This demo contain a issue (that is really of blur.js) like Edd Turtle mention on his post
Important Note: This technique doesn't work with local files and has to run through a server, likewise if the background is hosted on the Amazon S3 service you will need to enable cross-domain calls (CORS)..

A: I suggest you create a directive, restricted to attribute maybe, and have that applying your effect.
Something like this (not tested - and assuming you've included, in this order, jquery, blur.js, then angular;
angular.module('myApp', []).
directive('blurred', function () {
  var directive = { restrict: 'A' };
  directive.compile = function compile (tElement) {
    // taken from blur.js homepage
    tElement.blurjs({
      source: 'body',
      radius: 7,
      overlay: 'rgba(255,255,255,0.4)'
    });
  };
  return directive;
});

Then use it:
<p blurred>lorem ipsum</p>

The point with the order I mentioned above, is that if you include jquery before angular, then angular uses it to wrap its dom elements, otherwise it'll use jqlite.

A: You need to write a angularjs directive for blur.js. Here is an example of how to write a directive for a query plugin:
http://amitgharat.wordpress.com/2013/02/03/an-approach-to-use-jquery-plugins-with-angularjs/


text:
Q: Is there any way to calculate sum of node attributes in NetworkX I have the following network:
df = pd.DataFrame([
    {'Material': 'FG', 'Component': 'COMP1'},
    {'Material': 'FG', 'Component': 'COMP2'},
    {'Material': 'COMP1', 'Component': 'RAW1'},
    {'Material': 'COMP1', 'Component': 'RAW2'},
    {'Material': 'COMP2', 'Component': 'RAW3'},
    {'Material': 'COMP3', 'Component': 'RAW4'}
])
G = nx.from_pandas_edgelist(df, source='Material', target='Component', create_using=nx.DiGraph)

After assigning an attribute to each node
G.nodes['FG']['t'] = 2
G.nodes['COMP1']['t'] = 3
G.nodes['COMP2']['t'] = 5
G.nodes['COMP3']['t'] = 1
G.nodes['RAW1']['t'] = 6
G.nodes['RAW2']['t'] = 4
G.nodes['RAW3']['t'] = 1
G.nodes['RAW4']['t'] = 8

I would like to calculate the maximum sum of attribute 't' from selected node's descendants. In other words, to write a function:
max_att_sum(G, node, att)

whitch for example above returns, i.e.:
[in]  max_att_sum(G, 'COMP1', 't)
[out] 9

9, because 'RAW1' (6) + 'COMP1' (3) > 'RAW2' (4) + 'COMP1' (3)
Does someone have any idea how to approach this problem?

A: I've already found a solution. However, if you know a more effective solution, I will be grateful to learn it.
Step 1. Add weight to each edge:
for e in nx.edges(G):
    if nx.descendants(G, e[1]):
        G[e[0]][e[1]]['weight'] = G.nodes[e[0]]['t']
    else:
        G[e[0]][e[1]]['weight'] = G.nodes[e[0]]['t'] + G.nodes[e[1]]['t']

Step 2. Function to calculate longest path:
def max_att_sum(G, node, attr):
    if nx.descendants(G, node):
        return nx.dag_longest_path_length(G.subgraph(nx.descendants(G, node) | set([node])))
    else:
        return G.nodes[node][attr]


text:
Q: Figuring out how to power a solenoid I have a solenoid with unknown specifications. I have contacted the manufacturer, but they are reluctant when it comes to sharing information about this product.
The problem
I need to trigger a solenoid from my Raspberry Pi. I want to do this by providing power from a DC power supply that came with the original product (The product is not the solenoid). I am using a Raspberry Pi as the control unit and a relay (http://www.songle.com/en/pdf/20084141716341001.pdf).
We also think that our solenoid is similar to this one: http://www.testco-inc.com/ledex-solenoids/B22-254-M-36
What we know
Before starting this project I have measured the Voltage and Current from the original control unit that shipped with the product. When we want to trigger the solenoid, the existing control unit sends 0,355 Amps at 22,1 Volts through the circuit.
I did make my own power cable using the DC power adapter and that provides 0,375 Amps at 24,1 Volts.
But the solenoid does not trigger
Does anyone have any ideas that I might try out?
Other questions
Could the voltage provided be too high?
Does a solenoid requires more current to trigger, and then less to "keep holding?

A: You have not posted a schematic for your question so we can only give general advice on debugging your circuit.

simulate this circuit – Schematic created using CircuitLab
Figure 1. You should have wired the circuit up something similar to this.

Figure 2. You need to troubleshoot in a fashion similar to this.
Add a schematic to your question, do some basic troubleshooting and then modify your post to give the results of your investigation. Post a comment here to alert me to the update.

simulate this circuit
Figure 2. Where to take voltage readings.
If possible, create a program to turn the solenoid off and on every few seconds. Connect your multimeter on DC volts to 'B' and you should see the the voltage switch between 3.3 V and 0 V. Trace through the other points and record the values. Report back.


text:
Q: Excel format rule highlight duplicates based on each date column entry This excel doc is kind of like a guestbook, where there are numerous people's names and the date they visited on (written like 11/17/2014).
The doc is sorted by date, so there is like 100 or 200 names for 11/17/2014, then 200 or so for 11/18/2014...  it goes on for a bunch of consecutive dates.
I want to write a formatting rule where it highlights if there are name duplicates during the duration of each day in the date column.  This is to get rid of duplicates, and have an accurate representation of people visiting per day.
Things I tried:
regular dupe checker in conditional formatting - it is easy to run a dupe check all within one column.  But this is a dupe check based on two columns.  There will be many dupes for visitors returning daily.
The built-in formatting rule custom formula writer - it is easy to say "highlight all occurrences where column A cell and column B cell are equal" but not if the two cell patterns occurred more than once.
The Macro writer - I'm pretty rusty on visualbasic so I might be faster at generic dupe checking 100k or so entries by manually highlighting each day range.
TL;DR - Highlight all where 'name' and 'date' pattern occur more than once.
Any suggestions?

A: conditional formatting formula would be:
=IF(COUNTIFS($A:$A,$A1,$B:$B,$B1)>1, TRUE,FALSE)

dates in column "A", names in column "B", no difference if they are other way around, add conditional formatting whilst having all range selected and active in cell "A1". it WILL be slow though....


text:
Q: Stubbing existing object's method in RSpec test I'm using Mandrill to send emails, and I defined $m in itinializer:
$m = Mandrill::API.new 'XmylongkeygoeshereTg'

I need to test a function that send an email, so I need to stub the $m.messages.send method somehow on that existing object. I read that stub_chain is a messy way to achieve that, but even that didn't work. Another way I tried was with allow($m.messages).to like that:
 it "sends emails to a group" do
   # stub Mandril's email sending, so no actual emails will be sent.
   allow($m.messages).to receive(:send) { nil }
   expect(subject.my_sending_emails_method).to be_true
 end

While there's no error, there's also no effect of stubbing - the emails are still being sent.
Please suggest how to stub it?

A: There might be more than one answer, but what I found working is:
allow($m).to receive_message_chain(:messages, :send) { nil }


text:
Q: How to get all values of variables in class? class NiceClass():
    some_value = SomeObject(...)
    some_other_value = SomeOtherObject(...)

    @classmethod
    def get_all_vars(cls):
        ...

I want get_all_vars() to return [SomeObject(...), SomeOtherObject(...)], or more specifically, the values of the variables in cls.
Solutions tried that didn't work out for me:

*

*return [cls.some_value, cls.some_other_value, ...] (requires listing the variable manually)

*subclassing Enum then using list(cls) (requires using some_value.value to access the value elsewhere in the program, also type hinting would be a mess)

*namedtuples (nope not touching that subject, heard it was much more complicated than Enum)

*[value for key, value in vars(cls).items() if not callable(value) and not key.startswith("__")] (too hacky due to using vars(cls), also for some reason it also includes get_all_vars due to it being a classmethod)

A: There are two ways. This is a straight answer to your question:
class Foo:
    pass

class Bar:
    x: int = 1
    y: str = 'hello'
    z: Foo = Foo()

    @classmethod
    def get_all(cls):
        xs = []
        for name, value in vars(cls).items():
            if not (name.startswith('__') or isinstance(value, classmethod)):
                xs.append(value)
        return xs

This is what I suggest:
from dataclasses import dataclass, fields

class Foo:
    pass

@dataclass
class Bar:
    x: int = 1
    y: str = 'hello'
    z: Foo = Foo()

    @classmethod
    def get_defaults(cls):
        return [f.default for f in fields(cls)]

    @classmethod
    def get_all(cls):
        return [getattr(cls, f.name) for f in fields(cls)]

results:
Bar.get_defaults() == Bar.get_all()
# True -> [1, 'hello', __main__.Foo]

Bar.x = 10
Bar.get_defaults() == Bar.get_all()
# False -> [1, 'hello', __main__.Foo] != [10, 'hello', __main__.Foo]

A: You can create a list of values and define individual attributes at the same time with minimal boilerplate.
class NiceClass():
    (some_value,
     some_other_value,
    ) = _all_values = [
        SomeObject(...),
        SomeOtherObject(...)
    ]

    @classmethod
    def get_all_vars(cls):
        return cls._all_values

The most obvious drawback to this is that it's easy to get the order of names and values out of sync.
Ideally, you might like to do something like
class NiceClass:

    _attributes = {
        'some_value': SomeObject(...),
        'some_other_value': SomeOtherObject(...)
    }

    @classmethod
    def get_all_vars(cls):
        return cls._attributes.values()

and have some way to "inject" the contents of _attributes into the class namespace directly. The simplest way to do this is with a mix-in class that defines __init_subclass__:
class AddAttributes:
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.__dict__.update(cls._attributes)

class NiceClass(AddAttributes):
    # As above
    ...

A: This might sound like a https://xyproblem.info/ but my solution might work in the other case as well. You can get the fields of an object by using __dict__ or vars (which is considered more pythonic given: Python dictionary from an object's fields)
You could do something like:
class ClassTest:
   def __init__(self):
      self.one = 1
      self.two = 2
list(vars(ClassTest()).values())

But you will see that it has some limitations. It doesn't recognize the not in self.variable_name defined variables like you have used above. It might help you nonetheless, because you can simply define them in init.


text:
Q: How do I get the objective-c function call graph in a Xcode-prj I am a rookie to develop a tool to static analysis objective-c file with clang now.
And I want to find a way to get the funtion call graph with text (that I can analyze in the program) in the xcode-project but I can't find a good way to do it.
How do I get the graph with some tools?Or is it having a way that I can analyze the code with clang that provide for me.

A: You can use the inbuilt static analyzer-checker for CLANG which dumps in the output in two formats. 1) Purely screen based 2) in DOT format for image generation.
For example, call graph of a single file in text format
clang -Xclang -analyze -Xclang -analyzer-checker=debug.DumpCallGraph <filename.cpp>

And call graph of a single file in DOT format
clang -Xclang -analyze -Xclang -analyzer-checker=debug.ViewCallGraph <filename.cpp>

For your XCode Project it will be something like this: (more about scan-build here)
scan-build --use-analyzer=clang -enable-checker debug.DumpCallGraph xcodebuild


text:
Q: Hive UNION ALL returning incorrect results I have five tables that I need to union them.
My problem is that the first table has 6362 rows and with the union all I should have 14580 (sum of all five tables) but i still having 6362 with union all.
I try this:
CREATE TABLE example
AS
SELECT * FROM(
SELECT
A,
B,
C,
D
FROM nvl2
UNION ALL
SELECT
A,
B,
C,
D
FROM nvl3
UNION ALL
SELECT
A,
B,
C,
D
FROM nvl4
UNION ALL
SELECT
A,
B,
C,
D
FROM nvl5) TMP;

Also I have tried without the subquery, but the result is the same.
Thank you!


text:
Q: Conditions for a certain parametric matrix to be positive definite The task:

Let's consider matrix $A=\begin{bmatrix}1&a&a\\a&1&a\\a&a&1 \end{bmatrix}$. Show that $A>0$ if and only if $-1<2a<2$.

Solution attempt: By definition $A$ is positive definite iff $\forall_{z\in\mathbb{R}^3}z^{\operatorname{T}}Az>0$.
For $z=\begin{bmatrix}z_1\\z_2\\z_3\end{bmatrix}$, $$\left(z^{\operatorname{T}}A\right)z=\left(z_1^2+az_1z_2+az_1z_3\right)+\left(az_1z_2+z_2^2+az_2z_3\right)+\left(az_1z_3+az_2z_3+z_3^2\right)\\=z_1^2+z_2^2+z_3^2+2a\left(z_1z_2+z_1z_3+z_2z_3\right)>0\\\iff\\z_1^2+z_2^2+z_3^2>-2a\left(z_1z_2+z_1z_3+z_2z_3\right)$$
This is trivially true for $z_1z_2+z_1z_3+z_2z_3\geq0$, so without loss of generality let's assume that $z_1z_2+z_1z_3+z_2z_3<0$, and thus $-(z_1z_2+z_1z_3+z_2z_3)>0$. Therefore we need to prove that:
$$\left({\Large\forall_{z_1,z_2,z_3}}-\frac{z_1^2+z_2^2+z_3^2}{z_1z_2+z_1z_3+z_2z_3}>2a\right)\iff -1<2a<2$$
And this seems false to me. This is because $-\frac{z_1^2+z_2^2+z_3^2}{z_1z_2+z_1z_3+z_2z_3}$ is always $\geq0$. For this reason we have a trivial counterexample, eg when $2a=-1000$ then  $2a\not\in(-1;2)$ but nonetheless $\forall_{z_1,z_2,z_3}-\frac{z_1^2+z_2^2+z_3^2}{z_1z_2+z_1z_3+z_2z_3}>2a$.
I can't find my error; could you kindly help me please?

A:
$z_1^2+z_2^2+z_3^2+2a\left(z_1z_2+z_1z_3+z_2z_3\right)>0\iff z_1^2+z_2^2+z_3^2>-2a\left(z_1z_2+z_1z_3+z_2z_3\right)$
This is trivially true for $z_1z_2+z_1z_3+z_2z_3\geq0$

Not, it is not, since $a$ might be negative.
I suppose showing $A$ is definite positive could be done your way, but it's way too exhausting for me. I'd go with using the fact that $$A\text{ definite positive } \iff \text{ its eigenvalues are } > 0$$
Now choose your favorite way to find the eigenvalues of $A$. Note that the sum of the rows are $2a+1$ so this is one of them ; which by the way leads to $-1<2a$. Now your turn...

A: Let's determine the eigenvalues of $A$. If we can find the conditions for which those eigenvalues are all positive, then we can solve the question.
Let $u \in \mathbb R^3$ be the vector with $1$ for all its components. Then note that $uu^T$ is the $3\times 3$ matrix with $1$ for all its entries.
Therefore $$A=(1-a)I+auu^T$$
Now, notice that $$Au=(1-a)u+au (u^Tu)=(1-a)u+3au=(1+2a)u$$
So $u$ is an eigenvector of $A$ with eigenvalue $(1+2a)$.
Now, let's determine the other eigenvalues of $A$. Suppose $x\in\mathbb R^3$ is orthogonal to $u$, that is $u^Tx=0$, then
$$Ax=(1-a)x+auu^Tx=(1-a)x$$
so $x$ is an eigenvector of $A$ with eigenvalue $(1-a)$. Since the space of vectors $x$ orthogonal to $u$ is of dimension 2, we have now determined that $(1-a)$ is an eigenvalue of multiplicity 2 for $A$.
In summary, the spectrum of $A$ is $(1+2a)$ (multiplicity 1) and $(1-a)$ (multiplicity 2). Consequently, $A$ is positive definite iff $$1+2a>0 \text{ and } 1-a >0$$ that is iff $-1 < 2a < 2$$


text:
Q: Prove that if $A_n \rightarrow \infty$ and $B_n \rightarrow \infty$ then (a) $A_n+B_n \rightarrow \infty$ Let $A > 0$ be given. There exists a natural number $N_1$  Such that $a_n > A$ for all $n > N_1$.
Let $A > 0$ be given. There exists a natural number $N_2$ Such that $b_n > A
 $for all $n >N_2$.
Now let $N = \max\{N_1,N_2\}$. For all $n > N$, $a_n$ + $b_n > 2A$ by previous steps $> A$ as required.
My question is would it have been better to let $A = \frac{A}{2}$ as I would deduce that the sequence $> A$ straight away. Basically, am I wrong for doing what I did ?


text:
Q: When is Onepage SaveOrder being triggered | Magento Plugin I'm trying to find out where and when will this method be triggered. I also created a plugin to do a log on this. But it seems that this is not being triggered when I click the Proceed payment button. I'm not sure where this is called. Below is my code
<!--- di.xml --->
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
   <type name="Magento\Checkout\Controller\Onepage\SaveOrder">
        <plugin name="Custom_Module_Plugin" type="Custom\Module\Plugin\SaveOrder" sortOrder="10" disabled="false"  />
    </type>
</config>

And this is the class that should be displaying the log
namespace Custom\Module\Plugin;

class SaveOrder
{
    public function beforeExecute(\Magento\Checkout\Controller\Onepage\SaveOrder $subject)
    {
        // logging to test override
        $logger = \Magento\Framework\App\ObjectManager::getInstance()->get('\Psr\Log\LoggerInterface');
        $logger->debug("******* THE METHOD HERE ********" . __METHOD__ . ' - ' . __LINE__);
        return null;
    }
}

Now after filling up the shipping details and selecting the payment method. When I click the Proceed button I was expecting that the method will be called but this is not being called. Any idea?
Update:
I also tried doing a plugin for the checkout success page and I was able to intercept and output a log in the console. So this means that there are nothing wrong with how I did the plugin also I tried to modify the vendor/magento/module_checkout script and even if I modify the vendor directly it does not call the function/class


text:
Q: Javascript to check for certain time and return UTC timezone I am runnning Javascript code on a server using a schedule (cron job). I need to check for a certain time (i.e. 8AM) in every timezone every hour. Below is an example of workflow

*

*it is currently 13:00 UTC time

*job runs and executes javascript code (since it runs on an hourly schedule)

*javascript function checks which timezone (UTC) is currently between 7:58-8:02 (the 4 minutes timespan is just in case of a time delay and clock inaccuracy)

*the code finds that (UTC-5:00) Eastern Time (US & Canada) is currently 8:00 and prints the result like 'UTC-5:00'

*then, repeats this same process all over again at the next hour (14:00) - it would find that (UTC-6) Central Time is currently 8:00AM
Any help on this would be greatly appreciated. Please note that I don't need any of the job scheduling stuff. I already have the cron script necessary to run the script. What I am struggling with is the Javascript portion.

A: A problem i see is that you don't have a list of timezones that you care about. In fact i don't even see a good way of obtaining a list of official (or not official) timezones at all, in Javascript. Note that if you run once every 60 minutes you might miss 'odd' timezones such as New Delhi's (they are off by 30 minutes relative to most timezones). So the first step would be to somehow get a list of timezones that you care about. I see 2 methods for this:

*

*Make a list of timezones - simply an array of objects, or something like that, that contain the name of the timezones and their offsets to UTC. Then you can make your checks by constructing Date objects and adding/subtracting these predefined offsets. See the getMinutes(), getHours(), setMinutes(), setHours(), getUTCMinutes(), getUTCHours(), setUTCMinutes(), setUTCHours() functions of Date here.

*Use the moment.js library and this timezone builder they have. Personally i've never used this library so i don't know much about it. You can also check out this nice map.


text:
Q: Prove equation of two Integrals Let $f(x)$ be continuous in $[0,1]$
$$\int_{0}^\pi xf(\sin x) dx = \frac{\pi}{2} \int_{0}^\pi f(\sin x) dx $$
I tried integration by parts and substitution, in vain.
How else could I try to prove this?
Thanks

A: We must prove that $$\int_{0}^{\pi}(x-\frac{\pi}{2})f(\sin x)dx=0$$by substituting $u=x-\dfrac{\pi}{2}$ we have$$\int_{0}^{\pi}(x-\frac{\pi}{2})f(\sin x)dx=\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}uf(\cos u)du=0$$since $uf(\cos u)$ is an odd function and its integral over a symmetric interval is zero

A: Hint. By letting $t=\pi-x$ we get
$$\int_{0}^\pi xf(\sin x) dx=\int_{\pi}^0 (\pi-t)f(\sin (\pi-t)) (-dt).$$
Can you take it from here?


text:
Q: Which is the recommended driver for my graphics card? I have a Dell Latitude E6500 with Ubuntu 12.04 LTS and after a fresh reinstall, I notice some sluggishness, which is probably due to the video drivers.
My graphics card is a NVIDIA Quadro NVS 160M. When I open Additional Drivers, there are various options but I don't know which is the best one. Many thanks.
This is what I get with sudo lshw -c video
  *-display
       description: VGA compatible controller
       product: G98M [Quadro NVS 160M]
       vendor: NVIDIA Corporation
       physical id: 0
       bus info: pci@0000:01:00.0
       version: a1
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress vga_controller bus_master cap_list rom
       configuration: driver=nvidia latency=0
       resources: irq:16 memory:f5000000-f5ffffff memory:e0000000-efffffff memory:f2000000-f3ffffff ioport:df00(size=128) memory:f4000000-f401ffff

A: You will have to try them for yourself. In general, use the stable (rather then experimental) driver with the highest (version) number. If that fails, try the experimental driver.
You can always changes drivers if you do not like the current driver, but it does require rebooting between drivers.


text:
Q: Does mvc4 model object encapsulate sql? I have used asp.net web forms for the last four years. I am trying to familiarise myself with mvc4. Do you put sql code in the model if you are not using an orm like entity framework. For example, if you have a domain object (model class) called person then would you have functions like: person.select, person.update, person.delete.
I am confused because i thought that mvc4 was for the user interface so it doesn't seem right putting sql statements in the model.
I have read plenty of questions on here about mvc4 today but i have not found a specific answer

A: Any CRUD functions are executed from the controller level. You may have a Data Access Layer or Repository abstracting those away but the calls to those functions will be Controller level.
If data needs passed to the view, that data is put into a view model. The view model is then passed to the view to be consumed. The view can only access the data in that model. When you want to update something, you make a call back to the Controllers Update action, the Controller can then handle it from there.
The Model itself is just a POCO (Plain Old CLR Object) which will not have any methods. The @Htmland @Ajax helpers are useful for quickly accessing the Controller Actions. The Ajax ones can return partial views which will assist with updating data on screen without post backs.
There is a pretty good MVC4 (free) video tutorial, split up into small segments so you can easily find the bit you need. Take a look at it here


text:
Q: Mixed integer program python I have this optimization problem where I am trying to maximize column z based on a unique value from column X, but also within a constraint that each of the unique values picked of X added up column of Y most be less than or equal to (in this example) 23.
For example, I have this sample data:
X  Y  Z
1  9  25
1  7  20
1  5  5
2  9  20
2  7  10
2  5  5
3  9  10
3  7  5
3  5  5

The result should look like this:

   X  Y  Z

  1  9  25
  2  9  20
  3  5  5

This is replica for Set up linear programming optimization in R using LpSolve? with solution but I need the same in python.

A: For those who would want some help to get started with pulp in python can refer to http://ojs.pythonpapers.org/index.php/tppm/article/view/111
Github repo- https://github.com/coin-or/pulp/tree/master/doc/KPyCon2009 could be handy as well.
Below is the code in python for the dummy problem asked
            import pandas as pd
            import pulp

            X=[1,1,1,2,2,2,3,3,3]
            Y=[9,7,5,9,7,5,9,7,5]
            Z=[25,20,5,20,10,5,10,5,5]

            df = pd.DataFrame({'X':X,'Y':Y,'Z':Z})
            allx = df['X'].unique()
            possible_values = [(w,b) for w in allx for b in range(1,4)]

            x = pulp.LpVariable.dicts('arr', (allx, range(1,4)),
                                        lowBound = 0,
                                        upBound = 1,
                                        cat = pulp.LpInteger)

            model = pulp.LpProblem("Optim", pulp.LpMaximize)
            model += sum([x[w][b]*df[df['X']==w].reset_index()['Z'][b-1] for (w,b) in possible_values])

            model += sum([x[w][b]*df[df['X']==w].reset_index()['Y'][b-1] for (w,b) in possible_values]) <= 23, \
                                        "Maximum_number_of_Y"

            for value in allx:
                model += sum([x[w][b] for (w,b) in possible_values if w==value])>=1

            for value in allx:
                model += sum([x[w][b] for (w,b) in possible_values if w==value])<=1

            ##View definition
            model

            model.solve()

            print("The choosen rows are out of a total of %s:"%len(possible_values))
            for v in model.variables():
                print v.name, "=", v.varValue

For solution in R
    d=data.frame(x=c(1,1,1,2,2,2,3,3,3),y=c(9,7,5,9,7,5,9,7,5),z=c(25,20,5,20,10,5,10,5,3))
            library(lpSolve)
            all.x <- unique(d$x)
            d[lp(direction = "max",
                 objective.in = d$z,
                 const.mat = rbind(outer(all.x, d$x, "=="), d$y),
                 const.dir = rep(c("==", "<="), c(length(all.x), 1)),
                 const.rhs = rep(c(1, 23), c(length(all.x), 1)),
                 all.bin = TRUE)$solution == 1,]


text:
Q: Displaying text within a vector icon I'm trying to build a custom play / stop button that displays dynamic text in its center. Currently, I'm using the react-native-vector-icons native module to render the icons. The icons I'm using are play-circle-o and stop-circle-o from the FontAwesome fonts library. Could someone guide me whether this is doable and how to proceed to accomplish this?

A: You can use position: 'absolute' style attribute to position the text above the icon.


text:
Q: Python: How to make sorted skip/remove dictionaries without key? Say I have the following array:
pets = [
    {"owner": "Rick", "pet": "Fido"},
    {"owner": "Peter", "pet": "Hunter"},
    {"pet": "Dobbie"},
    {"owner": "Mason", "pet": "Tickles"},
]

I am looking for a (most efficient) way to to remove {"pet": "Dobbie"} entirely from the list, while sorting it.
if I were to do:
sorted(pets, key=lambda k: k["owner"])

I would get an error saying that it didn't find the key in the third element.
If I were to do:
sorted(pets, key=lambda k: k["owner"] if k.get("owner") else "ZZZ")

It would merely add it to the end of the list:
[
    {"owner": "Mason", "pet": "Tickles"},
    {"owner": "Peter", "pet": "Hunter"},
    {"owner": "Rick", "pet": "Fido"},
    {"pet": "Dobbie"},
]

There is also a Plus/Alternative input:
[
    {"owner": "Mason", "pet": "Tickles"},
    {"owner": "Peter", "pet": "Hunter"},
    {"owner": "Rick", "pet": "Fido"},
    {"owner": None, "pet": "Dobbie"},
]

Whereas it now has the key, but a null value. A solution for either this or the original input is equally valid for me.
Any pointers or ideas are greatly appreciated.

A: You could use a generator expression to filter out, then use sorted with a lambda
>>> sorted((i for i in pets if 'owner' in i), key=lambda k:k['owner'])
[{'owner': 'Mason', 'pet': 'Tickles'},
 {'owner': 'Peter', 'pet': 'Hunter'},
 {'owner': 'Rick', 'pet': 'Fido'}]

A: You could use dict.get which you can supply a default return other than it's default None.
sorted(pets, key=lambda x: x.get('owner', 'ZZZ'))

Also operator.methodcaller is the more efficient way than using a lambda:
>>> from operator import methodcaller
>>> sorted(pets, key=methodcaller('get', 'owner', 'ZZZ'))
[{'owner': 'Mason', 'pet': 'Tickles'}, {'owner': 'Peter', 'pet': 'Hunter'}, {'owner': 'Rick', 'pet': 'Fido'}, {'pet': 'Dobbie'}]

You can also use filter to remove any dicts without an owner:
>>> get_owner = methodcaller('get', 'owner')
>>> sorted(filter(get_owner, pets), key=get_owner)
[{'owner': 'Mason', 'pet': 'Tickles'}, {'owner': 'Peter', 'pet': 'Hunter'}, {'owner': 'Rick', 'pet': 'Fido'}]


text:
Q: Resistance D-C circuit This question seems simple, but gives two plausable answers:
On your first day at work as an electrical technician, you are asked to determine the resistance per meter of a long piece of wire. The company you work for is poorly equipped. You find a battery, a voltmeter, and an ammeter, but no meter for directly measuring resistance (an ohmmeter). You put the leads from the voltmeter across the terminals of the battery, and the meter reads 12.5 V . You cut off a 20.0-m length of wire and connect it to the battery, with an ammeter in series with it to measure the current in the wire. The ammeter reads 7.00 A . You then cut off a 40.0-m length of wire and connect it to the battery, again with the ammeter in series to measure the current. The ammeter reads 4.40 A . Even though the equipment you have available to you is limited, your boss assures you of its high quality: The ammeter has very small resistance, and the voltmeter has very large resistance.
From this i took the voltage of the battery to be 12.5 V, and using the relation shape V=IR, i found the resistance of the wire per meter to be 0.089 Ohms using the first set of data, and 0.071 ohms using the second set. Which, if any, is right?

A: This feels like a homework question, so let me give you a hint first:
You actually need both pieces of data to determine the resistance of the ammeter and the internal resistance of the battery. This resistance is in series with the resistance of the wire. Assuming that it is constant, two datapoints are sufficient to solve for the resistance of just the wire (two equations with two unknowns).
Putting the resistance of battery plus ammeter = $R_i$, and the resistance of the external wire $R_1$ and $R_2$ with measured currents $I_1$ and $I_2$, the equations you have to solve are
$$V = I_1\left(R_i + R_1\right)\\
V = I_2\left(R_i+R_2\right)$$
With a little manipulation, you will find that $R_i$ drops out, and you get an expression for $R_1-R_2$. Which gives you the resistance of 20 m of wire.
Note - the ammeter is said to have low resistance, but no mention was made of the voltage across the terminals of the battery with the wire connected across... An ohmmeter does exactly that - it measures both the voltage across the load, and the current through it. If you set up your experiment that way (rather than measuring the unloaded voltage of the battery), then the result would follow more obviously.
Apparently, although "the equipment is of high quality", the process used for measuring could be improved...


text:
Q: Copy Data From Azure Blob Storage to AWS S3 I am new to Azure Data Factory and have an interesting requirement.
I need to move files from Azure Blob storage to Amazon S3, ideally using Azure Data Factory.
However S3 isnt supported as a sink;

https://learn.microsoft.com/en-us/azure/data-factory/copy-activity-overview
I also understand from a variety of comments i've read on here that you cannot directly copy from Blob Storage to S3 - you would need to download the file locally and then upload it to S3.
Does anyone know of any examples, in Data factory, SSIS or Azure Runbook that can do such a thing, I suppose an option would be to write an azure logic-app or function that is called from Data Factory.

A: Managed to get something working on this - it might be useful for someone else.
I decided to write an azure function that uses a HTTP request as a trigger.
These two posts helped me a lot;
How can I use NuGet packages in my Azure Functions?
Copy from Azure Blob to AWS S3 using C#
Please note my answer to the Nuget packages if you are using Azure functions 2.x.
Here is the code - you can modify the basis of this to your needs.
I return a JSON Serialized object because Azure Data Factory requires this as a response from a http request sent from a pipeline;
#r "Microsoft.WindowsAzure.Storage"
#r "Newtonsoft.Json"
#r "System.Net.Http"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.Storage.Blob;
using System.Net.Http;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfer;
using Amazon.S3.Util;

public static async  Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("Example Function has recieved a HTTP Request");

    // get Params from query string
    string blobUri = req.Query["blobUri"];
    string bucketName = req.Query["bucketName"];

    // Validate query string
    if (String.IsNullOrEmpty(blobUri) || String.IsNullOrEmpty(bucketName)) {

        Result outcome = new Result("Invalid Parameters Passed to Function",false,"blobUri or bucketName is null or empty");
        return new BadRequestObjectResult(outcome.ConvertResultToJson());
    }

    // cast the blob to its type
    Uri blobAbsoluteUri = new Uri(blobUri);
    CloudBlockBlob blob = new CloudBlockBlob(blobAbsoluteUri);

    // Do the Copy
    bool resultBool = await CopyBlob(blob, bucketName, log);

    if (resultBool) {
        Result outcome = new Result("Copy Completed",true,"Blob: " + blobUri + " Copied to Bucket: " + bucketName);
        return (ActionResult)new OkObjectResult(outcome.ConvertResultToJson());
    }
    else {
        Result outcome = new Result("ERROR",false,"Copy was not successful Please review Application Logs");
        return new BadRequestObjectResult(outcome.ConvertResultToJson());
    }
}

static async Task<bool> CopyBlob(CloudBlockBlob blob, string existingBucket, ILogger log) {

        var accessKey = "myAwsKey";
        var secretKey = "myAwsSecret";
        var keyName = blob.Name;

        // Make the client
        AmazonS3Client myClient = new AmazonS3Client(accessKey, secretKey, Amazon.RegionEndpoint.EUWest1);

        // Check the Target Bucket Exists;
        bool bucketExists = await AmazonS3Util.DoesS3BucketExistAsync (myClient,existingBucket);

        if (!bucketExists) {
            log.LogInformation("Bucket: " + existingBucket + " does not exist or is inaccessible to the application");
            return false;
        }

        // Set up the Transfer Utility
        TransferUtility fileTransferUtility = new TransferUtility(myClient);

        // Stream the file
        try {

            log.LogInformation("Starting Copy");

            using (var stream = await blob.OpenReadAsync()) {

                // Note: You need permissions to not be private on the source blob
                log.LogInformation("Streaming");

                await fileTransferUtility.UploadAsync(stream,existingBucket,keyName);

                log.LogInformation("Streaming Done");
            }

            log.LogInformation("Copy completed");
        }
        catch (AmazonS3Exception e) {
                log.LogInformation("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
        catch (Exception e) {
                log.LogInformation("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
                return false;
        }

        return true;
    }

public class Result {

    public string result;
    public bool outcome;
    public string UTCtime;
    public string details;

    public Result(string msg, bool outcomeBool, string fullMsg){
        result=msg;
        UTCtime=DateTime.Now.ToString("yyyy-MM-dd h:mm:ss tt");
        outcome=outcomeBool;
        details=fullMsg;
    }

    public string ConvertResultToJson() {
        return JsonConvert.SerializeObject(this);
    }
}

A: You can use Skyplane to copy data across clouds (110X speedup over CLI tools, with automatic compression to save on egress). To transfer from Azure blob storage to S3 you can call one of the commands:
skyplane cp -r az://azure-bucket-name/ s3://aws-bucket-name/
skyplane sync -r az://azure-bucket-name/ s3://aws-bucket-name/

A: ADF now includes SFTP as a sink. From the same link provided in the question (supported as a sink is the far-right column):

Using the AWS Transfer family you can set up an SFTP server and add a user with an SSH public key, then use that configuration to set up an SFTP connection from ADF that will connect directly to an S3 bucket.

A: Download Files From Azure Storage using AzCopy into a temporal local repository
You can download the files from Azure Cloud storage to your local system, just follow the below command, use the recursive flag to copy all the files
azcopy /Source:[source_container_url] /Dest:[local_file_path] /Sourcekey:[source_storage_account_access_key] /s

Upload Local Files to Amazon S3 using aws s3 cp command
 aws s3 cp local_file_path s3://my-bucket/ --recursive