text:
Q: Web-scraping with Python to extract microdata for each page from a sitemap.xml I'm trying to extract name, brand, prices, stock microdata from pages extracted from sitemap.xml
But I'm blocked with the following step, thank you for helping me as I'm a newbie I can't understand the blocking element

*

*Scrape the sitemap.xml to have list of urls : OK

*Extract the metadata : OK

*Extract the product schema : OK

*Extract the products not OK

*Crawl the site and store the products not OK

*

*Scrape the sitemap.xml to have list of urls : OK

import pandas as pd
import requests
import extruct
from w3lib.html import get_base_url
import urllib.request
from urllib.parse import urlparse
from bs4 import BeautifulSoup
import advertools as adv
proximus_sitemap = adv.sitemap_to_df('https://www.proximus.be/iportal/sitemap.xml')
proximus_sitemap = proximus_sitemap[proximus_sitemap['loc'].str.contains('boutique')]
proximus_sitemap = proximus_sitemap[proximus_sitemap['loc'].str.contains('/fr/')]

*

*Extract the metadata : OK

def extract_metadata(url):

    r = requests.get(url)
    base_url = get_base_url(r.text, r.url)
    metadata = extruct.extract(r.text,
                               base_url=base_url,
                               uniform=True,
                               syntaxes=['json-ld',
                                         'microdata',
                                         'opengraph'])
    return metadata
metadata = extract_metadata('https://www.proximus.be/fr/id_cr_apple-iphone-13-128gb-blue/particuliers/equipement/boutique/apple-iphone-13-128gb-blue.html')
metadata

*

*Extract the product schema : OK

def get_dictionary_by_key_value(dictionary, target_key, target_value):
    for key in dictionary:
        if len(dictionary[key]) > 0:
            for item in dictionary[key]:
                if item[target_key] == target_value:
                    return item
Product = get_dictionary_by_key_value(metadata, "@type", "Product")
Product

*

*Extract the products not OK => errormessage = errorkey 'offers'

def get_products(metadata):

    Product = get_dictionary_by_key_value(metadata, "@type", "Product")

    if Product:

        products = []

        for offer in Product['offers']['offers']:
            product = {
                'product_name': Product.get('name', ''),
                'brand': offer.get('description', ''),
                'availability': offer.get('availability', ''),
                'lowprice': offer.get('lowPrice', ''),
                'highprice': offer.get('highPrice', ''),
                'price': offer.get('price', ''),
                'priceCurrency': offer.get('priceCurrency', ''),
            }

            products.append(product)

        return products

*

*Crawl the site and store the products not OK as blocked during previous step

def scrape_products(proximus_sitemap, url='url'):

    df_products = pd.DataFrame(columns = ['product_name', 'brand', 'name', 'availability',
                                          'lowprice', 'highprice','price','priceCurrency'])

    for index, row in proximus_sitemap.iterrows():

        metadata = extract_metadata(row[url])
        products = get_products(metadata)

        if products is not None:
            for product in products:
                df_products = df_products.append(product, ignore_index=True)

    return df_products
df_products = scrape_products(proximus_sitemap, url='loc')
df_products.to_csv('patch.csv', index=False)
df_products.head()

A: You can simply continue by using the advertools SEO crawler. It has a crawl function that also extracts structured data by default (JSON-LD, OpenGraph, and Twitter).
I tried to crawl a sample of ten pages, and this what the output looks like:
adv.crawl(proximus_sitemap['loc'], 'proximums.jl')
proximus_crawl = pd.read_json('proximums.jl', lines=True)
proximus_crawl.filter(regex='jsonld').columns

Index(['jsonld_@context', 'jsonld_@type', 'jsonld_name', 'jsonld_url',
       'jsonld_potentialAction.@type', 'jsonld_potentialAction.target',
       'jsonld_potentialAction.query-input', 'jsonld_1_@context',
       'jsonld_1_@type', 'jsonld_1_name', 'jsonld_1_url', 'jsonld_1_logo',
       'jsonld_1_sameAs', 'jsonld_2_@context', 'jsonld_2_@type',
       'jsonld_2_itemListElement', 'jsonld_2_name', 'jsonld_2_image',
       'jsonld_2_description', 'jsonld_2_sku', 'jsonld_2_review',
       'jsonld_2_brand.@type', 'jsonld_2_brand.name',
       'jsonld_2_aggregateRating.@type',
       'jsonld_2_aggregateRating.ratingValue',
       'jsonld_2_aggregateRating.reviewCount', 'jsonld_2_offers.@type',
       'jsonld_2_offers.priceCurrency', 'jsonld_2_offers.availability',
       'jsonld_2_offers.price', 'jsonld_3_@context', 'jsonld_3_@type',
       'jsonld_3_itemListElement', 'jsonld_image', 'jsonld_description',
       'jsonld_sku', 'jsonld_review', 'jsonld_brand.@type',
       'jsonld_brand.name', 'jsonld_aggregateRating.@type',
       'jsonld_aggregateRating.ratingValue',
       'jsonld_aggregateRating.reviewCount', 'jsonld_offers.@type',
       'jsonld_offers.lowPrice', 'jsonld_offers.highPrice',
       'jsonld_offers.priceCurrency', 'jsonld_offers.availability',
       'jsonld_offers.price', 'jsonld_offers.offerCount',
       'jsonld_1_itemListElement', 'jsonld_2_offers.lowPrice',
       'jsonld_2_offers.highPrice', 'jsonld_2_offers.offerCount',
       'jsonld_itemListElement'],
      dtype='object')

These are some of the columns you might be interested in (containing price, currency, availability, etc.)

jsonld_2_description
jsonld_2_offers.priceCurrency
jsonld_2_offers.availability
jsonld_2_offers.price
jsonld_description
jsonld_offers.lowPrice
jsonld_offers.priceCurrency
jsonld_offers.availability
jsonld_offers.price
jsonld_2_offers.lowPrice

0
nan
nan
nan
nan
nan
nan
nan
nan
nan
nan

1
Numéro 7
EUR
OutOfStock
369.99
nan
nan
nan
nan
nan
nan

2
nan
nan
nan
nan
Apple
81.82
EUR
InStock
487.6
nan

3
nan
nan
nan
nan
nan
nan
nan
nan
nan
nan

4
nan
nan
nan
nan
Huawei
nan
EUR
OutOfStock
330.57
nan

5
nan
nan
nan
nan
Apple
81.82
EUR
LimitedAvailability
487.6
nan

6
Apple
EUR
InStock
589.99
nan
nan
nan
nan
nan
99

7
Apple
EUR
LimitedAvailability
589.99
nan
nan
nan
nan
nan
99

8
nan
nan
nan
nan
nan
nan
nan
nan
nan
nan

9
nan
nan
nan
nan
nan
nan
nan
nan
nan
nan


text:
Q: Calling a member Function (size) of a Referenced Vector Throwing Error I'm trying to pass a vector to a function (printGrid) and have it print out the size of the vector. The vector is being passed by reference. When I try to compile, I get the error:
std::vector<char,std::allocator<char>>::size': non-standard syntax; use '&' to create a pointer to member

This is the relevant part of the program in question:
void printGrid(const std::vector<char>& grid, int width) {
    std::cout << grid.size;
}

int main() {

    int width, height;
    std::cin >> width >> height;

    std::vector<char> grid = getGrid(width, height);

    printGrid(grid, width);

    return 1;
}

A: You need to put parentheses after the size function, e.g.:
cout << grid.size();

Otherwise the compiler thinks you're trying to access a member variable named "size" instead of the member function of the same name.

redpajama_set_name: RedPajamaStackExchange


text:
Q: One maxlength for multiple text fields Hi say I have two text fields. I want to have just one maxlength for both of them. Wherein, for example 300 is the maxlength. And that is for both text fields. Is it possible to have 1 maxlength for multiple fields?

A: Edit:
You will need to use jquery/javascript and client side validation.  As a starting point
Something like
$('#text_field_1, #text_field_2').blur(function(){
  if($('#text_field_1').val() + $('#text_field_2').val() > 300){
    alert("Text Field max length has been reached");
  }
});

Building on that example you'll want to have a listener on form submission $().submit that will return false, show an error message, and stop submitting the form if the max length is greater that allowed.


text:
Q: A rope is cut into two piece. Find the probability that the shorter piece is 1/3 the size of the larger piece. The full question is: A rope of length L is cut at a random point. Find the probability that the ratio of the length of the
shorter piece of rope to the length of the longer piece of rope is less than 1/3.
So I started by saying that X is uniformly distributed over (0,L) and we're trying to find $P\left \{ X <\frac{L}{3} \right \}$.
So I said the probability density function is $$f(x) = \left\{\begin{matrix}\frac{1}{L} &0 < x < L \\ 0 & otherwise\end{matrix}\right.$$
and so
$$P\left \{ X <\frac{L}{3} \right \} = \int_0^\frac{L}{3} \frac{1}{L} dx$$
However this doesn't seem right to me. Am I on the right track?

A: Imagine your rope as one unit long. Putting it on the number line, the endpoints will be at 0 and 1. Cutting at $1/4$, the ratio is $1:3$, and any cuts left of that also give smaller ratios. By symmetry, the cuts at greater or equal to $3/4$ also give $3:1$ ratios. Thus, we have two quarter length segments that work, in a segment of unit length, giving the probability  $1/2$.


text:
Q: How can I add search help in a SAP Fiori Worklist Application created using CDS annotations? I want to add search help to a field in a SAP Fiori Worklist Application created using CDS annotations. What annotations should I use?

A: You create a value help view and associate it by using annotation @Consumption.valueHelp:
define view C_A_VIEW as select from I_A_VIEW as A
  association [0..1] to I_VALUEHELP_VIEW as _VALUEHLEP
    on $projection.....
{

    @Consumption.valueHelp: '_VALUEHLEP'
    A.Field

}

It is documented in here https://help.sap.com/viewer/cc0c305d2fab47bd808adcad3ca7ee9d/7.5.9/en-US/8a8415c033d441b2b079a53aff129463.html


text:
Q: Anonymous class derived from RequestListener My Project was using Glide V3.7.0. I need to add a listener. But it says Anonymous class derived from RequestListener. I tried updating my glide version. To do this I went to build.gradle: app and simply changed the version number from 3.7.0 to 4.8.0 and performed Gradle sync. But it did not help. Also tried changing Glide.with to GlideApp.with but it doesn't even recognize that keyword...
Glide.with(getApplicationContext())
                    .load(Uri.parse(url.get((int)(i))))

                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(Exception e, Object model, Target<Drawable> target, boolean isFirstResource) {

                            return false; // important to return false so the error placeholder can be placed
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, boolean isFromMemoryCache, boolean isFirstResource) {

                            return false;
                        }
                    })

                    .into(IMGS[i]);

I am new to Android Development. Please Help.

A: Easy Fix : Method 1
To fix this error just place your mouse cursor over new RequestListener() line and press [alt + enter] you will see a prompt and from that select Implement methods.
It will regenerate the methods for you .... and delete old methods
Method 2
Change your glide version in Gradle Use this two dependency
 annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
 implementation 'com.github.bumptech.glide:glide:4.9.0'

