text:
Q: WordPress wp_redirect clearing $_SERVER['REQUEST_URI'] before I can read it I need to redirect all traffic on my WordPress site to the homepage if not requested by AJAX, but I need to use the requested path after redirect.
I have redirection working via wp_redirect php and a template_redirect hook, however I can't read the REQUEST_URI to save it via cookie or header or anything.
As soon as wp_redirect is called it seemingly prevents me from ever reading the details of the request, pre redirect. Comment out the wp_redirect and it reads just fine.
Is there something I'm missing here, or a better way to go about it? I have a one page site that is loading content via AJAX.
add_action('template_redirect', 'pass_along_request_uri', 1);

function pass_along_request_uri() {
    // $_SERVER['REQUEST_URI'] is the path as expected only if the future wp_redirect is not called...
}

add_action('template_redirect', 'redirect_to_homepage', 10);

function redirect_to_homepage() {
    if (!is_front_page() && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')) {
        wp_redirect(home_url(), 301);
        exit;
    }
}

EDIT;
Only had 2 functions for testing, since logging $_SERVER['REQUEST_URI'] wasn't making sense to me. Thinking if I put the log at priority 1, it should be logged BEFORE the redirect happens with the priority 10 function.
However it doesn't. Doesn't matter when or where it seems, calling wp_redirect seemingly clears the original request data.
function console_log($output, $with_script_tags = true) {
    $js_code = 'console.log(' . json_encode($output, JSON_HEX_TAG) .
');';
    if ($with_script_tags) {
        $js_code = '<script>' . $js_code . '</script>';
    }
    echo $js_code;
}

console_log($_SERVER['REQUEST_URI']);

Logs say "/path/to/page" when not calling wp_redirect, once wp_redirect is in the chain it only spits out "/" (the redirected path).
I'm thinking it has something to do with how actions are queued up with add_action? I don't know WordPress well unfortunately.
Thanks!

A: Your mistake here was the way you are actually logging this.
The console.log(...) executes on the client side - but there it can't log while you are doing your redirect elsewhere (you can not send output for the browser to interpret, like your script element, and redirect at the same time.)
What you are seeing is the result of that same logging code, executed via the request after your redirect.
Easiest way to achieve what you want, would probably be to stick the REQUEST_URI value into a session. You might have to start one then for that purpose, because WP does not use a "traditional" session by default.


text:
Q: how to make row editable after selecting option from dropdown I want to make my table row editable when i will select edit option from dropdown box. Previously it was woring fine but that time i used Edit button inside all row. But now i have made edit button by putting into dropdown. but now it is not working. I am not able to find any error in my code but still it is not working.
 my html table is

                Parameter Names
                Parameter Values
                Remarks

                johncarter@mail.com
                John
                Carter

                peterparker@mail.com
                Peter
                Parker

Edit

Basically i am enabling right click menu. After clicking right dropdown box will open. whne i will click edit button then my row will become editable. I have added jquery for contextMenu and for edit button. Sorry for making code very dirty but currently i am practicing and also i am new in this.

A: Look at the output that the console gives you. Clicking edit results in TypeError: tdButtons.html is not a function which results from the two lines:
var tdButtons="";

and
tdButtons.html("Save");

So you are creating an empty string and trying to use it as if it was a jQuery object. You will need to change theses lines to get it to work again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dry up rails namespaces in routes I have a couple of namespaces which look identical, the only difference between the two are the names. So I have
namespace :narrow do
  resources :posts
  resources :comments
  ...
  ...
end

namespace :wide do
  resources :posts
  resources :comments
  ...
  ...
end

What I would like to do is have the same resources defined in each namespace without needing to make changes in two places when resources are added/removed/changed.
Is there any way to do this?

A: Isn't this just a ruby file?  couldn't you do:
[:narrow, :wide].each do |ns|
  namespace ns do
    resources :posts
    resources :comments
  end
end


text:
Q: AWS SimpleDB Select Expression iPhone I need to construct a selectExpression for SimpleDB where I only want items with attributes = to X, sorted in descending order by attribute Y.  All I have so far is this:
NSString *selectExpression = [NSString stringWithFormat:@"select itemName() from `%@`",domainString];

@try {
    SimpleDBSelectRequest  *selectRequest2  = [[[SimpleDBSelectRequest alloc] initWithSelectExpression:selectExpression] autorelease];
    SimpleDBSelectResponse *selectResponse = [[Constants sdb] select:selectRequest2];

    if (items == nil) {
        items = [[NSMutableArray alloc] initWithCapacity:[selectResponse.items count]];
    }
    else {
        [items removeAllObjects];
    }
    for (SimpleDBItem *item in selectResponse.items) {
        [items addObject:item.name];
    }
    [items sortUsingSelector:@selector(compare:)];
}
@catch (AmazonServiceException *exception) {
    NSLog(@"Exception = %@", exception);
}

I would prefer to only select items (above) with attributes X by Y rather than get all items and then sort. How do I add this? Does it go in the selectExpression string or somewhere else.  Many thanks!

A: NSString *selectExpression = [NSString stringWithFormat:@"select itemName() from `%@` where X = '%@' order by 'X' descending",domainName,attributeValue];

A: Try this out --
Select x,y from <domain_name> where itemName() is not null order by itemName() asc


text:
Q: Derivation, composition, constructors, interfaces and TDD When developing TDD your objects 'grow' as code evolves . First they include only some functionalities, and later you add new ones. You can basically do it with composition and/or inheritance.
At the same time, you almost always use interfaces (for test, and for production code) to ensure low coupling, dependency inversion, dependency injection and mocking.
How do you MANAGE this?
I mean, for example: you have created a class, and now it must include a new attribute (for example, a Person now can have an e-mail). What to do?

*

*Modify the class, adding the new attribute: Then you must ADD new constructors. But if you modify existing constructors then you must refactor all TEST involved, not only production code. You could try to keep all constructors as you add new attributes, but at the end mostly become unusefull, obsolete (only exist because of TESTS), with a complex logic of 'constructor calling another constructors' (or use some kind of 'factory')

*Derive the class: This is more compilant to OCP. But if you make a real TDD, with small steps, if you always derive, starting from a very simple class, you would end with a terribly complex and somehow unneccesary inheritance. And besides, it's supposed you always must test only PUBLIC exposed members. So, again, as base classes become protected, must refactor tests to access the public ones.

*Compose: Composing has no problem with constructors, but is not always a good solution. As for our current example.

And a similar thing happens, in some way, with interfaces.
So, as code grows, constructors an interfaces must evolve. And I have three precepts in mind:

*

*You should avoid refactor tests.

*The production code must not keep 'code only intended for testing' (i.e. constructors)

*ISP states to use specific interfaces. As code grows many of them become unnecesary, as they are only used for testing (i.e. mocking) classes that, in many cases, should be protected or private.

So, as I said... how can i manage all this while developing TDD? I know it's a question for a long answer, so, if you could refer to some good article, or resource

A: Changing your tests is OK
What you're describing (Person now has an Email) is a change in the specs. Unit Tests are supposed to be your specs, so it's only normal that you have to change them when introducing new data.
This kind of test fragility is a trade off for quality, a necessary evil.
Don't overengineer
By trying to apply OCP, inheritance and composition just to add one field, you're only making things more complicated for yourself. As you pointed out, it results in production code monstrosities just for the sake of testing, and you also have to modify the tests anyway.
OCP might be good if you're adding a new behavior in a family of existing behaviors, but it's not the case here.
Make changes more manageable
There are tactics to make your tests more resistant to small changes, but they are mainly implemented at the test level, not in production code. Besides, opportunities for this are easily spottable if you frequently look for duplication in your tests, during the Refactor step of the TDD cycle for instance.
One of them is to encapsulate your "system under test" creation in a Factory Method and call it instead of the normal constructor in each of your tests. Make most of its parameters optional with a default value. This will allow you to make changes (e.g. add the Email field) in one place and all the tests will benefit from it. This doesn't save you from modifying the test suite, but you do it just in one place.


text:
Q: JPA : Select JPQL with several new Could you tell me if it's possible to make a select JPQL with several new Object
like this:
Select new QueryOfSelectionList ( new param(q1, q1t), new param(q2, q2t) )
From ...
I success to do like this: new QueryOfSelectionList (q1, q1t, q2, q2t)
but I don't like because I would increase the number of params and have a several constructeur of param possible ( q1, q1t or q1 ).
I tried the example but i have : Exception: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: new
this exception is for the new of param(q1,q1t).
thanks for help.
Christian

A: In the document published at http://docs.oracle.com/cd/E12839_01/apirefs.1111/e13946/ejb3_langref.html, we see that:
Following is the syntax of constructor expression:

constructor_expression ::= NEW constructor_name ( constructor_item {,
  constructor_item}* )

Further it is said that:

A constructor may be used in the SELECT list to return one or more
  Java instances. The specified class is not required to be an entity or
  to be mapped to the database. The constructor name must be fully
  qualified.

An example is:

SELECT NEW com.company.PublisherInfo(pub.id, pub.revenue, mag.price)
      FROM Publisher pub JOIN pub.magazines mag WHERE mag.price > 5.00

So it is not possible to use the expression like Select new QueryOfSelectionList ( new param(q1, q1t), new param(q2, q2t) ) From. Hope this helps.


text:
Q: decimal in c# misunderstanding? (while trying to analyze how decimal works ) && after reading @jonskeet article  and seeing msdn , and thinking for the last 4 hours ,
I have some questions :
in this link they say something very simple :
1.5 x 10^2 has 2 significant figures
1.50 x 10^2 has 3 significant figures.
1.500 x 10^2 has 4 significant figures etc...
ok...we get the idea.
from jon's article  :
 sign * mantissa / 10^exponent

As usual, the sign is just a single bit, but there are 96 bits of
  mantissa and 5 bits of exponent

 ^ _ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^___ ^^^^^

 1 _                     96                         5

