Q: using destructuring switch statement in es6 Is there a way to use the destructuring feature in switch ... case statement instead of using nested if else statements ??
For example I would expect something like this :
const tall = true;
const clean = true;

switch ([tall, clean]) {
    case [true,true]:
        console.log("Perfect");
        break;
    case [false,true]:
        console.log("Ok");
        break;
    case [true,false]:
        console.log("Not so good");
        break;
    default:
        console.log("Terrible");
}

instead of using :
if (tall){
    if (clean){
        ...
    }else{
        ...
    }
}else{
    if (clean){
        ...
    }else{
        ...
    }
}

A: No, this has nothing to do with destructuring and No, you cannot use array literals in a switch statement since distinct objects never compare equal.
What you can do in your case is to map your two booleans to an integer score:
switch (clean * 2 + tall) {
    case 3:
        console.log("Perfect");
        break;
    case 2:
        console.log("Ok");
        break;
    case 1:
        console.log("Not so good");
        break;
    case 0:
        console.log("Terrible");
}

or the equivalent array lookup:
console.log(["Terrible", "Not so good", "Ok", "Perfect"][clean * 2 + tall]);

You might even want to make the bitwise magic more obvious:
switch (tall << 1 | clean << 0) {
    case true << 1 | true << 0:
        console.log("Perfect");
        break;
    case false << 1 | true << 0:
        console.log("Ok");
        break;
    case true << 1 | false << 0:
        console.log("Not so good");
        break;
    case false << 1 | false << 0:
        console.log("Terrible");
        break;
}

You can also call a helper function score(a, b) { return a << 1 | b << 0 } in both the switch and the cases.

A: Indeed, you can only use literals in a switch statement and you can't use primitive objects as keys in an array, so you can't do a mapping like:
{[true,true]: 'Perfect'
...}

Too bad. I wonder if there are languages where you can have a list/array as dictionary key.
I still might be tempted to do something like this which I think is quite readable (though it might get rejected in a code review!):
function hashKey([tall, clean]) {
  return `${tall}_${clean}`
}

let valMap = {
  'true_true': 'Perfect',
  'false_true': 'Ok',
  'true_false': 'Not so good',
  'false_false': 'Terrible'
}

console.log(valMap[hashKey([true, true ])])

A: Can do something like the following:

const tall = true;
const clean = false;

switch (true) {
    case tall && clean:
        console.log("Perfect");
        break;
    case !tall && clean:
        console.log("Ok");
        break;
    case tall && !clean:
        console.log("Not so good");
        break;
    default:
        console.log("Terrible");
}


Q: Gutenberg : how can I get the title of the current block within its 'edit' function? I'm a Gutenberg newbie.
I'm trying to display a placeholder component with my block's edit function:
export default function Edit( { attributes, setAttributes, className } ) {
  return (
    <Placeholder
      icon={ icon }
      label={ title }
    >
  );
}

I would like to display the block icon and title, as they have been defined within the function registerBlockType.
Could someone point me how to do this ?
Thanks !

A: You can use wp.blocks.getBlockType() to get the block type's settings.
So if you've registered a block type with the name my-guten/foo-block, just run getBlockType( 'my-guten/foo-block' ) to get the block type's title, icon, etc.
const { registerBlockType, getBlockType } = wp.blocks;

// Register a block type.
registerBlockType( 'my-guten/foo-block', { ... } );

// Get the block type settings (title, icon, etc.).
const blockType = getBlockType( 'my-guten/foo-block' );

// Inspect the settings:
console.log( blockType );

And from within a block type's edit function, the block type's name is passed as a property named name in the first function argument which is an object with other properties like attributes and className. So for examples:
// Using a Dashicons icon.
registerBlockType( 'my-guten/foo-block', {
    title: 'Foo Block',
    icon: 'heart',
    category: 'common',
    edit: function ( props ) {
        const blockType = getBlockType( props.name );

        console.log( blockType.title ); // Foo Block

        ... your code.
    },
    ... your code.
} );

// Using an SVG icon. (JSX)
registerBlockType( 'my-guten/foo-block', {
    title: 'Foo Block',
    icon: <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="none" d="M0 0h24v24H0V0z" /><path d="M19 13H5v-2h14v2z" /></svg>,
    category: 'common',
    // Unpack the first argument — so that we can use "name" and not props.name.
    edit: function ( { name } ) {
        const blockType = getBlockType( name );

        ... your code.
    },
    ... your code.
} );

Example based on your code
In edit.js:
const { getBlockType } = wp.blocks;
const { Placeholder } = wp.components;

export default function Edit( { attributes, setAttributes, className, name } ) {
    const blockType = getBlockType( name );

    return (
        <Placeholder
            icon={ blockType.icon.src }
            label={ blockType.title }
        />
    );
}

In index.js:
import Edit from './edit';

const { registerBlockType } = wp.blocks;

registerBlockType( 'my-guten/foo-block', {
    edit: Edit,
    ... your code.
} );


Q: Let $f(x,y) = \frac {-1}4 (3xy^2 - 5x^3y + 2x^4)$. Find the equation of the tangent plane to $f$ at the point $(2,4)$.
Let $f(x,y) = \frac {-1}4 (3xy^2 - 5x^3y + 2x^4)$. Find the equation of the tangent plane to $f$ at the point $(2,4)$.

Using vector dot product with:
$a = 2$
$b = 4$
$f(a,b) = -8$
$\frac {\partial f} {\partial x}(a,b) = -56$
$\frac {\partial f} {\partial y}(a,b) = -22$
I worked out the answer:
$56x + 22y - 2 = 192$
but according to the solution sheet this is wrong. Would really appreciate help on where I am going wrong.
Thanks!

A: @samuel With the information above and the equation of a tangent plane to be $z-z_o=F_x(x-x_o)+F_y(y-y_o)$ you can now plug in all the info we have:
$z + 8 = 32 (x-2)-2(y-4)$ Work this out and that should be it.

A: So, we have
$$f(x,y) = -\frac{1}{4}(3xy^2 - 5x^3y + 2x^4).$$
Then, $$f_x(x,y) = -\frac{1}{4}(3y^2 - 15x^2y + 8x^3),$$
and
$$f_y(x,y) = -\frac{1}{4}(6xy - 5x^3).$$
From this I get $f_x(2,4) = 212$ and $f_y(2,4) = -2$, which doesn't agree with what you got.  Maybe that's why things aren't working out?