and replace your code with below code
Glide.with(getApplicationContext())
            .load(Uri.parse(url.get((int)(i))))
            .listener(new RequestListener<Drawable>() {

                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                    return false;
                }

            })

            .into(IMGS[i]);

I recommend you to try the 1st method ...these are the most common problems that you face during development


text:
Q: How to trigger a Jenkins pipeline build for every artifact uploaded to Jfrog Artifactory I have set the Artifact Trigger for a jenkins multi branch pipeline and the schedule is as follows

I have noticed that the Artifactory Trigger only triggers 1 Jenkins build based on the last/ latest artifact uploaded after polling even if there were multiple artifacts uploaded within the polling period/ time i.e within the 10mins of the polling schedule in the above picture, but I would like a build to be triggered for every artifact that is uploaded to the "watched paths". Can someone please help me on how to achieve this?

A: We have encountered similar issues. One solution / workaround was to create a "handler" pipeline for our main pipeline. This would effectively be the pipeline triggered by artifacts, and would then have logic to split apart the triggers , and for each artifact, would trigger our main pipeline, passing in the parameters required from properties on the artifact.


text:
Q: Does `.git` directory get shared? is .git directory local or shared directory?
There's config files I want to change but don't want to share.
google won't answer me.

A: To me this question doesn't have any sense.
.git folder is a folder like others (but will keep all repository files) so, is it shared or local? It depends: it could be local if you (or your team buddies) have different locations for the repo. It could be shared if all of you point at the same physical resource.

A: If your question is "Does the .git folder get added to the repository?" then the answer is no. The .git folder is local to that specific checked out location and is not part of the repository that is shared.

A: .git is a Local folder which contains all the repository data + your local config per repository.
The folder does not pushed to the server and cannot be accessed outside of your repo (of course you can use it as network path but this is not the question)

By the way, there was a security issue with the folder name which was fixed.
The bug was that you could rename the folder in any anme combination (came casee) and this way you can "share" and expose your .git folder.
http://git-blame.blogspot.co.il/2014/12/git-1856-195-205-214-and-221-and.html

Exception:
If using the git new-workdir command its "creating" the same repo under a new location. git does it by using a symbolic link to the original git folder.


text:
Q: Compare $L_2$ norm of Fourier series of $ f$ and $ f'$ Let $f$ be a periodic continuous function on $[0,2\pi]$ with $f'$ continuous.
Let the Fourier series of $f$ be ${a_o\over 2} + \sum_{n=0}^\infty(a_n\cos nx  + b_n \sin nx).$
Is it true that $$||f-{a_0\over2}||^2 \leq ||f'||$$ , where ||.|| is the $L_2$ norm?
I have tried some functions and this seems to hold, but I don't know how to prove it.
My guess is to compare the Fourier series of $f$ and $f'$.
Let $s_n$ be the n-th partial sum of the Fourier series of $f$, then in $L_2$ $s_n$ converges to $f$. Let $\sum$ be the infinite summation part of the Fourier series ($s_n-{a_0\over2}$) then
$$||f-{a_0\over2}|| \leq ||f-s_n||+||\sum||$$
but since $||f-s_n||$ can be made as small as we want,
$$||f-{a_0\over2}|| \leq ||\sum||$$.
If I can compare $\sum_{n=0}^\infty(a_n\cos nx  + b_n \sin nx)$ and $f'$I can get somewhere....

A: I think I got it!
So I followed user1952009's suggestion.
Consider the Fourier series of f':
$$ {A_o\over 2} + \sum_{n=0}^\infty(A_n\cos nx  + B_n \sin nx)$$
Now, $A_o=\int_0^{2\pi}f'd{x}=f(2\pi)-f(0)=0  $ by periodicity of $f$
$A_n=\int_0^{2\pi}f'\cos{(nx)} dx$ integrating by part, this can be written in terms of f and you find $A_n=-nb_n$. Similarly $B_n=na_n$.
$f'$ is Riemann integrable, so its Fourier series converges to $f'$ in $L_2$ norm.
Also, $||\sin nx||=||\cos nx||$. Clearly $|a_n|\leq |na_n|$.
Therefore
$$||f-{a_n \over 2}||^2=||\sum_{n=0}^\infty(a_n\cos nx  + b_n \sin nx)||^2=\sum_{n=0}^\infty(|a_n|^2||\cos nx||^2  + |b_n|^2 ||\sin nx||^2) \leq $$
$$\leq\sum_{n=0}^\infty(|na_n|^2||\sin nx||^2  + |nb_n|^2 ||\cos nx||^2= ||f'||^2$$
And the desired inequality follows.
Let me know if you think that this works.

A: I believe your proof works, but it's probably overkill (for my taste at least). Once you realise that $\frac{a_0}{2}$ is just the mean value of $f$, you will see that your claimed inequality is nothing but the Poincaré(-Wirtinger) inequality, so you are done.


text:
Q: Execute part of the code in 32bit and other part from 64bit power-shell in one session I am starting a powershell session to a remote computer(oracle db server), to execute some queries.Before the actual deployment, there are some pre-deployment tests that are executed like checking if connection to the database is ok, ssh connection is ok, sftp.. In that session a lot of powershell scripts are getting called. I'll try to explain the flow as much as possible. First of all, we are loading those PS scripts we use later like this:
LogInfo("Load DatabaseActions")
$incFile = Resolve-Path .\deployment\DatabaseActions.ps1
. $incFile

Write-Host "Setup Environment"
LogInfo("Load SSH")
$incFile = Resolve-Path .\deployment\SSH.ps1

This is part of the code from the DatabaseActions.ps1:
Add-Type -Path "C:\somePath\Oracle.DataAccess.dll"
Function TestDBConnection($connectString)
{
  //Code for opening a connection to the database
}

After scripts are loaded, tests are getting executed one by one. There is a separate script for each test(db connection, ssh, sftp). First test is for connection to the database. There is a scripts called DatabaseConnectionTest.ps1 where I am just calling a function from DatabaseActions.ps1 :
$Result = TestDBConnection $RunSettings.ConnectionString

The problem here is that Oracle-Client.dll needs to be executed in a 32bit powershell and the other tests in 64bit powershell. When I start a 64bit session, Oracle dll is not loaded correctly. When I start a 32bit powershell, Oracle dll is good, but then it falls on ssh test since I am using a 64bit ssh client.I need to somehow switch between 32bit and 64bit powershell but without breaking something. :)I don't know if that is possible.
I tried creating an alias when starting the 64bit session like this :
Set-Alias Start-PowerShell32 "$env:windir\syswow64\WindowsPowerShell\v1.0\powershell.exe"

and then wrap the code in  DatabaseActions.ps1 like this:
Start-PowerShell32 {
Add-Type -Path "C:\somePath\Oracle.DataAccess.dll"
Function TestDBConnection($connectString)
{
  //Code for opening a connection to the database
} }

It is not working since it is a new session and it does not know the TestDBConnection function.
Do you have some idea how I can fix this issue?
Thanks


text:
Q: Can't Upload File to Google Cloud Storage with PHP Client Library I want this script to upload a text file to a bucket in my Google Cloud Storage Account.  I'm using the PHP Client Library, specifically the objects.insert method.  The script seems to work up until I actually call the insert method (if I cancel that line out, then I can at least see the results from the var_dump).  If I call the method, I get a HTTP 500 - Internal Server Error (and the file does not make it to my Cloud Storage account).
Some things to note:

*

*This script is for a service account

*The text file is in the same folder as this script

I think there's something wrong with the way I'm calling insert, but I can't figure it out.  I'd appreciate any suggestions on how to make this script work so that the text file uploads.
Here's the code:
<?php
    require_once 'lib/src/Google_Client.php';
    require_once 'lib/src/contrib/Google_StorageService.php';

    define("CLIENT_ID", "MY-CLIENT-ID");
    define("SERVICE_ACCOUNT_NAME", "MY-SERVICE-ACCOUNT-NAME");

    define("KEY_FILE", "/path/to/privatekey.p12");

    $client = new Google_Client();
    $client->setApplicationName("Google Cloud Storage Test Connection");

    session_start();
    if (isset($_SESSION['token'])) {
        $client->setAccessToken($_SESSION['token']);
    }

    // Load the key in PKCS 12 format (you need to download this from the
    // Google API Console when the service account was created.
    $key = file_get_contents(KEY_FILE);
    $client->setAssertionCredentials(new Google_AssertionCredentials(
        SERVICE_ACCOUNT_NAME,
        array('https://www.googleapis.com/auth/devstorage.read_write'),
        $key)
    );

    $client->setClientId(CLIENT_ID);

    //Define Storage Service
    $storageService = new Google_StorageService($client);
    $objects = $storageService -> objects;

    //Define Storage Object
    $gso = new Google_StorageObject ();
    $gso-> setName('myObj');

    //Define Storage Object Media
    $gsoMedia = new Google_StorageObjectMedia ();
    $gsoMedia-> setContentType('text/plain');
    $gsoMedia-> setData(file_get_contents('Test.txt'));

    //Link Storage Object Media to Storage Object
    $gso-> setMedia($gsoMedia);

    //Upload to Cloud Storage
    $result = $objects->insert(/*MY_BUCKET*/,  $gso);

    var_dump($gso);

?>