ok
so max mantiss val = 2^96-1 = 79228162514264337593543950335 which is : 7.9228162514264*10^28 (according to my iphone... could'nt see exponent representation in windows calc.)
notice :
7.9228162514264*10^28 has 14 significant figures (according to examples above)
now the part with the 5 bit in exponent is irrelevant because its in the denominator - so i need the min val which is 2^0
question #1 :
msdn say :  28-29 significant digits
but according to my sample (1.500 x 10^2 has 4 significant figures) they have 2   significant figures which is 7.9 ( 7 and 9).
if msdn would have written :
±79228162514264337593543950335 × 10^0

i would understand this ,  since all significant digits are in the expression.
why do they write 28-29 but display 2 ?
question #2 :
how will decimal representation ( mantiss && exponent) will be displayed for the value 0.5 ?
the max denominator can be 2^32-1 --> 31
thanks guys.
question #3 :
1+96+5 = 102 bits.
msdn says :

The decimal keyword denotes a 128-bit data type.

128-102 = 26

could understnad from article why there isnt a usage to those 26 bits

A: They've given the range to just two significant digits, but specified the precision separately. That's why the range is listed as "approximate range".
The decimal representation of 0.5 would be a mantissa of 5 and an exponent of 1 (which is treated in the inverse sense to normal, i.e. it's effectively -1).

A:
why do they write 28-29 but display 2?

For readability. It says "Approximate range" and 7.9E28 is more readable than 79228162514264337593543950335 (E0 here, not E1).

how will decimal representation ( mantiss && exponent) will be displayed for the value 0.5 ?

The exponent's range is -28...0, however, it is stored (and received via constructor parameters) as an absolute value of 0...28.
So 0.5 Would have the same mantissa representation as 5 with an exponent of -1 (stored as 1).


text:
Q: Input control losing focus after each keystroke I have an object state like this:
const [form, setForm] = useState({
  name: '',
  addr: '',
  ...
  })

And I use a helper component:
const InputField = (props) => {
  return (
    <Container>
      <Form.Control
        name={props.name}
        type={props.type}
        placeholder={props.label}
        value={form[props.name]}
        onInput = { (e) => {
          setForm( { ...form, [e.target.name]: e.target.value } )
        } }
      />
    </Container>
  )
}

I use this like:
return (
  ...
  <InputField name="name" type="text" label="Name, Firma:" />
  <InputField name="addr" type="text" label="Adresse:" />
  ...
)

Everything works fine, except the input control accepts only one keystroke. Only after I click the input again, it accepts another character. So, it seems, the input looses focus. But why, what's wrong? What can I do against this behavior?

A: The problem is that your InputField component is inside another component which re-renders every time you type something and it makes it look like you're losing focus. You need to move it out of there and pass down an onInput callback to handle the changes:
function InputField({ label, name, onInput, type, value }) {
  return (
    <Container>
      <Form.Control
        name={name}
        onInput={onInput}
        placeholder={label}
        type={type}
        value={value}
      />
    </Container>
  );
}

function ParentComponent() {
  const [form, setForm] = useState({
    name: '',
    addr: '',
  });

  function handleInputChange(e) {
    setForm({ ...form, [e.target.name]: e.target.value });
  }

  return (
    <Form>
      <InputField
        name="name"
        type="text"
        label="Name, Firma:"
        onInput={handleInputChange}
        value={form.name}
      />
      <InputField
        name="addr"
        type="text"
        label="Adresse:"
        onInput={handleInputChange}
        value={form.addr}
      />
    </Form>
  );
}

You could also loop through your state so you don't have to type every input field manually. And please, please, use labels in your forms, don't rely on placeholder values. They are there for hints, and they're not accessible. Assistive technology won't announce your inputs properly, and users who rely on such technology won't be able to use your form.

A: try these fixes:-
Fixes 1

*

*should use onChange instead of onInput

*should just straightaway use name than [e.target.name] in onChange event

*helper component:-

const InputField = (props) => {
  return (
    <Container>
      <Form.Control
        name={props.name}
        type={props.type}
        placeholder={props.label}
        value={form[props.name]}
        onChange = { (e) => {
          setForm( { ...form, name: e.target.value } )
        } }
      />
    </Container>
  )
}

You can see this working sandbox for reference


text:
Q: Local minimum implies local convexity? Consider a real function $f$, and suppose it has a local minimum at $a\in \mathbb R$.
It typically looks like

What hypotheses can be added to $f$ so that there is some $\epsilon >0$ such that $f$ is convex over $(a-\epsilon,a+\epsilon)$ ?

The motivation for this question is intuition, but I can't find any valid criterion.

A: No in the continuous case, a part requiring in practice convexity. Yes in the smooth case.
In general local minima have nothing to do with convexity:
The function $\sqrt{|x|}$ has a local minimum in $0$ but it is not convex
The function $e^x$ is striclty convex everywhere but has no minimum.
On the other hand, as pointed out in comments, if $f$ is continuously differentiable at least twice, and if $f''(x)\neq 0$ at a local minimum $x$, then we have $f'(x)=0$ and $f''(x)>0$, which forces local convexity.
In fact, this issue is the core of the so called maximum principle which is very useful in the theory of differential equations:
Suppose $f$ is a smooth function and you are able to show that at every critical point $f''<0$. Then $f$ has no local minima.
(Ex. $x''(t)=e^x\sin(x'(t)e^t) -1$. If $x'=0$ then $x''<0$)

A: As pointed out by the user above you certainly need more than just continuity. You also need more than differentiability since one could consider $f(x)=x^{2}(\sin(\frac{1}{x})+1)$ for $x\neq0$ and $f(0)=0$ which has a local minimum at $0$ but $f$ is not convex in any neighbourhood of $0$. By changing the exponent of the power of $x$ you can show further that to obtain local convexity it is not enough to be just $C^{2}$ unless you have positive derivative at the point of the minimum. Even worse, you can have a $C^{\infty}$ function with a local minimum at $x=0$ but still not be convex in any neighbourhood of $0$ provided you don't assume that $f''(0)>0$. This is shown by the function $f(x)=e^{\frac{-1}{x^{2}}}(\sin(\frac{1}{x})+1)$ for $x\neq0$ and $f(0)=0$.


text:
Q: yarn install error:Failed to download Chromium The Yarn install failed to download Chromium. Error is as follows:
D:\workspace\www\ant-design-mobile-pro
λ yarn
yarn install v1.12.3
//...
Directory: D:\\workspace\\www\\ant-design-mobile-pro\\node_modules\\puppeteer
Output:
ERROR: Failed to download Chromium r599821! Set \"PUPPETEER_SKIP_CHROMIUM_DOWNLOAD\" env variable to skip download.
{ Error: connect ETIMEDOUT 172.217.161.176:443
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1113:14)
  errno: 'ETIMEDOUT',
  code: 'ETIMEDOUT',
  syscall: 'connect',
  address: '172.217.161.176',
success Saved lockfile.
Done in 343.80s.

Question:
Can I download Chromium manually? I can download it from https://npm.taobao.org/mirrors/chromium-browser-snapshots/Win_x64/,the question is: Where should I put it after dowloading it?

A: If you don't intend to run the automated browser tests which depend upon Chromium, you can skip the install per the error message:
export PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true && yarn
I've occasionally encountered this yarn install timeout recently as well, and no cache clear or other manipulation has seemed to resolve it.


text:
Q: Two problems using Java / VS Code The code below compiles on two online Java compilers, but I am having trouble with VS Code.
Two problems:

*

*VS Code imports single items such as import java.util.Arrays; but does not import when using a wildcard like import java.util.*;

*When executing(edit) the code below in VS Code, the following exception occurs:

Exception in thread "main" java.lang.ClassCastException: Entry cannot be cast to java.base/java.lang.Comparable
      at java.base/java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source)
      at java.base/java.util.ComparableTimSort.sort(Unknown Source)
      at java.base/java.util.Arrays.sort(Unknown Source)
      at EntryTester.main(EntryTester.java:33)

I don't know why the cast is a problem. Here's the code:
import java.util.Arrays;

class Entry implements Comparable<Entry> {
    private String word;
    private String definition;
    public Entry(String wor, String def) {
        this.word = wor;
        this.definition = def;
    }
    public String getWord() {
        return word;
    }
    public String getDefinition() {
        return definition;
    }
    public String toString() {
        return word + "\t" + definition;
    }
    public int compareTo(Entry other) {
        return word.compareTo(other.getWord());
    }
}

class EntryTester {

    public static void main (String[] args) {
        Entry[] wordList = new Entry[5];
        wordList[0] = new Entry("WWW", "World Wide Web");
        wordList[1] = new Entry("HTTP","Hypertext Transport Protocol");
        wordList[2] = new Entry("DNS", "Domain Name System");
        wordList[3] = new Entry("AWT", "Application Windowing Toolkit");
        wordList[4] = new Entry("CPU", "Central Processing Unit");
        Arrays.sort(wordList);
        for (int j = 0; j < wordList.length; j++)
            System.out.println(wordList[j].toString());
    }
}

A:
VS Code imports single items such as import java.util.Arrays; but does not import when using a wildcard like import java.util.*;

Unclear what you mean by this.  But I suspect you are misunderstanding what a wildcard import means in Java:

*

*That import means to import classes in the java.util package.

*It does NOT include classes in subpackages such as java.util.concurrent and so on.

On the other hand, if you were expecting import java.util.*; to import the name of the Arrays::sort static methods, it doesn't.  And neither does import java.util.Arrays;!   If you want to import status methods you need to do this:
  import static java.util.Arrays.*;

If the Visual Studio Java compiler is telling you something different, something is very wrong.
(Comment: Most programmers tend to avoid wildcard imports in production code.  You can get into problems if names declared in multiple packages.)

When executing(edit) the code below in VS Code, the following exception occurs:
  Exception in thread "main" java.lang.ClassCastException:
          Entry cannot be cast to java.base/java.lang.Comparable

When you sort a list using the Arrays.sort, there are two ways that the sort method can order the elements of your Entry[]

*

*You can supply a Comparator<Entry> argument to the sort method.

*The Entry class can implement the Comparable<Entry> interface.

If you don't provide a Comparator, the sort method assumes that you are doing it the other way.  So it is now trying cast one of the Entry objects to Comparable so that it can call entry.compareTo(anotherEntry) on it.   Which fails ...
In your case, it appears that you have implemented Comparator in Entry.
So there are two possible explanations:

*

*You may be executing an old version of your code; i.e. one from before you modified Entry to implement Comparable.

*There may be something broken with your Visual Studio.

If we can assume the the problem is with Visual Studio Code, I suspect it is related to Java versions.  The documentation states that Java 11 is supported, but it may also be necessary to tell VS that it is using Java 11 rather than Java 8.  (There are some significant runtime differences due to the introduction of modules in Java 9 ....)


text:
Q: sql result in php matrix according sorted by branches/product/size I've been trying hard to figure out how to do matrix from the result of an sql query where the x is location, y is the size/description and the data filling are the quantities available in each location according to the size and color.
I have it done using pl/sql but not php. I want to transform the forms to a web layout in order to access it from anywhere.
the query is:
    $q5="select  artdesc DECRIPTON ,  ARTUPRB PRICE$ ,depcode LOCATION,  ARDQTDIS
          QUANTITY from fgart a, fgartdep b where a.soccode='01' and artfam =:fam and
    artdiv=:div  and artsec=:sec  and artsubsec =:subsec and
         (EXISTS
     (select distinct artserial from fgart   where soccode ='01' and artsec =:sec
     and artsubsec =:subsec and artfoucode =:wartfoucode   and artserial = a.artserial)
         or EXISTS
    (select distinct artfoucode from fgart where    soccode ='01' and artsec =:sec and
    artsubsec =:subsec and artfoucode = a.artfoucode and  artserial =:wserial))
    and
    b.soccode ='01' and b.bracode ='01' and a.artcode = b.artcode
     and   depcode  <> '99'
       AND ARDQTDIS <> '0'
         order by artdesc";

I have a small query prior of this one where I catch all the variables and pass them to the above sql.
I have managed to do a normal listing using the below code:
    <?php
    $r7=oci_parse($oconn,$q5);
    $r8 = oci_execute($r7);
    sleep(100);
    if (oci_execute($r7)){
    usleep(100);
    print "
";
    $first = 0;
    while ($row = @oci_fetch_assoc($r7)){
            if (!$first){
                    $first = 1;
                    echo ("
  " );
                    echo( implode("	", array_keys($row)));
                    echo ("
  \n");
            }
            echo ("
");
    echo (@implode("	 ",str_replace ($Woutl,  Wdesc,
    array_values($row))));
            echo ("
\n");
    }
    echo ("
");
    ?>

Please if anyone can direct me the right track in order to get result similar to the below:
              location (x) :         dt    sk    abc    ss
    Item desc /size (y):
    blue  46                         2      1     0     4
    blue  48                         1      1     1     0
    blue  50                         0      0     2     1
    grey  44                         5      1     1     1
    grey  46                         4      1     1     1
    grey  50                         3      2     2     0


text:
Q: How can I plot a line with markers for separate categories in a relplot? Using Seaborn I would like to plot both SBP and DBP columns as below.
To achieve this, I use:
plt.style.use('ggplot')
g = sns.relplot(data=r_29, x="DATE_TIME", y="SBP", col="VISIT", col_wrap=2, facet_kws={'sharey': False, 'sharex': False}, aspect=2, marker='o')
g = sns.relplot(data=r_29, x="DATE_TIME", y="DBP", col="VISIT", col_wrap=2, facet_kws={'sharey': False, 'sharex': False}, aspect=2, marker='+')
g.data = r_29  # Hack needed to work around bug on v0.11, fixed in v0.12.dev
g.map(sns.lineplot, 'DATE_TIME', 'SBP', color='r', ci=None, lw=3)
g.map(sns.lineplot, 'DATE_TIME', 'DBP', color='b', ci=None, lw=3)

However, I get the following plot

*

*How can I obtain the drawings of SBP and DBP variable in a single plot for each visit like the first plot?

*Is there a way to change the y axis name to something else than DBP?

A: *

*You can use FacetGrid to render plots in a way that is shown in your first figure.

*Then, use set_axis_labels option to change name of the x- and y- axis.
# LINE PLOT
g = sns.FacetGrid(r_29, col="VISIT", sharex=False, sharey=False,aspect=2,col_wrap=2,legend_out=True) # 2 columns, legend is outside of plot

g.map(sns.lineplot, "DATE_TIME", "SBP",color='red',label='SBP',style= r_29['MODE']) # style/shape of line changes with mode of therapy

g.map(sns.lineplot, "DATE_TIME", "DBP",color='blue',label='DBP',style= r_29['MODE'])
g.set_axis_labels("DATE_TIME", "Blood Pressure (mmHg)")
g.add_legend(title = 'LEGEND',label_order=['SBP','DBP','CKD','Dialysis','Late TPL']) # this creates legend which is for all legends


text: Q: Wintenberger's mystery Fontaine describes in §2 of this old survey work by Wintenberger and wonders (on p. 97) that the structures found by Wintenberger are a "complete mystery" and no-one knows a "reasonable geometric interpretation". Is that still a mystery?


text:
Q: Add files in solution level by nuget I want to add items (not projects) to a solution via a NuGet, but I have created a Nuspec file with the following files elements:
<files>
    <file src="..\A.txt" target="content" />
</files>

But the file A.txt is added to the project not solution. So I want to know is  there any way to add the file to solution level not the project level?

A:
So I want to know is there any way to add the file to solution level not the project level?

I am afraid there is no such direct way to do that. Because NuGet team deprecated solution level packages in NuGet 3.0.
So, at this moment, the nuget is package manager for project level, we could not add the file to solution level directly .
However, you can do this by install.ps1 file. Matt provided the PowerShell script in following thread, you can refer to:
Adding solution-level items in a NuGet package
Hope this helps.


text:
Q: SPARQL query with one mandatory filter and one optional filter I'm trying to run a SPARQL query against Wikidata that has one filter which is required and one filter which is optional.  I keep getting malformed query errors.  This query, without the Optional line, runs without issue:
SELECT ?person WHERE {
  ?person wdt:P106 wd:Q82955.
  ?person wdt:P27 ?citizenshipCountry.
  ?person wdt:P19/wdt:P17 ?birthCountry.
  filter(?citizenshipCountry = wd:Q30 || ?birthCountry = wd:Q30)
  }

When I try to add the optional filter, I get malformed query errors:
SELECT ?person WHERE {
  ?person wdt:P106 wd:Q82955.
  ?person wdt:P27 ?citizenshipCountry.
  ?person wdt:P19/wdt:P17 ?birthCountry.
  filter(?citizenshipCountry = wd:Q30 || ?birthCountry = wd:Q30)
  OPTIONAL: filter(!bound(?dob) || ?dob > "1980-01-01T00:00:00Z"^^xsd:dateTime)
  }

I know the syntax of the Optional line itself is ok, as I've used that separately in other queries where it's the only filter.


text:
Q: I get weird characters when removing line breaks in my aspx files I wrote a small .NET applications that removes all line breaks in aspx/html/css code to make it harder to read for people trying to steal my design. And surprisingly I get weird characters that appear out of nowhere such as Â, » and others. They all stay at the same places, but I have no clue why they appear.
Do you have any ideas on how to fix this?

A: I'm not sure on why you're getting the issue based on the information you've provided, but if I were you I probably wouldn't spend too much time working on this:  if you're just removing white space, someone could just simply paste your code into visual studio and hit the format button to bring it all back.
If you need it regardless, there are libraries out there that do just this, but they are mainly intended to compress what's sent to the clients.
Example:
http://madskristensen.net/post/Remove-whitespace-from-your-ASPNET-page.aspx

A: Are you removing the both the carriage return and linefeed characters?  Windows uses 2 line break characters for each line break.


text:
Q: Sublime Text 3 - How can i add my PHP tags I want to add some custom tags for my development - but I don't know how to do it.
I have tried snippets but it doesn't work because my tags have some special symbols. How can I add my tags so that the snippets work?
Eg: when I fill z_z in sublime text, it will auto-fill:
print("
".print_r($files,true)."
");

When I fill z_d, it will auto-fill:
echo "
" . preg_replace("/\]\=\>\n(\s+)/m", "] => ", $dump) . "
";

A: You can use sublime snippets, but you just need to escape the $ sign, as sublime thinks it's a variable, instead of an actual character you want to print out.
To create a snippet, in the top bar go to Tools > New Snippet.
You save these snippets as mysnippet.sublime-snippet in the /packages/user folder (it should save there automatically when you go to save it).
For your first one you can use the following snippet, you have to excape the $ sign by adding \ infront of it:
<snippet>
<content><![CDATA[
print("
".print_r(\$files,true)."
");
]]></content>
    <tabTrigger>z_z</tabTrigger>
</snippet>

For your second one also use a snippet and escape the $ sign again using a backslash (\) again:
<snippet>
<content><![CDATA[
echo "
" . preg_replace("/\]\=\>\n(\s+)/m", "] => ", \$dump) . "
";
]]></content>
    <tabTrigger>z_d</tabTrigger>
</snippet>

A: You can also use a .sublime-completions file
{
    "scope": "helper.sublime.property-name.sass",

    "completions": [

        { "trigger": "z_z", "contents": "print("
".print_r(\$files,true)."
");" }
        etc...
    ]
}

Quite useful when you have to do shit load of snippets
Matt

A: Open Sublime Text 3 and Open Key Bindings from Preferences Menu
Add below code on right side of sublime-keymap--user
{ "keys": ["ctrl+shift+c"], "command": "insert_snippet", "args": { "contents": "echo \"
\"; print_r(${0:\\$variable_to_debug}); die();\n" }}

A: Open Sublime Text 3 and go to Tools > Developer > New Snippet
replace below code <snippet> <content><![CDATA[
echo '
'; print_r(${1}); echo '
';
die;
]]></content><description>PHP: Pretty print_r</description><scope>source.php</scope>  <tabTrigger>pre</tabTrigger></snippet>
It's working.


text:
Q: Does ORDER BY affect multiple WHERE conditions? I'm trying to implement paging on a table named posts, and I'm using the columns time_created and post_id as the delimiter for the pages.
It's possible that multiple posts are created at the exact same time, so when retrieving the next page, I need to get all the remaining posts created at a specific time, and then get posts created before that time.
My concern is that postgres doesn't care about the order of WHERE conditions, and since I have 2 conditions separated by an OR, the following query may only use the second condition to fulfill the LIMIT requirement.
My question is: Does the ORDER BY clause guarantee that the first condition I provided (time_created = $1 AND post_id < $2) will be executed first since time_created = $1 should logically come before time_created < $1 when ordered by descending order?
SELECT * FROM posts
WHERE (time_created = $1 AND post_id < $2) OR time_created < $1
ORDER BY time_created DESC, post_id DESC
limit 50;

A: The query will be executed in three steps:

*

*Eliminate rows which do not satisfy conditions in the WHERE clause.

*Order remaing rows by expression(s) in the ORDER BY clause.

*Get first 50 rows according to the LIMIT.

So the order does not affect filtering.
If you run EXPLAIN ANALYSE <your query> you will get something like this:
                                                                                QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=430.71..430.84 rows=50 width=12) (actual time=1.727..1.730 rows=50 loops=1)
   ->  Sort  (cost=430.71..445.82 rows=6042 width=12) (actual time=1.726..1.727 rows=50 loops=1)
         Sort Key: time_created DESC, post_id DESC
         Sort Method: top-N heapsort  Memory: 27kB
         ->  Seq Scan on posts  (cost=0.00..230.00 rows=6042 width=12) (actual time=0.010..1.329 rows=6027 loops=1)
               Filter: (((time_created = '2018-07-01 00:00:00'::timestamp without time zone) AND (post_id < 1111)) OR (time_created < '2018-07-01 00:00:00'::timestamp without time zone))
               Rows Removed by Filter: 3973
 Planning time: 0.493 ms
 Execution time: 1.759 ms
(9 rows)

which can be interpreted as the three steps described above.


text:
Q: Cannot Rename/Move folder in Sharepoint Online I am trying to use Sharepoint as a fileserver to host a folder and share it out with sync in OneDrive.
I have create a SitePages and a main folder.
Folder contains circa 100gb in 385 sub folder, about 150.000 files.
When I try to rename i get this error:
"The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator."
I have also notice I am not able to move the folder to a root folder. I dont have the "move"
option.
I have tried to use file explorer but is not available.
I read to make it available I had to emulate Internet Explorer 10 or previos version, this leads to make the option visible but nothing happen when I click on it.

A: This is a known issue in SharePoint. If your view contains more than 5 thousands items you will get this error. However, it is notable - SharePoint list contain 30 million item, but at any point of times, the item view should not load more than 5k items. You can split your view into multiple views with the metadata filter conditions and ensure the query or filter returns less than 5k items.


text:
Q: Using a custom  stanza in tsung (for testing ejabberd)? I would like to use a custom <iq> stanza with tsung (to test ejabberd).
Suppose my <iq> looks like this:
<iq type="get">
    <query Xmlns="jabberd:test:sample">
        <search term="l"></search>
     </query>
</iq>

How would I add that into a tsung configuration like:
<transaction name="online">
    <request>
        <jabber type="chat" ack="no_ack" size="16" destination="online"</jabber>
    </request>
</transaction>
<thinktime value="300"></thinktime>`

A: Take a look at Section 6.6.3.11. raw XML here. You can specify custom XML stanzas using raw type jabber requests.
So your request above would look like this(make sure you escape your XML):
<jabber type="raw" ack="no_ack"
 data="<iq type="get"
         ><query Xmlns="jabberd:test:sample">
           <search term="l"></search>
         </query>
       </iq>">
</jabber>


text:
Q: React Native deep linking does not work when app is killed Possible solution
I found a solution myself in the meanwhile, probably not so 'clean'.
In App.js I specify my initialRouteName like this:
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';

import Home from './screens/Home';
import Form from './screens/Form';
import {Linking, Platform} from 'react-native';
import React from 'react';

function getRoute() {
  let route = "";
  Linking.getInitialURL().then(url => {
    route = url;
  })

  if (route === 'playgroundapp://form') {
    return 'Form';
  } else {
    return "Home"
  }
}

const AppNavigator = createStackNavigator(
    {
  Home: { screen: Home },
  Form: { screen: Form },
}, {
      initialRouteName: getRoute()
    });

export default createAppContainer(AppNavigator);

Question
I want to be able to deep link to my React Native application from my iOS widget.
Linking works fine when the app is running in the background, it navigates to the correct page. But when the app is killed, it only opens the app, but does not navigate to the correct page anymore.
I followed this tutorial: https://medium.com/react-native-training/deep-linking-your-react-native-app-d87c39a1ad5e
With a few adjustments from the official documentation: https://facebook.github.io/react-native/docs/linking
AppDelegate.m
#import "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

#import <React/RCTLinkingManager.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
   openURL:(NSURL *)url
   options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
  return [RCTLinkingManager application:application openURL:url options:options];
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity
 restorationHandler:(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler
{
 return [RCTLinkingManager application:application
                  continueUserActivity:userActivity
                    restorationHandler:restorationHandler];
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end

App.js
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';

import Home from './screens/Home';
import Form from './screens/Form';

const AppNavigator = createStackNavigator({
  Home: { screen: Home },
  Form: { screen: Form },
});

export default createAppContainer(AppNavigator);

Home.js
import React, {Component} from 'react';

import {
  Linking,
  Platform,
  Text,
  View,
} from 'react-native';

import Form from './Form';

export default class Home extends Component {
  componentDidMount() {
    if (Platform.OS === 'android') {
      Linking.getInitialURL().then(url => {
        this.navigate(url);
      });
    } else {
      Linking.addEventListener('url', this.handleOpenURL);
    }
  }

  componentWillUnmount() {
    Linking.removeEventListener('url', this.handleOpenURL);
  }

  handleOpenURL = event => {
    console.log(event.url)
    this.navigate(event.url);
  };

  navigate = url => {
    const {navigate} = this.props.navigation;
    const route = url.replace(/.*?:\/\//g, '');

    const routeName = route.split('/')[0];
    if (routeName === 'form') {
      navigate('Form');
    }
  };

  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.h1}>Playground</Text>
      </View>
    );
  }
}

So from my widget I link to the app like this:
extensionContext?.open(URL(string: "playgroundapp://form")! , completionHandler: nil)
Why doesn't it work when the app is not running in the background? I found a few similar questions, but no answers that worked for me or which were outdated.

A: If for iOS you have handled RCTLinkingManager as below
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<NSString *, id> *)options
{
  BOOL handled = [[RNFirebaseLinks instance] application:application openURL:url options:options];

  if(!handled)
  {
    handled = [RCTLinkingManager application:application openURL:url options:options];
  }

  return handled;
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler
{
  BOOL handled = [[RNFirebaseLinks instance] application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
  if(!handled)
  {
    handled = [RCTLinkingManager application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
  }

  return handled;
}

And you have followed the procedure as mentioned at React Native linking.
_dynamicLinkListener; // variable defined to hold listeener instance

 componentDidMount() {
        this.setUpDynamicLink();
        this.setUpDeepLink();
    }

 componentWillUnmount() {
        this.cleanUpDynamicLink();
        this.cleanUpDeepLink();
    }

setUpDynamicLink = () => {
        // will work when link is opening the app
        Firebase.links()
            .getInitialLink()
            .then((url) => {
                this.handleURL(url);
            });

        // listener will work when app is already opened or in background
        this._dynamicLinkListener = Firebase.links().onLink((url) => {
            this.handleURL(url);
        });
    }

setUpDeepLink = () => {
        // will work when link is opening the app
        Linking.getInitialURL().then(url => {
            this.handleURL(url);
        });

        // listener will work when app is already opened or in background
        Linking.addEventListener('url', this.handleURL);
    }

cleanUpDynamicLink = () => {
        this._dynamicLinkListener();
    }

cleanUpDeepLink = () => {
        Linking.removeEventListener('url', this.handleURL);
    }

handleURL = (event) => {
        let url = "";

        if (!event) {
            return "";
        }

        if (typeof event == 'string') {
            url = event;
        } else {
            url = (event.url) ? event.url : "";
        }

        if (!url) {
            return;
        }

        console.debug(url);
    }

Then you are good to go. I was getting deep-link callback when the application was in foreground, background but not in killed state.
Disable debugging for your application and use some Alert to show url instead of using console output. Linking has some issue when debugging is enabled. I was able to see url in alert after this.
Code mentioned above also has Firebase implementation for dynamic links, which you can remove you dont want it.

A: Check with this package.
import dynamicLinks from '@react-native-firebase/dynamic-links';
dynamicLinks().getInitialLink()
      .then(link => {
    // this method will call when app is closer or killed
        console.log('dynamicLinksnew :', link);

      });

dynamicLinks().onLink(async (link) => {
      // this method call when app is in background or foreground
     console.log('dynamicLinks :', link);

    });

A: if you use react-navigation deep link make sure your debugger turns off. and you can see params with Alert component replace

A: write config like this.
const config = {
  ...config,
  const onReceiveURL = ({ url }: { url: string }) => {
       listener(url);
    };

    // Listen to incoming links from deep linking
    Linking.addEventListener('url', onReceiveURL);

    return () => {
      // Clean up the event listeners
      Linking.removeEventListener('url', onReceiveURL);
    };

}


text:
Q: Is mass-energy conversion contradicting energy conservation? If mass can be transformed into energy, and energy transformed back into mass, isn't this at odds with the law of conservation of energy?
Because this would mean, that in theory, it would be possible to let an object fall down a certain distance, performing work along the way, then you would transform the object's mass into energy, transport the energy to a higher level, and rematerialize the object, and let it fall down again, performing work along the way?
This would enable an infinite loop whereby infinite amounts of energy can be gained through the gravitational field.

A: This shows the process you describe:

We drop the mass and it falls a distance $h$ picking up an energy $mgh$ as it falls. Then we convert the mass to a photon and send the photon back upwards. At the top we convert the photon back to a mass and repeat the cycle. The reason this doesn't violate conservation of energy is because of the gravitational redshift of the photon as we send it back upwards.
Light always moves at, well, the speed of light but that doesn't mean gravity has no effect on it. The energy of a photon is given by:
$$ E = h\nu $$
where $\nu$ is the photon frequency. As the photon moves upwards its energy decreases so its frequency $\nu$, decreases and this is the phenomenon known as the gravitational red shift. It turns out that the energy lost due to the gravitational red shift exactly balances out the energy gained by the mass as it falls, so as we go round the cycle the net energy change is zero and energy is conserved.
Let's go through this in detail: we start at the top with a mass $m$ so it has an equivalent energy $mc^2$. We let this fall a distance $h$ so its potential energy increases by $\Delta E = mgh$ so the total energy is $mc^2 + mgh$.
At the bottom we convert the mass to a photon and the photon frequency, $\nu_2$, is given by:
$$ h\nu_2 = mc^2 + mgh $$
Now we send the photon back upwards and as it moves up its frequency decreases to $\nu_1$ due to the gravitational red shift, so its energy decreases by $\Delta E = h\nu_2 - h\nu_1$.
At the top the photon frequency is $\nu_1$, so its energy is now $h\nu_1$, and we convert it back into a mass $M$ given by $hv_1 = Mc^2$. And what we find that the mass we end with, $M$, is exactly the same as the mass we started with, $m$, so the energy we ended with is exactly the same as the energy we started with.
You've probably spotted that I've just claimed the gravitational red shift exactly balances out the energy gained by the falling mass:
$$ h\nu_2 - h\nu_1 = mgh $$
We can prove this, but we're getting into the domain of general relativity so the working gets a bit involved.
Later: I've just realised the question is a duplicate, but I'll leave my answer here anyway in case it is of interest.

A: You can't gain infinite amounts of energy in this way. It takes work to raise the energy back up in the gravitational field... just as much as the work that was done by gravity on the falling mass. So there is no net energy gain in a cycle.
Your mistake is in assuming that only mass experiences gravity. Energy also experiences gravity. For example, even massless photons experience gravity. When they move upward against gravity, they lose energy and redshift. (Photons also cause gravity, despite being massless.)
You can't combine Newton's non-relativistic theory of gravity, in which only mass gravitates, with the relativistic theory of mass-energy conversion. You need to use a consistent nonrelativistic approach, or a consistent relativistic approach.


text:
Q: Loading command line arguments as file while enforcing required args I am working on a project with many command line arguments and I'd like to be able to specify all of the arguments in the form of a file (i.e. JSON), and load this file into an argparse object, instead of pasting them into the terminal every time. I also need to enforce the presence of required arguments. I've found a couple options but none of them do exactly what I need.
If I have something like this
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("--image_path", type=str, required=True)
parser.add_argument("--count", type=int, required=True)

args = parser.parse_args()

One approach might be to add something like this to update the dictionary with the JSON contents
args_dict = vars(args)
with open('path/to/args.json', 'rb') as f:
    args_dict.update(json.load(f))

But an error occurs at the parse_args() line, since it didn't see the required arguments passed in.
The other approach I considered is to use
parser = argparse.ArgumentParser(fromfile_prefix_chars='@')

and just pass the file name, prefixed with @, to the command. The problem here is that I have to convert the dictionary-like format (JSON) to a line-separated list of arguments, as noted in the documentation. This is not trivial in my case.
I also considered just saving the arguments as a line-separated list to begin with, but the way that I know how to do that involves iterating over sys.argv and printing to a text file, which is problematic because I have some args that are assigned default values, which are not represented in sys.argv. I need to record the default values that were used for later reference.
It seems like there should be a simple way to do this, but I'm stumped at the moment.


text:
Q: WPF update two values when a property is changed I've run into some difficulty with the following XAML:
<ListBox x:Name="lstRegion" ItemsSource="{Binding}" SelectionMode="Multiple">
    <ListBox.ItemTemplate>
        <DataTemplate DataType="ListBoxItem">
            <CheckBox  Content="{Binding Element.Region_Code}" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected, Mode=TwoWay}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

This code will update the IsSelected property on the containing ListBoxItem, allowing me to return this content from lstRegion.SelectedItems.
But, I also need to update a value in the ItemsSource when the checkbox IsChecked value changes.
Is there a way to update the value in the ItemsSource as well as the ListBoxItem?  It seems that I can either change one or the other, just not both.
I'm sure I can catch the PropertyChanged event and manually update the value, but that seems like I'm doing an extra step because I don't understand something correctly.  Any help is appreciated.
Here's the class that's used to populate the ItemsSource on the ListBox:
 public class SelectionItem<T> : INotifyPropertyChanged
    {
        #region private fields
        /// <summary>
        /// indicates if the item is selected
        /// </summary>
        private bool _isSelected;
        #endregion

        public SelectionItem(T element, bool isSelected)
        {
            Element = element;
            IsSelected = isSelected;
        }

        public SelectionItem(T element):this(element,false)
        {

        }

        #region public properties
        /// <summary>
        /// this UI-aware indicates if the element is selected or not
        /// </summary>
        public bool IsSelected
        {
            get
            {
                return _isSelected;
            }
            set
            {
                if (_isSelected != value)
                {
                    _isSelected = value;
                    PropertyChanged(this, new PropertyChangedEventArgs("IsSelected"));
                }
            }
        }

        /// <summary>
        /// the element itself
        /// </summary>
        public T Element { get; set; }
        #endregion

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;
   }

A: Something like this should give you what you need:
<ListBox x:Name="lstRegion" ItemsSource="{Binding}" SelectionMode="Multiple">
    <ListBox.ItemTemplate>
        <DataTemplate DataType="ListBoxItem">
            <CheckBox Content="{Binding Element.Region_Code}" IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemContainerStyle>
        <Style TargetType="x:Type ListBoxItem}">
            <Setter Property="IsSelected" Value="{Binding IsSelected}" />
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>


text:
Q: SQL Server : Join Two Tables and Return With Null Records I couldn't figure out how to join these two tables and get the result with NULL value that I want. I played around with LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN..., but couldn't get it to work. Please see this below.
Table1:
NameID  Name
1       N1
2       N2
3       N3
4       N4
5       N5

Table2:
NameID  AnotherID   Value
1       AID-111     1000
2       AID-222     2000
2       AID-222     3000
3       AID-333     4000
4       AID-444     5000

Select ...
JOIN Table1 and Table2
WHERE AnotherID = 'AID-222'

This is the result I want:
NameID  Name    AnotherID   VALUE
1       N1      NULL        NULL
2       N2      AID-222     2000
3       N3      AID-222     3000
4       N4      NULL        NULL
5       N5      NULL        NULL

Please help.
Thanks!

A: You did not explain why you want to return the value of 2000 instead of 3000 but you can use a LEFT JOIN  with a subquery to get the result:
select t1.nameid,
  t1.name,
  t2.anotherid,
  t2.value
from table1 t1
left join
(
  select nameid, anotherid, min(value) value
  from table2
  where anotherid = 'AID-222'
  group by nameid, anotherid
) t2
  on t1.nameid = t2.nameid;

See SQL Fiddle with Demo.  This gives the result:
| NAMEID | NAME | ANOTHERID |  VALUE |
--------------------------------------
|      1 |   N1 |    (null) | (null) |
|      2 |   N2 |   AID-222 |   2000 |
|      3 |   N3 |    (null) | (null) |
|      4 |   N4 |    (null) | (null) |
|      5 |   N5 |    (null) | (null) |

A: We can also use full join,it will give your answer too:
Select t1.nameid,t1.name,t2.anotherid,t2.value from tableA t1
full outer join
(
    select nameid,anotherid,value from tableB
    where anotherid IN ('AID-222','AID-333')

) t2
on t1.nameid = t2.nameid;


text:
Q: Why platform device need to be registered as another device? I'm a beginner in Linux driver development. I've been searched many references but i still didn't get this. That's why i ask here, sorry for that.
I found the codes in my project that the device is registered as a misc device via misc_register in platform driver's probe function. What make me confused is that, in my view, the physical device represented by platform_device has been matched with the platform_driver already, that means the device has been "driven" successfully. Then why we need another misc device? If these misc device and platform device is representing the same physical device, how they bind with each others?

A: misc_register() is mostly just a way of registering an individual character device (character special file) without using up a whole new major device number for a character device driver. It is accessible from user space using the file operation handlers specified by the struct file_operations referred to by the fops member of the struct miscdevice being registered by misc_register().


text:
Q: My C++ functions with Rcpp::List inputs are very slow While C++ and specifically the Rcpp package have been tremendously helpful to me in speeding up my codes, I noticed that my C++ functions which have a list or data frame input argument(arguments of the form Rcpp::DataFrame and Rcpp::List) are very slower compared to my other C++ functions. I wrote a sample code and I wanted to ask for tricks that can make my code faster:
First, let's simulate a List in R that contains two Lists inside of it. Consider myList as a list that includes two lists - measure1 and measure2. measure1 and measure2 are lists themselves each include vectors of measurements for  subjects. Here is the R code:
lappend <- function(lst, ...){
  lst <- c(lst, list(...))
return(lst)
}

nSub <- 30
meas1 <- list()
meas2 <- list()
for (i in 1:nSub){
  meas1 <- lappend(meas1, rnorm(10))
  meas2 <- lappend(meas2, rnorm(10))
}
myList <- list(meas1 = meas1, meas2 = meas2)

Now, suppose I want a C++ function that for each subject, finds summation of measure1 and summation of measure 2 and then creates two new measurements based on these two summation. Finally the function should return these new measurements as a list.
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::List mySlowListFn(Rcpp::List myList, int nSub){
   arma::vec myMult(nSub);
   arma::vec myDiv(nSub);
   for (int i = 0; i < nSub; i++){
     arma::vec meas1_i = Rcpp::as<arma::vec>(Rcpp::as<Rcpp::List>(myList["meas1"])[i]);
     arma::vec meas2_i = Rcpp::as<arma::vec>(Rcpp::as<Rcpp::List>(myList["meas2"])[i]);
     myMult[i] = arma::sum(meas1_i)*arma::sum(meas2_i);
     myDiv[i] = arma::sum(meas1_i)/arma::sum(meas2_i);
   }
   return Rcpp::List::create(Rcpp::Named("myMult") = myMult,
                             Rcpp::Named("myDiv") = myDiv);
}

How can I make the function above faster? I'm particularly looking for ideas that keep the input and output lists in the code (since in my own program dealing with lists is inevitable), but with some tricks to reduce some overhead time. One thing that I thought of was:
 Rcpp::List mySlowListFn(const Rcpp::List& myList, int nSub)

Thanks very much for your help.

A: First, note that copying semantics for lists have changed in recent versions of R (definitely in latest R-devel, not sure if it made it into R 3.1.0), whereby shallow copies of lists are made, and elements within are later copied if they are modified. There is a big chance that if you are running an older version of R, then its more expensive list copying semantics are getting in the way.
That said, here's how I would re-write your function for some extra speed, with a benchmark. sourceCpp it to compare on your own machine.
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::List mySlowListFn(Rcpp::List myList, int nSub){
   arma::vec myMult(nSub);
   arma::vec myDiv(nSub);
   for (int i = 0; i < nSub; i++){
     arma::vec meas1_i = Rcpp::as<arma::vec>(Rcpp::as<Rcpp::List>(myList["meas1"])[i]);
     arma::vec meas2_i = Rcpp::as<arma::vec>(Rcpp::as<Rcpp::List>(myList["meas2"])[i]);
     myMult[i] = arma::sum(meas1_i)*arma::sum(meas2_i);
     myDiv[i] = arma::sum(meas1_i)/arma::sum(meas2_i);
   }
   return Rcpp::List::create(Rcpp::Named("myMult") = myMult,
                             Rcpp::Named("myDiv") = myDiv);
}

// [[Rcpp::export]]
Rcpp::List myFasterListFn(Rcpp::List myList, int nSub) {

  Rcpp::NumericVector myMult = Rcpp::no_init(nSub);
  Rcpp::NumericVector myDiv = Rcpp::no_init(nSub);

  Rcpp::List meas1 = myList["meas1"];
  Rcpp::List meas2 = myList["meas2"];

  for (int i = 0; i < nSub; i++) {

    arma::vec meas1_i(
      REAL(VECTOR_ELT(meas1, i)), Rf_length(VECTOR_ELT(meas1, i)), false, true
    );

    arma::vec meas2_i(
      REAL(VECTOR_ELT(meas2, i)), Rf_length(VECTOR_ELT(meas2, i)), false, true
    );

    myMult[i] = arma::sum(meas1_i) * arma::sum(meas2_i);
    myDiv[i] = arma::sum(meas1_i) / arma::sum(meas2_i);
  }

  return Rcpp::List::create(
    Rcpp::Named("myMult") = myMult,
    Rcpp::Named("myDiv") = myDiv
  );
}

/*** R
library(microbenchmark)
lappend <- function(lst, ...){
  lst <- c(lst, list(...))
  return(lst)
}

nSub <- 30
n <- 10
meas1 <- list()
meas2 <- list()
for (i in 1:nSub){
  meas1 <- lappend(meas1, rnorm(n))
  meas2 <- lappend(meas2, rnorm(n))
}
myList <- list(meas1 = meas1, meas2 = meas2)
x1 <- mySlowListFn(myList, nSub)
x2 <- myFasterListFn(myList, nSub)
microbenchmark(
  mySlowListFn(myList, nSub),
  myFasterListFn(myList, nSub)
)
*/

gives me
> library(microbenchmark)

> lappend <- function(lst, ...){
+   lst <- c(lst, list(...))
+   return(lst)
+ }

> nSub <- 30

> n <- 10

> meas1 <- list()

> meas2 <- list()

> for (i in 1:nSub){
+   meas1 <- lappend(meas1, rnorm(n))
+   meas2 <- lappend(meas2, rnorm(n))
+ }

> myList <- list(meas1 = meas1, meas2 = meas2)

> x1 <- mySlowListFn(myList, nSub)

> x2 <- myFasterListFn(myList, nSub)

> microbenchmark(
+   mySlowListFn(myList, nSub),
+   myFasterListFn(myList, nSub)
+ )
Unit: microseconds
                         expr    min      lq  median      uq    max neval
   mySlowListFn(myList, nSub) 14.772 15.4570 16.0715 16.7520 42.628   100
 myFasterListFn(myList, nSub)  4.502  5.0675  5.2470  5.8515 18.561   100

Future versions of Rcpp and Rcpp11 will have the ListOf<T> class which will make it much easier to interact with lists where we know the inner type beforehand, after the proper semantics have been ironed out.


text:
Q: How to create tar.gz file in windows by only one step? I know that i can create tar.gz file by 7-zip in two steps. First step for tar format and second for tar.gz format. But is there a way to get tar.gz in only one step ?

A: After digging into the 7-zip source code, i extended the 7-zip context menu by adding "add to tar.gz" item. and it works !


text:
Q: Triangular link area Consider the following shapes:

*

*The grey area is an outside container. Disregard that.

*The white area is a link (a tag).

*The red triangular area is another link (a tag).

I have created a CSS triangle for the red area using the following code:
.ribbon {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 60px;
    height: 60px;
    border-left: 60px solid transparent;
    border-bottom: 60px solid red;
}

The problem is that in the following image, the link doesn't maintain it's boundaries in the red triangle shape. The in green triangle is also clickable :

Question is:
How do I make the red area link to one location, and the white to another, without having the browser count the green area in the second illustration as part of the red area?

A: Here's a solution using transform: skew: http://jsfiddle.net/0a8aq5ve/.
HTML:

CSS:
div {
    width: 100px;
    height: 100px;
    overflow: hidden;
}

div > a {
    display: block;
    height: 100%;
    background-color: red;
    transform-origin: bottom left;
    transform: skewX(-45deg);
}

A: The border technique won't allow you to maintain the boundaries of the hover and click event inside the triangular shape. You can use transform rotate on the link combined with oveflow:hidden; on the parent element to allow click and hover event only inside the triangle :
DEMO

html,body{
    height:100%;
    margin:0;
    padding:0;
}
div{
    height:90%;
    border:10px solid lightgrey;
    position:relative;
    overflow:hidden;
}
a{
    position:absolute;
    bottom:0;
    width:100%; height:20%;
    background:red;
    -webkit-transform-origin: 100% 0;
    transform-origin: 100% 0;
    -webkit-transform: rotate(-45deg);
    transform: rotate(-45deg);
}

This solution is adapted from this answer : CSS triangles with transform rotate.

EDIT :
This demo shows you can differenciate the click envent between gold and red areas :
DEMO

#area {
    height:50%;
    border:10px solid lightgrey;
    position:relative;
    overflow:hidden;
}
.gold{
    display:block;
    height:100%;
    background:gold;
}
.red {
    position:absolute;
    bottom:0;
    width:100%; height:20%;
    background:red;
    -webkit-transform-origin: 100% 0;
    transform-origin: 100% 0;
    -webkit-transform: rotate(-45deg);
    transform: rotate(-45deg);
}
/* FOLLOWING JUST FOR THE DEMO */
 html, body {height:100%;margin:0;padding:0;overflow:hidden;}
a{color:teal;text-decoration:none;font-family:arial;font-size:20px;padding:5%;text-align:center;}
#goldLink, #redLink {position:absolute;top:50%;left:100%;width:100%;text-align:center;}
#goldLink:target {background:gold;left:0;}
#redLink:target {background:red;left:0;}

        Click gold and red areas to see the diference.

        Triangular boundaries are maintained.

Gold area clicked

Red area clicked

A: Try this :
.triangle {
 width: 0;
 height: 0;
 border-bottom: 100px solid red;
 border-left: 100px solid transparent;
 }

A: Try that, instead of making a CSS triangle with borders, make a square a and rotate it to 45°:
.ribbon {
position: absolute;
right: 0;
bottom: 0;
width: 60px;
height: 60px;
transform: rotate(45deg);
}

And be sure to make the parent overflow: hidden; or all the red square will be visible :)


text:
Q: How to store the Visual C++ debug settings? The debug settings are stored in a .user file which should not be added to source control. However this file does contain useful information. Now I need to set each time I trying to build a fresh checkout.
Is there some workaround to make this less cumbersome?
Edit: It contains the debug launch parameters. This is often not really a per-user setting. The default is $(TargetPath), but I often set it to something like $(SolutionDir)TestApp\test.exe with a few command line arguments. So it isn't a local machine setting per se.

A: Well, I believe this file is human readable (xml format I think?), so you could create a template that is put into source control that everyone would check out, for instance settings.user.template. Each developer would than copy this to settings.user or whatever the name is and modify the contents to be what they need it to be.
Its been a while since I've looked at that file, but I've done similar things to this numerous times.

A: Set the debug launch parameters in a batch file, add the batch file to source control. Set the startup path in VS to startup.bat $(TargetPath).


text:
Q: Can XMLHttpRequest data be stored in localStorage? I am writing a Safari extension that makes an XMLHttpRequest for some XML data using jQuery.ajax. If I do console.log(data) in the process data function, I get an item Document which I can traverse.
I want to store this ajax data in localStorage. So in the first few lines of the processDocument function I have this:
function processResponse(data) {
    localStorage.removeItem("myData");
    localStorage.setItem("myData", data);
    console.log('post-load: there are ' + localStorage.length + ' items in the local storage array.');
    console.log("post-load data: " + data);
    console.log("post-load myData: " + localStorage.myData);

The console.log will show me:
post-load: there are 1 items in the local storage array.
post-load data: [object Document]
post-load myData: [object Document]
So it looks like I have valid data here. But the messageHandler function when it responds to the button on the toolbar also polls the local storage like this:
console.log('There are ' + localStorage.length + ' items in the local storage array.');
for (var x = 0; x < localStorage.length; x++) {
    console.log(x + ": " + localStorage[x]);
}
if (localStorage.myData == undefined) {
    console.log("myData is undefined");
    doSomething();
} else {
    console.log("myData is defined");
    doSomethingElse();
}

The console log here will show:
There are 1 items in the local storage array.
0: undefined
myData is defined
Is there something I need to do in order to properly store this XML data in localStorage? Shouldn't localStorage preserve the integrity of this object? Perhaps I am missing something here.

A: Despite what your initial debug output appears to be telling you, Local storage doesn't store objects it stores strings.  To get XML back you should store it as a string and then parse the string back into XML when you retrieve it.  This answer describes one approach, you may need to adapt it specifically for XML.


text:
Q: Basic Python Class Im just try to build a basic class so that I can learn some more about python.
So far I have the following :
class Bodymassindex:
  count = 0
  def __init__(self,name,weight,height):
    self.name = name
    self.weight = 14 * weight
    self.height = 12 * height
    notes = "no notes have been assigned yet"
    bmitotal = 0
    Bodymassindex.count += 1

  def displayCount(self):
    print "Total number of objects is %d" % Bodymassindex.count

  def notesBmi(self,text):
    self.notes = text

  def calcBmi(self):
    return ( self.weight * 703 ) / ( self.height ** 2 )

In terms of adding a note variable and viewing what is the correct way of doing so ?
Thanks,

A: The bmitotal and notes variables in __init__ will be local and garbage collected when __init__ finishes, so initializing them like that is useless. You probably want to initialize them as self.notes and self.bmitotal
Bodymassindex.count would be like a static variable, which shares its value with all the instances.

A: Just access the attribute:
class BodyMassIndex(object): #Inheriting from object in 2.x ensures a new-style class.
  count = 0
  def __init__(self, name, weight, height):
    self.name = name
    self.weight = 14 * weight
    self.height = 12 * height
    self.notes = None
    self.bmitotal = 0
    BodyMassIndex.count += 1

  def display_count(self):
    print "Total number of objects is %d" % BodyMassIndex.count

  def calculate_bmi(self):
    return ( self.weight * 703 ) / ( self.height ** 2 )

test = BodyMassIndex("bob", 10, 10)
test.notes = "some notes"
print(test.notes)

There is nothing wrong with direct access in Python. As others have noted, it's likely you meant to make notes and bmitotal instance variables, which I have done here.


text:
Q: odd IE9 with xml, php, curl I have a php function that communicates with UPS using curl, xml.The script was given to me and i dont know much about it.
It works in every browser except IE9
The function returns something like this:

HTTP/1.1 200 OK Date: Tue, 06 Dec 2011 21:36:41 GMT Server: Apache
  Pragma: no-cache Content-Length: 1481 X-Powered-By: Servlet/2.5
  JSP/2.1 Vary: User-Agent Content-Type: application/xml

it goes on to show all the responses
 from ups in xml
here is the function with the curl and xml parameters.
function ups($dest_zip,$service,$weight,$length,$width,$height) {

        // This script was written by Mark Sanborn at http://www.marksanborn.net
        // If this script benefits you are your business please consider a donation
        // You can donate at http://www.marksanborn.net/donate.

        // ========== CHANGE THESE VALUES TO MATCH YOUR OWN ===========

          $AccessLicenseNumber = '000000009F002AC0'; // Your license number

          $UserId = '+++++'; // Username

          $Password = '+++++'; // Password

          $PostalCode = '01862'; // Zipcode you are shipping FROM

          $ShipperNumber = '++++'; // Your UPS shipper number

        // =============== DON'T CHANGE BELOW THIS LINE ===============

            $data ="<?xml version=\"1.0\"?>
            <AccessRequest xml:lang=\"en-US\">
                <AccessLicenseNumber>$AccessLicenseNumber</AccessLicenseNumber>
                <UserId>$UserId</UserId>
                <Password>$Password</Password>
            </AccessRequest>
            <?xml version=\"1.0\"?>
            <RatingServiceSelectionRequest xml:lang=\"en-US\">
                <Request>
                    <TransactionReference>
                        <CustomerContext>Bare Bones Rate Request</CustomerContext>
                        <XpciVersion>1.0001</XpciVersion>
                    </TransactionReference>
                    <RequestAction>Rate</RequestAction>
                    <RequestOption>Rate</RequestOption>
                </Request>
            <PickupType>
                01
            </PickupType>
            <Shipment>
                <Shipper>
                    <Address>
                        <PostalCode>$PostalCode</PostalCode>
                        <CountryCode>US</CountryCode>
                    </Address>
                <ShipperNumber>$ShipperNumber</ShipperNumber>
                </Shipper>
                <ShipTo>
                    <Address>
                        <PostalCode>$dest_zip</PostalCode>
                        <CountryCode>US</CountryCode>
                    <ResidentialAddressIndicator/>
                    </Address>
                </ShipTo>
                <ShipFrom>
                    <Address>
                        <PostalCode>$PostalCode</PostalCode>
                        <CountryCode>US</CountryCode>
                    </Address>
                </ShipFrom>
                <Service>
                    $service
                </Service>
                <Package>
                    <PackagingType>
                        02
                    </PackagingType>
                    <Dimensions>
                        <UnitOfMeasurement>
                            IN
                        </UnitOfMeasurement>
                        <Length>$length</Length>
                        <Width>$width</Width>
                        <Height>$height</Height>
                    </Dimensions>
                    <PackageWeight>
                        <UnitOfMeasurement>
                            LBS
                        </UnitOfMeasurement>
                        <Weight>$weight</Weight>
                    </PackageWeight>
                </Package>
            </Shipment>
            </RatingServiceSelectionRequest>";
            $ch = curl_init("https://www.ups.com/ups.app/xml/Rate");
            //curl_setopt($ch, CURLOPT_HEADER, 1);
            curl_setopt($ch,CURLOPT_POST,0);
            curl_setopt($ch,CURLOPT_TIMEOUT, 60);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
            $result=curl_exec ($ch);
        echo ''; // THIS LINE IS FOR DEBUG PURPOSES ONLY-IT WILL SHOW IN HTML COMMENTS
            $data = strstr($result, '<?');
            $xml_parser = xml_parser_create();
            xml_parse_into_struct($xml_parser, $data, $vals, $index);
            xml_parser_free($xml_parser);
            $params = array();
            $level = array();
            foreach ($vals as $xml_elem) {
             if ($xml_elem['type'] == 'open') {
            if (array_key_exists('attributes',$xml_elem)) {
                 list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
            } else {
                 $level[$xml_elem['level']] = $xml_elem['tag'];
            }
             }
             if ($xml_elem['type'] == 'complete') {
            $start_level = 1;
            $php_stmt = '$params';
            while($start_level < $xml_elem['level']) {
                 $php_stmt .= '[$level['.$start_level.']]';
                 $start_level++;
            }
            //$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
            if (isset($xml_elem['value'])) {
                $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
                }
                else {
                $php_stmt .= '[$xml_elem[\'tag\']] = "";';
                }

            eval($php_stmt);
             }
            }
            curl_close($ch);
            return $params['RATINGSERVICESELECTIONRESPONSE']['RATEDSHIPMENT']['TOTALCHARGES']['MONETARYVALUE'];
        }

The page will not render the HTML
I have no clue what I am doing. HELP!

A: Double check that the output of headers hasn't been enabled
curl_setopt($curl_handle, CURLOPT_HEADER,1);

Comment out that line or set it to false.


text:
Q: OpenCV Release build error: expected a type specifier I'm getting some build error in my application (using OpenCV 3.0) when I compile it in release mode (MT runtime library, Visual Studio Express 2012 Update 5).
The build is fine in Debug mode (MTd).
The two builds link against the proper static libraries ("d" for debug, not for release) and the error happens before the linking stage, in the cvstd.hpp file.
This is a x64 build and WIN32 is defined (one of the libraries needs it).
Error in cvstd.hpp @ line 155: expected a type specifier
/*!
  The STL-compilant memory Allocator based on cv::fastMalloc() and cv::fastFree()
*/
template<typename _Tp> class Allocator
{
public:
    typedef _Tp value_type;
    typedef value_type* pointer;
    typedef const value_type* const_pointer;
    typedef value_type& reference;
    typedef const value_type& const_reference;
    typedef size_t size_type;
    typedef ptrdiff_t difference_type;
    template<typename U> class rebind { typedef Allocator<U> other; };

    explicit Allocator() {}
    ~Allocator() {}
    explicit Allocator(Allocator const&) {}
    template<typename U>
    explicit Allocator(Allocator<U> const&) {}

    // address
    pointer address(reference r) { return &r; }
    const_pointer address(const_reference r) { return &r; }

    pointer allocate(size_type count, const void* =0) { return reinterpret_cast<pointer>(fastMalloc(count * sizeof (_Tp))); }
    void deallocate(pointer p, size_type) { fastFree(p); }

    void construct(pointer p, const _Tp& v) { new(static_cast<void*>(p)) _Tp(v); }
    void destroy(pointer p) { p->~_Tp(); }

    size_type max_size() const { return cv::max(static_cast<_Tp>(-1)/sizeof(_Tp), 1); }
};

The error is at the void construct(...) line. I have no idea if it's a bug, an incompatibility with VC2012 STL implementation, or what?
I tried the 2.4.9, with same results.
Anybody?
Thanks!


text:
Q: QGIS 3.4.5-1 'Madeira' doesn't launch This has been probably asked many times before; looking for answers to no avail. After first click this is what I get ...

then this ...

I'm still stuck with QGIS 2.18 'Las Palmas'
I'm not savvy with programming or computer science or anything in that sphere. I'm a landscape architect who happens to use QGIS for variety of analyses but definitely not as intense as GIS professionals.


text:
Q: CouchDB read authorization In couchdb website -> technical overview -> security and validation -
http://couchdb.apache.org/docs/overview.html - it writes that (on reader access
part) "To protect document contents, CouchDB documents can have a reader list.
This is an optional list of reader-names allowed to read the document. When a
reader list is used, protected documents are only viewable by listed users." I
searched about how to use it but i found nothing. So is it actually used and if
it is how?
Thanks.
-- Mustafa

A: You are right, it is confusing. Please see the 0.11 "breaking" changes for more information.
Per-document read control is not possible; the readers field is for access to the entire DB. For more information, load your database in Futon and click the Security... link at the top.
The reason read control is not possible is because views (map and reduce) can draw information from all documents in the database, so it is generally impossible to prevent users from seeing private data in some form.
For detailed access control, you have two major choices:

*

*Have an application between your users and the DB. 99% of web applications using MySQL do this already (e.g. Ruby on Rails). Keep ACL information in the DB and your application grants/rejects access based on the ACL.

*Keep a dedicated database per user. You may have to modify your architecture but maybe not. You can use replication with a filter to copy only a user's data into his database. Then he reads from his database and writes to the central database.

A: *

*Login to the CouchDB as admin.

*Open a particular database you want to secure

*Click on Security button of that particular database.

*Add users to Members names who can read. (At least add admins username) as string element of an array.
Ex.
Names: ["username1", "username2"]

*Click on update button

Click here to see the image


text:
Q: Why doesn't SO syntax-highlight my PHP code?
Possible Duplicate:
Syntax highlighting language hints
Changes to syntax highlighting

I just asked a question on SO Facebook API scope and it's refusing to do a syntax highlight on my PHP code.
Is there anything extra required other than four spaces before each code line?

A: As announced in 2010 and specified on the Markdown Help Page, you have to either to tag with php or use one of the prettify language codes (<!-- language: lang-php -->) before the code.
E.g.
<!-- language: php -->

    // This is some PHP
    phpinfo();

https://github.com/google/code-prettify


text:
Q: Включение функции при подгрузе контента ajax Есть <script class="script" type="text/javascript" src="../js/main.js"></script>
на главной странице, но так функция не вызвается, и в один из блоков этой страницы мне необходимо подгружать контент и выполнять определенный js код, если подгружать эту строку <script class="script" type="text/javascript" src="../js/main.js"></script> в подгружаемый контент , то оно  накладывается и получается, что код выполняется сначала 1 раз , потом 2 , потом 3 и тд. Как можно решать эту проблему?


text:
Q: What is Kotlin's impact on JVM performance? I'm aware that functional programming/lambdas aren't the best option on the Java world when extreme high performance is the goal. Kotlin address to that issue with the inline keyword.
When Kotlin is compiled and lambdas are inlined, it is actually creating bigger methods and JIT has a hard cap of N bytes to inline to native code. With that in mind, doesn't Kotlin's inline hurts JIT's inlining and therefore affects performance?
Also, I noticed that Kotlin adds A LOT of nullchecks to the compiled code, those checks are really small methods and definitely are inlined by JIT, but due to the amount of calls, couldn't that also be a performance issue?
So, if you are aiming to the highest possible performance, what is Kotlin's impact on JVM?
Side node: I know, I know.. "over optimization is the evil of all roots", "you shouldn't care for performance at this level".

A: You can override the limit of what inlining value to use for bytecode. See the answer at What is the size of methods that JIT automatically inlines? for more details.
I'm surprised there's lots of null checks in the bytecode though. Normally Java doesn't do that and instead lets the CPU handle those automatically and with higher performance.
They may be elided by the JVM's JIT though so perhaps won't be an issue once warmed up, but if you want the higher performance you probably want to put your server through dummy data runs to ensure that the JIT is warmed up. There's nothing worse than a warm JIT hitting a compilation event and having to go through it all again.
If you look out for the JIT compilation events and look out for "hot method" messages not bring compiled or online then you can tweak those methods individually.
Generally though, if you avoid lambda then you'll find the JVM won't need to do so much inlining, and worse won't need to do as much allocating. Lambdas are pretty terrible at accidentally capturing state and causing allocations to occur. Ideally in a high throughput/low latency system you want to avoid as much allocation as possible.


text:
Q: Why am I getting rsExecutionNotFound in SSRS integrated mode? I'm currently setting up a SharePoint Foundation Farm with a front-end server hosting central administration (which we'll refer to as spfrontend) and a Sql Server with SSRS in SharePoint Integrated mode (which we'll refer to as ssrsserver). I can run SSRS reports uploaded to my SharePoint Site by navigating to the report through http://ssrsserver/ReportServer interface, and the reports render as expected. However, when I try to access it though the http://spfrontend/MySite interface, regardless of accessing it as a webpart on a webpart page, or clicking on the link directly, it always returns an error similar to the following:

Execution 'mofg0y450k5icx55iz1z31bj' cannot be found (rsExecutionNotFound)

Neither of the application logs on the ssrsserver or the spfrontend machines are reporting any special errors. How can I get the spfrontend server to correctly display my reports?

A: Sharepoint Foundation and Server 2010 require SQL Server 2008 R2 (Version 10.50). SQL Server 2008 (Version 10.00) itself will allow you to go through all the integration steps, but rendering a report on the site will yield the described error.


text:
Q: ZXing.Net.Mobile does not start scanning immediately I have a page with ScannerView as MainPage. When I start the app it can't scan a barcode. I have to set another page as mainpage then navigate to the scanner page, before it can scan a barcode. Or lock and then unlock the phone, then it will start scanning.
App.xaml.cs:
MainPage = new NavigationPage(new ScannerPage());

ScannerPage.xaml:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyApp.Pages.ScannerPage"
             xmlns:zxing="clr-namespace:ZXing.Net.Mobile.Forms;assembly=ZXing.Net.Mobile.Forms">
    <ContentPage.Content>
        <Grid>
            <zxing:ZXingScannerView x:Name="ScannerView"
                                    IsScanning="True"
                                    IsAnalyzing="True" />
            <zxing:ZXingDefaultOverlay x:Name="ScannerOverlay"
                                       TopText="Hold your phone up to the QR code"
                                       BottomText="Scanning will happen automatically"
                                       ShowFlashButton="True"/>
        </Grid>
    </ContentPage.Content>
</ContentPage>

ScannerPage.xaml.cs:
public partial class ScannerPage : ContentPage
{
    public ScannerPage ()
    {
        InitializeComponent ();

        ScannerView.Options = new MobileBarcodeScanningOptions
        {
            PossibleFormats = new List<BarcodeFormat>
            {
                BarcodeFormat.DATA_MATRIX,
            },
            TryHarder = true
        };

        ScannerView.OnScanResult += (result) => Device.BeginInvokeOnMainThread(async () =>
        {
            ScannerView.IsAnalyzing = false;
            await DisplayAlert("Scanned", result.Text, "Ok");
            ScannerView.IsAnalyzing = true;
        });
    }
}

A: I ended up using the following code programmatically:
    public static async Task ScanConnection()
    {
            MobileBarcodeScanningOptions options = new ZXing.Mobile.MobileBarcodeScanningOptions()
                {
                    TryHarder = true,
                    PossibleFormats = new List<ZXing.BarcodeFormat>() { ZXing.BarcodeFormat.QR_CODE }
                };

                MobileBarcodeScanner scanner = new ZXing.Mobile.MobileBarcodeScanner();

                ZXing.Result result = await scanner.Scan(options);

                if (result != null && !string.IsNullOrEmpty(result.Text))
                {
                    ...
                }
    }

You could call that code from an overridden OnAppearing() method from within your derived page.

A: I had a similar issue. At the first invocation of the scanner page, it would attempt to scan but wouldn't recoqnise any barcodes. After exiting the page and re-opening it, the problem disappeared.
Solution that worked in my case was adding the following in two places:
ZXing.Mobile.MobileBarcodeScanner.Initialize(Application);

*

*in AndroidManifest.xml

    ZXing.Net.Mobile.Forms.Android.Platform.Init();
    ZXing.Mobile.MobileBarcodeScanner.Initialize(Application);
    </manifest>

*Also MainActivity.cs (yours may be different)

         public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
        {
            protected override void OnCreate(Bundle savedInstanceState)
            {
                TabLayoutResource = Resource.Layout.Tabbar;
                ToolbarResource = Resource.Layout.Toolbar;
                base.OnCreate(savedInstanceState);
                ZXing.Net.Mobile.Forms.Android.Platform.Init();
                ZXing.Mobile.MobileBarcodeScanner.Initialize(Application);
                global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
                LoadApplication(new App());
            }
            //needed for zxing scanner..
            public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
            {
                global::ZXing.Net.Mobile.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }


text:
Q: C Socket EPOLLRDHUP not reliable I have a C program that uses epoll_ctl.
It waits for connections on a specific port, and when a device connects it determines if the device needs an updated firmware version or not. If it does, it sends the firmware version found on the linux host.
Where I am having trouble is detecting if the device receiving the update disconnects abruptly.
As I need to know this as the server only allows x# of devices to connect and then when the 1 device connects that exeeds this limit I need to restart the service. But only if I know that no devices are getting updates at the time.
I tried checking EPOLLRDHUP but this doesn't seem to work reliably. Any help would be appreciated thanks.


text:
Q: Is there a quick way to compute the order of this element in $GL(2,\mathbb{Z}/5\mathbb{Z})$? Is there a quick way to compute the order of the element
$\begin{bmatrix}0 & 2\\2 & 4\end{bmatrix}$
in $GL(2,\mathbb{Z}/5\mathbb{Z})$?
I think the order of the group is $(5^2-1)(5^2-5)=480$, so the order of the element would need to divide it… but there's lots of possibilities.

A: It really should not be too hard to compute the first couple of powers of this matrix.
But you can also compute its characteristic polynomial and use that $4=-1$ in $\mathbb Z/5$, which makes it
$$T^2+T+1$$
which you might now is the third cyclotomic polynomial, in particular divides $T^3-1$, and so must the minimal polynomial, hence ...

Added: Quite generally, a short consideration of possible Jordan blocks / eigenvalues / characteristic polynomials, together with the fact that $\mathbb F_5$ has a unique quadratic extension $\mathbb F_{5^2}$, shows -- as user Servaes points out in a comment -- that the maximal possible order of any element in $GL_2(\mathbb Z/5)$ is $24$. And indeed this maximal order is attained e.g. by $$\begin{bmatrix} 2&2\\2&1 \end{bmatrix} = 2\cdot Id_2 + \begin{bmatrix} 0&2\\2&4 \end{bmatrix}.$$
To find this and/or see that this has order $24$, note that your element $\xi_3 := \begin{bmatrix} 0&2\\2&4 \end{bmatrix}$ via the first part of this answer basically behaves like a primitive third root of unity. To find a generator of the multiplicative group of $\mathbb F_5(\xi_3) \simeq \mathbb F_{5^2}$, obviously $\mathbb F_5$-multiples of $\xi_3$ will not do. Next I tried $1 + \xi_3$, but that is well-known to be a primitive sixth root of unity. So the next I checked is $2+\xi_3$, where we get
$$(2 + \xi_3)^2 = 4 + 4 \xi_3 + \xi_3^2 = 4+4\xi_3 - \xi_3 - 1 = 3+3\xi_3 = 3\cdot (1+\xi_3).$$
That's a bingo, because $3 \in \mathbb F_5$ is a primitive fourth root of unity, and as just recorded $(1+\xi_3)$ is a primitive sixth one, so their product is a primitive twelfth ($12 =lcm(4,6)$) root of unity, and hence its square root there must be a primitive $24$-th one.
Of course there are many others.


text:
Q: Understanding which P FET to use for reverse polarity protection I use a Schottky diode as reverse polarity protection on earlier versions but have decided to change to something more appropriate and energy efficient.
The voltage input on the left is a 12-14.8 V vehicle battery and current will not be more than about 500 mA @ 12 V.
I want to use an AO3401 N-MOSFET as it is a basic part with JLCPCB for manufacture and it's small. However, I'm not sure it will work as Vgs is about 12 V but Vds is 30 V.
Does that mean it is not suitable for this use? I also know I need a Zener diode between the source and gate of the FET.

A: If the vehicle battery is discharged so that the MOSFET is partially on then the MOSFET will overheat and likely be destroyed due to the diminutive package of the AO3401.
I don't see any significant disadvantage in using a Schottky diode if that is your actual circuit- the drop out will be increased by a few hundred mV but it won't save any energy at all, just move some mW from the linear regulator to the diode.
As you know, vehicle electrical systems can have large and destructive transients (load dump and so the MOSFET ratings may also be insufficient depending on what protection you've added. As you say, the Zener is definitely required, but 30V Vds rating does not leave much margin for the suppression circuitry to work with.