text:
Q: Compare the highest value between two different objects for each property and value I have two objects
object1 = {num: 0, num2: 0}
object2 = {num: 3, num2: 0}

I would like to compare both objects and get the highest one per object key, so my end results should be
result = {num: 3, num2: 0}

or if I had
object1 = {num: 0, num2: 0}
object2 = {num: 100, num2: 15}

I should get
result = {num: 100, num2: 15}

The highest math value per key.
The goal is to go through each object key comparing the two objects and pulling the highest numbered one. Per key also "num" is a var it can be anything and there could be more than two for example "num", "num1", "num2", "num3" and so forth.

A: Dynamic solution:
let ob1 = {a: 1, c:4};
let ob2 = {a: 2, b:3};
let ob3 = {b:5};

let lamba = function(...objects) {
    let result = {};
    objects.forEach(function (object) {
        for(let key in object) {
            if (object.hasOwnProperty(key) && typeof object[key] === "number") {
                result[key] = result[key] || 0;
                result[key] = (object[key] > result[key]) ? object[key] : result[key];
            }
        }
    });
    return result
};

let result = lamba(ob1, ob2, ob3);

console.log(result); // { a: 2, c: 4, b: 5 }

A: You can use Object.keys() to firstly get the keys from one of your objects and then use .reduce() to build a new object from those keys. For each newly created key in the object, you can get the max of all the values for that key from the passed-in objects. This can be achieved by mapping each value to an array with .map(), and then getting the maximum number from that array. This approach will work for N objects which all have the same keys.
See example below:

const object1 = {num: 0, num2: 10, num3: 5};
const object2 = {num: 3, num2: 0, num3: 2};
const object3 = {num: 3, num2: NaN, num3: 2};

const getMaxObject = (...objects) => {
  const keys = objects.map(Object.keys).reduce((acc, arr) => acc.length > arr.length ? acc : arr, []);
  return keys.reduce(
    (acc, key) => ({...acc, [key]: Math.max(...objects.map(
      o => o[key] || 0
    ))}), {}
  );
}

console.log(getMaxObject(object1, object2, object3));

A: hope this helps

let high1 = 0, high2 = 0;
const object1 = {num: 0, num2: 0}
const object2 = {num: 3, num2: 0}

Object.keys(object1).forEach(item =>{
  if(object1[item] > high1){
    high2 = high1;
    high1 = object1[item];
  }
});

Object.keys(object2).forEach(item =>{
  if(object2[item] > high1){
    high2 = high1;
    high1 = object2[item];
  }
});

let result = {
  num : high1,
  num2 : high2,
}

console.log('result', result);

A: If you choose to keep your numbers object inside an array.

let high1 = 0, high2 = 0;

const numbers = [
  {num: 0, num2: 0},
  {num: 3, num2: 0}
];

numbers.forEach( itemA =>{
  Object.keys(itemA).forEach(item =>{
    if(itemA[item] > high1){
      high2 = high1;
      high1 = itemA[item];
    }
  });
});

let result = {
  num : high1,
  num2 : high2,
}


text:
Q: JavaFX mp3 on Raspberry OS I'm trying to create simple audio player for mp3 files which i'm going to use on my Raspberry Pi 4.
Because of default OpenJDK which installed on Raspberry Pi not included JavaFX framework, i've installed Java 13 from Bellsoft/Liberica (it can be important for another raspberry users) which have JavaFx on board.
But code below is not working and throwing errors:
media = new Media("path/to/mp3-file");
MediaPlayer mp = new MediaPlayer(media);

Exception in Application init method
java.lang.reflect.InvocationTargetException
 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.base/java.lang.reflect.Method.invoke(Method.java:567)
 at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
 at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.base/java.lang.reflect.Method.invoke(Method.java:567)
 at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application init method
 at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:895)
 at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
 at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: MediaException: UNKNOWN : com.sun.media.jfxmedia.MediaException: Could not create player! : com.sun.media.jfxmedia.MediaException: Could not create player!
 at javafx.media/javafx.scene.media.MediaException.exceptionToMediaException(MediaException.java:146)
 at javafx.media/javafx.scene.media.MediaPlayer.init(MediaPlayer.java:518)
 at javafx.media/javafx.scene.media.MediaPlayer.<init>(MediaPlayer.java:421)
 at sample.FX_Player.init(FX_Player.java:86)
 at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:824)
 ... 2 more
Caused by: com.sun.media.jfxmedia.MediaException: Could not create player!
 at javafx.media/com.sun.media.jfxmediaimpl.NativeMediaManager.getPlayer(NativeMediaManager.java:295)
 at javafx.media/com.sun.media.jfxmedia.MediaManager.getPlayer(MediaManager.java:118)
 at javafx.media/javafx.scene.media.MediaPlayer.init(MediaPlayer.java:474)
 ... 5 more
Exception running application sample.FX_Player

I have read that trouble could be because of bad file path but i've tried different ways and no one is not working
file:///home/pi/test.mp3
file:/home/pi/test.mp3
/home/pi/test.mp3

i faced similar questions:
JavaFX and "MediaException: UNKNOWN ... Could not create player!"
JavaFX Media Player not working
but different paths i tried and i use java version higher than 9
Can someone explain how to solve this trouble?

redpajama_set_name: RedPajamaStackExchange


text:
Q: coldfusion - Entity has incorrect type for being called as a function I have a situation where I'm refactoring some code - I segregated out a lot of code in a loop and put it into a component, each activity is a method, all called w/i a loop.
when it runs - the second time thru the loop, it fails to resolve a.id - at line "var b = b( i, a.id );"
If i do a writeOutput() at each line, I see my vals at the start of the loop and at each line, until the last time.
    function a() {
        //do thing
        return id;
    }

    function b() {
        //do thing
        return id;
    }

    function bigOne() {
        for( var i=1; i<2; i++; ) {
            var a = a( i );
            var b = b( i, a.id );
        }
    }

Ive tried this too - same issue
function bigOne() {
    var a = '';
    var b = '';

    for( var i=1; i<2; i++; ) {
        a = a( i );
        b = b( i, a.id );
    }
}

I've read this Coldfusion, The symbol you provided [method_name] is not a function - but it's not the same thing, this article is dealing with getters and setters... I don't think this applies to my issue.
If I put my output like this (to 'see' it):
function bigOne() {
    var loopcount = 1;
    for( var i=1; i<2; i++; ) {
        writeOutput( 'loop count = ' & loopcount );
        var a = a( i );
        writeoutput( 'a.id = ' & a.id );
        var b = b( i, a.id );
    }
}

I get this:
loop count = 1
a.id = 52978
loop count = 2

then error. ERROR MSG:  Entity has incorrect type for being called as a function.
The symbol you provided insStop is not the name of a function.

A: Functions are pointed to by references just like variables are, so when you do this:
a = a();

you are overwriting the reference that points to the function a with the value returned from it.  So the next time you try to call a(), a ia no longer your function, it is the value returned from it the previous time it was called.
When you get an error along the lines of a variable not being able to be used in the way you want to use it... dump it out and look at what it contains. That generally points you in the right direction as to what you're doing wrong.

A: To support what Adam says, you can avoid this by scoping your variables inside your function. By default, unscoped variables are placed in the "variables" scope and this applies to functions called within the same template. So instead of naming your function var "loopcount", you could scope it to the "local" scope i.e
var local.loopcount = 1

This will make the function var belong only to the function and thus unaffected by anything occurring outside the function and vice-versa.


text:
Q: Using a single column table for generation sequence in SQL Server 2008 is scalable solution? Currently we are relying on a formula for generating confirmation numbers, but on heavy loads we observed duplicate confirmation numbers are being generated. We are considering switching to a sequence table as a quick fix, but we're worried about how it will perform. How can we calculate the risk in using the following approach?
CREATE TABLE dbo.TRN_CNFRM_SEQUENCE_UC_LOC_1
(
       id INT IDENTITY(seed,increment)
)

declare @confirm table (id int);
BEGIN TRAN
INSERT INTO dbo.TRN_CNFRM_SEQUENCE_UC_LOC_1
       output inserted.id into @confirm
DEFAULT VALUES
ROLLBACK TRAN
select ID from @confirm

A: First, creating a memory table means a table will be created in tempdb requiring schema lock. Adding a row to that table requires an additional exclusive page lock. If you're only acquiring a single "confirmation number" at the time you could get around that by altering the code to:
BEGIN TRAN
INSERT INTO dbo.TRN_CNFRM_SEQUENCE_UC_LOC_1
DEFAULT VALUES
ROLLBACK TRAN
SELECT SCOPE_IDENTITY()

Inserting into the table will also require an exclusive page lock. Having a high degree of concurrent work loads can lead to latch contention on the single page this table will allocate.


text:
Q: Deriving 2-variable Taylor expression from 1-variable Suppose we know Taylor's theorem for $f: \mathbb{R} \rightarrow \mathbb{R}$ with remainder. How would we use this to derive Taylor's theorem for $g: \mathbb{R}^2 \rightarrow \mathbb{R}$ with remainder?
To start, I'm trying to figure out which version of the 1-dimensional Taylor remainder to use (options are Lagrange, Cauchy, or integral form). To do this, I need to figure out the remainder for 2-variable Taylor. Wikipedia lists the remainder for a general n-variable Taylor's theorem, but I'm having trouble extracting the 2-dimensional case from it.