text:
Q: "Literal" and numerical numbering of chapters I ask another question related to this one
"Literal" numbering of chapters but not in contents
which was not "precise"... This question is the exact one, with an example...
This example gives me chapters "one" and "two" in the first pages of chapters (and this is what I want), and in the contents "1" and "two" (and this isn't what I want..). I want to obtain the same thing in the text but, in the contents, "1" and "2".. Then how to change the chapterhead, to be numeric.. I want it "1.1" for the section 1 not "one.1" like in my example.
I write all the packages for preventing eventual conflicts because I use all this packages in my book (of probability in arabic)...
    \documentclass[14pt,a4paper]{extbook}%{article}%

    \usepackage{titletoc}
    \usepackage{etoolbox}
    \usepackage{multicol}
    \usepackage{amsmath,amssymb}
    \usepackage[most]{tcolorbox}
    \usepackage{boxedminipage}
    \usepackage{slashbox}
    \usepackage{titlesec}
    \usepackage{enumitem}
    \usepackage{minitoc}
    \usepackage{rotating}
    \usepackage{fmultico}
    \setlength{\columnseprule}{0.1pt}
    \usepackage{fancyhdr}
    \pagestyle{fancy}
    \usepackage{pdflscape}
    \usepackage{array}

    \usepackage{polyglossia}
    \setmainlanguage{english}
    \setotherlanguage[numerals=maghrib]{arabic}

    \makeatletter
    \let\old@makechapterhead\@makechapterhead
    \def\@makechapterhead{\def\thechapter{\words{chapter}}\old@makechapterhead}
    \makeatother

    \newcommand\words[1]{\expandafter\xwords\csname c@#1\endcsname}
    \def\xwords#1{\ifcase#1\or
    one\or
    two\or
    three\or
        \else
        I need more words\fi}

    \begin{document}
    \tableofcontents
    \chapter{Simulation}
    \section{Introduction 1}
    Simulation
    \section{Introduction 2}
    \chapter{Simulation}
      Simulation
     \end{document}

A: Instead of modifying the macro \thechapter that's used inside the macro \@makechapterhead, one could patch \@makechapterhead directly to make it use \words{chapter} instead of \thechapter when typesetting the representation of the chapter's "number". (The patching may be done via a \patchcmd instruction. As it looks like you're loading the etoolbox package anyway, you'll have access to \patchcmd.) By not touching the definition of \thechapter, no downstream complications result in terms of uses of \thechapter in, say, the creation of the table of contents.
Summarizing, I suggest that instead of
\makeatletter
\let\old@makechapterhead\@makechapterhead
\def\@makechapterhead{\def\thechapter{\words{chapter}}\old@makechapterhead}
\makeatother

you execute
% \usepackage{etoolbox} %% uncomment if 'etoolbox' isn't already being loaded
\makeatletter
\patchcmd{\@makechapterhead}{\thechapter}{\words{chapter}}{}{}
\makeatother

Aside: In order to get your code to compile on my system (MacOSX 10.9.2, TeXLive2104/pre with all packages fully up to date), I had to comment out the instruction \usepackage{titletoc} that's in your preamble. It looks like titletoc tries to load the inputenc package, either directly or through a subsidiary package. When compiling a document under XeLaTeX -- which seems to be the case here, since you're also loading polyglossia -- the inputenc package should not be loaded. XeLaTeX (and LuaLaTeX too, for that matter) can handle only one input encoding system: UTF8. I think that until quite recently only a warning message would be issued if you (or one of the packages you specify) loaded inputenc; with the most recent update to TeXLive an outright error message is generated and compilation hangs. Let's all hope that the titletoc package gets upgraded soon to no longer load inputenc (and especially not if running under either XeLaTeX or LuaLaTeX).


text:
Q: Run Five SQL query from a script I have Five SQLquery that I need to run, either Sequentially means one by one or Independently. As currently what I am doing is that, I need to run all those Five SQL query sequentially in one Putty session or I can open five Putty Session and  enter one query each in those five Putty Sessions. So its very tedious and I need to run it manually. So I was thinking to automate the process.
Is there any way using some sort of scripts like Perl Script or Python script from which I can run all my Five queries either Sequentially or Independently?
Queries in my case are little bit complex and long but considering the above scenario I am taking the below five queries as an example- And these Five queries are not related to each other. And also these five SQL queries I am running using Hive.
SELECT * FROM Table1;
SELECT * FROM Table2;
SELECT * FROM Table3;
SELECT * FROM Table4;
SELECT * FROM Table5;

So My Question is how can I do that in any script language? Also I am not specific to any script, Just wanted to know which is better approach in my case. Any code snippets fulfilling my requirement will be appreciated.
I am working with HiveQL and HiveQL syntax is same as SQL Sytnax.
P.S. I am new to all the scripting languages.

A: There are a lot of ways to do this and this is a pretty basic example.  The upshot is that in Perl you control the sequence of execution by simply placing the "execute" commands in the order desired.  I'm assuming you're familiar with Perl DBI and how to connect to your dbase.
#!/usr/bin/perl
use DBI;
use strict;

my $dbh = DBI->connect($your_connect_string) || die qq{Could not connect to $dbase\n};
my $sql_1 = qq{ select * from table1};
my $sql_2 = qq{ select * from table2};
my $sql_3 = qq{ select * from table3};

my $sth_1 = $dbh->prepare($sql_1);
my $sth_2 = $dbh->prepare($sql_2);
my $sth_3 = $dbh->prepare($sql_3);

$sth_1->execute();
$sth_2->execute();
$sth_3->execute();

while (my $hashref_1 = $sth_1->selectrow_hashref()) {
...do something
}

while (my $hashref_2 = $sth_2->selectrow_hashref()) {
...do something
}

while (my $hashref_3 = $sth_3->selectrow_hashref()) {
...do something
}

$sth_1->finish();
$sth_2->finish();
$sth_3->finish();

$dbh->disconnect();

exit;


text:
Q: Percentage Calculation for values less than 1 and greater than 0 I am trying to display the percentage using BigDecimal.
for example if i have to do
    double val = (9522 / total ) * 100;

    System.out.println("Val is :" + val);

where total is 1200000.
I want to display the calculation as a percentage but since the calculation comes to a value less than 0 , I am unable to display the percentage
I also tried
    BigDecimal decimal = new BigDecimal((9522 * 100 ) / total);
    BigDecimal roundValue = decimal.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println("decimal: " + decimal);
    System.out.println("roundValue: " + roundValue);

but with the same result.
How can I display the percentage even if it is in Decimals?

A: The problem is you are doing integer division.
If you want fractional results, you need to do floating point division.
double val = (9522 / (double) total) * 100;

Casting one of your operands to a double will cause Java to perform the correct type of division instead of defaulting to integer division.

A: You have to inform Java that you want at least one of the numerator or denominator treated as a double, to make sure the result is a double.
This will work:
double val = ((double)9522 / total ) * 100;

System.out.println("Val is :" + val);

A:
BigDecimal decimal = new BigDecimal((9522 * 100 ) / total);

This is not how you do operations on BigDecimal: by the time the BigDecimal is constructed, the precision is gone, because the calculation (9522 * 100 ) / total is done at compile time. That's why the result is the same as with integers: in fact, the entire calculation is done in integers.
Here is how you calculate with BigDecimal objects:
BigDecimal decimal = new BigDecimal(9522)
    .multiply(new BigDecimal(100))
    .divide(new BigDecimal(total));

A: If you divide two integer you will get the result truncated. Add a .0 so that it is converted to floating point, and then you will not get a truncated result
new BigDecimal((9522.0 / total) *100);

A: You may be missing a cast.
double val = (9522 / (double)total ) * 100;

System.out.println("Val is :" + val);

My suspect is that total is an int, and hence 9522/1200000 results in an integer, which is truncated to 0 because the operation implies that the result must be smaller than 1. If you convert total to double the result is going to be a double, and you will be able to retain the decimals.


text:
Q: How to unify js files, when is about jQuery plugins On a prestoshop ecommerce site I have some modules which use jQuery plugins. The problem is that i have a lot of file requests and YSlow recommends me to use fewer requests by unifying the .js files.
Can you give me an advice about how can I unify the files used by those modules(which are basicaly jQuery plugins)?

A: It's telling you to use pack multiple javascript files into one. This may or may not be neccesary depending on how you load your files.
If you use something like head.js which loads your files async after the page is loaded then your page won't be blocking whilst your loading so packing them together doesnt matter
Or you can use something like multi-part XHR which will combine them for you. Take a look at supply.js.
Another popular option is require.js (Havn't checked that website in a while. It looks pretty neat. Loving the layout)
If you using a lot of <script src="foo"> in your <head> tag well then that's not a good way to go about it.


text:
Q: Jump in Extrinsic Curvature In the thin shell formalism, the components of the surface stress-energy tensor are found using the next equation:
\begin{equation}
S^{a}_{\, \, \, b} = const\left([K^{a}_{\, \, \, b}] - \delta^{a}_{\, \,\, b}[K] \right) ,\tag{12.125}
\end{equation}
where $K = h^{ab}K_{ab}$ and $[K] = K_{+} - K_{-} $ defines extrinsic curvature's jump.
Moreover, using the following equations, one can easily encounter the extrinsic curvature components:
\begin{equation}
K_{\tau\tau} = -n_{\mu}a^{\mu}
\\
K_{\phi\phi} = - \Gamma^{\mu}_{\phi\phi}n_{\mu}
\end{equation}
However, I am not understanding how to compute the jump after having the expression for the extrinsic curvature. How do you compute this explicitly for any two spacetimes metrics?
Reference:
Padmanabhan's book - "Gravitation: Foundations and Frontiers". The surface stress-energy tensor is defined on page 554.


text:
Q: GLES20.glTexImage2D is occurred GL_OUT_OF_MEMORY on Galaxy Note3(SM-N900L, SDK 5.0) When GLSurfaceView is Created, call GLES20.glGenTextures and then Every time a call GLES20.glDeleteTextures in GLThread, but sometimes, the gl_out_of_memory occurs. How do I solve this problem?
[Error Log]
02-18 11:44:04.317: W/Adreno-GSL(25831): <sharedmem_gpumem_alloc_id:1498>: sharedmem_gpumem_alloc: mmap failed errno 12 Out of memory
02-18 11:44:04.317: E/Adreno-GSL(25831): <gsl_memory_alloc_pure:2042>: GSL MEM ERROR: kgsl_sharedmem_alloc ioctl failed.
02-18 11:44:04.327: I/Timeline(25831): Timeline: Activity_idle id: android.os.BinderProxy@325bb5f9 time:1454439379
02-18 11:44:04.357: W/Adreno-GSL(25831): <sharedmem_gpumem_alloc_id:1498>: sharedmem_gpumem_alloc: mmap failed errno 12 Out of memory
02-18 11:44:04.357: E/Adreno-GSL(25831): <gsl_memory_alloc_pure:2042>: GSL MEM ERROR: kgsl_sharedmem_alloc ioctl failed.
02-18 11:44:04.357: W/Adreno-ES20(25831): <core_glTexImage2D:539>: GL_OUT_OF_MEMORY
02-18 11:44:05.197: E/qdmemalloc(25831): ion: Failed to map memory in the client: Out of memory
02-18 11:44:05.197: E/qdgralloc(25831): Could not mmap handle 0xa1fdaba0, fd=43 (Out of memory)
02-18 11:44:05.197: E/qdgralloc(25831): gralloc_register_buffer: gralloc_map failed
02-18 11:44:05.197: W/GraphicBufferMapper(25831): registerBuffer(0xa1fdaba0) failed -12 (Out of memory)
02-18 11:44:05.197: E/GraphicBuffer(25831): unflatten: registerBuffer failed: Out of memory (-12)
02-18 11:44:05.197: E/Surface(25831): dequeueBuffer: IGraphicBufferProducer::requestBuffer failed: -12
02-18 11:44:05.197: W/Adreno-EGLSUB(25831): <DequeueBuffer:720>: dequeue native buffer fail: Out of memory, buffer=0x0, handle=0x0
02-18 11:44:05.197: E/qdmemalloc(25831): ion: Failed to map memory in the client: Out of memory
02-18 11:44:05.197: E/qdgralloc(25831): Could not mmap handle 0xb3bcb380, fd=49 (Out of memory)
02-18 11:44:05.197: E/qdgralloc(25831): gralloc_register_buffer: gralloc_map failed
02-18 11:44:05.197: W/GraphicBufferMapper(25831): registerBuffer(0xb3bcb380) failed -12 (Out of memory)
02-18 11:44:05.197: E/GraphicBuffer(25831): unflatten: registerBuffer failed: Out of memory (-12)
02-18 11:44:05.197: E/Surface(25831): dequeueBuffer: IGraphicBufferProducer::requestBuffer failed: -12
02-18 11:44:05.197: W/Adreno-EGLSUB(25831): <DequeueBuffer:720>: dequeue native buffer fail: Out of memory, buffer=0x0, handle=0x0
02-18 11:44:05.197: W/Adreno-EGL(25831): <qeglDrvAPI_eglSwapBuffers:3702>: EGL_BAD_SURFACE
02-18 11:44:05.197: W/OpenGLRenderer(25831): swapBuffers encountered EGL_BAD_SURFACE on 0x877fea00, halting rendering...
02-18 11:44:06.207: A/libc(25831): Fatal signal 11 (SIGSEGV), code 1, fault addr 0x54 in tid 25848 (RenderThread)

[When surface is created, call glTexImage2D.]
    mProgram_y_texture = GLES20.glGetUniformLocation(mProgram, "y_texture");
    mYTextureHandle = new int[1];
    GLES20.glGenTextures(1, mYTextureHandle, 0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mYTextureHandle[0]);
    GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, VIDEO_WIDTH, VIDEO_HEIGHT, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);

    mProgram_u_texture = GLES20.glGetUniformLocation(mProgram, "u_texture");
    mUTextureHandle = new int[1];
    GLES20.glGenTextures(1, mUTextureHandle, 0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mUTextureHandle[0]);
    GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, VIDEO_WIDTH/2, VIDEO_HEIGHT/2, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);

    mProgram_v_texture = GLES20.glGetUniformLocation(mProgram, "v_texture");
    mVTextureHandle = new int[1];
    GLES20.glGenTextures(1, mVTextureHandle, 0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mVTextureHandle[0]);
    GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, VIDEO_WIDTH/2, VIDEO_HEIGHT/2, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);