Q: Contribution to the emblackening factor from massive gravitons I have been studying the effects of massive gravitons on the emblackening factor $f(r)$; i.e., given a Reissner-Nordstrom AdS geometry
$$ds^2=L^2 \left(\frac{dr^2}{f(r)r^2}+\frac{-f(r)dt^2+dx^2+dy^2}{r^2}  \right)\quad(\textrm{Eqn. } 1) $$
and
$$A(r)=\mu\left(1-\frac{r}{r_0}\right)dt\quad(\textrm{Eqn. } 2) $$
how does $f(r)$ change if we have an additional term in the action proportional to $m^2$, where $m$ is the mass of the graviton and $r_0$ is the black hole event horizon? The additional mass terms from the graviton are discussed here ( "Holography without translational symmetry", by Vegh), and the end result is an emblackening factor given by Eqn. 26:
$$f(r)=1+\alpha F\frac{L m^2}{2}+\beta F^2 m^2 r^2-Mr^3+\frac{\mu^2}{4r_h^2}r^4\quad(\textrm{Eqn. } 3) $$
where $\alpha$ and $\beta$ are proportional to the massive gravity term in the action, $M$ is the mass of the black hole, and the massive gravity action is given by $f_{\mu \nu}=\textrm{diag}(0,0,F^2,F^2)$. The derivation of this form appears to make sense to me, but I've also noticed a similar term discussed in this work ("Solid Holography and Massive Gravity" by Alberte et. al.), where Eqn. 5.5 yields
$$f(r)=1+\frac{\mu^2 r^2}{2r_h^2}+r^3\int^r dr' \frac{1}{r'^4}V(r')\quad(\textrm{Eqn. } 4)$$
where $V(r)$ is the background potential from the massive graviton.
My main question concerns the derivation of Eqn. 4, and how it relates to Eqn. 3. The two solutions look very similar; i.e., it seems as if the effects from the massive gravity term are simply added on to the AdS Schwarzschild solution. Therefore, would it be correct to say that, for some general metric, the addition of a massive gravity background amounts to a constant term multiplying the emblackening factor? If that is the case, how is Eqn. 4 derived? This seems unclear in the reference I linked. Is the additional term proportional to $V(r')$ due to Einstein's equations reducing to a set of  inhomogeneous differential equations? Any explanation would be greatly appreciated.


Q: Case agnostic lexicographical ordering in redis sorted set I have a large list of strings (contains usernames, approx 350K records). I need to store it sorted by lexicographical ordering, and ought to be able to retrieve member existence* and member likeness** efficiently. Redis sorted sets look like the data type for the job.
However, I seem to be falling at the first hurdle. Specifically, one of my key requirements is to keep different letter cases together as long as they start with the same letter. E.g. both Bender and bender should end up being ordered side by side. However, redis' sorted sets are strict in following lexicographical ordering rules, thus all strings starting with uppercase are by default sorted before all strings starting with lower case (e.g. Z is ordered before a, but after A).
Is there any way I can workaround this and still use redis sorted sets to fulfil my requirements? FYI, I'm using redis version 2.8.4. Thanks in advance.

*member existence: given a username, check whether it already exists in the stored set
**member likeness: given a username, pull up N stored usernames that are most like the given username

A: You need to do some special encoding with the names. The following is an example.
Let's suppose the length of all names are less than 100 characters. For each name, do the following steps to encode it:

*

*record the indices of upper case letters with 2 digits: for BeNd, the indices are 00 and 02.

*convert upper case letters of the name into lower cases to get a lower case name: from BeNd to bend

*append the indices to the lower case name to get the encoded name: from bend to bend0002

*add the encoded name into the sorted set: zadd key 0 bend0002
In this way, BeNd and bend should be ordered side by side.
When you want to do the search, use the same encoding method to encode the given name, do the search, and decode the results. Since the encoded name records the indices of upper case letters, you can decode it easily.


Q: How to send few parameters via POST method? I want to send parameters as Key-Value via POST. With GET method it easy to make:

myDomain.com?a=3&b=2&c=1

But how to make same request via POST method (I dont want to send all data as String with some delimiter and then parse this String on server via Split() method)?

A: The traditional format is the same. It just appears in the HTTP request body instead of as part of the URI. Whatever library you use to parse the query string should handle x-www-form-urlencoded data just as easily.
POST / HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

a=3&b=2&c=1

A: You should use either form method = POST or ajax.
Jquery ajax is easier. Just google it. (if you want it that way).
P.s. You can't send post parameters via url.

A: The most common way to send POST data is from an html form:
<FORM action="http://somesite.com/somescript.php" method="post">

   First name:
          <INPUT type="text" id="firstname">

   Last name:
          <INPUT type="text" id="lastname">

   email:
          <INPUT type="text" id="email">

   <INPUT type="radio" name="sex" value="Male"> Male

   <INPUT type="radio" name="sex" value="Female"> Female

   <INPUT type="submit" value="Send"> <INPUT type="reset">

</FORM>

Then process the $_POST vars similar to how you would with $_GET vars in PHP.


Q: Is it possible to restart spyder console and run script again, every n iterations? Currently I am trying to do 3000 iterations of some function using a for-loop (using Spyder). The function however, which I imported from a package, contains a bug. Because of the bug, the function gets slower with every iteration. When I restart the IPython console, the function is fast again but it again gets slower with every iteration.
So, this is what I want to do:

*

*Run (for example) 100 iterations

*Restart console

*Run the next 100 iterations

*Restart console

And so forth, until I've done 3000 iterations.
I know this sounds like a cumbersome process but I don't know how to do it differently since I don't have the skills (and time) to debug the complicated function I am using.
Thanks in advance


Q: How to create executable with Python 3.5 on Windows? I'm starting with Python so I downloaded the 3.5 version on my Windows 7 (64), and developped a small app in Eclipse Luna (4.4.1) with PyDev and the Tkinter library. It has only 4 modules and a text file.
I'd like to know how I could export an executable version of my project, like when you do File>Export>Runnable Jar File with a Java project. Is there a way to do this in Eclipse for Python projects ?
I have already tried tools like py2exe or cx_Freeze, but they tell me they have to be used respectively with Python 2.7 and 3.4... Does there exists some piece of software that could do the same for Python 3.5 ?
Thank you very much for any piece of help you could bring.

A: PyInstaller (version 3.2) works for Python 3.5, according to their website.


Q: Why exactly does Java not allow numeric conditionals like if(5) { ...} if C does? I have these two little programs:
C
#include <stdio.h>
int main()
{
    if (5) {
        printf("true\n");
    }
    else {
        printf("false\n");
    }

    return 0;
}

Java
class type_system {
   public static void main(String args[]) {
       if (5) {
           System.out.println("true");
       }
       else {
           System.out.println("false");
       }
   }
}

which reports the error message:
type_system.java:4: error: incompatible types: int cannot be converted to boolean
       if (5) {
           ^
1 error

My understanding
So far, I understood this example as a demonstration of the different type systems. C is more weakly typed and allows conversion from int to boolean without errors. Java is more strongly typed and fails, because no implicit conversation is allowed.
Therefore, my question: Where did I misunderstand things?
What I'm not looking for
My question is not related to bad coding style. I know it's bad, but I'm interested in why C does allow it and Java not. Therefore, I'm interested in the language's type system, specifically its strongness.

A: Many of the answers seem to be targeting the embedded assignment expression that is within the conditional expression.  (While that is a known kind of potential pitfall, it is not the source of the Java error message in this case.)
Possibly this is because the OP did not publish the actual error message, and, the ^ caret points directly to the = of the assignment operator.
However the compiler is pointing to the = because it is the operator that produces the final value (and hence the final type) of the expression that the conditional sees.
It is complaining about testing a non-boolean value, with the following kind of error:

error: incompatible types: int cannot be converted to boolean

Testing integers, while sometimes convenient, is considered a potential pitfall that the Java designers choose to avoid.  After all, Java has a true boolean data type, which C does not (it has no boolean type).
This also applies to C's testing pointers for null/non-null via if (p) ... and if (!p) ..., which Java similarly does not allow instead requiring an explicit comparison operator to obtain the required boolean.

A:
incompatible types: int cannot be converted to boolean
I'm interested in why C does allow it and java not. Therefore, I'm interested in the language's type system, specifically its strongness.

There are two parts to your question:
Why does Java not convert int to boolean?
This boils down to Java being intended to be as explicit as possible. It is very static, very "in your face" with its type system. Things that are automatically type-cast in other languages are not so, in Java. You have to write int a=(int)0.5 as well. Converting float to int would lose information; same as converting int to boolean and would thus be error-prone. Also, they would have had to specify a lot of combinations. Sure, these things seem to be obvious, but they intended to err on the side of caution.
Oh, and compared to other languages, Java was hugely exact in its specification, as the bytecode was not just an internal implementation detail. They would have to specified any and all interactions, precisely. Huge undertaking.
Why does if not accept other types than boolean?
if could perfectly well be defined as to allow other types than boolean. It could have a definition that says the following are equivalent:

*

*true

*int != 0

*String with .length>0

*Any other object reference that is non-null (and not a Boolean with value false).

*Or even: any other object reference that is non-null and whose method Object.check_if (invented by me just for this occasion) returns true.

They didn't; there was no real need to, and they wanted to have it as robust, static, transparent, easy to read etc. as possible. No implicit features. Also, the implementation would be pretty complex, I'm sure, having to test each value for all possible cases, so performance just may have played a small factor as well (Java used to be sloooow on the computers of that day; remember there was no JIT compilers with the first releases, at least not on the computers I used then).
Deeper reason
A deeper reason could well be the fact that Java has its primitive types, hence its type system is torn between objects and primitives. Maybe, if they had avoided those, things would have turned out another way. With the rules given in the previous section, they would have to define the truthiness of every single primitive explicitely (since the primitives don't share a super class, and there is no well defined null for primitives). This would turn into a nightmare, quickly.
Outlook
Well, and in the end, maybe it's just a preference of the language designers. Each language seems to spin their own way there...
For example, Ruby has no primitive types. Everything, literally everything, is an object. They have a very easy time making sure that every object has a certain method.
Ruby does look for truthiness on all types of objects you can throw at it. Interestingly enough, it still has no boolean type (because it has no primitives), and it has no Boolean class either. If you ask what class the value true has (handily available with true.class), you get TrueClass. That class actually does have methods, namely the 4 operators for booleans (| & ^ ==). Here, if considers its value falsey if and only if it is either false or nil (the null of Ruby). Everything else is true. So, 0 or "" are both true.
It would have been trivial for them to create a method Object#truthy? which could be implemented for any class and return an individual truthiness. For example, String#truthy? could have been implemented to be true for non-empty strings, or whatnot. They didn't, even though Ruby is the antithesis of Java in most departments (dynamic duck-typing with mixin, re-opening classes and all that).
Which might be surprising to a Perl programmer who is used to $value <> 0 || length($value)>0 || defined($value) being the truthiness. And so on.
Enter SQL with its convention that null inside any expression automatically makes it false, no matter what. So (null==null) = false. In Ruby, (nil==nil) = true. Happy times.

A: C 2011 Online Draft
6.8.4.1 The if statement
Constraints
1    The controlling expression of an if statement shall have scalar type.
Semantics
2    In both forms, the first substatement is executed if the expression compares unequal to 0.
In the else form, the second substatement is executed if the expression compares equal to 0. If the first substatement is reached via a label, the second substatement is not
executed.
3    An else is associated with the lexically nearest preceding if that is allowed by the
syntax.

Note that this clause specifies only that the controlling expression shall have a scalar type (char/short/int/long/etc.), not specifically a Boolean type.  A branch is executed if the controlling expression has a non-zero value.
Compare that with
Java SE 8 Language Specification

14.9 The if Statement
The if statement allows conditional execution of a statement or a conditional
choice of two statements, executing one or the other but not both.

    IfThenStatement:
        if ( Expression ) Statement

    IfThenElseStatement:
        if ( Expression ) StatementNoShortIf else Statement

    IfThenElseStatementNoShortIf:
        if ( Expression ) StatementNoShortIf else StatementNoShortIf

The Expression must have type boolean or Boolean, or a compile-time error
occurs.

Java, OTOH, specifically requires that the controlling expression in an if statement have a Boolean type.
So, it's not about weak vs. strong typing, it's about what each respective language definition specifies as a valid control expression.
Edit
As for why the languages are different in this particular respect, several points:

*

*C was derived from B, which was a "typeless" language - basically, everything was a 32- to 36-bit word (depending on the hardware), and all arithmetic operations were integer operations.  C's type system was bolted on a bit at a time, such that...

*C didn't have a distinct Boolean type until the 1999 version of the language.  C simply followed the B convention of using zero to represent false and non-zero to represent true.

*Java post-dates C by a good couple of decades, and was designed specifically to address some of C's and C++'s shortcomings.  No doubt tightening the restriction on what may be a control expression in an if statement was part of that.

*There's no reason to expect any two programming languages to do things the same way.  Even languages as closely related as C and C++ diverge in some interesting ways, such that you can have legal C programs that are not legal C++ programs, or are legal C++ programs but with different semantics, etc.

A: 1. C and Java are different languages
The fact that they behave differently should not be terribly surprising.
2. C is not doing any conversion from int to bool
How could it? C didn't even have a true bool type to convert to until 1999. C was created in the early 1970s, and if was part of it before it was even C, back when it was just a series of modifications to B1.
if wasn't simply a NOP in C for nearly 30 years. It directly acted on numeric values. The verbiage in the C standard (PDF link), even over a decade after the introduction of bools to C, still specifies the behavior of if (p 148) and ?: (p 100) using the terms "unequal to 0" and "equal to 0" rather than the Boolean terms "true" or "false" or something similar.
Conveniently, ...
3. ...numbers just happen to be what the processor's instructions operate on.
JZ and JNZ are your basic x86 assembly instructions for conditional branching. The abbreviations are "Jump if Zero" and "Jump if Not Zero". The equivalents for the PDP-11, where C originated, are BEQ ("Branch if EQual") and BNE ("Branch if Not Equal").
These instructions check if the previous operation resulted in a zero or not and jump (or not) accordingly.
4. Java has a much higher emphasis on safety than C ever did2
And, with safety in mind, they decided that restricting if to booleans was worth the cost (both of implementing such a restriction and the resulting opportunity costs).

1. B doesn't even have types at all. Assembly languages generally don't, either. Yet B and assembly languages manage to handle branching just fine.
2. In the words of Dennis Ritchie when describing the planned modifications to B that became C (emphasis mine):

...it seemed that a typing scheme was necessary to cope with characters and byte addressing, and to prepare for the coming floating-point hardware. Other issues, particularly type safety and interface checking, did not seem as important then as they became later.

A: In addition to the other fine answers, I'd like to talk about the consistency between languages.
When we think of a mathematically pure if-statement, we understand that the condition can be either true or false, no other value. Every major programming language respects this mathematical ideal; if you give a Boolean true/false value to an if-statement, then you can expect to see consistent, intuitive behavior all the time.
So far so good. This is what Java implements, and only what Java implements.
Other languages try to bring conveniences for non-Boolean values. For example:

*

*Suppose n is an integer. Now define if (n) to be shorthand for if (n != 0).

*Suppose x is a floating-point number. Now define if (x) to be shorthand for if (x != 0 && !isNaN(x)).

*Suppose p is a pointer type. Now define if (p) to be shorthand for if (p != null).

*Suppose s is a string type. Now define if (s) to be if (s != null && s != "").

*Suppose a is an array type. Now define if (a) to be if (a != null && a.length > 0).

This idea of providing shorthand if-tests seems good on the surface... until you run into differences in designs and opinions:

*

*if (0) is treated as false in C, Python, JavaScript; but treated as true in Ruby.

*if ([]) is treated as false in Python but true in JavaScript.

Each language has its own good reasons for treating expressions one way or another. (For example, the only falsy values in Ruby are false and nil, hence 0 is truthy.)
Java adopted an explicit design to force you to supply a Boolean value to an if-statement. If you hastily translated code from C/Ruby/Python to Java, you cannot leave any lax if-tests unchanged; you need to write out the condition explicitly in Java. Taking a moment to pause and think can save you from sloppy mistakes.

A: Well, every scalar type in C, pointer, boolean (since C99), number (floating-point or not) and enumeration (due to direct mapping to numbers) has a "natural" falsey value, so that's good enough for any conditional expression.
Java has those too (even if Java pointers are called references and are heavily restricted), but it introduced auto-boxing in Java 5.0 which muddles the waters unacceptably. Also, Java-programmers exhort the intrinsic value of typing more.
The one error which spawned the debate whether restricting conditional expressions to boolean type is the typo of writing an assignment where a comparison was intended, which is not addressed by restricting the conditional expressions type at all, but by disallowing use of a naked assignment-expression for its value.
Any modern C or C++ compiler handles that easily, giving a warning or error for such questionable constructs if asked.
For those cases where it is exactly what was intended, adding parentheses helps.
To summarize, restricting to boolean (and the boxed equivalent in Java) looks like a failed attempt to make a class of typos caused by choosing = for assignment compile-errors.

A:
My question is not related to bad coding style. I know its bad, but i'm intersted in why C does allow it and java not.

Two of the design goals of Java were:

*

*Allow the developer to focus on the business problem.  Make things simpler and less error-prone, e.g. garbage collection so developers don't need to focus on memory leaks.

*Portable between platforms, e.g. run on any computer with any CPU.
Use of assignment as an expression was known to cause a lot of bugs due to typos, so under goal #1 above, it is not allowed the way you are trying to use it.
Also, inferring that any nonzero value = true and any zero value = false is not necessarily portable (yes, believe it or not, some systems treat 0 as true and 1 as false), so under goal #2 above, is not allowed implicitly.  You can still cast explicitly of course.

A: As an example what other languages do: Swift requires an expression of a type that supports the "BooleanType" protocol, which means it must have a "boolValue" method. The "bool" type obviously supports this protocol and you can create your own types supporting it. Integer types don't support this protocol.
In older versions of the language optional types supported "BooleanType" so you could write "if x" instead of "if x != nil". Which made using an "Optional bool" very confusing. An optional bool has values nil, false or true and "if b" would be not executed if b was nil and executed if b was true or false. This is not allowed anymore.
And there seems to be one guy who real dislikes opening your horizons...


Q: How to format postgres result in the same way that "TABLE name;" does? I am using Postgres in a nodejs program, and I want to have functions that print the output to the terminal.
When you run the command "TABLE table_name;" in the terminal, you get a nice looking table with space for all characters in all columns shown here
When I run this same query, and try to display it like this:
console.log(pool.query("TABLE table_name")

I get something that looks way worse. Is there some plugin I can get to make it look as good as the first image? Note: It would be displaying in the windows command prompt if that changes anything.
I tried doing my own with some character counting and inserting "\t|\t" into strings, however if the database gets quite large, running multiple times through the data would take  too long.

A: console.table() worked perfectly for me.


Q: Fastest string searching algorithm for fixed text and a lot of substrings I am trying to find an algorithm to search for binary strings of fixed size (64 bit) in a large binary buffer (100 MB). The buffer is always the same and i have got lots and lots of strings to search for (2^500 maybe).
I have to find all the occurrences of any given string, not only the first one.
What algorithm can i choose from? Maybe one that benefits from the constant buffer in which i search.
Links to C source code for such algorithm is appreciated.

A: Assuming your string are 8-bit aligned, from 100MB buffer you'll get 100 millions different strings, which can be put into the hash table approximately 800MB in size with constant (O(1)) access time.
This will allow you to make the search as fast as possible, because once you have your 8 byte string, you immediately know where this string was seen in your buffer.


Q: assembly code for a reference I have not deeply understood the reference type in c++. So I wrote a tiny piece of code:
int a = 10;
int& b = a;

cout << "a: " << a << endl;
cout << "b: " << b << endl;

cout << "&a: " << &a << endl;
cout << "&b: " << &b << endl;

the output is:
a: 10
b: 10
&a: 0x7ffebd76ac6c
&b: 0x7ffebd76ac6c

And I noticed, without surprise, that a's and b's addresses are the same.
Then I disassembled to find out how actually the reference is considered for the compiler. Here the code:
 40096e:    c7 45 dc 0a 00 00 00    mov    DWORD PTR [rbp-0x24],0xa
 400975:    48 8d 45 dc             lea    rax,[rbp-0x24]
 400979:    48 89 45 e0             mov    QWORD PTR [rbp-0x20],rax

If I'm correct, rbp-0x24 refers to the variable a, whereas rbp-0x20 refers to the variable b. But my doubt is: if after this three lines (and if I haven't done mistakes)
[rbp-0x20] = rbp-0x24

how could it be possible that both the variables' addresses are the same?


Q: Save ListView items I want to save my downloaded ListView items so that for example next time the app starts, it should not start my download dialog, instead my previous ListView items should turn up.
Some useful code snippets would be appreciated.
Thanks in advance and please tell me if I need to clarify!

A: It depends on the kind of data that is displayed in your ListView.
You can store the data into a SQLite database. This means designing an appropriate schema and implementing create/read/update/delete methods.
The process is too long to be explained here in detail; I invite you to read the Notepad tutorial on the official Android developer site.

A: Depending on the amount of data you are saving you can have many options.
I am assuming you are starting out so it is probably best to go with a straight forward solution utilizing the SQLiteDB instead of preferences or saving to a file.
This is a link to a complete solution for creating the views adapters and database objects.
You could just cut and paste, but read through it and it will be better for you in the long run
Complete ListView Database Tutorial
Android SQLite Basics
List View loaded from XML Resource File

A: In order to do this, you need to think of a strategy for saving data. The most common one is through a SQLite Android DB, nevertheless you might also use Internal Storage if your data is not that complex. Also saving data on Android has been a common topic (check this post)

A: Have a look at the Java Serialization API.
It has its drawbacks (concurrent access....), but maybe it's enough for you.
That's just a quick google hit for that topic.
http://java.sun.com/javase/technologies/core/basic/serializationFAQ.jsp

A: You can use SharedPreferences


Q: How to loop through a list of dictionaries and write the values as individual columns in a CSV I have a list of dictionaries
d = [{'value':'foo_1', 'word_list':['blah1', 'blah2']}, ...., {'value': 'foo_n', 'word_list':['meh1', 'meh2']}]
I want to write this to a CSV file with all the 'value' keys in one column, and then each individual word from the "value"'s word_list as its own column.  So I have the first row as
foo_1 blah_1 blah_2
and so on.
I don't know how many dictionaries I have, or how many words I have in "word_list".
How would I go about doing this in Python 3?
Thanks!

A: It would probably be easiest to flatten each row into a normal list before writing it to the file. Something like this:
with open(filename, 'w') as file:
    writer = csv.writer(file)
    for row in data:
        out_row = [row['value']]
        for word in row['word_list']:
            out_row.append(word)
        csv.writerow(out_row)
    # Shorter alternative to the two loops:
    # csv.writerow((row['value'], *row['word_list']) for row in data)

A: I figured out a solution, but it's kind of messy (wow, I can't write a bit of code without it being in the "proper format"...how annoying):
with open('filename', 'w') as f:
    for key in d.keys():
      f.write("%s,"%(key))
    for word in d[key]:
      f.write("%s,"%(word))
    f.write("\n")

A: You can loop through the dictionaries one at a time, construct the list and then use the csv module to write the data as I have shown here
import csv

d = [{'value':'foo_1', 'word_list':['blah1', 'blah2']}, {'value': 'foo_n', 'word_list':['meh1', 'meh2']}]

with open('test_file.csv', 'w') as file:
    writer = csv.writer(file)
    for val_dict in d:
        csv_row = [val_dict['value']] + val_dict['word_list']
        writer.writerow(csv_row)

It should work for word lists of arbitrary length and as many dictionaries as you want.


Q: Need to Delete current password (if Prepopulated) in reset popup window using selenium After clicking reset password link I need to verify whether password (i.e testdemo)is prepopulating in current password text box, if so then I need to clear those values.

A: As far I understood your scenario, you are checking that your password is auto populated in password field and If so then you need to clear that
You can do this - First you need to check is there any value in password field if so then do clear
    int passLength = driver.findElement(By.id("Password")).getAttribute("value").length();
    if(passLength>0)
    {
            driver.findElement(By.id("Password")).clear();
     }


Q: Android WebView- Scroll bar not visible after few scrolling inWebView In webView after a few scrolls, the webView default scrollbar gets disappears.
This is my webView code:
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false"
android:fadeScrollbars="false"
android:focusable="false"
android:focusableInTouchMode="true"
android:scrollbarThumbVertical="@android:color/holo_blue_bright"
android:scrollbarTrackVertical="@android:color/darker_gray"
android:scrollbars="vertical"></WebView>


Q: Stage3D and AIR 3 How does one get a project setup in Flash Builder 4 with Adobe AIR 3 that uses Stage3D?
Whenever I add "-swf-version=13" to the compiler options, I get the following error:
Process terminated unexpectedly.

error while loading initial content

Launch command details:  "/Applications/Adobe Flash Builder 4/sdks/4.5.1.21328/bin/adl" -runtime "/Applications/Adobe Flash Builder 4/sdks/4.5.1.21328/runtimes/air/mac" "/Users/joverton/Documents/Prototyping and Testing/Virtual Library AIR/bin-debug/Main-app.xml" "/Users/joverton/Documents/Prototyping and Testing/Virtual Library AIR/bin-debug"

I have gpu mode enabled in my App.xml file, and am using the newest Flex SDK (4.6).
Similar question was asked here:
AIR 3.0 and Stage3D
but the solution is no longer valid!  The link in the accepted answer just annoyingly redirects to the home page, and you can't even get to it by looking at Google's cached version of the page.
Also here:
http://www.dreaminginflash.com/2011/10/12/adobe-flex-adobe-air-3-alternativa-3d-real-3d-engine/
does not work for me.

A: You can not use "gpu" mode and Stage3D. You need to specify "direct". Hope this works. Confusing, I know :) If not, try making a regular flash player project first, and run with all debug flags on. AIR is usually more complicated with all the SDKs and stuff.

A: Got it!  The solution turned out to be building from the command line, rather than using Flash Builder (4, can't speak for 4.5/6).  Here is the sequence of commands:
I. axmlc compile the application (Main.as) file, with all the correct options:

$FLEX_4.6_SDK/bin/amxmlc -static-link-runtime-shared-libraries=true
  -library-path+='$ALTERNATIVA/Alternativa3D.swc' -debug=true -swf-version=13 -load-config $FLEX_4.6_SDK/frameworks/air-config.xml -- Main.as

(where $FLEX_4.6_SDK and $ALTERNATIVA are the locations of the Flex SDK and Alternativa3D SWC, naturally)
II. adl run the application

$FLEX_4.6_SDK/bin/adl Main-app.xml

which for convenience I setup in my .bash_profile like so:
alias run_virtual_library="cd '/Users/joverton/Documents/Prototyping and Testing/Virtual Library/src/' && /Applications/Adobe\ Flash\ Builder\ 4/sdks/4.6/bin/amxmlc -static-link-runtime-shared-libraries=true -library-path+='/Users/joverton/Documents/Libraries & Tools/Alternativa3D/Alternativa3D_8.17.0/Alternativa3D.swc' -debug=true -swf-version=13 -load-config /Applications/Adobe\ Flash\ Builder\ 4/sdks/4.6/frameworks/air-config.xml -- Main.as && '/Applications/Adobe Flash Builder 4/sdks/4.6/bin/adl' Main-app.xml &"

Note that in my AIR application descriptor file I set the renderMode to "gpu", but "direct" will also work.  Also, in the amxmlc command you needn't set the debug compiler option to true; I only do for the sake of testing.
EDIT: Additional note is that - because I was building from the command line rather than from Flash Builder - I had to explicitly set the value of   in my AIR Descriptor file (in this case to "Main.swf"), else I received "content not found" errors when trying to run the application.


Q: How to access non container App data/Logs from an Azure-IoT-Edge Container App in gateway/Server? In  Azure-IoT-Edge, How to Access non container App data/Logs from an Azure-IoT-Edge Container App in gateway/Server and Push data to Azure IoT Hub cloud?

A: At the end of the day it's the docker container running on a machine and in docker container you can run services that listen to the data that is posted on those services. Some solutions can be:-

*

*A http server running on your edge module container and producers posting data to the RESTful api exposed by the container. Once data received, push it to IoT Hub using routes in edgeHub.

*You can also run a consumer on docker container that listens to a message broker and passes that data to IoT hub using edgeHub routes.


Q: Powershell - Read, Alter Line, Write new line over old in Text Document I am reading in line by line of a text file.  If I see a specific string, I locate the first and last of a specific character, use two substrings to create a smaller string, then replace the line in the text file.
The difficult part: I have the line of text stored in a variable, but cannot figure out how to write this new line over the old line in the text document.
Excuse the crude code - I have been testing things and only started playing with PowerShell a few hours ago.
foreach($line in [System.IO.File]::ReadLines("C:\BatchPractice\test.txt"))
{
       Write-Output $line
       if ($line.Contains("dsa")) {
           Write-Output "TRUEEEEE"

       }
       $positionF = $line.IndexOf("\")+1
       $positionL = $line.LastIndexOf("\")+1
       $lengthT = $line.Length
       Write-Output ($positionF)
       Write-Output $positionL
       Write-Output $lengthT
       if($line.Contains("\")){
           Write-Output "Start"
            $combine = $line.Substring(0,$positionF-1) + $line.Substring($postionL,($lengthT-$positionL))
            Write-Output $combine
            $line1 = $line.Substring(0,$positionF-1)
            $line2 = $line.Substring($positionL,($lengthT-$positionL))
            $combined = $line1 + $line2
            Write-Output $combined
            Write-Output "Close"
       }
}```

A: You can save the file as arrays in Get-Content and Set-Content:
$file=(Get-Content "C:\BatchPractice\test.txt")

Then you can edit it like arrays:
$file[LINE_NUMBER]="New line"

Where LINE_NUMBER is the line number starting from 0.
And then overwrite to file:
$file|Set-Content "C:\BatchPractice\test.txt"

You can implement this in code. Create a variable $i=0 and increment it at the end of loop. Here $i will be the line number at each iteration.
HTH

A: Based on your code it seems you want to take any line that contains 'dsa' and remove the contents after the first backslash up until the last backslash. If that's the case I'd recommend simplifying your code with regex. First I made a sample file since none was provided.
$tempfile = New-TemporaryFile

@'
abc\def\ghi\jkl
abc\dsa\ghi\jkl
zyx\vut\dsa\srq
zyx\vut\srq\pon
'@ | Set-Content $tempfile -Encoding UTF8

Now we will read in all lines (unless this is a massive file)
$text = Get-Content $tempfile -Encoding UTF8

Next we'll make a regex object with the pattern we want to replace. The double backslash is to escape the backslash since it has meaning to regex.
$regex = [regex]'(?<=.+\\).+\\'

Now we will loop over every line, if it has dsa in it we will run the replace against it, otherwise we will output the line.
$text | ForEach-Object {
    if($_.contains('dsa'))
    {
        $regex.Replace($_,'')
    }
    else
    {
        $_
    }
} -OutVariable newtext

You'll see the output on the screen but it's also capture in $newtext variable. I recommend ensuring it is the output you are after prior to writing.
abc\def\ghi\jkl
abc\jkl
zyx\srq
zyx\vut\srq\pon

Once confirmed, simply write it back to the file.
$newtext | Set-Content $tempfile -Encoding UTF8

You can obviously combine the steps as well.
$text | ForEach-Object {
    if($_.contains('dsa'))
    {
        $regex.Replace($_,'')
    }
    else
    {
        $_
    }
} | Set-Content $tempfile -Encoding UTF8


Q: Label the internal memory file At Run Time I have an application that

*

*takes data from the user and

*creates a file in the internal memory based on the name entered by the user

*and saves the user data.

But when the file is saved by that name, the fileInputStream does not respond to that name.
what should I do ?
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_load_food);
    bundle = getIntent().getExtras();
    Toolbar toolbar=(Toolbar)findViewById(R.id.food_lood_toolbar);
    setSupportActionBar(toolbar);
    file=bundle.getString("diname");

    getSupportActionBar().setTitle(file);
    String q=”123”;

    if (bundle.getString("activity").equals(q)) {

        String e1=editText1.getText().toString() +"/";

            fileOutputStream=openFileOutput(file,Context.MODE_PRIVATE);
            fileOutputStream.write(e1.getBytes());

    }
    String t="321";
    if (bundle.getString("activity").equals(t)){
            try {
                fileInputStream= openFileInput(file);
                int x;
                StringBuffer y = new StringBuffer();
                while((x=fileInputStream.read())!=-1){
                y.append((char)x);
                }
                String c=y.toString();
                txt=c.split("/");

            editText1.setText(txt[0]);

        } catch (FileNotFoundException e) {
            Toast.makeText(getBaseContext(),"file not found",Toast.LENGTH_LONG).show();

            e.printStackTrace();
        } catch (IOException e) {
            Toast.makeText(getBaseContext(),"io",Toast.LENGTH_LONG).show();

            e.printStackTrace();
        }
        finally {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

}


Q: i can't insert photo in database I have a big problem in insertion of photo (blob) into database with php. I can't execute query. It returns false. This is my code
public function addPhoto()
 {
   $ret        = false;
   $img_blob   = '';
   $img_titre    ='';
   $description = "hhhhh";
   $selogon = '';
   $ret= is_uploaded_file($_FILES['fic']['tmp_name']);

   if (!$ret) {
       echo "Problème de transfert";
       return false;
   } else {
       $img_titre  = $_FILES['fic']['name'];
       $img_blob = file_get_contents ($_FILES['fic']['tmp_name']);
       $conn = connection();
       $sql = "INSERT INTO image (titre,selogon,description,img_blob)
               VALUES ( '$img_titre','$selogon','$description','".addslashes ($img_blob)."')" ;

                 if ($conn->query($sql) === TRUE) {
                     echo "New record created successfully";

                     }
                     else {
                       echo "string";
                     }

       $conn->close();
 }

A: PDO solution
Assuming you're using PDO(not specified by you), if you want to save it as blob then following steps should be done
try
{
  $fp = fopen($_FILES['fic']['tmp_name'], 'rb'); // read the file as binary
  $stmt = $conn->prepare("INSERT INTO image (titre, selogon, description, img_blob) VALUES (?, ?, ?, ?)"); // prepare statement

   // bind params
   $stmt->bindParam(1, $img_titre);
   $stmt->bindParam(2, $selogon);
   $stmt->bindParam(3, $description);
   // this is important I will explain it below after the code
   $stmt->bindParam(4, $fp, PDO::PARAM_LOB);
   $stmt->execute();
   // if you want to check if it was inserted use affected rows from PDO
}
catch(PDOException $e)
{
   'Error : ' .$e->getMessage();
}

The most important thing is bind the file pointer ($fp) to PDO param called LOB which stands for Large Object

PDO::PARAM_LOB tells PDO to map the data as a stream, so that you can manipulate it using the PHP Streams API.

http://php.net/manual/en/pdo.lobs.php
After that you can use power of PHP streams and save it as binary safe stream. Reading the from streams make more sense but if I were you I'd really think if you want to save pictures directly in db, this doesn't seem to be a good idea.
MYSQLI solution:
If you don't use PDO but for example mysqli then streams are good idea as well but the solution is different.
The best option is to check SHOW VARIABLES LIKE 'max_allowed_packet'; this will print what is max allowed package size, if your image is bigger the blob will be corrupted.
To make it work you'll need to send data in smaller chunks using fread() + loop + feof() and mysqli function send_long_data
Example from php.net site: you can adjust it to your needs quite similar as I did above, the difference is that params are bound in different way.
$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen($_FILES['fic']['tmp_name'], "r");
while (!feof($fp)) {
    $stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();

A: I have been solve the problem  :
solution : in augmentation of size of photo in type (blob --> longblob ) .


Q: Is this a valid shortcut (using induction hypothesis) for the proof of the sum of the first n natural numbers? http://jriedy.users.sonic.net/VI/math202-f08/Solutionsforthirdweeksassignments.html
If you look at this link and go down to the equation right after
To proceed, we pull the n+1  term out of the sum to see that

Couldn't you stop then and there, since by the induction hypothesis you assume that
$$\sum_{i=1}^{n}{i} = \frac{n*(n+1)}{2}$$
So, all you're left with is
$$n+1 = n+1$$
which is true.
So, basically all that factoring out and other steps in that website are redundant?

A: No, you cannot stop there, because the purpose of the induction is not to show the truth of
$$ \sum_{i=1}^{n} i + (n+1) = \frac{n(n+1)}{2} + n+1$$
Indeed, that statement is a trivial consequence of the induction hypothesis, as you correctly noted. The purpose of the inductive step is to show that
$$ \sum_{i=1}^{n+1} i = \frac{(n+1)(n+2)}{2}$$
To establish the general formula
$$\sum_{i=1}^{k} i = \frac{k(k+1)}{2}$$
To get the second formula written above, you must resort to the factoring.

A: One can indeed reduce the inductive proof to verifying the equality $\rm\: n+1 = n+1\:$ by using a special form of induction tailored specifically for such indefinite sums. Namely we can invoke the Fundamental Theorem of Difference Calculus (which has a simple inductive proof).
$$\rm\ F(n)\ =\ \sum_{i\:=\:1}^n\ f(i)\  \iff\ \ F(n\!+\!1) - F(n)\ =\ f(n\!+\!1),\ \ \ F(1) =\: f(1)$$
In your example we have $\rm\:F(n)\, =\, n(n\!+\!1)/2,\ \ f(n)\, =\, n,\:$ hence $\rm\: F(1) = 1 = f(1),\:$ and
$$\rm\ F(n\!+\!1)-F(n)\ =\ \dfrac{(n\!+\!1)(n\!+\!2)}2-\dfrac{n(n\!+\!1)}2\ =\ (n\!+\!1)\left(\dfrac{n\!+\!2}2-\dfrac{n}2\right)\, =\, n\!+\!1\, =\, f(n\!+\!1)$$
hence the sought equality follows by the Fundamental Theorem.
Note that by employing the Fundamental Theorem we have reduced the proof to the mechanical verification of the equations on the RHS of the $\iff$, which here amount to checking that two polynomials in $\rm\,n\,$ are equal (here $\rm = n\!+\!1).\:$ No ingenuity is required in devising the inductive step. Instead that ingenuity has been encapsulated once and for all in the proof of the Fundamental Theorem -  whose inductive proof is obvious because we have abstracted away from all the peculiarities of its special cases. Namely, the inductive step  amounts simply to telescopic cancellation - a general method behind may inductive proofs. For further discussion and examples see my many posts on telescopy.


Q: XPiNC in Notes sidebar without use of Composite App? I seem to remember at Lotusphere 2011 discussion that there would be a way to deploy an XPiNC page to a sidebar widget without using a composite app. Is this possible with 8.5.3 clients? I need to be able to deploy the XPage via the widget catalog, and I cannot have a composite app tab appearing in the client. (I could use a composite app if the only UI would be in the sidebar panel).  Any ideas?

A: Yes it is possible to put an XPage in the sidebar without Composite Applications. What you need to do here is to go to File -> Preferences ->Widget Catalog and check the "Show widgets toolbar and My Widgets Panel". Now Open the XPage you want to create as a widget in XPiNC. In the toolbar, click on the "Configure a widget from the current context". Choose "Display as Panel" , click next and then the finish button. Your XPage should now display in the sidebar. Another way is to just click the "Display as Panel" button in the MyWidgets toolbar, this will also put your XPage in the sidebar. If you go to the MyWidgets sidebar Panel, you will be able to see your XPage Widget there and it is possible to export it as a widget to send to other users. Or use the widget catalog and deploy the widget to your users via a policy setting.


Q: In Nielsen's explanation of backpropagation, why does the way he defines error change? Is it actually a change? Specifically, why does Equation (BP1) not have the same form as (29)?1
In order to explain backpropagating the gradient through the neural net, he starts by defining something he calls error (Equation (29)).

The error in a neuron j in a layer l is given by the partial derivative of the cost function C with respect to the weighted input z of the neuron j in layer l. Weighted input to a neuron is simply the input to that neuron, multiplied by its weight, summed with the neuron's bias. It is what the neuron's activation function takes as its input.
He then defines the error for a neuron in the final, output layer of the net as follows (Equation (BP1)):

Where $\sigma$ is the activation function and $\sigma'$ is its derivative.
What I thought he was going to do was use the first definition of error in combination with the chain rule to derive $\partial C$ in terms of $\partial w$ and $\partial b$ for the j-th neuron in layer l, thereby providing a way to backpropagate through the net.
Why does he change the definition for error immediately after he defines it? Are these two equations actually saying the same thing? If so why?
1 Nielsen, Neural Networks and Deep Learning, Chapter 2 - http://neuralnetworksanddeeplearning.com/chap2.html

A: Okay bit of a goof on my part. Nielsen addresses this a couple sections later in the same chapter, in Proof of the four fundamental equations (optional).
Briefly, Eqn (29) above can be re-expressed (using the chain rule) as partial derivatives with respect to the output activations aL. Simplifying gives you the form seen in (BP1).

A: In Nielsens explanation of bp, he doesn't go in to the details and actually complicates it.
There is a video by 3blue1brown on youtube that explains bp really well by simplifying the case to just one neuron for each layer and then when you add more neurons it is not that different.
Highly recommend watching that 7 minute video and then coming back to Nielsens for the code.


Q: How to install scoped private npm package from Artifactory in Github Actions This question includes a specific use-case:

*

*I have a private scoped package: @myscope/mypackage

*It hosted in Artifactory NPM registry: https://company.jfrog.io/artifactory/api/npm/my-npm-registry/

*I need to use my credentials to consume it.

*I want to consume it in Github Actions.

How can I do that?

A: .npmrc
First, you need to configure your access in a local .npmrc file. You can put this file in your source root folder.
always-auth = true

# First, set a different registry URL for your scope
@myscope:registry=https://company.jfrog.io/artifactory/api/npm/my-npm-registry/
# Then, for this scope, you need to set the token
//company.jfrog.io/artifactory/api/npm/my-npm-registry/:_auth = {{your token - see below}}

Token
You need to get the NPM Token from Artifactory (note it isn't your API Key.

*

*Get your Artifactory API Key from your Artifactory profile: https://company.jfrog.io/ui/admin/artifactory/user_profile

*Run the next command on your Linux terminal: curl -u {{ ARTIFACTORY_USERNAME }}:{{ ARTIFACTORY_API_KEY }} https://company.jfrog.io/artifactory/api/npm/auth/

*

*Powershell:
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f {{ ARTIFACTORY_USERNAME }},{{ ARTIFACTORY_API_KEY }})))
Invoke-RestMethod -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} https://company.jfrog.io/artifactory/api/npm/auth/

*You should receive this:
_auth = {{ YOUR_NPM_TOKEN }}
always-auth = true

*So now you can take this Token and put it in the .npmrc file above.

Github Actions
How to do all this in Github Actions?

*

*First, save your Jfrog username and API Key in Github Secrets: JFROG_USER & JFROG_PAT.

*And you can add the next step to your workflow, after checkout and before yarn/npm install:
- name: npm token
  run: |
    echo "@myscope:registry=https://company.jfrog.io/artifactory/api/npm/my-npm-registry/" > .npmrc
    echo "//company.jfrog.io/artifactory/api/npm/my-npm-registry/:$(curl -u ${{ secrets.JFROG_USER }}:${{ secrets.JFROG_PAT }} https://company.jfrog.io/artifactory/api/npm/auth/)" >> .npmrc


Q: how to push multiple objects into one object serially I have 2 or multiple objects in a single variable and i want to push these objects into one object.
let a = {"device_type":"iphone","filter_data":{"title":{"value":"Lorem Ipsum..","data":{}},"message":{"value":"Lorem Ipsum is simply dummy text of the printing...","data":{}},"dismiss_button":{"value":"Ok","data":{}},"action_url":{"value":"","data":{"type":"custom"}}}}

{"device_type":"iphone","filter_data":{"message":{"value":"Push Message goes here.","data":{}}}}

I want the output to be:
{
  "0": {
    "device_type": "iphone",
    "filter_data": {
      "title": {
        "value": "Lorem Ipsum..",
        "data": {}
      },
      "message": {
        "value": "Lorem Ipsum is simply dummy text of the printing...",
        "data": {}
      },
      "dismiss_button": {
        "value": "Ok",
        "data": {}
      },
      "action_url": {
        "value": "",
        "data": {
          "type": "custom"
        }
      }
    }
  },
  "1": {
    "device_type": "iphone",
    "filter_data": {
      "message": {
        "value": "Push Message goes here.",
        "data": {}
      }
    }
  }
}

How can I do this?

A: You could replace }{ with a },{, parse it and take Object.assign for getting an object with indices as properties from an array.

const
    data = '{"device_type":"iphone","filter_data":{"title":{"value":"Lorem Ipsum..","data":{}},"message":{"value":"Lorem Ipsum is simply dummy text of the printing...","data":{}},"dismiss_button":{"value":"Ok","data":{}},"action_url":{"value":"","data":{"type":"custom"}}}}{"device_type":"iphone","filter_data":{"message":{"value":"Push Message goes here.","data":{}}}}';
    result = Object.assign({}, JSON.parse(`[${data.replace(/\}\{/g, '},{')}]`));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: auto; }

A: If they're in an array, it's fairly simple - just use reduce:

const data = [{"device_type":"iphone","filter_data":{"title":{"value":"Lorem Ipsum..","data":{}},"message":{"value":"Lorem Ipsum is simply dummy text of the printing...","data":{}},"dismiss_button":{"value":"Ok","data":{}},"action_url":{"value":"","data":{"type":"custom"}}}},{"device_type":"iphone","filter_data":{"message":{"value":"Push Message goes here.","data":{}}}}];
const res = data.reduce((a, c, i) => (a[i] = c, a), {});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

A: You can use Array.protoype.match to separate each object then Array.protoype.reduce to get expected oject.

let a = '{"device_type":"iphone","filter_data":{"title":{"value":"Lorem Ipsum..","data":{}},"message":{"value":"Lorem Ipsum is simply dummy text of the printing...","data":{}},"dismiss_button":{"value":"Ok","data":{}},"action_url":{"value":"","data":{"type":"custom"}}}}{"device_type":"iphone","filter_data":{"message":{"value":"Push Message goes here.","data":{}}}}';
let objects = a.match(/({"device_type".*?}}}})/g).map(e => JSON.parse(e));
console.log('Array of objects',objects)
const out = {...[objects]};
console.log('\ndesired output',out)

Also, it seems to be useless to convert the array into an object when the keys are just the indexes.


Q: Spring Cloud Data Flow Aggregator processor won't start I want to deploy a test stream using the app starter aggregator processor.
Just using the default settings, the processor aggregator doesn't start, I have no log, readiness and liveness probes fail.
My SCDF is deployed on a minikube and using bitnami chart version 2.11.3.
What would be a minimum configuration for the aggregator processor to start properly?


Q: how to call all Google font CSS under specific font face Can I call all the CSS of google font API under specific font-face?
I have here "Quattrocento Sans" that has 8 different font-style, the link below only call the CSS which font-style is only normal,
 <link href='http://fonts.googleapis.com/css?family=Quattrocento+Sans' rel='stylesheet' type='text/css'>

This second link call 400italic style:
  <link href='http://fonts.googleapis.com/css?family=Quattrocento+Sans:400italic' rel='stylesheet' type='text/css'>

However I like to call all the CSS which contains all 8 different styles with single link only.
So I'm thinking Something like this: Using ( * ) all
  <link href='http://fonts.googleapis.com/css?family=Quattrocento+Sans:*' rel='stylesheet' type='text/css'>

Is there any idea how to call all the CSS for this?

A: Don't Include Separate links:

*

*Instead again Go to the google font

*Open Quattrocento Sans font

*Add Whatever weight and style you need for that font

*And, add this code to your website

Link will be like following:
<link href='http://fonts.googleapis.com/css?family=Quattrocento+Sans:400,400italic' rel='stylesheet' type='text/css'>

A: Use this as an example:
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,800italic|Roboto:400,500,900|Oswald:400,300|Lato:400,100' rel='stylesheet' type='text/css'>

That way you can gather them all in one specific link.

A: try this example:
standart:
<link href='http://fonts.googleapis.com/css?family=Quattrocento+Sans:400,400italic,700,700italic&subset=latin,latin-ext' rel='stylesheet' type='text/css'>

@import:
 `@import url(http://fonts.googleapis.com/css?family=Quattrocento+Sans:400,400italic,700,700italic&subset=latin,latin-ext);`

javascript:
 <script type="text/javascript">
      WebFontConfig = {
        google: { families: [ 'Quattrocento+Sans:400,400italic,700,700italic:latin,latin-ext' ] }
      };
      (function() {
        var wf = document.createElement('script');
        wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
          '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
        wf.type = 'text/javascript';
        wf.async = 'true';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(wf, s);
      })(); </script>

use: font-family: 'Quattrocento Sans', sans-serif;


Q: Checking file checksum in Python I have to write in Python that performs the following tasks:
1- Download the Movielens datasets from the url ‘http://files.grouplens.org/datasets/movielens/ml-
25m.zip’
2- Download the Movielens checksum from the url ‘http://files.grouplens.org/datasets/movielens/ml-
25m.zip.md5’
3- Check whether the checksum of the archive corresponds to the downloaded one
4- In case of positive check, print the names of the files contained by the downloaded archive
This is what I wrote up to now:
   from zipfile import ZipFile
    from urllib import request
    import hashlib
    def md5(fname):
        hash_md5 = hashlib.md5()
        with open(fname, "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                hash_md5.update(chunk)
        return hash_md5.hexdigest()
    url_datasets = 'http://files.grouplens.org/datasets/movielens/ml-25m.zip'
    datasets = 'datasets.zip'
    url_checksum = 'http://files.grouplens.org/datasets/movielens/ml-25m.zip.md5'
    request.urlretrieve( url_datasets, datasets)
    request.urlretrieve (url_checksum, checksum)
    checksum = 'datasets.zip.md5'
    with ZipFile(datasets, 'r') as zipObj:
     listOfiles = zipObj.namelist()
     for elem in listOfiles:
           print(elem)

So what I'm missing is a way to compare the checksum I computed with the one I downloaded and maybe I can create a function "printFiles" that checks the checksum and in the positive case prints the list of files.
Is there something else I can improve?

A: Your code isn't actually making any of the requests.
from zipfile import ZipFile
import hashlib
import requests

def md5(fname):
    hash_md5 = hashlib.md5()
    hash_md5.update( open(fname,'rb').read() )
    return hash_md5.hexdigest()

url_datasets = 'http://files.grouplens.org/datasets/movielens/ml-25m.zip'
datasets = 'datasets.zip'
url_checksum = 'http://files.grouplens.org/datasets/movielens/ml-25m.zip.md5'
checksum = 'datasets.zip.md5'

ds = requests.get( url_datasets, allow_redirects=True)
cs = requests.get( url_checksum, allow_redirects=True)

open( datasets, 'wb').write( ds.content )

ds_md5 = md5(datasets)
cs_md5 = cs.content.decode('utf-8').split()[0]
print( ds_md5 )
print( cs_md5 )

if ds_md5 == cs_md5:
    print( "MATCH" )

    with ZipFile(datasets, 'r') as zipObj:
        listOfiles = zipObj.namelist()
        for elem in listOfiles:
            print(elem)
else:
    print( "Checksum fail" )


Q: Does GIT merges based on datetime? I would like to understand how GIT merge happens.
Master & Feature
A--B--C --G--H--I

       --D--E--F

Here is the changes made and date when it was changed.
G(Master) - Aug - 8th
H(Master) - Aug - 10th
I(Master) - Aug - 15th
D(Feature) - Aug - 9th
E(Feature) - Aug - 11th
F(Feature) - Aug - 12th
So, now If I merge master branch into feature how does the history appear? Does it merge based on the date change and display like this?
Feature branch
A--B--C--G--D--H--E--F

A: The way git does a merge is that it creates if you will, a patch of the diff between your current branch and the branch you are trying to merge. It then simply applies that patch as a whole to your branch with the commit -
Merge "Source Branch" into "Target Branch"

This is basically the only new commit that you are having. If you want to revert --D--E--F then you don't revert them individually, but revert this big merge commit.
As for the time stamp, yes git will now also give you a merge of the commits themselves in both the branches that you can revert by yourself.
So imagine it something like this,
Branch 1: A - B - C -           - G - H - I
Branch 2:             D - E - F

Merging these together in Branch 1 will give you -
Branch 1: A - B - C - D - E - F - G - H - I - J (Here, J = D + E + F)

On the other hand, a rebase would give you :
Branch 1: A - B - C - G - H - I - J - D* - E* - F* (Here, D* = D's changes)

A: If you are on branch master, and execute git merge feature, your history will be changed from this :
A--B--C---G--H--I (master)
       \
        \-D--E--F (feature)

to this :
A--B--C---G--H--I---J (master)
       \           /
        \-D--E--F-/ (feature)

git will compare the two diffs C vs I and C vs F, and try to build a new commit which combines the changes in these two diffs.
git mays ask you to manually solve conflicts if some changes on I overlap some changes in F.
git will not modify any of the existing commits, so that, on a shared repo, the other developpers' copy of the repo is not messed up.
git merge does not take into account the date of the commit(s) ; it just looks at the succession of commits (the fact that G comes after C in the graph, for example).

There is another command, git rebase, which will change the structure of the existing commits, and may force other developpers to do extra work if they want to keep their local copy in sync with the remote server.
git rebase is a useful command, but it is generally advised to use it only locally, before you share some modification (e.g. : only use it on modifications which have not yet been git pushed).

A: If you merge master branch to feature, it will make a new commit with its log like "Merge branch master to into feature".
you won't get history like A-B-C-G-D-H-E-F


Q: How to move DataTable to another DataSet? How can I move the DataTable object from one dataset to another and avoid duplicating data in memory? Something, like this:
var ds1 = new DataSet();
var ds2 = new DataSet();
IDataAdapter da = myDataAdapterFactory.New();
da.Fill(ds1);
Console.WriteLine(ds1.Tables.Count);//1
Console.WriteLine(ds2.Tables.Count);//0
ds1.MoveDataTableTo(ds2, ds1.Tables[0]);
Console.WriteLine(ds1.Tables.Count);//0
Console.WriteLine(ds2.Tables.Count);//1

I cannot spend memory, and it is the reason why I dont'use DataTable.Copy() or DataSet.Merge() or other ways to duplicate rows in memory.

A: You can take the datatable you need to move, Remove it from the first dataset and Add it to the other
var dt = ds1.Tables[0];
ds1.Tables.Remove(dt);
ds2.Tables.Add(dt);

A: Use this function
public DataTable CopyDataTable(DataTable dtSource)
{
        // cloned to get the structure of source
        DataTable dtDestination = dtSource.Clone();
        for (int i = 0; i < dtSource.Rows.Count; i++)
        {
            dtDestination.ImportRow(dtSource.Rows[i]);
        }
        return dtDestination;
}

Suppose you want to copy first table of sourceSet to destinationSet.
Call it like
DataTable destinationTable = CopyDataTable(ds1.Tables[0]);
DataSet destinationSet = new DataSet();
ds2.Tables.Add(destinationTable);


Q: Accessing SQL array element from Libreoffice Basic I have a postgresql database that contains program data. In Libreoffice Calc, I have Basic macros that interact with the postgresql database and uses Calc as the user client.  One of the postgresql tables has an array and I can't index into that array directly from Basic.
Here is the table setup, as shown in pgAdmin:
  sq_num integer,
  year_start integer,
  id serial NOT NULL,
  "roleArray" text[]

Say I want to SELECT roleArray[50]. My every attempt to do this out of Basic results in the entire array being passed.  I can certainly split the array myself and get the element I'm after, but I was using SQL arrays to help automate this stuff.
My Basic code uses a Libreoffice Base file for the connection to the postgresql database.  Going to the Base file, I cannot create a query that will select an individual element and not return the entire array UNLESS I select the button "Run SQL command directly" and run this query:
SELECT "roleArray"['50'] FROM myTableThatHasArrays

Then I get element 50 from every record as intended.
I believe there is a bug report that describes this, where the Base command parser can't handle indexing an array.  My question is what is the best method to overcome this?
The best scenario is to be able to index an element in the SQL array directly from Basic.

A: It sounds like you used XRow.getString, which (sensibly enough) retrieves the array as a single large string.  Instead, use XRow.getArray and then XArray.getArray.  Here is a working example:
sSQL = "SELECT id, ""roleArray""[2] FROM mytablethathasarrays;"
oResult = oStatement.executeQuery(sSQL)
s = ""
Do While oResult.next()
    sql_array = oResult.getArray(2)
    basic_array = sql_array.getArray(Null)
    s = s & oResult.getInt(1) & " " & basic_array(1) & CHR$(10)
Loop
MsgBox s


Q: Help showing that set of all finite sums of $rx + lx$ is an ideal of commutative ring $R$. This question is related to another one I asked here. Suppose I wanted to consider the set $(x)$, which consists of all finite sums of elements of the form $rx + lx$, where $r \in R$, a commutative ring (not necessarily with unity), and $l \in \mathbb{Z}$.
If I wanted to show that $(x)$ is an ideal in the ring $R$, I would need to show that $rx + lx$ is an additive subgroup of $R$, and also that $(x)R \subseteq (x)$ and $R(x) \subseteq (x)$.
I'm a little confused about how to actually go about showing this though.
Here's what I've done:
$$ \text{To show that}\, (x)\, \text{is an additive subgroup of}\, R, \,$$

*

*$0_{R} \in R, \, 0 \in \mathbb{Z}, \, \text{so when}\, r = 0_{R},\, l=0,\, rx + lx = 0_{R}x + 0x = 0.\, \text{So,}\, 0 \in (x).$

*$\text{Let}\, r_{1},r_{2} \in R \,\text{and}\, l_{1}, l_{2} \in \mathbb{Z}. \,$ Then, $r_{1}x+l_{1}x-(r_{2}x+l_{2}x) = r_{1}x+l_{1}x - r_{2}x-l_{2}x = (r_{1}-r_{2})x + (l_{1}-l_{2})x \in (x), \, \text{since}\, r_{1}-r_{2} \in R$ because $R$ is a ring, and thus is closed under additive inversion; and since $l_{1}-l_{2} \in \mathbb{Z}$, because $\mathbb{Z}$ is certainly closed under additive inversion.

$$\text{To show that}\,R(x) \subseteq (x),$$

Consider $rx + lx \in (x)$. Then, consider any element $s \in R$.
$s(rx+lx)=srx + slx = srx + lsx$ (because $R$ is commutative).
However, and now's the part where I'm in real trouble, while $sr \in R$, $ls$ is not necessarily in $\mathbb{Z}$, so I'm obviously doing something wrong.

Could somebody please help me finish the proof that this set $(x)$ is an ideal of the commutative ring $R$? Thank you.

A: $srx+lsx =(sr+ls)x+0.x$ and $sr+ls=r'\in R$. So $srx+lsx=r'x+0.x$.


Q: how to get value hidden in C# when it is set by jquery after postback i am nwe to jquery.how i get value of hidden field after post back in csharp. when ever post back occures value dissapear.
this is my hidden field.
<asp:HiddenField ID="Hid_BasicSalary" runat="server" />

this is jquery code where is assign data to it after succsesful execution of ajax web service.
var BasicSalary = $('Hid_BasicSalary');
 BasicSalary.val(data["BasicSalary"]);

this is c sharp code when i click on button postback occurs afte this node data.
protected void Btn_PIncrementSave_Click(object sender, EventArgs e)
    {
        try
        {
            TxBx_IncrementAmount.Text = Hid_BasicSalary.Value.ToString();

        }
        catch (Exception ex)
        {

            Utility.Msg_Error(this.Master, ex.Message);
        }
    }

please help me

A: In jQuery we use the selector for select any elements, and we have to put . for the class and # to the id selector so please put # or . before your element.
In your case, $('#Hid_BasicSalary'); or $('.Hid_BasicSalary'); is your answer.

A: i was missing # with $.
var BasicSalary = $('Hid_BasicSalary');

i write this instead of this
 var BasicSalary = $('#Hid_BasicSalary');

A: Try this
var BasicSalary = $('#Hid_BasicSalary');

A: Use  This code is page load to get new value from hidden
Request.Form["hdnvalue"];

A: you missed the "#" and i think that you should use the hidden control's clientid.
var BasicSalary = $('#<%=Hid_BasicSalary.ClientID%>');

A: try this to get value of server control from javascript/jquery
var BasicSalary = document.getElementById('<%=Hid_BasicSalary.ClientID%>').value


Q: Traffic is routed via unknown means I have 2 machines running CentOS:
Machine A has two NICs: 192.168.150.1/255.255.255.0 and 192.168.1.1/255.255.255.0
Machine B has one NIC:  192.168.150.2/255.255.255.0

Machine B is connected directly to A (NIC to NIC), and has a route defined:
Destination     Gateway           Genmask
192.168.1.0     192.168.150.1     255.255.255.0

On machine A, sshd is bound to 192.168.1.1. However it's possible to ssh into 192.168.1.1 from machine B. Why could that be the case?
TCP forwarding is not enabled on Machine A. Also, machine B does not have an SSH ProxyCommand defined. Is there some other way that traffic received on 192.168.150.1 is being routed to 192.168.1.1?

A: Linux uses the strong end system model. IP addresses do not act in a way as if they were different machines. Instead a machine acts like it owns all its IP addresses.
Since 192.168.150.1 and 192.168.1.1 are the same machine, no forwarding or routing is needed. If you reach one, you've reached the other.


Q: grep --output-only onto single line I'm currently running a grep that is very close to what I want:
$grep ! myinput_file/* | grep  -Po '\d+\.\d+|\d+'

I like that this command only returns the matching contents of the line, but want the output to be on a line by line basis. E.g. when I run the command currently I get:
7.969
80
2
152.03886767
7.969
80
4
152.10112473
7.969
80
6
152.10200398
7.969
80
8
152.10203172

Where I would rather get output of the form:
7.969 80 2 152.03886767
7.969 80 4 152.10112473
7.969 80 6 152.10200398
7.969 80 8 152.10203172

I could write a script or use vim on the output, but I suspect there is a more elegant solution...
PS the source file looks like:
$grep ! encutkpoint_calculations/* | grep  -P '\d+\.\d+|\d+'

encutkpoint_calculations/MgO.scf.a=7.969.ecut=80.k=2.out:!    total energy              =    -152.03886767 Ry
encutkpoint_calculations/MgO.scf.a=7.969.ecut=80.k=4.out:!    total energy              =    -152.10112473 Ry
encutkpoint_calculations/MgO.scf.a=7.969.ecut=80.k=6.out:!    total energy              =    -152.10200398 Ry
encutkpoint_calculations/MgO.scf.a=7.969.ecut=80.k=8.out:!    total energy              =    -152.10203172 Ry

A: Since data is being extracted from file names as well, I'll leave the first use of grep as is
$ # this won't depend on knowing how many matches are found per line
$ # this would also work if there are different number of matches per line
$ grep '!' encutkpoint_calculations/* | perl -lne 'print join " ", /\d+(?:\.\d+)?/g'
7.969 80 2 152.03886767
7.969 80 4 152.10112473
7.969 80 6 152.10200398
7.969 80 8 152.10203172

Alternate is to post process the data, if number of matches is constant per line
grep '!' encutkpoint_calculations/* | grep -oP '\d+(\.\d+)?' | pr -4ats' '


Q: Changing width of UISlider programmatically? I am creating a UISlider programmatically. When initializing it, I use initWithFrame and pass in CGRect and it doesn't have any effect. I thought maybe I can change it after I initialize but still nothing...I can change it via I.B. so there's got to be a way to change it's width.

A: You definitely can specify the width of the slider by using initWithFrame or changing the bounds of it. There has to be something else going on here that's preventing it from working.


Q: Single Group Pre-Post McNemar Table Set Up I am looking to evaluate if the change in proportion for a group changed pre-to-post intervention.

Essentially, is the ~7% increase from pre (~2%) to post (~9%) significant. I am running the McNemar test in SAS 9.3 as follow:
ODS HTML CLOSE; ODS HTML;
PROC FREQ DATA = AGE0_10_SUM ORDER = DATA;
WEIGHT MEMCOUNT;
TABLES AGE0_10*SRC / AGREE;
TITLE "AGE0_10";
RUN;
;QUIT;

This is resulting in a p-value less than 0.0001. I think the change is significant but not at this magnitude, also, when running other age groups the results for a 0.02% increase was also <0.0001. Something is wrong.
How should the table be set-up to run the McNemar test with AGE0_10 as being the repeated subject pre and post.
Thank you.

A: You have very large denominators, so you should not be surprised if quite small differences give low p-values.
One should be careful to not confuse p$\leq$0.05 with practical relevance or the magnitude of an effect. Differences that are completely irrelevant for any practical purposes can be "statistically significant" with enough data.
The language you use of "repeated subject" does not seem to make a lot of sense in connection to a variable that seems to have two levels and does not sound like it would indicate a particular individual person/experimental unit.
For McNemar's test, your data should be structured like this with each row giving the number of units (Number) with result of assessment 1 = Result1 and the result of assessment 2 = Result2):
Result1    Result2    Number
0          0          900
0          1          100
1          0          100
1          1          900

Other note: pre-/post-tests are typically irrelevant for (almost) any question a researcher truly wants to answer (particularly, if they are to see whether some intervention/change/something had an effect).


Q: How to add jstree to angular 2 application using typescript with @types/jstree Hi I believe it's some kind of a newbee question, but I'm new to ng2 so please bear with me...
I've done:
npm i jstree --save

After I created using angular-cli application.
Then I installed:
npm i @types/jstree --save-dev

And that's on setup, then I tried to use it and no luck.
Please can someone show me how to use that 3rd party library with typescript

A: Here are the steps I took to get it to work.
I started with a new cli application.
npm install --save jquery jstree
npm install --save-dev @types/jquery @types/jstree
I then updated the angular.json file, if you are using an older version of angular-cli, makes changes to the angular-cli.json file. I added "../node_modules/jstree/dist/themes/default-dark/style.min.css" to the styles property array.
I also added two items into the scripts property array:

"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/jstree/dist/jstree.min.js"

I then updated src/app/app.component.html to

Root node 1

Child node 1

Child node 2

I also update src/app/app.component.ts to
import { Component, OnInit } from '@angular/core';

declare var $: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  ngOnInit(): void {
    $('#foo').jstree();
  }
}

Hope this helps!

A: @IamStalker, it seems that i know what the problem is. But can you present more code to show how you want to use it?

As jstree depends on jQuery, you have to import it too.
You may have to use scripts config.
Here is the reference: https://github.com/angular/angular-cli/wiki/stories-global-scripts.


Q: How to map table name to EF Entity? I have been using EF Code First for 1 month. My project needs to work with many tables (over 100 tables of data) and they will be changed many times in the future. It hard to control and take time to add the migration.
So is there any solution to skip the add-migration step, just create the table in the database and create a mapping to the Entity?
Example:
In database I have a table like this:
CREATE TABLE dbo.MyTable
(
    Id INT,
    Name VARCHAR(255),
    Description VARCHAR(1000)
);

I want to map it to the following entity:
public class MyEntity
{
   public Id int {get; set;}
   public Name string {get; set;}
   public Description string {get; set;}
}

My expected solution is something like this:
CreateMap("dbo.MyTable", MyEntity)

A: Use the attribute System.ComponentModel.DataAnnotations.Schema.Table
[Table("MyTable")]
public class MyEntity
{
   public Id int {get; set;}
   public Name string {get; set;}
   public Description string {get; set;}
}

If you don't actually want to run the migrations, I suggest create them anyway and comment out the relevant code before you run them. That way you will be well set up for the occassion  when you do actually want to run them.

A: You can define the entity maps by overriding the method called OnModelCreating in your DbContext:
Then you can add some maps similar to:
modelBuilder.Entity<Order>(m => {
     m.ToTable("MyTable", "dbo");
})

Info: https://learn.microsoft.com/en-us/ef/core/modeling/relational/tables
EDIT: I don't like adding annotation directly to my entity as I prefer to centralize it in one place. Easier to manage. After all I guess it's a question of preferences :)


Q: Gagliardo-Nirenberg interpolation inequality when $p=N\geq 2$ and the order of highest derivative is $1$ I am going through the proof of Gagliardo-Nirenberg interpolation inequality, in A First Course in Sobolev Spaces, by Giovanni Leoni, Chapter 12. Here I am stuck with a Exercise problem comes in the middle of the proof (page 376):

Let $u\in \dot{W}^{1,N}(\mathbb{R}^N)$, $N\geq 2$, with $u\in L^q(\mathbb{R}^N)$ for some $1\leq q<\infty$. Let $v:=|u|^t$, where $t>1$ is such that $v\in W^{1,1}(\mathbb{R}^N)$. Prove that
$$\|u\|_{L^{tN/(N-1)}}\leq c\|u\|_{L^{(t-1)N/(N-1)}}^{(t-1)/t}\|\nabla u\|_{L^N}^{1/t}.$$

Here $\dot{W}^{1,N}$ denots homogeneous Sobolev space.
My best try was that, by using $L^p$ type interpolation inequality to $\|v\|_{L^{N/(N-1)}}$ as $\frac{1}{\frac{N}{N-1}}=\frac{1-\frac{1}{t}}{\left(1-\frac{1}{t}\right)\frac{N}{N-1}}+\frac{\frac{1}{t}}{\infty}$,
$$\|u\|_{L^{tN/(N-1)}}=\|v\|_{L^{N/(N-1)}}^{1/t}\leq\|v\|_{L^{(1-1/t)N/(N-1)}}^{(1-1/t)1/t}\| v\|_{L^\infty}^{1/t^2}\\=\|u\|_{L^{(t-1)N/(N-1)}}^{(t-1)/t}\| v\|_{L^\infty}^{1/t^2}.$$
I believe such $v\in L^\infty$, however I cannot proceed further than this. I will deeply appreciate if somebody can provide some help.

A: Assume $u\in C_0^\infty({\mathbb R}^N)$, apply the classical Sobolev inequality
$$
\Big(\int_{{\mathbb R}^N} (u^t)^{\frac{N}{N-1}}\Big)^{\frac{N-1}{N}}
\leq C\int_{{\mathbb R}^N} |\nabla(u^t)|,
$$
then apply Holder on the right hand side:
$$
\int_{{\mathbb R}^N} |\nabla(u^t)|=t\int_{{\mathbb R}^N} |u^{t-1}\nabla u|
\leq t\Big(\int_{{\mathbb R}^N} |u^{t-1}|^{\frac{N}{N-1}}\Big)^{\frac{N-1}{N}}\Big(
\int_{{\mathbb R}^N} |\nabla u|^N\Big)^{\frac{1}{N}},
$$
thus
$$
\|u\|_{\frac{tN}{N-1}}^t\leq Ct\|u\|_{\frac{(t-1)N}{N-1}}^{t-1}\cdot \|\nabla u\|_N.
$$
Take $\frac 1t$ power.


Q: Oracle connection test We are developing java based web application, which runs on Ubuntu 12.04. At the start of installation, we prompt for Oracle server's Host, Port, user, password & SID details and then passed them to installer to build jdbc:oracle:thin url. Eventually, our installer connects to Oracle and creates some tables.
Now I am trying to write a script(shell or python) to quickly verify user entered Oracle settings are correct or not by simply connecting to Oracle and disconnecting before passing those to our installer. I tried to use echo "exit" | sqlplus -L user/password@//host:port/SID | grep Connected > /dev/null but sqlplus easy connect is only taking service-name not SID.
Is there any easy way to test Oracle connectivity. I need to write it in script, which needs to run automatically as a part of installation steps.
Thanks for all the help.

A: Read https://asktom.oracle.com/pls/asktom/f?p=100:11:0::NO::P11_QUESTION_ID:45033135081903
Oracle listener is expected to listen to your request for connection.
Here is the copy of Tom's answer
[tkyte@desktop tkyte]$ sh -vx test.sh
sqlplus
'scott/tiger@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost.localdomain)(PORT=152
1)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=ora9ir2.kyte.com)))'
Use your host, port and service_name.


Q: Can you help me please about fsck Check the image or ask me for details. Thanks

A: Start a live session, using the Ubuntu installation DVD.
Then in the live session, open a terminal and run on it:
sudo umount /dev/sda7
sudo fsck /dev/sda7

Then reboot
And boot from hard drive


Q: Change pages margins (right & left) I have a problem with the margins that don't seem appropriate ... and i want to change these margins to make it equal on the left and the right, this is a sample of my code :
\documentclass[ a4paper, 12pt, blue, rgb,]{tubsbook}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{lipsum}
\usepackage{listings}
\usepackage{xcolor}
\usepackage{mathtools}
\usepackage{hyperref}
\usepackage{url}
\usepackage{array,multirow}
\usepackage{graphicx}
\usepackage{subfig}
\usepackage{amsmath}
\usepackage{algorithmic,algorithm}
\usepackage[activate]{pdfcprot}
\usepackage{setspace}
\onehalfspacing

\title{MULTI-CORE SYSTEM}
\logo{\includegraphics{images/c3e_logo.pdf}}
\titleabstract{\lipsum[2]}
\titlepicture{images/infozentrum.jpg}

\begin{document}
....
....
\end{document}

and this is how the margins in the pages look like :

Can someone help me on this?


Q: Find the maximum area possible of equilateral triangle that inside the given square How can I find the maximum area possible of equilateral triangle that inside a square whose sides have length a.
And how does that triangle look like? Can we construct it (with compass and straightedge)?

A: The last paragraph at the Mathworld piece on equilateral triangles gives the answer, and cites Madachy, J. S. Madachy's Mathematical Recreations. New York: Dover, pp. 115 and 129-131, 1979.
EDIT (in response to request from Taha Akbari for more detail): Let the square have horizontal and vertical sides. Consider an equilateral triangle with one vertex at the lower left corner, $A$, of the square, and one vertex at the upper left corner, $B$, of the square, and the third vertex, $Z$, inside the square. Now consider moving the triangle vertex at $B$ to the right, toward the upper right corner, $C$, of the square, while moving $Z$ so as to keep the triangle equilateral. This increases the area of the triangle, since it increases the length of the side of the triangle, since the second vertex, $X$, of the triangle is moving away from the first vertex of the triangle.
Eventually, the triangle vertex $Z$ lies on the right side of the square, and you can't move $X$ any farther right without pushing $Z$ outside the square, so you've made the triangle as large as possible. Now the question is, why are the angles $BAX$ and $ZAD$ 15 degrees (where $D$ is the lower right corner of the square)?
The triangles $BAX$ and $ZAD$ are congruent, since $BA=AD$, $AX=AZ$, and the angles at $B$ and $D$ are equal. So the angles $BAX$ and $ZAD$ are equal. But they, together with the 60 degree angle $XAZ$, add up to the 90 degree angle $BAD$. So, they measure 15 degrees.

A: The answer is 15° so stop here if you want to have a go at the proof (not given by the Mathworld link); it's basically trigonometry. I give it here because the result was needed by a friend for making furniture. It's best to start with a good diagram (to be added) but for now imagine a square with side length $A$ containing an equilateral triangle (also of side length $A$) with a horizontal base. The tip of the triangle will not touch the top of the square, but if it is rotated anticlockwise about the origin (at the bottom left) and the base is extended as $H$, the tip will touch the top after rotation $\theta$.
This creates three triangles outside the main triangle. For the one below we have:
$$O=H\sin{\theta}$$
For the one to the right we have (for the lowest angle $\phi$):
$$\phi=180°-60°-(90°-\theta)=30°+\theta=\frac{\pi}{6}+\theta$$
$$H\cos(\theta+\frac{\pi}{6})=A-O=A-H\sin\theta$$
$$\cos(\theta+\frac{\pi}{6})=\frac{A}{H}-\sin\theta$$
Using the cosine sum identity this yields:
$$\cos\theta\cos\frac{\pi}{6}-\sin\theta\sin\frac{\pi}{6}=\frac{A}{H}-\sin\theta$$
Substituting $\cos\theta$ for $A/H$ and rearranging gives:
$$\sin\theta=(2-\sqrt{3})\cos\theta$$
$$\theta=\tan^{-1}(2-\sqrt{3})=\frac{\pi}{12}=15°$$
EDIT The area of an equilateral triangle $A_T$ is:
$$A_T=\frac{\sqrt{3}}{4}H^2$$
For our case the side length $H$ is:
$$H=\frac{A}{\cos(15°)}$$
Therefore:
$$A_T=\frac{\sqrt{3}}{4}\times\frac{(2\sqrt{2})^2A^2}{(1+\sqrt{3})^2}=\frac{2\sqrt{3}A^2}{4+2\sqrt{3}}=\frac{\sqrt{3}A^2}{2+\sqrt{3}}$$

A: The story of why we know that the largest equilateral triangle inscribed in a square is positioned as shown below, can be found in a video here. Just press the green button marked "Video".

I don't know if Taha Akbari is interested in the other part of the OP question, namely "Can we construct it (with compass and straightedge)?", but I found it interesting. And the answer is yes. It takes $3$ basic steps:

*

*Construct a $30^\circ$ angle from a corner of the square
See here for an animated version of how this is done. The end result is shown below.

*Construct the bisector of the $30^\circ$ angle
See here for an animated version of how this is done. The end result is shown below.

*Construct the rest of the equilateral triangle
a. The intersection of the line BF with the side of the square gives the point G. The line BG is one side of the triangle.
b. Construct the perpendicular bisector of BG using the intersection points of circles at B and G. Point J, which is the intersection of the bisector with the square, provides the last point of the equilateral triangle $\triangle BGJ$.

A: Simplified construction of the triangle:

Draw the diagonal $AC$ and the arcs through $B$ centred on $A$ and through $A$ centred on $B$. The arcs intersect at point $D$ and the arc-diagonal intersection is at point $E$. Draw a circle centred on $D$ through $E$, finding $F$ as the other intersection with the arc.
Draw the line $AF$ and extend to $G$ on the side of the square. Draw an arc centred on $C$ (or $A$) through $G$ to find $H$ as the other intersection with the square. $\triangle AGH$ is the desired triangle.
($\triangle ADB$ is equilateral and $\angle BAC = 45°$ thus $\angle EAD = 15°$ so also $\angle DAF = 15°$.)

A: Already there are number of solutions in this thread. I'll try to clarify Taha Akbhari's question on how we get that $15$ degrees via a different approach. But first lets call this angle as $\theta$.
The problem can be formulated as follows,
$$ \max ~~\frac{\sqrt(3)}{4} (a^2 + y^2), \\ \text{subject to}: ~ (x-a)^2 + (y-a)^2 = a^2 + y^2 = x^2 + a^2 \\ 0 \leq x,y \leq a, $$
where WLOG $(0,0), (x,a)$ and $(a,y)$ are the points of vertices of the equilateral triangle inscribed in the square of side $a$. (Exercise: If one of the vertices of the triangle is strictly inside the square then the area of this new triangle is not the maximum possible.)
So simplifying out the constraints one gets, $$x = y \\ x^2 - 4ax + a^2, $$ which yields us with the solution $x=y=2-\sqrt(3)$.
So $\tan(\theta) = 2-\sqrt(3)$. From https://www.algebra.com/algebra/homework/Trigonometry-basics/Trigonometry-basics.faq.question.207450.html, $\theta = 15^{\circ}$.

A: Based on my answer to the question Finding the largest equilateral triangle inside a given triangle, I present the following solution:

*

*Draw the diagonal BD, and draw circles with radius BD at both ends.

*Mark E, the intersection of the two circles, and draw intervals EB and ED.

*Draw a line parallel to EB through A, marking the intersection with CD at F. Draw a line parallel with ED through A, marking the intersection with BC at G. Then join F to G.

*Shade $\triangle$AFG, the required equilateral triangle.

The proof is elementary, since $\triangle$BDE is equilateral, and corresponding angels between parallel lines are equal.


Q: How can I implement this L1 norm Robust PCA equation in a more efficient way? I recently learned in class the Principle Component Analysis method aims to approximate a matrix X to a multiplication of two matrices Z*W. If X is a n x d matrix, Z is a n x k matrix and W is a k x d matrix. In that case, the objective function the PCA tries to minimize is this. (w^j means the j_th column of W, z_i means the i_th row of Z)

In this case it is easy to calculate the gradient of f, with respect to W and Z.

However, instead of using the L2 norm as above, I have to use the L1 norm, like the following equation, and use gradient descent to find the ideal Z and W.

In order to differentiate it, I approximated the absolute function as follows (epsilon is a very small value).

However, when I tried to calculate the gradient matrix with respect to W of this objective function, I derived an equation as follows.

I tried to make the gradient matrix elementwise, but it takes too long if the size of X is big.
g = np.zeros((k, d))
for i in range(k):
            for j in range(d):
                for k2 in range(n):
                    temp = np.dot(W[:,j], Z[k2,:])-X[k2, j]
                    g[i, j] += (temp * Z[k2, i])/np.sqrt(temp*temp + 0.0001)
g = g.transpose()

Is there any way I can make this code faster? I feel like there is a way to make the equation way more simple, but with the square root inside I am completely lost. Any help would be appreciated!