A: (this is pretty much what Michael said, I just happen to have a few notes on this and I thought this might be helpful. If I were you I would try to extrapolate from Lagrange's form of the remainder)
We already know Taylor's theorem for functions on $\mathbb{R}$,
$$ g(x) = g(a)+g'(a)(x-a) + \frac{1}{2}g''(a)(x-a)^2 +\cdots +\frac{1}{k!}g^{(k)}(a)(x-a)^k + R_k $$
and... If the remainder term vanishes as $k \rightarrow \infty$ then the function $g$ is represented by the Taylor series given above and we write:
$$ g(x) = \sum_{k=0}^{\infty}\frac{1}{k!}g^{(k)}(a)(x-a)^k. $$
Consider the function of two variables $f: U \subseteq \mathbb{R}^2 \rightarrow \mathbb{R}$ which is smooth with smooth partial derivatives of all orders. Furthermore, let $(a,b) \in U$ and construct a line through $(a,b)$ with direction vector $(h_1,h_2)$ as usual:
$$ \phi (t) = (a,b) + t(h_1,h_2) = (a+th_1, b+th_2) $$
for $t \in \mathbb{R}$. Note $\phi(0)=(a,b)$ and $\phi '(t) = (h_1,h_2) = \phi ' (0)$. Construct $g = f \,{\scriptstyle \stackrel{\circ}{}}\, \phi  : \mathbb{R} \rightarrow \mathbb{R}$ and choose $dom(g)$ such that $\phi(t) \in U$ for $t \in dom(g)$. This function $g$ is a real-valued function of a real variable and we will be able to apply Taylor's theorem from calculus II on $g$. However, to differentiate $g$ we'll need tools from calculus III to sort out the derivatives. In particular, as we differentiate $g$, note we use the chain rule for functions of several variables:
$$
\begin{align} \notag
   g'(t) =(f \,{\scriptstyle \stackrel{\circ}{}}\, \phi)'(t) &= f'(\phi(t))\phi '(t)  \\ \notag
         &= \nabla f(\phi(t)) \cdot (h_1,h_2) \\ \notag
         &= h_1f_x(a+th_1, b+th_2)+h_2f_y(a+th_1, b+th_2) \notag
\end{align}
$$
Note $g'(0)=h_1f_x(a, b)+h_2f_y(a, b)$. Differentiate again (I omit $(\phi(t))$ dependence in the last steps),
$$
\begin{align} \notag
   g''(t) &= h_1f_x '(a+th_1, b+th_2)+h_2f_y '(a+th_1, b+th_2)  \\ \notag
          &= h_1 \nabla f_x (\phi(t)) \cdot (h_1,h_2) +h_2 \nabla f_y (\phi(t)) \cdot (h_1,h_2)  \\ \notag
          &= h_1^2f_{xx}+ h_1h_2f_{yx} + h_2h_1f_{xy}+ h_2^2f_{yy}  \\ \notag
          &= h_1^2f_{xx}+ 2h_1h_2f_{xy} + h_2^2f_{yy}  \notag
\end{align}
$$
Thus, making explicit the point dependence, $g''(0) = h_1^2f_{xx}(a,b)+ 2h_1h_2f_{xy}(a,b) + h_2^2f_{yy}(a,b)$. We may construct the Taylor series for $g$ up to quadratic terms:
$$
\begin{align} \notag
   g(0+t) &= g(0)+tg'(0)+\frac{1}{2}g''(0) + \cdots \\ \notag
&= f(a,b)+t[h_1f_x(a, b)+h_2f_y(a, b)]+\frac{t^2}{2}\bigl[ h_1^2f_{xx}(a,b)+ 2h_1h_2f_{xy}(a,b) + h_2^2f_{yy}(a,b) \bigr] + \cdots \\ \notag
\end{align}
$$
Note that $g(t)= f(a+th_1, b+th_2)$ hence $g(1) = f(a+h_1, b+h_2)$ and consequently,
$$
\begin{align} \notag
 f(a+h_1, b+h_2) &= f(a,b)+h_1f_x(a, b)+h_2f_y(a, b)+ \\ \notag
                 & \qquad +\frac{1}{2}\biggl[ h_1^2f_{xx}(a,b)+ 2h_1h_2f_{xy}(a,b) + h_2^2f_{yy}(a,b) \biggr] + \cdots  \notag
\end{align}
$$
Omitting point dependence on the $2^{nd}$ derivatives,
$$ \boxed{ f(a+h_1, b+h_2) = f(a,b)+h_1f_x(a,b)+h_2f_y(a,b)+
                 \tfrac{1}{2}\bigl[ h_1^2f_{xx}+ 2h_1h_2f_{xy} + h_2^2f_{yy} \bigr] + \cdots }$$
Sometimes we'd rather have an expansion about $(x,y)$. To obtain that formula simply substitute $x-a = h_1$ and $y-b = h_2$. Note that the point $(a,b)$ is fixed in this discussion so the derivatives are not modified in this substitution,
$$
\begin{align} \notag
 f(x, y) &= f(a,b)+(x-a)f_x(a, b)+(y-b)f_y(a, b)+ \\ \notag
                 & \qquad +\frac{1}{2}\biggl[ (x-a)^2f_{xx}(a,b)+ 2(x-a)(y-b)f_{xy}(a,b) + (y-b)^2f_{yy}(a,b) \biggr] + \cdots  \notag
\end{align}
$$
At this point we ought to recognize the first three terms give the tangent plane to $z = f(z,y)$ at $(a,b,f(a,b))$. The higher order terms are nonlinear corrections to the linearization, these quadratic terms form a quadratic form. If we computed third, fourth or higher order terms we will find that, using $a=a_1$ and $b=a_2$ as well as $x=x_1$ and $y=x_2$,
$$ \boxed{f(x, y) = \sum_{n=0}^{\infty} \sum_{i_1=0}^{2}\sum_{i_2=0}^{2} \cdots \sum_{i_n=0}^{2} \frac{1}{n!}
\frac{\partial^{(n)}f(a_1,a_2)}{\partial x_{i_1}\partial x_{i_2} \cdots \partial x_{i_n}}
(x_{i_1} -a_{i_1})(x_{i_2} -a_{i_2})\cdots (x_{i_n} -a_{i_n})} $$

A: This probably isn't totally what you want, but I'll leave it here anyway as it may help you on your way.
This proves the second-order Taylor formula for scalar fields. I think the general case just involves some pencil pushing to figure out the $n^\text{th}$ derivative of $f$.
Let $g:\Bbb R^2 \to \Bbb R$. Then consider $f(t)=g(\mathbf a + t \mathbf y)$ for $|t|\le 1$. Then apply the Taylor formula to $f$, i.e. we have that $$f(1)=f(0)+f'(0)+\frac 1 {2!}f''(c), \quad\text{where}\quad 0<c<1$$
(Here we used Lagrange's form for the remainder.) Now since $f$ is a composite function, we have that $f'(t)=\nabla g(\mathbf a + t\mathbf y)\cdot \mathbf y$. In particular, $f'(0)=\nabla g(\mathbf a)\cdot \mathbf y$. Now all that's left is to differentiate $f'(t)$ again. Write
$$\begin{array}{rl}f'(t)=&D_1 g(\mathbf a+ t \mathbf y)y_1+D_2g(\mathbf a +t\mathbf y)y_2\\
\implies f''(t)=&D_1D_1g(\mathbf a + t \mathbf y)y_1^2+D_2D_1g(\mathbf a +t\mathbf y)y_2y_1+\\
&D_1D_2g(\mathbf a + t\mathbf y)y_1y_2+D_2D_2g(\mathbf a + t \mathbf y)y_2^2\\
=&\sum_{i=1}^2\sum_{j=1}^2D_{ij}g(\mathbf a + t \mathbf y)y_iy_j\end{array}$$
Note that we may write $f''(t)=\mathbf y H[\mathbf a + t\mathbf y] \mathbf y^\text T$, where $H$ is the Hessian Matrix of $f$. Thus we have (from the Taylor formula for $f$):
$$g(\mathbf a+\mathbf y)=g(\mathbf a)+\nabla g(\mathbf a )\cdot \mathbf y + \frac 1 2 \mathbf y H[\mathbf a+c\mathbf y]\mathbf y^\text T$$
It seems like this can be extended further, by a general formula for the calculation of the $n^\text{th}$ derivative of $f$, which is what they do on the Wikipedia page. Also note that here I used Lagrange's form of the remainder, while Wikipedia has the Integral form of the remainder. Essentially any form of the remainder will work, however certain forms may be more useful than others for particular applications.


text:
Q: Json.net no longer throws in case of duplicate I'm trying to upgrade my C# application from Newtonsoft.JSON 6 to the latest version (9.0.1).
I noticed a change of behavior when deserializing object containing duplicate elements, such as :
{
     "name": "test",
     "data":
     {
        "myElem": 1,
        "myElem": 2
    }
}

When deserializing such object, Json.net was previously throwing an ArgumentException. Now the deserialization succeed and it seems that it uses the value of the last duplicated key (hence "2" in above example).
From what I read, there is some debate around duplicates but the RFC only recommend to have unique keys.
I'd like to keep the previous behavior in order to validate the data received by my application. Is there a way to configure Json.net to do so? I tried to look into JsonSerializerSettings but did not find anything matching my need.
The code I use to deserialize JSON :
JsonSerializer.Create(new JsonSerializerSettings())
                          .Deserialize<JObject>(new JsonTextReader(new StringReader(rawJson));

or
JsonConvert.DeserializeObject<JObject>(rawJson);


text:
Q: How to make the bullets in my unordered list not underlined So I am just learning CSS in my Web Programming 1 class, and the exercise is teaching us about class selectors, so our teacher wants us to make a page which has an unordered listed with only some of the listed items to be underlined. However, when I do this, my bullets in the lists get underlined aswell, where as in the page he wants us to make, they are not.
I've included my code below
<!doctype html>

        <meta charset="utf-8">
        <title>Untitled Document</title>

 Solids

 Tetrahedron

 Pentahedron

 Cube

 Heptahedron

 Octahedron

 Dodecahedron

 Icosahedron

 What's special about the underlined items.

A: I agree with, Huangism's answer. Adding the span element inside the
 and making that underlined will solve you problem. This way you can colour and style the bullets without effecting the list itself.

A: You should give .underline class text-decoration css property:
li.underline{
    text-decoration:underline
}

JSFIDDLE

A: Your code is fine, it must be a browser glitch. Actually, to make a browser display underlined bullets is not that easy. It would have to be something like this:
/* this will display underlined bullets. It can also be done in the markup without the second rule and adding an • in between the tags */
 li.underline {
            text-decoration: underline;
            list-style: none;
        }

     li.underline:before {
            content: "\2022";
        }

The best solution was suggested by @Huangism in the comments. The markup would look like this:

 Tetrahedron

Still, that's a strange glitch. No browser I tested with your markup displays the bullets incorrectly.


text:
Q: Google play store - How to grant enterprise access I have an app on play store, a company has now approached me and have asked if they can bring the app to their managed play store area.
Would I need to give them the apk for this? If yes then how will I know how many users have downloaded it?
What is the best industry practice to do this? Any pointers would be much appreciated.


text:
Q: How do you validate a new user's account on PHP? I am using PHP for my project. How can I prompt a new user to enter their email address so I can send a verification link to their?

A: You can write a simple form html like this :
form.html :
  <form action="submit.php" method="post">
      <input type="email" name='email'>
      <input type="submit" name="submit" value="send">
  </form>

submit.php :
   <?php

       if(isset($_POST['submit']) && !empty($_POST['email'] )){
          $email = $_POST['email'];
          // you've got the email so far , you can do what ever you want with it
         // for example : you can send email or ...

         $to      = $email;
         $subject = 'the subject';
         $message = 'hello';
         $headers = 'From: webmaster@example.com' . "\r\n" .
             'Reply-To: webmaster@example.com' . "\r\n" .
             'X-Mailer: PHP/' . phpversion();

         mail($to, $subject, $message, $headers);

       }else{

           echo "You can go fuzz yourself :D";
     }

    ?>

This is not safe and nor a powerful way of sending email , I just wanted to give you the hint , so be sure to check user inputs and so on ...


text:
Q: Appending specific indices from zipped lists I have been succesfull in filtering a list by appending the value of the list index if it's first three characters are digits. This filters out certain values, although the original list is connected to three other lists that need to be filtered in the same pattern. Thus I've been trying to zip the lists and filter them from there. Although I'm a new coder so I've met a dead end ability-wise. There are 4 input lists and an output (where I'll return a list of lists). Here's my code:
list0=IN[0]
list1=IN[1]
list2=IN[2]
list3=IN[3]

f_list=[]

for x in list0:
    if x[0:3].isdigit():
        f_list.append(x)
    else:
        continue

OUT=f_list

How do I make the matching values in list1, list2 and list3 filter in the same pattern as list0 filters to f_list?
Thanks for your time.

A: You may do what you want like this using only standard Python means:
# initial sample data
IN = [['502', 'a503', '-5.1.0', 'qwe', '999', '1 1 1'],
      [1, 2, 3, 4, 5, 6],
      ['a', 'b', 'c', 'd', 'e', 'f'],
      [0, 0, 0, 0, 0, 0]]

# dictionary with the data we want to filter (single dictionary instead of 3 lists)
data_in = {idx: IN[idx] for idx in range(3)}
print(data_in)

# empty dictionary to store filtered data
data_out = {idx: list() for idx in data_in}

# processing
for pos, elem in enumerate(data_in[0]):
    # condition
    if elem[:3].isdigit():
        # if condition is true then we treat all the data in the dictionary
        for idx in data_in:
            data_out[idx].append(data_in[idx][pos])

print(data_out)

Output:
{0: ['502', 'a503', '-5.1.0', 'qwe', '999', '1 1 1'], 1: [1, 2, 3, 4, 5, 6], 2: ['a', 'b', 'c', 'd', 'e', 'f']}
{0: ['502', '999'], 1: [1, 5], 2: ['a', 'e']}

Problems like this can be solved with libraries like pandas much easier and more efficiently with literally couple lines of code.


text:
Q: How to access data stored in structure within array I have an array which holds a structures which represents form fields of a web page. My question is how can I easily access data in the array to get the value I am looking for. In this case I am trying to get the value for the field with the name "availableScreensCSV" for now I am looping thru the array and if the key = "name' and is "availableScreensCSV" then I get the data for the value. I hope there is a simpler way to do this. Below is what my array / structure looks like
array

1   struct
    NAME    templateId
    TYPE    hidden
    VALUE   [empty string]

2   struct
    NAME    useTestSystem
    TYPE    hidden
    VALUE   false

3   struct
    NAME    availableScreensCSV
    TYPE    hidden
    VALUE   ICASR,ICADM,ICTQ1,ICTQA,ICTQB,ICTQ6,ICFGB

4   struct
    NAME    ccna
    TYPE    hidden
    VALUE   IFX

5   struct
    NAME    pon
    TYPE    hidden
    VALUE   I11192014013

6   struct
    NAME    asr
    TYPE    hidden
    VALUE   1432310020

7   struct
    NAME    icsc
    TYPE    hidden
    VALUE   SW80

A: My gut reaction is, "how did your data get into that array?" If it's a form post, you should be able to simply get form fields by name: form.availableScreensCSV -- but that hinges on your form post.
Since you neglected to mention, I'm assuming that the array may not always be in the same order, in which case looping is your only reasonable option. There are functional approaches like arrayFind with an inline function but that is some syntactic sugar on top of a loop. If you're just looking for cleaner, more readable code, then arrayFind with an inline function may be the way to go.
If you're looking for the most performant option, then a simple loop that does a <cfbreak /> once it finds the desired element will be the best option.


text:
Q: R - meet the condition then continue loop, otherwise repeat I now have a vector x, and I want to create another vector y. Its role is to divide x into many groups by comparing the x value with a specific value(e.g 30).
here is the vector x:
x <- c(1,2,5,34,21,6,0,56,77,21,3,0)

If describe this problem with loops and conditional statements, I think that is:
when the conditions are satisfied, then continue the loop, otherwise repeat the it.
For example, in the vecor x, 1, 2, and 5 is less than 30, so "1" is repeated for three times in y; 34 is greater than 30, so the loop continue to the value of 2, and 21 is less than 30, so "2" is repeated for 1 time, and so on.
The final value of y should be like this:
y <- c(1,1,1,2,2,2,2,3,4,4,4,4)

Maybe my expression is not very clear, because I am a Non-Native English speaker, and I'm a little confused right now, I hope someone can help me.

A: We can use cumsum here and increment the count every time we find a value greater than 30.
cumsum(x > 30) + 1
#[1] 1 1 1 2 2 2 2 3 4 4 4 4


text:
Q: How can I specify a method as a parameter of my method? New to C#, how can I create a method that will accept a method as one of its parameters?
Sounds little weird but I hope that it will be supported in c#.
That what I tried:
public void CalculateRepairedCars(int total, /*here I want to pass a method..*/)
{
    ...
}

This is the method which I would like to pass:
public int Calculate{int totalCars, Condition condition}
{
...
}

A: "Putting a method inside a value" (which you can then do many things with, such as passing as an argument to another method) in C# is called creating a delegate to that method.
A delegate has a type that directly corresponds to the signature of the method it points to (i.e. the number and types of its arguments and the return value). C# offers ready-made types for delegates that do not return a value (Action and its siblings) and for those that do (Func and its siblings).
In your case, the signature of Calculate matches the type Func<int, Condition, int> so you would write
public void CalculateRepairedCars(int total, Func<int, Condition, int> calc)
{
    // when you want to invoke the delegate:
    int result = calc(someCondition, someInteger);
}

and use it like
CalculateRepairedCars(i, Calculate);

A: There are multiple ways. I've used an Action to do it before.
private void SomeMethod()
{
    CalculateRepairedCars(100, YetAnotherMethod);
}

public void CalculateRepairedCars(int total, Action action)
{
    action.Invoke();  // execute the method, in this case "YetAnotherMethod"
}

public void YetAnotherMethod()
{
    // do stuff
}

If the method being passed as a parameter has parameters itself, (such as YetAnotherMethod(int param1)), you'd pass it in using Action<T>:
CalculateRepairedCars(100, () => YetAnotherMethod(0));

In my case, I didn't have to return a value from the method passed as a parameter. If you have to return a value, use Func and its related overloads.

Just saw you updated your code with the method you're calling.
public int Calculate(int totalCars, Condition condition)
{
    ...
}

To return a value, you'd need Func:
public void CalculateRepairedCars(int total, Func<int, string, int> func)
{
    var result
        = func.Invoke(total, someCondition);  // where's "condition" coming from?

    // do something with result since you're not returning it from this method
}

Then call it similar to before:
CalculateRepairedCars(100, Calculate);

A: The c# method type is called delegate. You declare it, assign a method and then you can do many things with it including passing it as a parameter. Look it up! Note: delegates are sort of type safe in that the must share the signature with the methods they point to.


text:
Q: Converting mysql query to be used in vb.net I am newbie in mysql and vb.net and have this query:
select `db_employee`.`firstName` as `firstName`, `db_employee`.`lastName` as `lastName`,
       `tbl_employment`.`position` as `position`
  from (`db_employee` `db_employee`
  inner join `tbl_employment` `tbl_employment` on (`tbl_employment`.`ctrlID` = `db_employee`.`ctrlID`))
 where (`tbl_employment`.`companyName` like 'MES%')

And I want to convert it to be used here:
Dim MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = connStr
Dim SDA As New MySqlDataAdapter
Dim dbdataset As New DataTable
Dim bsource As New BindingSource
MySqlConn.Open()
Dim query As String
query = ?

A: you can use below code for displaying data... i hope this what you want.. :)
Dim cn As SqlConn= New SqlConn("Connecting String")
    Dim cmd As sqlCommand
     Dim dr As sqlDataReader
cn.open()
cmd = New sqlCommand("select * from table or your query, cn)
            dr = cmd.ExecuteReader()
            dr.Read()
            textbox1.Text = dr(1).ToString()
cn.close()

A: You can do something like this with the MySQL provider you're using.  This will create your connection, command and data reader and close and dispose of everything properly.  If you want a DataTable instance, you can load it from the DataReader.
    Using conn As New MySql.Data.MySqlClient.MySqlConnection("YourConnectionString")
        conn.Open()

        Using cmd As MySql.Data.MySqlClient.MySqlCommand = conn.CreateCommand
            cmd.CommandText = "select db_employee.firstName as firstName, " & _
                                        "db_employee.lastName as lastName, " & _
                                        "tbl_employment.position as position " & _
                                        "from db_employee db_employee " & _
                                        "inner join tbl_employment tbl_employment on tbl_employment.ctrlID = db_employee.ctrlID " & _
                                        "where tbl_employment.companyName like 'MES%' "

            ' Get a data reader that you can loop over or load a data table with
            Dim dr As MySql.Data.MySqlClient.MySqlDataReader = cmd.ExecuteReader

            ' How to read with a DataReader
            While dr.Read
                ' Do something with this
                Dim lastName As String = dr("lastName")

            End While

        End Using

        conn.Close()
    End Using


text:
Q: GitHub Actions mysql service not working (Access denied) I try to use GitHub actions to check the functionality of my application. I'm using the mysql service and want to set up a database with a SQL file named db_structure.sql. But as soon as I run the action, it just gives me a Access denied error message.
Here's my full workflow:
name: CI

on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]
  workflow_dispatch:

jobs:
  cypress_testing:
    runs-on: ubuntu-latest

    services:
      mysql:
          image: mysql:5.7
          env:
              MYSQL_DATABASE: database
              MYSQL_USER: foo
              MYSQL_PASSWORD: bar
              MYSQL_ROOT_PASSWORD: bar
          ports:
              - 3306
          options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=5

    steps:
      - uses: actions/checkout@v2

      - name: Install dependencies
        run: npm install --save-dev

      - name: Create DB structure
        run: |
          sudo /lib/systemd/systemd-sysv-install enable mysql
          sudo systemctl enable mysql.service
          sudo systemctl start mysql.service
          sudo systemctl status mysql.service
          sudo mysql -h 127.0.0.1 -ufoo -pbar database < db_structure.sql

      # I would then run my tests here

And here is the full error message:
ERROR 1045 (28000): Access denied for user 'foo'@'localhost' (using password: YES)

I already tried adding -h 127.0.0.1 to the mysql command. I also tried starting the service before running the mysql command.
Thanks for your help in advance.


text:
Q: Open the about:addons page with my plugin's options page on screen In Firefox, is there a way to open the add-on's own options page within about:addons through a button in the add-on? (Not just the options.html page by itself, but within the about:addons page, the same one that you can get to when pressing "more" beside the description of the add-on).
I got this:
function OpenOptionsMenu() {
  browser.tabs.create({
  url: "???"
});

But, I have no idea what to put as the URL.
I found this: browser.runtime.getURL('/options.html'), but that will only get the options page by itself.

A: There is a function specifically for this:
browser.runtime.openOptionsPage()

https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/openOptionsPage
However, opening the options page in a separate tab is a perfectly valid UI choice.

A: The command to do this is:
chrome.runtime.openOptionsPage();

or
browser.runtime.openOptionsPage();

This will open the options page displayed as it would normally be if the user clicked on the Options button from about:addons. If it is supposed to be displayed within about:addons (i.e. open_in_tab not specified in options_ui) then it will be displayed in about:addons.
If you did specify open_in_tab in the options_ui key within your manifest.json, then it will be opened in a separate tab. With open_in_tab specified, there no way to open it within about:addons. If open_in_tab is not specified you can open it in a tab, or window, should you choose to do so.


text:
Q: Pythonic way to round a float to specific min AND max number of decimal places I would like to implement a function round(num, min, max) that rounds a float to at least min decimal places and at most max. I want it to return a string. I have something that works, but it was surprisingly long. Can you write something more pythonic than me?
Usage
round(3.14159, 2, 4) --> '3.1416'
round(3.14159, 0, 2) --> '3.14'
round(3.14159, 0, 1) --> '3.1'
round(3.14159, 0, 0) --> '3'
round(3.14159, 4, 6) --> '3.141590'
round(3.14, 4, 6)    --> '3.1400'
round(3, 4, 6)       --> '3.0000'

I think you get the idea. Here's what I've got.
def normalize(amount, min=0, max=2):
    """
    Rounds to a variable number of decimal places - as few as necessary in the range [min,max]
    :param amount: A float, int, decimal.Decimal, or string.
    :param min: the minimum number of decimal places to keep
    :param max: the maximum number of decimal places to keep
    :return: string.
    """
    if not amount:
        return amount

    # To Decimal, round to highest desired precision
    d = round(Decimal(amount), max)
    s = str(d)

    # Truncate as many extra zeros as we are allowed to
    for i in range(max-min):
        if s[-1] == '0':
            s = s[:-1]

    # Lose a trailing decimal point.
    if s[-1] == '.':
        s = s[:-1]

    return s

A: You're confusing float rounding with print formatting.*
The float 3.14 is a different number than 3.1415. So rounding 3.1415 to 2 digits makes sense.
But the float 3.00 is the exact same number as 3.0. So rounding 3.0 to 2 digits isn't going to do anything; it's still going to be the same thing you started with.
Meanwhile, if you want to change the way numbers are printed out, you can do that using the format function, the str.format method, f-strings, % formatting, etc. For example:
>>> pi = 3.1415
>>> indianapi = round(pi, 0)
>>> indianapi
3.0
>>> f'{indianapi:.3f}'
'3.000'

See Format Specification Mini-Language for details on how to use f-strings (and str.format and format), and printf-Style String Formatting for details on how to use %.

* Either that, or you're expecting floats to keep track of their precision and preserve it through a chain of operations. If that's what you're after, floats can't do that, but decimal.Decimal can, so you may want to look at the decimal module. But I don't think that's what you want here.

A: Just some small improvements, but keeping the basic idea (convert value, strip zeroes, strip trailing decimal point).
First change is to avoid name clash with builtin functions min and max. I think that using functions designed for the particular purpose (str.format for value formatting, str.rstrip for stripping from right, str.endswith for testing the last character) makes it little bit more pythonic.
def round(amount, dmin, dmax):
    assert 0 <= dmin <= dmax
    astr = '{:.{prec}f}'.format(amount, prec=dmax)
    if dmax != dmin:
        astr = astr[:dmin-dmax] + astr[dmin-dmax:].rstrip('0')
        if astr.endswith('.'):
            astr = astr[:-1]
    return astr


text:
Q: How to get Junit class name in another class Below is a JUnit Runner from which I need to get class name RunTest in another class.
@RunWith(Cucumber.class)
@CucumberOptions(
        features = { "src/test/resources/features/Automated" },
        tags = { "@Create_Account_Without_Entering_Mandatory_Fields", "~@ToBeSkipped","~@P2" }
        , dryRun = false,

        monochrome = true,
        glue = "tv.nativ.mio.automation.stepdef", plugin = {"html:target/cucumber", "json:target/cucumber/cucumber1.json"})

public class RunTest  {
}

I have tried Thread.dumpStack() and Thread.currentThread().getStackTrace() but not getting class RunTest in the list

A: I wouldn't recommend that, but you can remember the test class in some static variable. Do in the test:
@BeforeClass
public static void beforeClass() {
    // holder is just a class with static variable, create it
    CurrentClassHolder.setClass(RunTest.class);
}

You can do such thing in every test class and then get it from there..


text:
Q: signed arithmetic on multiword numbers? Say I have a 4 bit ALU, I have a carry flag, overflow flag, and a sign flag(MSB). How would I go about subtracting for example, two signed 8 bit numbers? I take the lower nibble of both numbers and subtract them right, but I don't understand how to know if there needs to be a 5th bit, and carry that over to the LSB of the high nibble of the number, and if so, how to add it considering I am doing this in 2's complement so I already have Carryin being used.. Any help would be appreciated.

A: This has been asked and answered here many times.
You know the rule about twos complement yes?  Invert and add one.  Also from grade school
a + b = a + (-b).

We dont have subtract hardware we have add hardware.   What you do is a + (-b).   Also from grade school we learned about carrying, 9+3 = 2 carry the 1.  And from the second column on we have either two or three operands that are added together (a + (-b) + c, c being the carry in).  If you think about it we can have a carry in on every column, sometimes it is zero.  That is how the hardware works, each column is three in two out, carry in[n], a[n], b[n] the output is result[n] and carry out[n].  and as we know from grade school the carry out of this column is the carry in of the next column.   So for a normal add the carry in of the least significant bit is always a zero, but for subtract we want to invert and add one so what we do is invert b and change the carry in of that first bit to a 1 which is the same as
a + (~b) + 1 which equals a + (-b) which equals a - b.

As far as addition and subtract hardware is concerned there is no such thing as signed or unsigned add or subtract.  There does exist an unsigned overflow (carry out of the msbit) and a signed overflow (true if carry in and carry out of the msbit are not the same, false if they match).
This works for any number of bits, for example if you have 8 bit hardware but want to do math on 256 bit numbers, just do them 8 bits at a time and apply the carry out to the next 8 bits (add with carry or subtract with borrow instruction).  Visualize the single columns one at a time, 4 bits is just four of those columns, 8, 9 bits 37 bits, etc.  You can easily take any of those larger numbers draw a vertical line anywhere separating it into two operations all you have to do is what you do for single columns the carry out of the msbit of the thing on the right becomes the carry in of the lsbit of the thing on the left of the dividing line.  Apply this to 8 bit math with 4 bit hardware...
So a subtract is an add with a carry in of 1 and the second operand inverted.  Now some hardware inverts the carry out (unsigned overflow) on a subtract so that it becomes 1 for borrow and 0 for not borrow (unsigned borrow/overflow).  Some dont.  So you have to know how this works if you dont have a subtract with borrow instruction. If you have a subtract with borrow it doesnt matter if they invert carry out they will generically invert carry in (on a subtract).  If they dont then again they wont on a subtract with borrow.  but if you have to use an add with carry to simulate a subtract with borrow you need to possibly not only invert the second operand but invert the carry bit. If you dont have an add with carry then you have to simulate that as well by simply adding 1 or not.


text:
Q: Change background color of ListTile upon selection and custom height of tiles flutter I've made a GridView, but now I have some ListTiles in this GridView that I need to be selected Upon selection, I want the background color to change.
And I am also facing one more issue, I want to custom the heights of these ListTile, but I am not getting any success to do so. I am gonna attach the picture the output that I am getting and the output that I want.
What I am getting:

What I want:

Here is the code:
class _SelectLanguageNewState extends State<SelectLanguageNew> {

List<Results> listResponseData;
bool _color;

@override
void initState() {
// TODO: implement initState
super.initState();
getLang();
_color = false;

}

Future getLang() async {

await getLanguage().then((GetLanguageResponse getlanguage)
{
  if(getlanguage.isSuccess)
    {
      setState(() {
        listResponseData = getlanguage.responseData.listResults;
      });
    }

});
}

@override
Widget build(BuildContext context) {

var size = MediaQuery.of(context).size;

final double itemHeight = (size.height - kToolbarHeight - 24) / 2;
final double itemWidth = size.width / 2;

void _onTileClicked(int index){
  debugPrint("You tapped on item $index");
}

// Get grid tiles
List<Widget> _getTiles() {
  final List<Widget> tiles = <Widget>[];
  for (int i = 0; i < listResponseData.length; i++) {
    tiles.add(ListTileTheme(

      selectedColor: Colors.blue,
      child: new InkWell(
        child: new Card(
          elevation: 5.0,
          child: new Container(
            color: _color ? Colors.black : Colors.grey,
            alignment: Alignment.center,
            child: new Text(listResponseData[i].nativeText,
            style: TextStyle(color: Colors.white),),
          ),
        ),
        onTap: () {

          setState(() {
            _color = !_color;

          });

         /* showDialog(
            barrierDismissible: false,
            context: context,
            child: new CupertinoAlertDialog(

              content: new Container(
                  width: 40.0,
                  child: new CircularProgressIndicator()),
              actions: <Widget>[
                new FlatButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: new Text("OK"))
              ],
            ),
          );*/
        },
      ),
    ));
  }
  return tiles;
}

return Scaffold(
  bottomNavigationBar: BottomAppBar(
    child: Container(
      height: 50.0,
      child: InkWell(
        onTap: ()=> print('pressed'),
        child: Center(
          child: Text('Next', style: TextStyle(color: Colors.white,

          ),

          ),
        ),
      ),
    ),
    color: Colors.blue,
  ),

  body: new Container(
    child: listResponseData == null || listResponseData.isEmpty ? new Container(
      child: new Text('Loading data......'),
    ) : new GridView.count(

      shrinkWrap: true,
      scrollDirection: Axis.vertical,
      childAspectRatio:1.0,
      crossAxisCount: MediaQuery.of(context).size.width <= 400.0 ? 3 : MediaQuery.of(context).size.width >= 1000.0 ? 5 : 2,

      // Create a grid with 2 columns. If you change the scrollDirection to
      // horizontal, this would produce 2 rows.

      crossAxisSpacing: 5.0,
      // Generate 100 Widgets that display their index in the List

      children: _getTiles() ,

     ),
   ),

  );
  }
 }

A: Screenshot

Complete solution:
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(scaffoldBackgroundColor: Colors.black, brightness: Brightness.dark),
      home: Scaffold(
        appBar: AppBar(title: Text("Choose Language")),
        body: HomePage(),
      ),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _languageIndex = -1;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Stack(
        alignment: Alignment.bottomCenter,
        children: <Widget>[
          GridView.count(
            crossAxisCount: 2,
            crossAxisSpacing: 10,
            mainAxisSpacing: 10,
            childAspectRatio: 2.4,
            children: <Widget>[
              GestureDetector(
                child: _buildWidget("English", 0),
                onTap: () => setState(() => _languageIndex = 0),
              ),
              GestureDetector(
                child: _buildWidget("Española", 1),
                onTap: () => setState(() => _languageIndex = 1),
              ),
              GestureDetector(
                child: _buildWidget("Française", 2),
                onTap: () => setState(() => _languageIndex = 2),
              ),
              GestureDetector(
                child: _buildWidget("Gaeilge", 3),
                onTap: () => setState(() => _languageIndex = 3),
              ),
              GestureDetector(
                child: _buildWidget("العربية", 4),
                onTap: () => setState(() => _languageIndex = 4),
              ),
              GestureDetector(
                child: _buildWidget("جغتای", 5),
                onTap: () => setState(() => _languageIndex = 5),
              ),
              GestureDetector(
                child: _buildWidget("ગુજરાતી", 6),
                onTap: () => setState(() => _languageIndex = 6),
              ),
              GestureDetector(
                child: _buildWidget("हिन्दी", 7),
                onTap: () => setState(() => _languageIndex = 7),
              ),
              GestureDetector(
                child: _buildWidget("日本語", 8),
                onTap: () => setState(() => _languageIndex = 8),
              ),
              GestureDetector(
                child: _buildWidget("коми", 9),
                onTap: () => setState(() => _languageIndex = 9),
              ),
              GestureDetector(
                child: _buildWidget("ਲਹਿੰਦੀ", 10),
                onTap: () => setState(() => _languageIndex = 10),
              ),
              GestureDetector(
                child: _buildWidget("Schwyzerdütsch", 11),
                onTap: () => setState(() => _languageIndex = 11),
              ),
            ],
          ),
          SizedBox(
            width: double.maxFinite,
            height: 44,
            child: RaisedButton(
              child: Text("SUBMIT"),
              onPressed: () {
                print("languageIndex = ${_languageIndex}");
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildWidget(String language, int index) {
    bool isSelected = _languageIndex == index;
    return Container(
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6),
        border: Border.all(color: isSelected ? Colors.blue[300].withOpacity(0.8) : Colors.grey[700]),
        color: Colors.grey[900],
      ),
      child: Text(
        language,
        style: TextStyle(fontSize: 16, color: isSelected ? Colors.blue[400] : null),
      ),
    );
  }
}

You can watch which language user selected by using the _languageIndex.


text:
Q: Unable to create process because python.exe & pythonw.exe under Conda environment MISSING/GONE From [Anaconda installer archive], I install Anaconda3-4.2.0-Windows-x86_64.exe, I open a conda prompt. I create conda environment.
conda create -n keras_tensorflow_2 python=3.5

Activate it.
activate keras_tensorflow_2

Install Theano, Tensorflow & Keras.
conda install theano
pip install --ignore-installed --upgrade tensorflow
pip install keras

*Although here, theano is successfully installed but does not work. But that's a different matter.
Run python & test for tensorflow inside the conda prompt.
python
import tensorflow

No error. It works.
So now I want to open using Spyder.
If I directly open Spyder, and import tensorflow inside the IPython, error shows:

ImportError: No module named tensorflow

So what I did that work is

*

*Open Anaconda Navigator

*Anaconda Navigator>Environments. Click keras_tensorflow_2 environment. [Pic_1]

*Anaconda Navigator>Home. At dropdown menu for "Applications on", choose tensorflow_2. Install Spyder. [Pic_2]

Then, open Spyder from Start Menu. Windows Security Alert pop up. Click Allow access. [Pic_3] . Test tensorflow, still not working.
So have to go back to Conda Prompt. Type
activate tensorflow_2
spyder

Conda prompt will automatically close and Spyder will automatically open. Import Tensorflow. Finally WORKS!
Up until this point, the folder Anaconda3>envs>tensorflow_2 still has python.exe and pythonw.exe as show here [Pic_4].
HOWEVER, once I close/restart Spyder, the folder Anaconda3>envs>tensorflow_2automatically has MISSING python.exe and pythonw.exe. [Pic_5] I don't know why this would happen. So I can no longer use this environment. When I tried to 'Open with IPython' through anaconda navigator [Pic_1], error:

Unable to create process using
  'C:\Anaconda3\envs\keras_tensorflow_2\python.exe
  C:\Anaconda3\envs\keras_tensorflow_2\Scripts\ipython-script.py -i'

And every time I want to use Tensorflow, I have to recreate the environment. Any advice please? Thank you.
All pictures available here: https://drive.google.com/open?id=0B6eS8bjSwwBLSzFRTFVHdG9zTTA

A: I found a way around it. Python.exe and Pythonw.exe still missing. Maybe it actually doesn't matter them being missing. I don't know.
Anyway, when inside conda prompt, if I navigate to my specific environment's Script, activate the environment and then run Spyder from there, it will work.
cd C:\Anaconda3\envs\keras_tensorflow_2\Scripts
activate keras_tensorflow_2
spyder

Reference: How to ensure that Spyder runs within a conda environment?


text:
Q: Критика чистого js Друзья, покритикуйте пожалуйста код, он писался для тренировки. Условия следующие:

*

*Максимальная структурированость кода с расчётом на то, что проект будет поддерживаться много лет и очень часто дорабатываться разными участниками.

*Проект высоконагруженный и поэтому использование библиотек типа jquery, mootools и т.д. не допускается.

Буду благодарен за советы, которые помогут сделать код и стиль понятнее и рациональнее
Даже если не можете предложить что конкретно исправить, но видите слабое место, то всё равно скажите — я сам подумаю что можно сделать.
// ------------ PLUGIN kalininCarousel INITIALIZATION ------------
var kalininCarousel = new KalininCarousel({
    carouselWrap: document.getElementById('carousel_wrap'),
    offsetElements: 0,
    autoScroll: false,
    effectSpeed: 300,
    autoScrollSpeed: 1000,
    arrowsType: 'auto', //'visible', 'hidden', 'auto'
    rotateBy: 1
});
/*
    INFO:
    project: kalininCarousel
    browsers: opera/chrome/FF/ie9/safari
    coding: Sergey Kalinin 07/2013 (prozaik81-2@yandex.ru)
    desc: графический компонент для преобразования списка в карусель с возможностью прокрутки при помощи стрелок-указателей. слайды карусели должны быть одинаковой длины
    version 1.1
*/

// ------------ PLUGIN kalininCarousel IMPLEMENTATION ------------
function KalininCarousel(options) {
    // --------- properties ---------
    var carouselWrap = options.carouselWrap,
        carousel = document.getElementById('carousel'),
        wrapperElements = carousel.getElementsByTagName('ul')[0],
        carouselElements = wrapperElements.getElementsByTagName('li'),
        carouselElementsWidth;
    if (window.getComputedStyle) {
        carouselElementsWidth = carouselElements[0].offsetWidth
                                + parseInt(getComputedStyle(carouselElements[0], '').marginLeft, 10)
                                + parseInt(getComputedStyle(carouselElements[0], '').marginRight, 10);
    }
    else {
        carouselElementsWidth = carouselElements[0].offsetWidth
                                + parseInt(carouselElements[0].currentStyle.marginLeft, 10)
                                + parseInt(carouselElements[0].currentStyle.marginRight, 10);
    }

    var carouselLength = carouselElements.length,
        running = false,
        autoScroll = 0,
        prev,
        next;

    init();

    // --------- methods ---------
    function init() {
        wrapperElements.style.width = carouselElementsWidth * carouselLength * 2 + 'px';

        prev = prepend(carouselWrap, 'div');
        prev.id = 'prev';
        prev.className = 'prev';

        next = prepend(carouselWrap, 'div');
        next.id = 'next';
        next.className = 'next';

        if ((options.arrowsType == 'auto') || (options.arrowsType == 'hidden')) {
            toggleControls('none', 'none');
        }

        setIntervalAutoScroll();
    }

    function shift(direction) {
        var offset,
            cloneSlides,
            lastSlide,
            i;

        if (!running) {
            running = true;

            if (options.autoScroll) {
                window.clearInterval(autoScroll);
            }

            if (direction == -1) {
                offset = (carouselElementsWidth * options.rotateBy * direction);

                for (i = 0; i < options.rotateBy; i++) {
                    cloneSlides = carouselElements[i].cloneNode(true);

                    wrapperElements.appendChild(cloneSlides);
                }

                shiftAction();
            }
            else {
                offset = 0;

                for (i = (carouselLength - 1) ; i > (carouselLength - options.rotateBy - 1) ; i--) {
                    cloneSlides = carouselElements[carouselLength - 1].cloneNode(true);

                    wrapperElements.insertBefore(cloneSlides, wrapperElements.firstChild);
                }

                wrapperElements.style.left = (-1 * options.rotateBy * carouselElementsWidth) + 'px';

                shiftAction();
            }
        }

        function shiftAction() {
            var interval,
                offset;

            if (direction == -1) {
                offset = 0;

                function animateLeft() {
                    offset -= 13;

                    wrapperElements.style.left = offset + 'px';

                    if (offset <= (-1 * options.rotateBy * carouselElementsWidth)) {
                        clearInterval(interval);

                        for (i = 0; i < options.rotateBy; i++) {
                            wrapperElements.removeChild(document.getElementsByTagName('li')[0]);
                        }

                        wrapperElements.style.left = 0;

                        running = false;
                    }
                }

                setIntervalCustom(animateLeft);
            }
            else {
                offset = parseInt(wrapperElements.style.left, 10);

                function animateRight() {
                    offset += 13;

                    wrapperElements.style.left = offset + 'px';

                    if (offset >= 0) {
                        clearInterval(interval);

                        for (i = options.rotateBy; i > 0; i--) {
                            wrapperElements.removeChild(document.getElementsByTagName('li')[carouselLength + i - 1]);
                        }

                        wrapperElements.style.left = 0;

                        running = false;
                    }
                }

                setIntervalCustom(animateRight);

            }

            function setIntervalCustom(animate) {
                return interval = setInterval(animate, 25);
            }
        }
    }

    function toggleControls(prevState, nextState) {
        prev.style.display = prevState;

        next.style.display = nextState;
    }

    function prepend(id, tag) {
        var first = id.firstChild,
            newNode = document.createElement(tag);

        id.insertBefore(newNode, first);

        return newNode;
    }

    function setIntervalAutoScroll() {
        if (options.autoScroll) {
            autoScroll = window.setInterval(function () {
                shift(-1);
            }, options.autoScrollSpeed);
        }
    }

    function addEvent(elem, type, handler) {
        if (elem.addEventListener) {
            elem.addEventListener(type, handler, false);
        }
        else {
            elem.attachEvent('on' + type, handler);
        }
    }

    // --------- handlers ---------
    function onClickControls(direction) {
        shift(direction);
    }

    function onHoverWrap() {
        if (options.arrowsType == 'auto') {
            toggleControls('block', 'block');
        }
    }

    function onLeaveWrap() {
        if (options.arrowsType == 'auto') {
            toggleControls('none', 'none');
        }
    }

    // --------- events ---------
    addEvent(prev, 'click', function (e) {
        onClickControls(-1);
    }, false);

    addEvent(next, 'click', function (e) {
        onClickControls(1);
    }, false);

    addEvent(carouselWrap, 'mouseover', function (e) {
        onHoverWrap();
    }, false);

    addEvent(carouselWrap, 'mouseleave', function (e) {
        onLeaveWrap();
    }, false);
}

A: Мельком посмотрел код, в глаза бросились несколько моментов:
Настройки карусели

Не увидел у Вас стандартных настроек для быстрого запуска карусели например с указанием одного лишь id элемента на странице. Думаю имеет смысл их добавить.

Создание карусели. привязка к DOM элементам
У Вас идет привязка карусели к конкретным элементам на странице, в частности элементу с id="carousel". Также Вы всегда исходите из того, что карусель будет создана на основе ul. Как на счет нескольких каруселей на странице? Рекомендую дать возможность задавать через настройки какой элемент является каруселью, какие теги являются элементами итд.

Структура кода
Мне кажется имеет смысл вынести в отдельные методы получение ширины элемента (строки 19-28) и установку css свойств (аналог функции css в jquery). Это сделает код более читабельным.
Определите значения для таких вещей как тип отображения стрелок и направление ротации, в отдельные константы и используйте их в коде, а не сами значения напрямую. (DIRECTION_LEFT/RIGHT, ARROW_TYPE_HIDDEN/VISIBLE/AUTO)


text:
Q: Laravel overrides named route and takes wrong one I have this defined in my routes.php file
Route::post('gestionAdministrador', array('as' => 'Loguearse', 'uses' => 'AdministradorController@Login'));

Route::post('gestionAdministrador', array('as' => 'RegistrarAdministrador', 'uses' => 'AdministradorController@RegistrarAdministrador'));

And in my login.blade.php file, the form starts as this
{{ Form::open(array('route'=>'Loguearse'))}}

I dont know why when i submit the form takes the second route instead the first one, even though I am pointing to the first one.
There must be a way to go to the same url from two different forms, that is what I want.

A: If you have two routes with the exact same URI and same method:
Route::post('gestionAdministrador', array('as' => 'Loguearse', 'uses' => 'AdministradorController@Login'));

Route::post('gestionAdministrador', array('as' => 'RegistrarAdministrador', 'uses' => 'AdministradorController@RegistrarAdministrador'));

How can Laravel know the difference between them when something hit /gestionAdministrador?
It will always assume the first one.
The name you set 'as' => 'RegistrarAdministrador' will be used to create URLs based on that route name, only, when something (browser, curl...) hit the URL the only ways to differentiate them is by
1) URL
2) URL parameters (which is basically number 1 plus parameters)
3) Method (GET, POST)
So you could change them to something like:
Route::post('gestionAdministrador/loguearse', array('as' => 'Loguearse', 'uses' => 'AdministradorController@Login'));

Route::post('gestionAdministrador/registrar', array('as' => 'RegistrarAdministrador', 'uses' => 'AdministradorController@RegistrarAdministrador'));

EDIT 2
What you really need to understand is that the name you give to a route ('as' => 'name') will not be part of your url, so this is not something that Laravel can use to differentiate your two URls, this is for internal use only, to identify your routes during the creation of URLs. So, those instructions:
$loguearse = URL::route('Loguearse');
$registrar = URL::route('RegistrarAdministrador');

Would generate exactly the same URL:
http://yourserver.dev/gestionAdministrador

EDIT 1 - TO ANSWER A COMMENT
Redirecting in Laravel is easy, in your controller, after processing your form, in any of your methods you can just:
return Redirect::to('/');

or
return Redirect::route('home');

Having a route like this one:
Route::get('/', array('as' => 'home', 'uses' => 'HomeController@index'));

So, your controller would look like this:
class AdministradorController extends Controller {

    public function RegistrarAdministrador()
    {
        ...

        return Redirect::route('home');
    }

    public function Login()
    {
        ...

        return Redirect::route('home');
    }
}

A: Actually you have only one route in your route collection, because:
You have following routes declared:
Route::post('gestionAdministrador', array('as' => 'Loguearse', 'uses' => 'AdministradorController@Login'));

Route::post('gestionAdministrador', array('as' => 'RegistrarAdministrador', 'uses' => 'AdministradorController@RegistrarAdministrador'));

Both of these used post method and this is post method:
public function post($uri, $action)
{
    return $this->addRoute('POST', $uri, $action);
}

It calls addRoute and here it is:
protected function addRoute($methods, $uri, $action)
{
    return $this->routes->add($this->createRoute($methods, $uri, $action));
}

Here $this->routes->add means Illuminate\Routing\RouteCollection::add() and the add() method calls addToCollections() and it is as follows:
protected function addToCollections($route)
{
    foreach ($route->methods() as $method)
    {
        $this->routes[$method][$route->domain().$route->getUri()] = $route;
    }

    $this->allRoutes[$method.$route->domain().$route->getUri()] = $route;
}

The $routes is an array (protected $routes = array();) and it's obvious that routes are grouped by methods (GET/POST etc) and in each method only one unique URL could be available because it's something like this:
$routes['post']['someUrl'] = 'a route';
$routes['post']['someUrl'] = 'a route';

So, in your case, the last one is replacing the first one and in this case you may use different methods to declare two routes using same URL so it would be in different array, something like this:
$routes['post']['someUrl'] = 'a route';
$routes['put']['someUrl'] = 'a route'; // Route::put(...)

There must be a way to go to the same url from two different forms

Yes, there is a way and it's simply that you have to use the same route as the action of your form and therefore, you don't need to declare it twice.

A: What you want to do is a bad idea, you shouldn't be logging in and registering from the same route. With that said what you are saying isn't really possible. Routing in Laravel is first come first served. Basically it checks the route until the URI matches one and then calls that method on the controller or executes the callback. Your routes have to be the other way in your routes file. This will be fixed by changing the url.


text:
Q: AJAX success not render properly since second request I  use ajax to render output to below HTML element.

The result is :

Everything works fine when rendering result for the 1st input request.
When I update my input, the console changes and  prints desired data but the webpage including the text does not change.
I get Cannot read property 'setAttribute' of null at canvas_and_ploton the 2nd+ time refresh below, If I remove setAttribute, I get Cannot read property 'getAttribute' of null at canvas_and_plot.
$(document).on('submit','#cat_select',function(e){
    e.preventDefault();
    $.ajax({
        type:'POST',
        url:'/cat_select',
        data:{
            l2:$('#l2').val(),
            l3:$('#l3').val(),
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
        },
        success: function server_response(response) {
                const r = JSON.parse(response);
                console.log(r); //updated
                var cat_result = r.cat_result;
                console.log(cat_result[0]) //updated
                var text=$('');
                $.each(cat_result, function(idx, value) {
                text.append('<id="result'+idx+'">' + cat_result[idx][0]+ '
'); //even the text output are not updated
                text.append('<canvas id="canv_'+idx+'" width="200" height="200"></canvas>
');
               });
               $('#result').replaceWith(text);
               $.each(cat_result, function(idx, value) {
                canvas_and_plot(idx,cat_result[idx][9],cat_result[idx][10],cat_result[idx][11])});

}
function canvas_and_plot(idx,a,b,c) {
var canv = document.getElementById('canv_'+idx);
canv.setAttribute('id', 'canv_'+idx);
var C = document.getElementById(canv.getAttribute('id'));
//plot...
}

I tried adding cache: false and adding random number to the url but neither of them works.
Why only error after the first request? How can I fix this? Thanks

A: The reason for it not changing is that you are replacing your block #result with received data.
$('#result').replaceWith(text);
After which you'll a dom tree that looks something like this:

        The result is :

            <id="result123">...

            <canvas id="canv123" width="200" height="200"></canvas>

            <id="result321">...

            <canvas id="canv321" width="200" height="200"></canvas>

So the second time you click there is no element with #result id.
I suggest (as a rough and quick solution):
On every request remove all children of your #result element and fill it again with new data. So add this line before making the request - $('#result').empty(); and replace $('#result').replaceWith(text); with $('#result').append(text);
The main idea is to keep the place you put and add your server data. Hope this helps!


text:
Q: Replace  with  using jQuery I'm doing a lazy-ass table transpose here.
I have a table like this:

     Unique
     x1
     y2

     a1
     b2
     b3

which I need to look like this:

a1	<.tr>

b2

b3

It only has two rows, one of which is header.
So I hide the header like this:
        $("table:contains('Unique')").find("th").addClass("hidden");

Which works fine. Now I need to add a
 to each , and here where I have trouble. I use this:
       $('div.content').html($('div.content').html().replace(//g,'
'));

which works, but I want to narrow it to the table containing "Unique", without using global.
This
       $('div.content').html($('div.content').html().replace(/	/g,'
'));

doesn't work at all. I tried playing with replaceWith and replaceAll, but failed to do the trick.
Questions:
1) The best way to add the formatting to transpose the remaining row into a column?
2) How can I specify " and / as parameters?
3) What's the difference between 'and "?
Thank you for your time.

A: You can use wrap in jQuery to do that:
$("td[nowrap='true']").wrap("tr");

Or for items only with your Unique contains selector:
$("table:contains('Unique') td[nowrap='true']").wrap("tr");


text:
Q: change theme color angular material 2 I'm using Angular 2. I want to use different themes color from Angular Material.
In particular, I want to use a different theme for each slide I have.
But where can I change them?

A: Just write styleUrl with css/scss file path  (Do this for all component you have in your project)  like this :-
   import { Component, OnInit } from '@angular/core';
    import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
    import { AuthenticationService } from '../services/authentication.service';
    import { Router } from "@angular/router";
    import { User } from '../Models/User.interface';

    @Component({
        templateUrl: '/Html/Account/Login.html',
        styleUrls: ['../Content/AppStyles/login.css']
    })

    export class LoginComponent  {

    }


text:
Q: Where can I find debug symbols for KDE Discover I am trying to provide a backtrace for repeated crashes of KDE Discover, but cannot find (much less install) the needed debug files.
I have attempted to find debugging symbols for Discover by adding the following repositories to my Software Sources:
deb http://ddebs.ubuntu.com jammy main restricted universe multiverse
deb http://ddebs.ubuntu.com jammy-updates main restricted universe multiverse
deb http://ddebs.ubuntu.com jammy-security main restricted universe multiverse
deb http://ddebs.ubuntu.com jammy-proposed main restricted universe multiverse

as recommended in this thread:

How to install debug symbols for installed packages?

However, I was then prompted to refresh the cache, which produced the following error message:
Could not refresh cache
pk-client-error-quark: E: The repository 'http://ddebs.ubuntu.com jammy-security Release' does not have a Release file.
W: Updating from such a repository can't be done securely, and is therefore disabled by default.
W: See apt-secure(8) manpage for repository creation and user configuration details.
W: GPG error: http://ddebs.ubuntu.com jammy Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY C8CAB6595FDFF622
E: The repository 'http://ddebs.ubuntu.com jammy Release' is not signed.
W: Updating from such a repository can't be done securely, and is therefore disabled by default.
W: See apt-secure(8) manpage for repository creation and user configuration details.
W: GPG error: http://ddebs.ubuntu.com jammy-updates Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY C8CAB6595FDFF622
E: The repository 'http://ddebs.ubuntu.com jammy-updates Release' is not signed.
W: Updating from such a repository can't be done securely, and is therefore disabled by default.
W: See apt-secure(8) manpage for repository creation and user configuration details.
W: GPG error: http://ddebs.ubuntu.com jammy-proposed Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY C8CAB6595FDFF622
E: The repository 'http://ddebs.ubuntu.com jammy-proposed Release' is not signed.
 (319)

I have performed the recommended "sudo apt install ubuntu-dbgsym-keyring", but I am still unable to find or install Discover debug symbols to enable a backtrace of the problem.

A: First, add the missing GPG key:
sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com C8CAB6595FDFF622
sudo apt update
Try installing the symbols again.

A: I am posting this as an answer, even though it isn't one, because it is too long for a comment.
@George
The first command above yielded:
Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)).
Executing: /tmp/apt-key-gpghome.qiNcMjEc9W/gpg.1.sh --recv-keys --keyserver keyserver.ubuntu.com C8CAB6595FDFF622
gpg: key C8CAB6595FDFF622: "Ubuntu Debug Symbol Archive Automatic Signing Key (2016) <ubuntu-archive@lists.ubuntu.com>" 2 new signatures

Executing the 2nd command apparently updated all of the newly added repositories but one:
Err:13 http://ddebs.ubuntu.com jammy-security Release
  404  Not Found [IP: 185.125.190.17 80]
Get:14 http://ddebs.ubuntu.com jammy-proposed Release [40.5 kB]
Reading package lists... Done
E: The repository 'http://ddebs.ubuntu.com jammy-security Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.

However, I am still unable to find any "dbgsym" packages.


text:
Q: npm fails on windows I've installed the latest node.js msi on windows vista. I try to use npm but always get the error "failed to fetch from registry" in \lib\utils\npm-registry-client\get.js:139:12 with any package. I also used an http registry to disqualify an ssl issue with no avail. Also when I set http-proxy I see that nothing is actually sent.
Any idea?

A: I've upgraded to a newer version (1.1.6) and it works great now!


text:
Q: Alfresco Rest api get document shared link I need to share and unshare the content in alfresco using Rest API,
I read the sharedLinks documentation but I don't know how to retrieve the document url I want to share.
This endpoint return an object with this properties :
{
  "entry": {
    "id": "string",
    "expiresAt": "2022-03-23T18:16:00.603Z",
    "nodeId": "string",
    "name": "string",
    "title": "string",
    "description": "string",
    "modifiedAt": "2022-03-23T18:16:00.603Z",
    "modifiedByUser": {
      "displayName": "string",
      "id": "string"
    },
    "sharedByUser": {
      "displayName": "string",
      "id": "string"
    },
    "content": {
      "mimeType": "string",
      "mimeTypeName": "string",
      "sizeInBytes": 0,
      "encoding": "string"
    },
    "allowableOperations": [
      "string"
    ],
    "allowableOperationsOnTarget": [
      "string"
    ],
    "isFavorite": true,
    "properties": {},
    "aspectNames": [
      "string"
    ],
    "path": {
      "elements": [
        {
          "id": "string",
          "name": "string",
          "nodeType": "string",
          "aspectNames": [
            "string"
          ]
        }
      ],
      "name": "string",
      "isComplete": true
    }
  }
}

How can i retrieve the path from the response?
Is there another way to get the effective complete shared link for a document ?

A: The response returns you an ID of the share link.
Example:  "id": "riqJ3xV3M4RNxJm6Haa7-w"
Use this ID to access the share link :
https://your.alfresco.domaine/share/s/riqJ3xV3M4RNxJm6Haa7-w
You can also use this web service : emailSharedLink to send an email with the link to the shared document.


text:
Q: Google Cloud Platform permissions using filezilla I'm having a problem when trying to change the permissions of a particular wordpress folder
/var/www/html/wp-content
When trying to chmod, i can only change the rights of certain folders, and i keep having an error message saying :

I've tried many things like : chmod -R [permissionsettings] [dirname]
Followed many tutorials also, but any of them helps me understanding why i don't have the permissions to some of the folders.. is this some issue related with the ssh key i'm using ?
I used puttygen to create a SSH key and added it to the vm instance
Basically what i wanted to do is, simply change the /wp-content folder permissions to 777 or 775 to be able to import files into it

A: You are logged in with your Google SSH username. The Apache/WordPress files are owned by another user, typically www-data (OS specific).
The simplest solution is the following but there are better ways.
sudo chmod -R [permissionsettings] [dirname]

Note: I do not recommend changing the directory/file permissions unless you understand the impact. For Apache/WordPress files, you must pay attention to what the permission do and what they protect your from such as hackers.
There are many ways to manage this:

*

*add the sudo command in front of your commands:
sudo chmod -R [permissionsettings] [dirname]

*Add your username to the group that owns the files:
usermod -a -G www-data your-username
Note: you must logout and relogin to effect group membership changes.
I recommend this method as the SSH file transfer tools will now work.

*Switch to the www-data user
su www-data /bin/bash
Note: This method might require enabling and setting a password for the www-data user which is not recommended.

*Do everything as the root user:
sudo bash
Note: be careful as you are now acting as the system's super user.
The key is to understand Linux users, permissions, user and group ownership, and the commands to switch between them.


text:
Q: How to achieve a page turning in a facebook canvas app using either javascript or vb.codebehind? I found multiple suggestions on how to turn pages on the internet, unfortunately I was unable to implement one of them so far to achieve a page turning from my default.aspx page to a secondpage.aspx page. I have tried the following:
calling the following vb.codebehind methods using the onclick.event of an asp:LinkButton
    Protected Sub OpenSecondPage()
      Server.Transfer("secondpage.aspx")
    End Sub

    Protected Sub OpenSecondPage()
      Response.Redirect("secondpage.aspx")
    End Sub

In both cases I get an error message: "this content cannot be displayed in a frame"
The same error occurs using these javascript functions:
    function GetFacebookId() {
          FB.api('/me', function (response) {
              document.getElementById("fbId").value = response.id;
              document.getElementById("fbName").value = response.name;
              window.location.replace="http://apps.facebook.com/myapp/secondpage.aspx";
          })
      }

     function GetFacebookId() {
          FB.api('/me', function (response) {
              document.getElementById("fbId").value = response.id;
              document.getElementById("fbName").value = response.name;
              window.location.href="http://apps.facebook.com/myapp/secondpage.aspx";
          })
      }

I also tried simulating a buttonclick.event with javascript which called the vb.codebehind sub. This seemed to work from my pc, but apparently this is blocked by common security settings on browsers and also generally frowned upon.
I just started my second year of job training and I am out of ideas at this point. Any help would be appreciated. Thank you.
This is the code of my secondpage.aspx site:
     <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Woerterbuch.aspx.vb" Inherits="Facebook2SeitenLoesung.secondpage" %>
     <%@ Register assembly="DevExpress.Web.v13.1, Version=13.1.7.0, Culture=neutral, PublicKeyToken=somenumber" namespace="DevExpress.Web.ASPxGridView" tagprefix="dx" %>
     <%@ Register assembly="DevExpress.Web.v13.1, Version=13.1.7.0, Culture=neutral, PublicKeyToken=somenumber" namespace="DevExpress.Web.ASPxEditors" tagprefix="dx" %>

          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0   Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

          <html xmlns="http://www.w3.org/1999/xhtml">
          <head runat="server">
          <title></title>
          </head>


text:
Q: Get content from  tags I'm trying to collect the contents from all the strong tag in the div id='content' and fill [ul id='loop'] with them
Before:

     this is a long content

After:

    this is a long content

is

long

A: you can iterate through all strong elements and add its text to ul, see below code

$(function(){
   $('#content strong').each(function(){ // get all strong from content
     $('#loop').append('
' + $(this).text() + '
'); // create li with text
   });

});

this is a long content

A: You could map the strong elements to li elements and then appendTo the ul element.

$('#content strong').map(function () {
    return $('
').text($(this).text()).get();
}).appendTo('#loop');

this is a long content

Make sure to put the code near the end of the body tag if it has to execute immediately or else wrap it in $(function () { .... })

A: You don't need jquery to do this - just straight js. Using querySelectorAll to get the elements. Then iterate over that list to create the li's for the #loop list.

var strongElements = document.querySelectorAll('#content strong');

var loopStr = '';

strongElements.forEach(function(element) {
  loopStr += '
' + element.innerText + '
';
})

document.querySelector('#loop').innerHTML = loopStr

this is a long content


text:
Q: S3 to store static contents only, or together host the presentation tier of the 3-tiers architecture? As we normally know the 3-tiers architecture: Presentation layer(Web Server), Logic tier(App Server), and Data layer(Database).
And we know the S3 in AWS is not only providing the capability to store the static contents, but also can act the role of presentation layer(Web Server).
So there are two options in my mind that:

*

*S3 as content holder, EC2 act as web server: put all static contents(like images for this case) in S3, build web server by EC2 instance, upload web pages(the link of the images points to S3, the dynamic portion points to the app server by reverse proxy)

*S3 as both content holder and web server, but need to work with App server like presentation layer web server do
My questions are:

*

*Is it reasonable for the above option 2? (The case is not a static web hosting)

*If reasonable, what's the difference between option 1 and 2?

*If not reasonable, why S3 is able to host static web site, but can't act as the presentation layer(web server) of a multi-tier web site(static+dynamic)?


text:
Q: Which is better, have a primary key composed of an integer and a foreign key or have a primary key autoincrement and a foreign key? I have a problem, the database admin have the follow structure:

As you can see the primary key of the table TCModulo is a composed key of the ID_modulo and ID_sistema which is a foreign key of the table TCSistemas.
I think that is better that the field ID_modulo from the table TCModulo must be the primary key with an auto_increment constrain, and the field ID_sistema must be only a foreign key.
Wich one is better?

A: Whether the PK of TCmodulo is (ID_modulo) or (ID_modulo,ID_sistema) depends on what goes in the table. We cannot answer your question unless you tell us. Presumably an ID_modulo value in a row is how you refer to some modulo. You have to tell us how to do that. But after that (for every column) (and given what situations can arise) there is no choice left about which sets of columns are candidates for primary key.
A set of columns whose subrow values are unique in a table is called a superkey. Any subrow containing a unique subrow is unique. So any set of columns containing a superkey is a superkey. A subrow that contains no (smaller) unique subrow is called a candidate key. So a superkey that contains no (smaller) superkey is a candidate key. One of the candidate keys of a table is chosen as primary key.
If ID_modulo uniquely determined a module over the whole application, then (ID_modulo) would be unique with no smaller unique subrow inside so it would be a candidate key. It would be the only one so it would be the primary key.
If ID_modulo uniquely determined a module only per sistema, then (ID_modulo,ID_sistema) would be unique with no smaller unique subrow (assuming there can more than one sistemo) so it would be a candidate key. It would be the only one so it would be the primary key.
So what candidate keys are available to be chosen as primary key is up to how your application refers to modulos. After that there is no choice about candidate keys. In each of these two cases there's only one candidate key so there's no choice about primary key either.
As to whether you should have a unique id overall or only within sistema or both or anything else, that depends on other ergonomic issues. Eg you are uniquely kentverger in stackoverflow (now; user names aren't necessarily unique), but perhaps uniquely Kent at home. Eg you probably prefer to call today something like the 4th of July, rather than day 185. But note that any candidate key serves as a unique identifier. So if ID_modulo is unique only within sistema, still (ID_modula,ID_sistema) is unique overall.
Note that this has nothing to do with modulos being many-to-one with sistemas per se. It has to do with columns forming unique subrows.

A: I always prefer to use an identity (auto-increment) for the primary key, as it keeps the pages clustered better and avoids fragmentation on the disk.  You need a foreign key ID_sistema anyway, so add that too.


text:
Q: Logstash can't communicate with elasticsearch through readonly rest elasticsearch plugin. I am trying to connect logstash with elasticsearch through authentication but this configuration gives me the following error :    [401] Forbidden by ReadonlyREST ES plugin {:class=>"Elasticsearch::Transport::Transport::Errors::Unauthorized", :level=>:error}
Configuration files are given below:
[Elasticsearch conf file]
http.cors.enabled: true
http.cors.allow-origin: /https?:\/\/localhost(:[0-9]+)?/

readonlyrest:
    enable: true
    response_if_req_forbidden: Forbidden by ReadonlyREST ES plugin
    access_control_rules:

    - name: "Logstash can write and create its own indices"
      auth_key: logstash:logstash
      type: allow
      actions: ["indices:data/read/*","indices:data/write/*","indices:admin/template/*","indices:admin/create"]
      indices: ["logstash-*", "<no_index>"]

    - name: Kibana Server (we trust this server side component, full access granted via HTTP authentication)
      auth_key: admin:pass3
      type: allow

    - name: Developer (reads only logstash indices, but can create new charts/dashboards)
      auth_key: dev:dev
      type: allow
      kibana_access: ro+
      indices: ["<no-index>", ".kibana*", "logstash*", "default"]

[logstash conf file]
input {
    file {
    path =>"/var/log/site.log"
    start_position => beginning
     }

}
filter {
    grok {
        match => { "message" => "%{COMBINEDAPACHELOG}"}
    }
    geoip {
        source => "clientip"
    }
}

output {
    elasticsearch {
    user => "logstash"
    password => "logstash"
    }
}

A: Mention output in logstash config file like below :-
output {
    elasticsearch {
        hosts => ["localhost:9200"]
        user => ["logstash"]
        password => ["logstash"]
    }


text:
Q: Azure DNS: NXDOMAIN for existing record I have created a cname record for my domain(login.auditman.sam-solutions.in) using Azure DNS. Cname record points to the azure front door.
When I'm doing DNS Lookup for the record, I can successfully get the result, but when I'm trying to open the domain on a web browser, I'm getting NXDOMAIN error.
Can anyone please help me to understand what can be the possible issue regarding this?


text:
Q: True keyboard mimic in python I need to be able to mimic the keyboard function "ctrl+c" to copy highlighted texts.  But that's not it... I have tried ctypes, pywin32api, pywin32, pyautogui,
pywinauto, ... and just about every other module out there.  I know how to use them all.  I have also made other successful auto gui programs.
The problem is that I'm trying to automate a program on a windows computer that is not a native windows program.  When I physically press "ctrl+c" in the program it works and copies the data.  But when I use any of the modules to simulate a hotkey function they simply fail and don't copy to clipboard.  So I need to fully, completely, exactly, and in every way MIMIC keystrokes in windows.  Is there a module out there that can do this?  Any help is greatly appreciated.


text:
Q: How to record pid of job(s) launched in a bash script I have a bash script that sends many jobs to a cluster, it looks something like this:
for i in `seq 1 ${MIN}`

do
  cd longjob_${i}/
  make
  nohup ./prog.x &
done

prog.x is a fortran executable. I would like to record the pid of each job, so I could
kill at will jobs when needed. Is there a way of doing this, for instance, recording the pid
number in the nohup.out file?

A: The variable $! contains the PID of the last background job that was started:
for i in `seq 1 ${MIN}`
do
  cd longjob_${i}/
  make
  nohup ./prog.x &
  echo $! >> ~/pids.txt
done


text:
Q: Fluid 3-Column Layout in HTML & CSS I'm working with a basic 3-column layout, using HTML and CSS. My columns float left, so when I resize the width of the window, the columns gradually "collapse". i.e. First, col-3 will collapse under col-1, then col-2 will collapse under col-1.
HTML:

Quick win face time goalposts wheelhouse mobile friendly. Pixel pushing. On your plate. Who's responsible for the ask for this request?. Market-facing drink from the firehose, or table the discussion , we need distributors to evangelize the new line to local markets. Baseline the procedure and samepage your department. Are we in agreeance cross sabers timeframe, so productize baseline the procedure and samepage your department. Not the long pole in my tent not the long pole in my tent red flag.

We need to leverage our synergies three-martini lunch not the long pole in my tent, yet cloud strategy. Killing it where do we stand on the latest client ask curate sacred cow, so drop-dead date herding cats. I just wanted to give you a heads-up win-win-win get all your ducks in a row action item not enough bandwidth. Closer to the metal i don't want to drain the whole swamp.

CSS:
body {
    width: 90%;
    max-width: 1000px;
    margin: 0 auto; }

#col1, #col2, #col3 {
    float: left;
    width: 30%;
    margin: 10px;
    min-width: 200px; }

What I would like to happen is this. At a specified width, the 3 columns will collapse directly into 1 column (col1 above col2 above col3), instead of them moving one at a time.
Can this be done with HTML & CSS, or is another language required? How do I accomplish this?

A: You can use

body {
    width: 90%;
    max-width: 1000px;
    margin: 0 auto;
}
#col1, #col2, #col3 {
    float: left;
    width: 30%;
    margin: 10px;
    min-width: 200px;
}
@media (max-width: 768px) { /*set here you specified width*/
    #col1, #col2, #col3 {
        width: 100%;
    }
}

3333We need to leverage our synergies three-martini lunch not the long pole in my tent, yet cloud strategy. Killing it where do we stand on the latest client ask curate sacred cow, so drop-dead date herding cats. I just wanted to give you a heads-up win-win-win get all your ducks in a row action item not enough bandwidth. Closer to the metal i don't want to drain the whle swamp.

Quick win face time goalposts wheelhouse mobile friendly. Pixel pushing. On your plate. Who's responsible for the ask for this request?. Market-facing drink from the firehose, or table the discussion , we need distributors to evangelize the new line to local markets. Baseline the procedure and samepage your department. Are we in agreeance cross sabers timeframe, so productize baseline the procedure and samepage your department. Not the long pole in my tent not the long pole in my tent red flag.

We need to leverage our synergies three-martini lunch not the long pole in my tent, yet cloud strategy. Killing it where do we stand on the latest client ask curate sacred cow, so drop-dead date herding cats. I just wanted to give you a heads-up win-win-win get all your ducks in a row action item not enough bandwidth. Closer to the metal i don't want to drain the whole swamp.

Here a jsfiddle example to play with
If the content inside your div#col is really text, not just an example I really recommend you use: CSS3 Multiple Columns


text:
Q: How to make an array within a for loop? for i in range(len(DH4_3)):
    Keqs=np.exp(-(DH4_3[i]-T4[i+127]*DS4)/(R*T4[i+127]))
    print(Keqs)

I want to assign the index [i] to each Keqs[i]
The goal is to be able to indexing Keq, for instance, to be able to call the different data as Keqs[0], Keqs[1], and so on

A: This should work
Keqs = []
for i in range(len(DH4_3)):
  Keqs[i]=np.exp(-(DH4_3[i]-T4[i+127]*DS4)/(R*T4[i+127]))
print(Keqs) # print out array after all items are added


text:
Q: Purpose of "Target machine" field in Visual studio -> Linker-> Advanced Options->Target Machine I'm porting a 32-bit C++ app to 64-bit (using VS2008).
I'm not sure what does this field mean in the VS2008 ::
Visual studio ->Configuration Properties-> Linker-> Advanced Options->Target Machine.

By default it's value is set to "Not set".
Is it compulsory to change it's value to "MACHINEx64" if I want my application to be ported to 64-bit executable.

A: Yes, this is a very important option.  It sets the IMAGE_FILE_HEADER.Machine field in the executable file.  The very first field of the EXE or DLL header.
Windows check this when it loads an EXE and knows whether it needs to create a 32-bit or a 64-bit process from that field.  The only reason it is a the Linker + Advanced property page is because you don't normally change it.  The setting is pre-selected by the project configuration you created.  If you get "Not Set" then you are basically doing it wrong, hard to guess what you are doing.
Assuming you have a properly configured project that builds a working 32-bit build for your program, you create the 64-bit build with Build + Configuration Manager.  In the "Active solution platform" combobox at the upper right, select <New...>.  Pick "x64" in the dialog.  Hopefully the other defaults (Copy settings from = Win32, Create new project platforms ticked) are correct for yours.  Go back to the Linker + Advanced property page and the setting should have changed to MachineX64.

A: This option relates to the linker option /MACHINE and is a hint for the linker for what target architecture to link the object code if he (the linker) cannot determine this from the object file. As MSDN states you usually have not to specify this. So no you don't need to explicitly specify this flag when porting your code.


text:
Q: text area fields in sencha touch are not scrollable in devices TextArea scroll on devices not working
On any device, when text area is used there is not way to scroll it...
but in browser it works fine..
Any way to scoll the text area / atleast to auto resize. in Device
{
            xtype: 'fieldset',
            title: 'TExt aRea',

            defaults: {
                labelWidth: '36%'
            },
            items: [{
                xtype: 'textareafield',
                label: 'textareafield',

                clearIcon: true
            },
            ]
}

A: The way I'm handling it is to listen the keyup event on the textareafield, and in the event handler, set enough height to the textarea to show all the content. Scrolling is then handled by the container's scroller.
Here is an example:
Ext.define('ExamplePanel', {
    extend: 'Ext.Panel',
    config: {
        fullscreen: true,
        scrollable: true,
        items: {
            xtype: 'textareafield',
            itemId: 'textarea',
            clearIcon: false
        }
    },

    initialize: function() {
        this.down('#textarea').on('keyup', this.grow, this);
        this.textarea = this.element.down('textarea');
        this.textarea.dom.style['overflow'] = 'hidden';
    },

    grow: function() {
        this.textarea.setHeight(this.textarea.dom.scrollHeight); // scrollHeight is height of all the content
        this.getScrollable().getScroller().scrollToEnd();
    }
});

Try it on Sencha Fiddle.
My solution is based on this article Gmail for Mobile HTML5 Series: Autogrowing Textareas. You can find a more in-depth explanation and a bare JavaScript solution in the article.

A: so i have tried auto expand code using the following logic.
               {
                    xtype: 'textareafield',

                     id:'NotesTextArea',

                     maxRows: 4,
                    styleHtmlContent: true,
                    label: '',
                    clearIcon: true
                },

the logic for auto expand text area field:
initComponent: function(component, options) {

           var textarea = Ext.getCmp('NotesTextArea');
           textarea.on("keyup", function(field, event) {
                       var numOfRows=field.getValue().split("\n").length;

                       if( numOfRows>=4)
                       {
                          numOfRows= numOfRows++;
                          textarea.setMaxRows( numOfRows );
                       }

                       });
}

it expands the text area field for each new line perfectly ,

A:                    textarea.on("keyup",

                   function(field, event) {

                   var numOfRows=field.getValue().split("\n").length;

                   if( numOfRows>=4)
                   {
                      numOfRows= numOfRows++;
                      textarea.setMaxRows( numOfRows );
                   }

                   });

}
is correct but on text clear it does not minimises the height
So, need to remove that if loop then ans will be
                textarea.on("keyup",
                    function(field, event) {
                   var numOfRows=field.getValue().split("\n").length;

                      numOfRows= numOfRows++;
                      textarea.setMaxRows( numOfRows );

                   });

A:     Ext.define('MyApp.util.TextArea', {
override: 'Ext.form.TextArea',
adjustHeight: Ext.Function.createBuffered(function (textarea) {
    var textAreaEl = textarea.getComponent().input;
    if (textAreaEl) {
        textAreaEl.dom.style.height = 'auto';
        textAreaEl.dom.style.height = textAreaEl.dom.scrollHeight + "px";
    }
}, 200, this),

constructor: function () {
    this.callParent(arguments);
    this.on({
        scope: this,
        keyup: function (textarea) {
            textarea.adjustHeight(textarea);
        },
        change: function (textarea, newValue) {
            textarea.adjustHeight(textarea);
        }
    });
}});


text:
Q: Java double initilization with 0 I recently came across some code where double are initialized the following way:
double nb = 0.;
A very similar question has already been asked here but doesn't cover this specific case. Are there any benefits or special behavior of such initialization?

A: 0. is a perfectly legal double, and has the same value as 0.0
You can test it with jshell
jshell> 0. == 0.0
$1 ==> true

Here is the formal specification for how to represent a floating point (i.e. float or double) literal
The gist of it is that these are all valid ways to represent a double
1e1
2.
.3
0.0
3.14
1e-9d
1e137