[When surface is destroy, call glDeleteTextures.]
    GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mYTextureHandle[0]);
    GLES20.glDeleteTextures(1, mYTextureHandle, 0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);

    GLES20.glActiveTexture(GLES20.GL_TEXTURE1);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mUTextureHandle[0]);
    GLES20.glDeleteTextures(1, mUTextureHandle, 0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);

    GLES20.glActiveTexture(GLES20.GL_TEXTURE2);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mVTextureHandle[0]);
    GLES20.glDeleteTextures(1, mVTextureHandle, 0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);


text:
Q: Trouble using openpyxl to read row values I am trying to read the row values in two columns (A and B).
This is my current code:
import openpyxl as op
wb = op.load_workbook ('Canopy\Scripts\De Velliers.xlsx')
ws = wb['Sheet1']; colA = ws.columns[1]; row = ws.row[1]
for row in ws.rows:
    for cell in row:
        C_vel = np.array(cell.value) / (A_c * rho)
wb = op.load_workbook('Canopy\Scripts\De Velliers.xlsx')
ws = wb['Sheet1']; colB = ws.columns[2]; row = ws.row[2]
for row in ws.row:
    for cell in row:
        P_s3 = P_t1 * np.array(cell. value)
        P_t3 = P_s3 + (rho * sp.sqrt(C_vel))/2.
        print (cell. value)
    print "C_vel:",C_vel
    print "P_s3:",P_s3
    print "P_t3:",P_t3
    print"_________"
wb = op.load_workbook('Canopy\Scripts\De Velliers.xlsx')
ws = wb['Sheet4']
for row in ws.rows:
    for cell in row:
        T_t3 = ((((P_t3 / P_t1)**((k - 1) / k)) - 1) * T_t1)/(cell.value) + T_t1
        T_s3 = T_t3 - (sp.sqrt(C_vel)) / (c_p * 2.)
        rho_ new = P_s3 / (T_s3 * R)
        print (cell. value)
        print "T_t3:",T_t3
        print "T_s3:", T_s3
        print "rho_new:", rho_new
        print "________"

When I try and run this, I get the following error:

     25 wb = op.load_workbook ('Canopy\Scripts\De Velliers.xlsx')
---> 26 ws = wb['Sheet1']; colA = ws.columns[1]; row = ws.row[1]
     27 for row in ws.rows:
     28     for cell in row:

Attribute Error: 'Worksheet' object has no attribute 'row'

How would I fix this?

A: The exception could be avoided by replacing 'row' with 'rows' in a couple of places.e.g.:
...
wb = op.load_workbook('Canopy\Scripts\DeVelliers.xlsx')
ws = wb['Sheet1']
colA = ws.columns[1]
row = ws.rows[1]
for row in ws.rows:
    for cell in row:
        ...


text:
Q: Configure SLURM sview to show recent history Does anyone know of a way to configure the built in SLURM GUI sview so that it will show recent job history? I'd like to have it show something like the last 6 hours of jobs or at least display the jobs a little longer before they disappear after completion.
The motivation for this is that user of the cluster often run array jobs wth thousands of sub-jobs. Some of these sub-jobs often fail due to something in the data that needs to be investigated. Having a GUI for this has been an imense help. We used to have a custom scheduler and GUI for this but have moved to more opensource software.


text:
Q: Using Matlab 32 and 64 bit on the same machine, how do you store settings in a different place? For various reasons I need to do things in 64 bit and 32 bit Matlab.
Much to my chagrin... I found out recently that settings for both 32 and 64 bit Matlab are both stored in the same folder:
C:\Users\$USERNAME\AppData\Roaming\MathWorks\MATLAB\$MATLAB_VERSION

Here is a simple thing that I try to do... and it fails because they share the same settings folder!:

*

*open Matlab 32 bit

*choose a 32 bit C/C++ compiler

*compile some code

*close Matlab 32 bit

*open Matlab 64 bit

*compile the same code

*ERROR... your compiler is not 64 bits...

I get an error in the 64 bit matlab... because !ARG! as soon as I change something in matlab 32 bit... it changes the same setting in Matlab 64 bit! In this case the setting is the C/C++ compiler.

Is there any way to have all your settings for Matlab 32 bit and 64 bit in separate folders?

*

*If yes, how?

*If no, using the same settings folder is there a workaround for this specific setting (compopts.bat stores the C/C++ compiler you choose)?

Here is an example of what I would like to have:
C:\Users\$USERNAME\AppData\Roaming\MathWorks\MATLAB\$MATLAB_VERSION\32bit
C:\Users\$USERNAME\AppData\Roaming\MathWorks\MATLAB\$MATLAB_VERSION\64bit

A: You can change the location of the preferences directory using the MATLAB_PREFDIR environment variables. Refer to this technical solution for a complete instructions.


text:
Q: Ubuntu 20.04 Bluetooth File Transfer Too Slow . Despite reasonable internet speed (see details below), I have a serious issue with getting acceptable file transfer speed from my Bluetooth connection.
I see mention of something similar here. But no suggested solution.
Every file of a few MB takes ~ 5 minutes or more.
Can anyone offer any remedy for this ?
EDIT
$ lspci -knn | grep Net -A3

02:00.0 Network controller [0280]: Qualcomm Atheros QCA9377 802.11ac Wireless Network Adapter [168c:0042] (rev 31)
Subsystem: Dell QCA9377 802.11ac Wireless Network Adapter [1028:1810]
Kernel driver in use: ath10k_pci
Kernel modules: ath10k_pci
03:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL810xE PCI Express Fast Ethernet controller [10ec:8136] (rev 07)

$ lsusb

Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 007: ID 0cf3:e009 Qualcomm Atheros Communications
Bus 001 Device 005: ID 0bda:0129 Realtek Semiconductor Corp. RTS5129 Card Reader Controller
Bus 001 Device 003: ID 1bcf:28c1 Sunplus Innovation Technology Inc. Integrated_Webcam_HD
Bus 001 Device 010: ID 413c:2003 Dell Computer Corp. Keyboard
Bus 001 Device 009: ID 0a46:9621 Davicom Semiconductor, Inc. Integrated_Webcam_HD
Bus 001 Device 008: ID 0bc2:5030 Seagate RSS LLC FreeAgent GoFlex Upgrade Cable STAE104
Bus 001 Device 006: ID 0d8c:0008 C-Media Electronics, Inc. USB 2.0 Hub [MTT]
Bus 001 Device 004: ID 045e:07fd Microsoft Corp. Nano Transceiver 1.1
Bus 001 Device 002: ID 1a40:0201 Terminus Technology Inc. FE 2.1 7-port Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub


text:
Q: Insert html element into a previously dynamically inserted element? Here is my first question here, I've been looking for an small clue on many researches but didn't found any piece of answer, hope it's not a silly thing.
I'll try to be straight: I'm working on a website dealing with xml files (data is stored in an array then displayed and fully editable).
Until now and despite some troubles I figured out, everything works fine.
I loop on my array to get all the required string then create jQuery object (such as $("<input id='xxx' value='yyy' />") that I appendTo a specific div).
At first start, I have an empty #insertXml div (written in my html).
One my xml files parsed and my array ready, I dynamcically create a #content div appended to my #insertXml, then for each index I'll have its key written in a #keyInput" div (dynamic insert, only once), then 1st value in a #lang1 div (still dynamic insert), 2nd in #lang2 div, etc.
lang1, lang2, etc are variables, so it's written:
 $("<input .../>").appendTo("#"+langN);

where langN changes on each loop.
Everything works FINE!... at 1st display :/
The trouble is, when I'm using my function that creates new data.
I work first on a modal window, to retrieve user values through the listener function, then pass it to another function that pushes it in my array.
I debugged it, that works, my array is correctly updated.
Then I want to simply refresh my page, so I try, the same way I did previously for my whole data, to append a few inputs.
It works then correctly on my #keyInput div, but NOT on my #lang divs !?!?!
No matter how I try (even forgetting jQuery and using html document.xxx functions), no way.
While debugging, all my variables are OK, it just does nothing when doing the "appendTo", except once for the keyInput div.
I tried then to remove the #content div and relaunch the whole displayInit() method (heavy operation but, just to see) and same damn problem: only the #keyInput is correctly refreshed.
The only thing I've read that may be interesting, is that dynamically created elements (through script) are not registered in the DOM, so it can't be found.
BUT in that case, none of my display attempts should work, so?
In advance, THANK YOU very much for taking care about my nightmare.
Attached: my html + JS function.my DOM

function displayInsert() {

    var firstLang = stripXmlExtension(paths[0]); // same keys on every language, so we grab the 1st one
    var lastKeyIndex = mapXml[firstLang].key.length - 1;
    var keyToInsert = mapXml[firstLang].key[lastKeyIndex]; // == last insertion

    var inputKey = "<input size=35 type=text id=k" + lastKeyIndex + " value=" + stripHTML(keyToInsert.replace(/ /g, " ")) + " readonly />";
    // while appending tag to the HTML content page, we add a dblclick listener that will morph the input into a textarea when double dblclicked
    $(inputKey).css("margin-bottom", "15px").dblclick(function (e) {
        e.preventDefault();
        tempEditId = $(this).attr('id');
        $(".modal-body").html("<textarea cols='65' rows='10' id='txt" + $(this).attr('id') + "'>" + $(this).val() + "</textarea>");
        $("#modalEdit #btn-correct").css("display", "none");
        $("#modalEdit").modal({backdrop: "static"});
    }).appendTo("#keyInput");

    for (var i = 0; i < paths.length; i++) {
        var lang = stripXmlExtension(paths[i]);
        var lastValueIndex = mapXml[lang].value.length - 1;
        var valueToInsert = mapXml[lang].value[lastValueIndex]; // == last insertion

        var inputValue = "<input size=35 type=text id=" + lang + "---" + lastValueIndex + " value=" + stripHTML(valueToInsert.replace(/ /g, " ")) + " readonly />";
        // while appending tag to the HTML content page, we add a dblclick listener that will morph the input into a textarea when double clicked
        $(inputValue).css("margin-bottom", "15px").dblclick(function (e) {
            e.preventDefault();
            tempEditId = $(this).attr('id');
            $(".modal-body").html("<textarea cols='65' rows='10' id='txt" + $(this).attr('id') + "'>" + $(this).val() + "</textarea>");
            $("#modalEdit #btn-correct").css("display", "none");
            $("#modalEdit").modal({backdrop: "static"});
        }).appendTo("#" + lang);

    }

}

A: OMG, I'm ashamed.
My problem came from an input generated in a modal window that took the same id that was duplicated...
I was hoping it would be a little more complicated ^^
Solved!


text:
Q: How to iterate through a tree structure using a generator? I'm trying to figure out how to implement a function in a tree node which returns all its descendant leaves (whether direct or indirect). However, I don't want to pass a container in which the leaf nodes will be put recursively (the tree could be huge), instead I'd like to use a generator to iterate through the tree. I've tried a few approaches but none of them worked so far. This one is the closest I've come to a possible solution:
    public interface ITreeNode
    {
        IEnumerable<ITreeNode> EnumerateLeaves();
    }

    class Leaf : ITreeNode
    {
        public IEnumerable<ITreeNode> EnumerateLeaves()
        {
            throw new NotImplementedException();
        }
    }

    class Branch : ITreeNode
    {
        private List<ITreeNode> m_treeNodes = new List<ITreeNode>();

        public IEnumerable<ITreeNode> EnumerateLeaves()
        {
            foreach( var node in m_treeNodes )
            {
                if( node is Leaf )
                    yield return node;
                else
                    node.EnumerateLeaves();
            }
        }
    }

But this is not working either. What am I doing wrong? Seems like calling .EnumerateLeaves recursively won't work if there's a yield statement in the same function.
Any help would be very much appreciated. Thanks in advance.
Edit: I forgot to mention that a branch can have either leaves or branches as children, hence the recursion.

A: Here's how you should implement Branch.EnumerateLeaves:
public IEnumerable<ITreeNode> EnumerateLeaves()
{
    foreach( var node in m_treeNodes )
    {
        if( node is Leaf )
            yield return node;
        else
        {
            foreach (ITreeNode childNode in node.EnumerateLeaves())
                yield return childNode;
        }
    }
}

A: lassevk is right - one potential issue with that method, however, is that recursively calling into enumerables can yield O(n^2) performance. If this is an issue, then you should instead factor the recursion out and use an internal stack.
public IEnumerable<ITreeNode> EnumerateLeaves()
{
    Stack<ITreeNode> workStack = new Stack<ITreeNode>(m_treeNodes);

    while(workStack.Count > 0) {
        var current = workStack.Pop();
        if(current is Leaf)
            yield return current;
        else {
            for(n = 0; n < current.m_treeNodes.Count; n++) {
                workStack.Push(current.m_treeNodes[n]);
            }
        }
    }
}

This should perform the same function, without the recursion.
Edit: Daniel Plaisted posted in a comment about a bigger problem with recursively calling Enumerators, summed up in a post on the MSDN Blogs regarding iterators. Thanks Daniel. =)
Another Edit: Always remember that code simplicity can be more important than performance, especially if you expect others to maintain your code. If you don't expect your tree to grow very large, use the recursion method lassevk outlined in his answer.

A: The other answers are correct, but the pattern of having a yield return inside a foreach loop with a recursive call will make the running time to iterate through the tree something like O(number of nodes * average depth of a node).  See this blog post for more details about the problem.
Here is an attempt at a generator which is efficient in both runtime and memory usage:
class Node
{
    List<Node> _children;

    public bool IsLeaf { get { return _children.Count == 0; } }

    public IEnumerable<Node> Children { get { return _children; } }

    public IEnumerable<Node> EnumerateLeaves()
    {
        if (IsLeaf)
        {
            yield return this;
            yield break;
        }

        var path = new Stack<IEnumerator<Node>>();

        path.Push(Children.GetEnumerator());

        while(!path.Empty)
        {
            var cur = path.Pop();
            if (cur.MoveNext())
            {
                path.Push(cur);
                if (cur.IsLeaf)
                {
                    yield return cur;
                }
                else
                {
                    path.Push(cur.Children.GetEnumerator());
                }
            }

        }
    }

}


text:
Q: Was the painting "In the Ring of Saturn" by artist Andrei Sokolov used as a book cover? The BBC News exposé 'Our Saturn years'; Cassini's epic journey to the ringed planet, told by the people who helped make it happen includes the text:

"The Voyagers gave us a really wonderful impression of Saturn. It's a beautiful gas giant," says Nasa's director of planetary science Jim Green.
Prof Andrew Coates, from the Mullard Space Science Laboratory in Surrey, UK, agrees:
"Saturn is the most spectacular planet in our Solar System. The incredible rings, visible even in binoculars or a small telescope, make it stand out compared to all the rest."
In places, the rings are only about as tall as a telephone pole. Yet from end-to-end they are more than 20-times as wide as the Earth.
They have influenced decades of science fiction book covers.

Followed by a reproduction of the painting In the Ring of Saturn by artist Andrei Sokolov.
The painting is stylized and shows a spacecraft beaming something to the planet Saturn, with the suggestions of the planet's rings in the background, all in various shades of green and yellow.
Question: But there is no indication that this art is related to any specific book cover. So I would like to ask; Was the painting "In the Ring of Saturn" by artist Andrei Sokolov used as a book cover? If not, was any of this artist's work used in book covers?
Per Wikimedia Commons:

Andrei Konstantinovich Sokolov (1931—2007) was a Soviet and Russian science fiction painter and a graphic artist, a designer of stamps, an architect.

For some other examples of work by the artist, see for example

*

*https://vintagetech.blognook.com/?s=sokolov&submit=Go

*http://www.artnet.com/artists/andrei-sokolov/

*https://gizmodo.com/the-first-spacewalker-and-his-painter-friend-created-th-1729276737

*https://www.pinterest.com/nikosretiniotis/andrei-sokolov/

*https://commons.wikimedia.org/wiki/Category:Andrei_Konstantinovich_Sokolov

Reproduction of "In the Ring of Saturn" by artist Andrei Sokolov
(Topfoto)

A: The ISFDb page for Andrei Konstantinovich Sokolov (Андрей Константинович Соколов) does not list "In the Ring of Saturn" as one of the works that have been published as cover art.


text:
Q: Is there a single word for "Parts of Speech"? Is there a word that refers to the different forms of a word, or a word's following four parts of speech—verb, adverb, noun, adjective?
For example:

confuse verb confusedly adverb confusion noun confused, confusing, & confusable adjective

What word should be inserted if I wanted to say: "I'm looking for all the [forms/parts of speech] of confuse." or "I want to use a [form/part of speech] of startle that is not in the dictionary; bestartlement, for example."
I think the answer to my question might be here Word form dictionary/system/tool, but I couldn't understand the descriptions of Inflection and Conjugation well enough to be certain that either is the word I am looking for.
EDIT:After reading through the links on declensions and derivational morphology provided by Benjamin Harman and John Lawler respectively, I agree with Lawler that declensions are not what I am talking about. I think I want to refer to the set of any given content word's semantically associated parts of speech, i.e. all the various derivational morpheme altered forms of a given content word (and sometimes to just one of a content word's corresponding forms in a different lexical category).All these terms are new to me, so I apologize if I used any of them incorrectly.

A: Different variations of a non-verb word by parts of speech, by syntactic function, are called "declensions," so "confusedly" is the adverbial declension, "confusion" is the nounal declension, "confused" an adjectival declension. Another word used is "case," like "happy," "happily," and "happiness" are all different cases (i.e., adjective, adverb, and noun, respectively).
When the word is a verb, the variations are called "conjugations."
https://en.wikipedia.org/wiki/Declension


text:
Q: DAX to perform count after grouping rows I have a single table in the Azure SQL database. I want to connect it to Power BI using DirectQuery and perform a calculation - count the number of jobs that failed and that are successful.
SQL  Table
There is a parent job and a child job. If the status of all child jobs is "finished", parent job is successful else, parent job failed.
In the screenshot above, job1 and job4 are successful since both of their child jobs finished but job2 and job3 failed. So, I want to create a card showing 2 jobs failed and 2 jobs successful.
I know how to do this calculation in SQL using window functions but I am struggling in DAX. I don't want to create a view in SQL and then connect to PowerBI. I want to do this with the help of DAX. Can anyone help me?

A: create a table/matrix with parent_jobName on the row, and add a measure like:
status_parent = if( contains( [SQL Table Name], [status], "Error")
     ,"Failed"
     ,"Successful"),

A: sample data I am using:

Add a new column with if condition like:
value = if ( 'datadax (2)'[Status] = "finished", 1, 0)

It will create a value column where it will insert 1 when status is "finished" and 0 if other than finished.

from visualization select card >> select column which you want to show on card >> select Count (Distinct)

In filters (For Failed jobs):

*

*add your newly created column

*set filter type >> Advance filtering

*Show items when the value >> is >> 0 (For Failed jobs)

*Show items when the value >> is greater than >> 0 (For successed jobs)

OUTPUT


text:
Q: discord py в цикле не меняется embed Делаю розыгрыш в боте и столкнулся с проблемой то, что он изменяет текст один раз, а надо, что бы изменял embed до конца розыгрыша каждые 2 секунды, не изменяется только embed
    con = connect["time"]

    while connect["time"] != 0:

        embed = discord.Embed( title = f"""
Победитель получит: {text}
Победителей: {win}
Секунды: {connect["time"]} | Минуты: {round(connect["time"] / 60)} | Часа: {round(connect["time"] / 60 / 60)}
        """, colour = 0xe821f8 )

        await message.edit( embed = embed )
        con -= 2

        winer.update_one( {"guild": ctx.guild.id}, {"$set": {"time": con}} )
        await asyncio.sleep(2)

вот часть кода

A: Из кода не выяснил, устанавливаете ли вы переменной message само сообщение или как.
Но лично у меня всё заработало с подобным кодом:
@client.command()
async def test(ctx):
    con = 10
    embed = discord.Embed( title = f"""
Победитель получит: {random.randint(1,100)}
Победителей: {random.randint(1,100)}
Секунды: {random.randint(1,100)} | Минуты: {random.randint(1,100)} | Часа: {random.randint(1,100)}
        """, colour = 0xe821f8 )
    message = await ctx.send(embed=embed)
    while con != 0:
        embed = discord.Embed( title = f"""
Победитель получит: {random.randint(1,100)}
Победителей: {random.randint(1,100)}
Секунды: {random.randint(1,100)} | Минуты: {random.randint(1,100)} | Часа: {random.randint(1,100)}
        """, colour = 0xe821f8 )
        await message.edit( embed = embed )
        con -= 1
        await asyncio.sleep(1)

Прошу также обратить внимание что я убрал код для pymongo и заменил во всех эмбедах всё на рандомные числа ради примера, по своему опыту знаю что иногда mongodb не выводит ошибку, перепроверьте код, удалив код для pymongo, или же перепроверьте, устанавливаете ли вы переменную message, а именно: message = await ctx.send(embed=embed)


text:
Q: fixed points for the following system I'm trying to find the fixed point for the system (see document attached) but it seems so hard and I don't know what Im doing wrong. Can somebody help me with this. I need to find the to look for the value where the bifurcation occur (for that process i need to evaluate the jacobian matrix for the system on the fixed points and the looks for the delta, which is really easy) but this is the only part where I'm stuck. Please see document attached

A: We need to simultaneously solve:
$$\begin{align*} a(1 - u) - u v^2 = 0 \\ u v^2 -(a + k) v = 0 \end{align*}$$
From the first equation we get:
$$u = \dfrac{a}{a+v^2}$$
Substituting this into the second equation yields:
$$-(a+k) v + \dfrac{a v^2}{a + v^2} = -(a+k)(v)(a + v^2) + av^2 = 0$$
Expanding and simplifying, yields:
$$ -a^2 v-a k v-a v^3+a v^2-k v^3=0$$
The three roots (critical or fixed points) to this cubic are:
$$v = 0, \dfrac{a-\sqrt{-4 a^3-8 a^2 k+a^2-4 a k^2}}{2 (a+k)}, \dfrac{a+\sqrt{-4 a^3-8 a^2 k+a^2-4 a k^2}}{2 (a+k)}$$
Now, we need to find the corresponding $u$ values using either equation. We have:
$$u = \dfrac{a}{v^2 + a}$$

*

*At $v = 0$, we get $u = 1$.

*At $v = \dfrac{a-\sqrt{-4 a^3-8 a^2 k+a^2-4 a k^2}}{2 (a+k)}, u = \dfrac{a+\sqrt{a \left(-4 a^2-8 a k+a-4 k^2\right)}}{2 a}$

*At $v = \dfrac{a+\sqrt{-4 a^3-8 a^2 k+a^2-4 a k^2}}{2 (a+k)}, u = \dfrac{a-\sqrt{a \left(-4 a^2-8 a k+a-4 k^2\right)}}{2 a}$


text:
Q: How do I get the default value for a field in a Django model? I have a Django model with some fields that have default values specified.  I am looking to grab the default value for one of these fields for us later on in my code.  Is there an easy way to grab a particular field's default value from a model?

A: TheModel._meta.get_field('the_field').get_default()

A: As of Django 1.9.x you may use:
field = TheModel._meta.get_field('field_name')
default_value = field.get_default()

A: if you don't want to write the field name explicitly, you can also do this:
MyModel._meta.get_field(MyModel.field.field_name).default

A: You can get the field like this:
myfield = MyModel._meta.get_field_by_name('field_name')

and the default is just an attribute of the field:
myfield.default

A: If you need the default values for more than one field (e.g. in some kind of reinitialization step) it may be worth to just instantiate a new temporary object of your model and use the field values from that object.
temp_obj = MyModel()
obj.field_1 = temp_obj.field_1 if cond_1 else 'foo'
...
obj.field_n = temp_obj.field_n if cond_n else 'bar'

Of course this is only worth it, if the temporary object can be constructed without further performance / dependency issues.


text:
Q: How to add hashtag and mention in textInput react-native I'm facing this challenge when client want me to add mention and hashtag to the textInput, will look like this

I tried some lib , but they are not give me the result like this, so i tried to make a custom one,, but i wonder how can we detect when we type "@" or "#", i struggle for days because of this, please help

A: Regex is perfect for this:
inputStr.replace(/(?<=#).*?(?=( |$))/g, hashtag => {
    // do something with hashtag, e.g. "fenty"
    return hashtag;
});

Breaking the regex down:
(?<=#)       # match anything preceded by "#"
.*?          # match everything without greedy matching
(
  ?=         # match anything with the following after it:
  ( |$)      # space or end of text
)

g (global) means to match all occurrences.
The same thing can be done for @:
inputStr.replace(/(?<=@).*?(?=( |$))/g, mention => {
    // mention == "fenty"
    return mention;
});

You can also perform manipulations on, say, the hashtags to turn them into links or whatever:
const newString = inputStr.replace(/(?<=#).*?(?= )/g, hashtag => {
    // do something with hashtag, e.g. "fenty"
    return `<a href="/hashtags/${hashtag}">${hashtag}</a>`; // "stunna new year highlighter  fenty @fenty"
});

Demo:

"hello #yes no #maybe so #ionter6 #000".replace(/(?<=#).*?(?=( |$))/g, hashtag => {
    console.log("Hashtag from post:", hashtag);
    return hashtag;
});

A: I think you should give this library a try, I did the same using
react-native-controlled-mentions


text:
Q: Excel: Display only values in cells with specific values only in certain ranges I would appreciate any help with this.
I have a schedule of employees that is site centric and I want to adapt it to be employee centric as well.  I am attempting to adapt the sheet so that the only cells with selected name (in a toggle) display. I need it to be reference only the ranges that have the employee names.
Here's my concept for the functions:
for ranges (C5:I8,C10:I13C15:I15,C17:I18,C20:I23,C26:I28,C30:I31,C33:I33)
if cell contains 'Name selected in toggle',
leave name in that cell
if not displayed in cell hide contents or change font to white "something that makes the cells look empty"
if row does not contain any cells with the 'Name selected in toggle'
hide row
Example:
1                Title
2          11/01 11/02 11/03
3           Mon   Tue  Wed
4          Work Location 1
5     8-4    Bob   Ann  Bob
6     4-12   Tim   Ann  Tim
7     12-8   Ann   Tim  Bob
8          Work Location 2
9     8-4    Pat   Pat  Pat
10    4-12   Gus   Bob  Gus
11    12-8   Eve   Eve  Eve
There is a toggle where I select 'Bob" as the value for the function criteria. It needs to work in ranges as the rows: Title, Dates, Days, and Work Locations and the column with the shift times need to be displayed (static).  It needs to hide other values in the ranges.  It needs to hide the columns that do not contain 'Bob'.
Example output:
1                Title
2          11/01 11/02 11/03
3           Mon   Tue  Wed
4          Work Location 1
5     8-4   Bob         Bob
7     12-8              Bob
8          Work Location 2
10    4-12        Bob
Thank you!
John
I tried using the filter function but it disallows ranges.


text:
Q: Bay Trail Z3740 and Ubuntu issues, any help? I am having trouble to run Ubuntu on my LG SlidePad 2 with Z3740 processor.
The problem is that I can't find a way to boot the pendrive on it. I can get into the BIOS/UEFI but there is no way I can boot the pen drive. I tried to follow the same procedures of Asus T100 but it isn't the same, so it didn't work.
Is there any way I can boot up from the pendrive?

A: I got to boot my 11T540 through a pendrive following this procedure 'https://github.com/lopaka/instructions/blob/master/ubuntu-14.10-install-asus-x205ta.md
Now I can not make the wifi device work properly.
If you get to use the wireless device, please answer my question regarding 11T540.
thanks

A: Use Rufus http://rufus.akeo.ie/ to create bootable drives to install any OS on PCs with UEFI. Disable "secure boot" in BIOS.


text:
Q: Exporting raster to rendered image using standalone script in QGIS? Using standalone script I loaded a layer, and now I need to export it as an image. See code below:
 from qgis.core import *
 from qgis.utils import *
 from qgis.gui import *
 from PyQt4.QtGui import *
 from PyQt4.QtCore import *
 QgsApplication.setPrefixPath("C:\OSGeo4W\apps\qgis", True)
 qgs = QgsApplication([], True)
 qgs.initQgis()
 rasterpath = "E:/MODIS DATA/2016/15-10-2016/TIRUNELVELI.tif"
 lyr = QgsRasterLayer(rasterpath, "TIRUNELVELI")
 QgsMapLayerRegistry.instance().addMapLayer(lyr)

I checked the post QGis Save Raster as Rendered Image, but the code is executed using Python console. If I use the same code it shows an error:

NoneType object has no attribute 'clone'.

Updated Code after Comment
from qgis.core import *
from qgis.utils import *
from qgis.gui import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
rasterpath = "E:/MODIS/TIRUNELVELI.tif"
layer = QgsRasterLayer(rasterpath, "TIRUNELVELI")
QgsMapLayerRegistry.instance().addMapLayer(layer)
uri = "E:/MODIS/newStyleqgis.qml"
layer.loadNamedStyle(uri)
extent = layer.extent()
width, height = layer.width(), layer.height()
renderer = layer.renderer()
provider=layer.dataProvider()
crs = layer.crs().toWkt()
pipe = QgsRasterPipe()
pipe.set(provider.clone())
pipe.set(renderer.clone())
file_writer = QgsRasterFileWriter('E:/MODIS/abcd.tif')
file_writer.writeRaster(pipe,
                       width,
                       height,
                       extent,
                       layer.crs())

updated but showing error as shown :

A: From Python: Attribute Error - 'NoneType' object has no attribute 'something':

NoneType means that instead of an instance of whatever Class or Object
  you think you're working with, you've actually got None. That usually
  means that an assignment or function call up above failed or returned
  an unexpected result.

The error is probably given by the path of your layer because there is a blank space.
For example, try to add an underscore to the pathname (you need to make the change in the system folder too):
rasterpath = "E:/MODIS_DATA/2016/15-10-2016/TIRUNELVELI.tif"

or change the input folder.

A: Along with what HowToInQGIS mentioned,  I think you also need to include the QgsApplication class in your updated code. Putting this together with your code works (note that you may need to escape your backslashes "C:\OSGeo4W\apps\qgis" to something like "C:/OSGeo4W64/apps/qgis"):.
Here is the complete code which worked for me:
from qgis.core import *
from qgis.utils import *
from qgis.gui import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *

QgsApplication.setPrefixPath("C:/OSGeo4W64/apps/qgis", True)
app = QApplication([], True)
QgsApplication.initQgis()

rasterpath = "C:/Users/You/Desktop/New folder/vir.tif"
layer = QgsRasterLayer(rasterpath, "TIRUNELVELI")
QgsMapLayerRegistry.instance().addMapLayer(layer)
uri = "C:/Users/You/Desktop/style.qml"
layer.loadNamedStyle(uri)
extent = layer.extent()
width, height = layer.width(), layer.height()
renderer = layer.renderer()
provider=layer.dataProvider()
crs = layer.crs().toWkt()
pipe = QgsRasterPipe()
pipe.set(provider.clone())
pipe.set(renderer.clone())
file_writer = QgsRasterFileWriter('C:/Users/You/Desktop/result.tif')
file_writer.writeRaster(pipe,
                       width,
                       height,
                       extent,
                       layer.crs())

Note the 0 at the end indicating it was successfully written.


text:
Q: vector of strings error there is an error in the following code that I don't get , I tried debugging but it wasn't useful .
#include <iostream>
#include <algorithm>
#include <string>

    using namespace std;

    int main()
    {
        int n;

        string s ;
        cin>>s;

        vector<string> v ;

        for (int i=0;i<s.size()-1;i+=2)
        {
            v[i]=s.substr(i,2);
        }

    }

A: There are couple issues:

*

*Missing #include <vector> - on some compiler it may work without it.

*size of the vector is zero so operator[] leads to segmentation fault

*-1 in loop is not needed

*even if size of vector is ok, indexing by i is not desired since it is incremented by 2, so you are skipping elements.

So it should go like this:
for (size_t i=0; i<s.size(); i+=2)
{
    v.push_back(s.substr(i,2));
}


text:
Q: Parameter selection in multiple kernel learning I just got to apply multiple kernel learning to my data recently. I have data from three sources, so I want to learn three RBF kernels for each data source. But the MKL algorithms so far I know assume that the kernel parameters and the cost are fixed. When I used SVM with single RBF kernel before, I need to make a grid search for two variables (gamma and C) and do cross validation as well. I wonder how people in the application field usually deal with the kernel parameters. Take an n+1 dimension exhaustive search for n kernels? Use heuristic? Or make it into a convex problem to solve? Is there any method or tool related? Thanks.

A: One way to do it is to represent a kernel as a convex combination of kernels having different parameters and have MKL algorithm decide which kernels to use. Here is great paper on MKL algorithms:
Sonnenburg, Sören, et al. "Large scale multiple kernel learning." The Journal of Machine Learning Research 7 (2006): 1531-1565.

A: The easiest practical approach is to find suitable kernel parameters per data set separately, as you usually would when you only have a single source. When combining the kernels later on, there is usually some form of weighting involved.
The improvement of finding kernel parameters globally (e.g. for each data source based on the accuracy of the final MKL model) is almost always small/insignificant. I therefore recommend finding kernel parameters per single data source and then using a weighting scheme.
Finding kernel parameters globally does not generally lead to a convex optimization problem, and that is the key issue (for example, consider the RBF kernel). Finding weights per kernel is convex (often formulated as a QCLP).


text:
Q: Connect Android to MySQL So I'm really new to this.
I modified the code of new project in Android Studio to work on HTML5 with webview class, I have created a database with phpmyadmin and I created a search engine php to retrieve data from the database.
My project is really about connecting the android application with the database, which contains a list of products like catalog, at the end it must be able to retrieve each record individually and allow user feedback. With all that I've gotten to the point that I do not know how I can connect android application with the database using all the php code that I created earlier as a seeker (with modifications or something). As I said, I'm new to all this so I do not know if use the webview to bring the search application created with php can be considered correct in android application project, important factor in the case of a school project.
Thank you very much for any comments or help that you can offer.
EDIT*
Now I have this:
<?php

$server = "localhost";
$user = "root";
$pass = "XXX";
$bd = "XXX";

$conexion = mysqli_connect($server, $user, $pass,$bd)
or die("Ha sucedido un error inexperado en la conexion de la base de datos");

$input=$_REQUEST['input'];

$sql="SELECT * FROM registres where id=".$input;
mysqli_set_charset($conexion, "utf8"); //formato de datos utf8

if(!$result = mysqli_query($conexion, $sql)) die();

$registres = array();

while($row = mysqli_fetch_array($result))
{
    $id=$row['id'];
    $isbn=$row['ISBN'];
    $titol=$row['titol'];
    $autor=$row['autor'];
    $any=$row['any'];
    $descripcio=$row['descripcio'];
    $format=$row['format'];

    $registres[] = array('id'=> $id, 'ISBN'=> $isbn, 'titol'=> $titol, 'autor'=> $autor, 'any'=> $any, 'descripcio'=> $descripcio, 'format'=> $format);

}

//desconectamos la base de datos
$close = mysqli_close($conexion)
or die("Ha sucedido un error inexperado en la desconexion de la base de datos");

$json_string = json_encode($registres);
echo $json_string;

?>

But but the system returns the following:
Notice: Undefined index: input in E:\xampp\htdocs\json4\api\api3.php on line 13
Thanks!

A: you can not run PHP code in WebView. but you can use HTML5 and Javascript. To connect database,

*

*First You need to make API, for that create a page called search.php and host that to your server eg. www.yourdomain.com/search.php

*Now code search.php to connect database and get results from mysql, store them in array and finally output as JSON

search.php
<?php
$con=mysql_connect(host,user,pass);
$input=$_REQUEST['input'];

$sql="select * from table where field=".$input; //change table and field

$result=mysql_query($sql,$con);

$rows=array();

while($row=mysql_fetch_array($result)){
    $rows[]=$row;
}

echo json_encode($rows); //it outputs results as JSON
?>

// Now Your android Application can use AJAX call using javascript to make request to the URL, use JQUERY Mobile for easy AJAX call
www.yourdomain.com/search.php?input=some+text
and AJAX call returns JSON data that can be parsed and displayed in webview.

A: Hope you don't do this. Sqlite is the recommendation of database from Android. So don't try to use other databases. All the others are too heavy for Android.


text:
Q: Call javascript function on all events on a page I am trying to write a framework and I should be able to capture all the user events on a page like text change, button click, drop down selected, iframe loaded, page loaded.
I have all the code to capture the event, but that would be called only when we call that function onchange or onclick events.
@Html.TextBox("tLoanNo",null, new { @onchange = "onChangeOfValue(this);" })
<button id="Search" class="tracker" onclick="onChangeOfValue(this);">Search</button>

Is there a way to call my function without adding extra code? I have tried something like this:
$("input[type='text']").change(function() {
  var oldValue = $(this).attr("defaultValue");
  var newValue = $(this).val();
  var name = $(this).attr("name");
  if(oldValue != newValue) {
    LogEvents(name + " Text Changed", ' from :' + oldValue + ' To :' + newValue,@((int)TrackerHitTypeLID.Event),@((int)TrackerCategoryLID.Text),232);
  }
});

However it does not get called all times.


text:
Q: NodeJS: Capturing a stereo PCM wave stream into mono AudioBuffer I'm recording audio from nodejs using node-microphone (which is just a javascript interface for arecord), and want to store the stream chunks in an AudioBuffer using web-audio-api (which is a nodejs implementation of the Web Audio API).
My audio source has two channels while my AudioBuffer has only one (in purpose).
This is my working configuration for recording audio with arecord through my USB sound card (I'm using a Raspberry pi 3 running on Raspbian buster):
arecord -D hw:1,0 -c 2 -f S16_LE -r 44100

Running this command with an output path and playing the resulting wav file with aplay works just fine. So node-microphone is able to record audio with these parameters, and at the end I get a nodejs readable stream flowing wave data.
But
I'm struggling doing the bridge from the stream chunks (Buffer instances) to the AudioBuffer. More precisely; I'm not sure of the format of the incoming data, not sure of the destination format, and not sure of how I would do the conversion whatever:
The stream chunks are Buffers so they also are Uint8Arrays. Regarding my configuration, I guess they are binary representations of 16 bits signed integers (little endian, I don't know what it means).
The AudioBuffer holds multiple buffers (one per channel, so only one in my case) that I can access as Float32Arrays by calling AudioBuffer.prototype.getChannelData(). MDN also says:

The buffer contains data in the following format: non-interleaved IEEE754 32-bit linear PCM with a nominal range between -1 and +1, that is, 32bits floating point buffer, with each samples between -1.0 and 1.0.

The point is to find what I have to extract from the incoming Buffers and how I should transform it so it's suitable for the Float32Array destination (and remains valid wave data), knowing that the audio source is stereo and the AudioBuffer isn't.
My best contender so far was the Buffer.prototype.readFloatLE() method whose name looks like it would solve my problem, but this wasn't a success (just noise).
My first try (before doing research) was just to naively copy buffer data to Float32Array and interleaving indexes to handle stereo/mono conversion. Obviously it mostly produced noise but I could hear some of the sound I recorded (incredibly distorted but surely present) so I guess I should mention that.
This is a simplified version of my naive try (I'm aware this is not meant to work well, I just include it in my question as a base of discussion):
import { AudioBuffer } from 'web-audio-api'
import Microphone from 'node-microphone'

const rate = 44100
const channels = 2 // Number of source channels

const microphone = new Microphone({ // These parameters result to the arecord command above
  channels,
  rate,
  device: 'hw:1,0',
  bitwidth: 16,
  endian: 'little',
  encoding: 'signed-integer'
})

const audioBuffer = new AudioBuffer(
  1, // 1 channel
  30 * rate, // 30 seconds buffer
  rate
})

const chunks = []
const data = audioBuffer.getChannelData(0) // This is the Float32Array
const stream = microphone.startRecording()

setTimeout(() => microphone.stopRecording(), 5000) // Recording for 5 seconds

stream.on('data', chunk => chunks.push(chunk))

stream.on('close', () => {
  chunks.reduce((offset, chunk) => {
    for (var index = 0; index < chunk.length; index += channels) {
      let value = 0

      for (var channel = 0; channel < channels; channel++) {
        value += chunk[index + channel]
      }

      data[(offset + index) / channels] = value / channels // Average value from the two channels
    }

    return offset + chunk.length // Since data comes as chunks, this offsets AudioBuffer's index
  }, 0)
})

I would be really grateful if you could help :)

A: So the input stereo signal is coming as 16 bits signed integers, interleaving left and right channels, meaning that the corresponding buffers (8 bits unsigned integers) have this format for a single stereo sample:
[LEFT ] 8 bits (LSB)
[LEFT ] 8 bits (MSB)
[RIGHT] 8 bits (LSB)
[RIGHT] 8 bits (MSB)

Since arecord is configured with little endian format, the Least Significant Byte (LSB) comes first, and the Most Significant Byte (MSB) comes next.
The AudioBuffer single channel buffer, represented by a Float32Array, expects values between -1 and 1 (one value per sample).
So to map values from the input Buffer to the destination Float32Array, I had to use the Buffer.prototype.readInt16LE(offset) method incrementing the bytes offset parameter by 4 each sample (2 left bytes + 2 right bytes = 4 bytes), and interpolating input values from range [-32768;+32768] (16 bits signed integer range) to range [-1;+1]:
import { AudioBuffer } from 'web-audio-api'
import Microphone from 'node-microphone'

const rate = 44100
const channels = 2 // 2 input channels

const microphone = new Microphone({
  channels,
  rate,
  device: 'hw:1,0',
  bitwidth: 16,
  endian: 'little',
  encoding: 'signed-integer'
})

const audioBuffer = new AudioBuffer(
  1, // 1 channel
  30 * rate, // 30 seconds buffer
  rate
})

const chunks = []
const data = audioBuffer.getChannelData(0)
const stream = microphone.startRecording()

setTimeout(() => microphone.stopRecording(), 5000) // Recording for 5 seconds

stream.on('data', chunk => chunks.push(chunk))

stream.on('close', () => {
  chunks.reduce((offset, chunk) => {
    for (var index = 0; index < chunk.length; index += channels + 2) {
      let value = 0

      for (var channel = 0; channel < channels; channel++) {
        // Iterates through input channels and adds the values
        // of all the channel so we can compute the
        // average value later to reduce them into a mono signal

        // Multiplies the channel index by 2 because
        // there are 2 bytes per channel sample

        value += chunk.readInt16LE(index + channel * 2)
      }

      // Interpolates index according to the number of input channels
      // (also divides it by 2 because there are 2 bytes per channel sample)
      // and computes average value as well as the interpolation
      // from range [-32768;+32768] to range [-1;+1]
      data[(offset + index) / channels / 2] = value / channels / 32768
    }

    return offset + chunk.length
  }, 0)
})


text:
Q: Can't use all cores in R I was trying to make a parallel loop, but I've found R can't utilize all my 8 cores, it uses only 1 with this code:
library(parallel)
library(foreach)
library(doParallel)
no_cores <- detectCores() - 1
cl <- makeCluster(no_cores)
registerDoParallel(cl, cores = no_cores)

sum.of.squares <- foreach(i = 1:10e4, .combine = "+", .init = 0) %dopar% {
  sqrt(i)
}

stopCluster(cl)

It uses only about 13-15% of CPU. Why?
Using Windows 8.1 with R 3.2.1.

A: Use R Revolution Open (RRO) 3.2
http://mran.revolutionanalytics.com/documents/rro/installation/
It comes integrated with the Intel MKL parallel math libraries.
See a fuller comparison here.


text:
Q: Interpreting the variance of random effects in Mixed Linear Models? When fitting the following simple model, using the 'lme4' R package and including a fixed and random slope term, I get:
Linear mixed model fit by REML ['lmerMod']
Formula: s ~ -1 + v8 + ((0 + v8 | Test))
   Data: d

Random effects:
 Groups   Name Variance Std.Dev.
 Test     v8   0.07676  0.2771
 Residual      3.56656  1.8885
Number of obs: 1647, groups:  Test, 41

Fixed effects:
  Estimate Std. Error t value
v8  2.83955    0.07845    36.2

Accordingly to my understanding of the model, the random effects of the above model are assumed to be a sample from a normal distribution with zero mean and variance equal to 0.07676. However when computing the variance directly from the estimated random effects I get a different result:
> var(ranef(m)$Test[,1])
[1] 0.02310659

> ranef(m)$Test[, 1]
[1] -0.160035611  0.091979744  0.024448306  0.103303471 -0.209127498 -0.115072081 -0.100169758 -0.439242134 -0.099724601  0.025481345
[11]  0.029968465 -0.099253951  0.166403989 -0.219299028  0.223841767  0.153699949  0.264563114 -0.143304606  0.177523761  0.054762082
[21] -0.056088689 -0.079896085 -0.013745153  0.122520213  0.214254150  0.252858418 -0.082402046 -0.095554209  0.000000000  0.045516274
[31] -0.017687631  0.003380337 -0.034645355 -0.184548770  0.143998225 -0.178323836  0.144361920 -0.106175741 -0.030701297  0.000000000
[41]  0.222132549

I was expecting to see something close to 0.07676 rather than 0.02310659?Could anybody clarify why I'm seeing this discrepancy?
If I plot the results I get:
plot(density(ranef(m)$Test[,1]), col="green")
hist(ranef(m)$Test[,1], freq=F, add=T)
curve(dnorm(x,mean=0,sd=0.2771), -1,1, col='red', add=T)
curve(dnorm(x,mean=0,sd=sd(ranef(m)$Test[,1])), -1,1, col='blue',add=T)

Where the green curve is the random effects non parametric density estimate, the blue curve is a gaussian with the variance estimated directly from the random effects and the red curve is a gaussian with a variance equal to the one returned by the lmer model.


text:
Q: Insert values in second row of csv file, pertaining the first line in ksh script I am trying to insert values to the second row of a csv file. Firstly, I am inserting the header to the file as:
echo 'FILE_TYPE,PERCENT_SPACE_USED,DB_NAME,THRESHOLD' > output.csv

Secondly I want to insert value under each column. First two of which I have in a text file (output.txt) and 3rd and 4th are in variables.
awk -F"," -v DB="ABCDE",THRESH="75" 'BEGIN{OFS=","} NR>2{$1=$1+DB+THRESH} {print $0}NR!=1' output.txt > output.csv

But what I am getting is that my header is overwritten and the output of text file in 2 lines as:
        ARCHIVED LOG        ,               .09
        ARCHIVED LOG        ,               .09

Below is how my input file (output.txt looks like):
        ARCHIVED LOG        ,               .09

A: If you simply want to add something like header before your output shown then following may help you, this is why awk have BEGIN section where we could do stuff before reading an Input_file eg-->
awk 'BEGIN{print "FILE_TYPE,PERCENT_SPACE_USED,DB_NAME,THRESHOLD"} ...... your_code' Input_file

A: you can also use sed for this purpose, to insert a line on top of a file just do a:
sed -i.bak '1s/^/\"FILE_TYPE,PERCENT_SPACE_USED,DB_NAME,THRESHOLD\"\n/g' file

This will insert a line on top of the file defined by 1s , 2s will insert it in second line and so on.


text:
Q: TFS 2015 Build: Test results not being published I'm having a really weird error when TFS 2015 executes an automated test step.
The results are generated, but it seems TFS unable to find them.
In the end, it just says that no results were found to publish (which is weird, because it even outputs the result full path)
Check below the build logs for more info:
2015-12-16T15:44:29.5816976Z Executing the powershell script: C:\TfsBuildAgents\VsoBuildAgent\tasks\VSTest\1.0.22\VSTest.ps1

2015-12-16T15:44:29.7066995Z ##[debug]Calling Invoke-VSTest for all test assemblies

2015-12-16T15:44:30.4723241Z Working folder: C:\TfsData\Build\_work\1

2015-12-16T15:44:30.4723241Z Executing C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe "C:\TfsData\Build\_work\1\s\Rx.Api.V2.Tests\bin\Rx.Api.V2.Tests.dll"  /Settings:"C:\TfsData\Build\_work\1\s\Staging.runsettings" /EnableCodeCoverage /inIsolation /logger:trx

2015-12-16T15:44:30.7379639Z Microsoft (R) Test Execution Command Line Tool Version 14.0.24720.0

2015-12-16T15:44:30.7379639Z Copyright (c) Microsoft Corporation.  All rights reserved.

2015-12-16T15:44:30.9567007Z Starting test execution, please wait...

2015-12-16T15:44:38.2067012Z Passed   Login

2015-12-16T15:44:39.6129523Z Passed   GetMyEndpoints

2015-12-16T15:44:39.6129523Z Passed   GetEndpoint

2015-12-16T15:44:42.3648007Z Passed   Impersonate

2015-12-16T15:45:23.0904977Z Passed   SingleHotel_BookTwoPaxesOnSingleRoom

2015-12-16T15:45:50.8053379Z Passed   SingleHotel_BookOnePaxOnSingleRoom

2015-12-16T15:46:20.5444670Z Passed   SingleHotel_BookFourPaxesOnTwoRooms

2015-12-16T15:46:53.4013344Z Passed   SingleHotel_BookFourPaxesOnFourRooms

2015-12-16T15:47:03.3137055Z Passed   Location_BookOnePaxOnOneRoom

2015-12-16T15:47:03.5168256Z Results File: C:\TfsData\Build\_work\1\s\TestResults\LOCAL SERVICE_YODA 2015-12-16 15_44_38.trx

2015-12-16T15:47:03.5168256Z Attachments:

2015-12-16T15:47:03.5324554Z   C:\TfsData\Build\_work\1\s\TestResults\46904440-50c9-4522-b3c8-a84356b83b27\LOCAL SERVICE_YODA 2015-12-16 15_44_33.coverage

2015-12-16T15:47:03.5324554Z Total tests: 9. Passed: 9. Failed: 0. Skipped: 0.

2015-12-16T15:47:03.5324554Z Test Run Successful.

2015-12-16T15:47:03.5324554Z Test execution time: 2.4823 Minutes

2015-12-16T15:47:03.6887046Z ##[warning]No results found to publish.

A: In your runsettings file, comment out the ResultsDirectory tag under the RunConfiguration section.


text:
Q: How can two or more lists be traversed in O(N) I have a question that doesn't seem possible to me. I have 2+ arrays which I have to compare for common values. I am supposed to do this in O(N) comparisons but can't think of a way. Specifically (k-1)N comparisons where k is the number of arrays. I've narrowed down how I can take multiple arrays and just merge them into a single array. I've gotten that the smallest array is the limiting factor so if I sort that I can save the most comparisons. After spending half the day staring at my screen I've even come up with a way to do this linearly if I discount any duplicates, but I have to keep duplicates So, as far as I know in order to compare any arrays you need at least 2 for loops which would be O(N^2) wouldn't it? I'm also not allowed to hash anything.
For example if I had {1,3,4,3,4,5} as a master and {1,1,3,5,9,3,7} and {3,5,8,4,0,3,2} as arrays to be compared I'd need to have a final of {3,3,5} since I can't get rid of any dupiclates.
I don't want anyone to write the code, I just need to know what I should be doing in the first place.

A: If the lists are sorted, then it's relatively straightforward if you do something like this:
List<Integer> intersection = new ArrayList<>();
int i = 0;
int j = 0;
while (i < list1.size() && j < list2.size()) {
  int a = list1.get(i);
  int b = list2.get(j);
  if (a < b) {
    i++;
  } else if (b < a) {
    j++;
  } else { // a == b
    intersection.add(a);
    i++;
    j++;
  }
}

On each iteration of the loop, the quantity i + j increases by at least 1, and the loop is guaranteed to be done when i + j >= list1.size() + list2.size(), so the whole thing does at most O(list1.size() + list2.size()) comparisons.

A: Use an array of ints. Taking your first list, for each element, set the value at that index to 1. So if the first element is 3, put 1 in array[3]. Now, we know that 3 is present in first list. Putting 1 will help you distinguish from a 3 that is present in the earlier list versus a 3 which is repeated in current list.

*

*Iterate through all the other k-1 lists

*For every element, check the value in array for that index

*If the value is 0, set it to this list number

*If the value is a number less than this list number, this number is a duplicate and has already appeared in a previous list.

*If this number is equal to this list index it means this number already occurred in this list but not in previous lists, so not yet a duplicate.

*The numbers that you are getting as duplicates, add them to another list.

*Finish all iterations

Finally print the duplicates.

Original Wrong Answer

*

*Create a HashSet<int>

*Take all values from master and add to it - O(master list count)

*Now just iterate through first and second arrays and see if their elements are in that HashSet - O(each list count)


text:
Q: Configure which Nameserver responds to domain name I have a domain with four name servers (Two behind a Firewall and two on the public network).
We were required to have two of the servers behind the firewall.  It's causing issues when bringing new equipment online because it sometimes needs to happen before firewall exceptions can be implemented.
If I configure devices which use LDAP authentication to point at example.com, sometimes they pick up the Nameservers inside the firewall and sometimes those outside.  If they pick up the ones inside, authentication fails and essentially bricks the device until I can hard reset it.
Is there a way to configure what server responds to a request such as 'ping domain.com'?
I'm guessing that there is but I'm missing what to do.  Thanks for any help!
EDIT:  Just to clarify, I know it's not best practices but that's out of my control.  My goal is to use 'domain.com' as my LDAP server so the device should be directed to one of several AD servers for authentication.  I can't enter values separated by commas or the like to allow it to point to multiple servers by itself.  So far it sounds like it's not possible to limit but just figured I'd explain further.

A: You register your domain name with only external, publicly available name-servers. No discussion about it.
There might be a reason1  to have authoritative name-servers in your internal network for the top of your domain (the whole of example.com) but they shouldn't be listed in your public DNS. That breaks stuff, as you've already experienced.
Your internal systems should be using an internal resolver (and not those of your ISP nor public services like 8.8.8.8 and 8.8.4.4).
That internal resolver is (pointed at) the authoritative name-server for the internal version of the   example.com zone.
The result: internal systems can see the internal IP-addresses, external systems can only see your public IP-addresses.

Footnote 1 No there isn't. It is kludge that will bite you in the ass.
You configure a sub-domain for internal use, such as intranet.example.com which can only be found internally and you explicitly configure your internal systems to use internal resources.