text:
Q: PHP - IF doesn't check if the condition is true I'm creating a verb conjugator based on the endings of a verb that the user inputs.
For now it should work on verbs ending with "aic", "eic", "oic" (one array of endings) and "bic", "fic", "mic", "nic", "pic" and "wic" (another array of endings).
Unfortunately, it keeps assigning the first array to anything I put - even if it doesn't end with the specified endings.
This is the page: www.alweso.2ap.pl/koniugator/index.php
Here's the code:
<?php

$verb = $_POST["verb"];
$last2 = substr ($verb, -2);
$last3 = substr($verb, -3);
$last4 = substr($verb, -4);
$last5 = substr($verb, -5);
$last6 = substr($verb, -6);
$last7 = substr($verb, -7);
$last8 = substr($verb, -8);
$last9 = substr($verb, -9);

$root2 = str_replace($last2, "", $verb);
$root3 = str_replace($last3, "", $verb);
$root4 = str_replace($last4, "", $verb);
$root5 = str_replace($last5, "", $verb);
$root6 = str_replace($last6, "", $verb);
$root7 = str_replace($last7, "", $verb);
$root8 = str_replace($last8, "", $verb);
$root9 = str_replace($last9, "", $verb);

$aic_eic_oic = array("je", "isz", "i", "imy", "icie", "ja" );
$bic_fic_mic_nic_pic_wic = array("ie", "isz", "i", "imy", "icie", "ia" );
$cic_lic_sic_zic = array("e", "isz", "i", "imy", "icie", "a" );

?>

<?php

if ($last3 == ("aic" || "eic" || "oic")) {
        foreach ($aic_eic_oic as $one) {
        echo "
$root2$one
";
    }
    }

elseif ($last3 == ("bic" || "fic" || "mic" || "nic" || "pic" || "wic")) {
        foreach ($bic_fic_mic_nic_pic_wic as $one) {
        echo "
$root2$one
";
        }
    }

    ?>

A: You can't do if($value = ($a || $b || $c)) do if(in_array($value, array($a, $b, $c)).
if($value = ($a || $b || $c)) means : $value == true, because 'foo' || 'bar' || 'barfoo' is evaluate as true (non-empty strings are alway true in php).

A: Who told you that would work? Where did you read that? That isn't in any documentation; it doesn't work like that.
if( in_array($last3, array("aic","eic","oic")))

// ...

elseif( in_array($last3, array("bic","fic","mic","nic","pic","wic")))

Alternatively:
switch($last3) {
  case "aic":
  case "eic":
  case "oic":
    // do something
    break;
  case "bic":
  case "fic":
  case "mic":
  case "nic":
  case "pic":
  case "wic":
    // do something else
    break;
  default:
    // optional, do something to indicate error
}

A: your if statement syntax is incorrect, you cant do if($last3 == (x || y || z)) because its illogical, this statement reads `if ($last3 == (x == true || y == true || z == true))
you must write it out fully:
if ($last3 == x || $last3 == y || $last3 ==z)
or use in_array()


text:
Q: How to center one of the child widget out of 2 child widgets Currently, I have a LinearLayout with NumberPicker & TextView (With text "long string string")

This is not something I wish to achieve. What I wish to achieve is

*

*NumberPicker will be at horizontal center

*"long string string" TextView will just sit nicely at the right side of NumberPicker
The following layout won't work. As it treats NumberPicker + TextView as single element, and center horizontal both of them together.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/message_text_view"
        android:text="@string/might_drain_battery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <NumberPicker
            android:id="@+id/number_picker"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:text="long string string"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>

I change the code slightly. I remove gravity from inner LinearLayout, and place layout_gravity in NumberPicker
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <NumberPicker
        android:layout_gravity="center"
        android:id="@+id/number_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:text="long string string"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

But, that won't work still (I was wondering why NumberPicker no longer in center)

Any suggestion how can I achieve my desired layout?

A: I wouldn't use a LinearLayout for that.
A RelativeLayout allows the attribute android:layout_centerHorizontal="true" for its children (so the NumberPicker is placed) or even android:layout_centerInParent="true" (if the alignment has to be also vertical).
It also allows the attribute android:layout_toRightOf="@id/nameOfAnotherControl" for a child which wants to be placed at the right of another control (and so the TextView is also placed).
And that's all
This would be your (slightly) modified layout:
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <NumberPicker
        android:layout_gravity="center"
        android:id="@+id/number_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
    />
    <TextView
        android:text="long string string"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/number_picker"
        android:layout_centerVertical="true"
    />
</RelativeLayout>

Note: I replaced "Linear" with "Relative" and added an attribute to both the controls.
Now the NumberPicker is relative to the parent and the TextView is relative to the NumberPicker AND the parent.
I also added an extra attribute to the TextView, to center it vertically.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to write a recursive function to get the top parent in a tree structure in TypeScript I have a function that looks like that:
private getTopParentNode(rowNode): any {
    if (rowNode.parent == null) {
        return rowNode;
    } else {
        this.getTopParentNode(rowNode.parent);
    }
}

I want to return a rowNode when it's parent property equals null but it always returns undefined instead. As I search for similar problems this function looks good to me. Where am I getting it wrong?

A: Solution: Thanks to @TadhgMcDonald
private getTopParentNode(rowNode): any {
    let result = null;

    if (rowNode.parent == null) {
        result = rowNode;
    } else {
        result = this.getTopParentNode(rowNode.parent);
    }

    return result;
}


text:
Q: Accelarating image processing algorithm on GPU, parallel processing Matlab I want to accelerate my algorithm because I need to run it on hundreds of images,so I tried to use unvectorized GPU code, running the same code on GPU, I have nvidia Geforce GT 650M with 2 GB on my PC, however it was very slow than the CPU version. After searching I am convinced to pass to vectorized GPU code using batch process (pagefun, bsxfun), I tried so much to solve this problem without a solution. can someone help me about this code:
Q=100;
       for i=3:n-2
        for j=3:m-2
         A(i,j)=0;
            for c=1:Q
                        if B(i,j,c)~=0
                        A(i,j)=A(i,j)+(-(B(i,j,c)).*log(B(i,j,c)));
                        end
            end
        end
       end

Another question Why Matlab uses just 20% of my CPU? How I can take benefits of my CPU to accelerate my processing
Is Matlab a single threaded app?
Thanks in advance

A: The vectorized version is this:
BB = B(3:(n-2),3:(m-2),:);
cutoff = 10^(-6);
logBB = log(BB);
logBB(BB<cutoff) = 0; % remove divergent terms
A = -sum(BB.*logBB,3);

This should already run much faster even on a CPU. If you have a GPU, all you need to do is have the input array
BB = gpuArray(BB);

stored on the GPU, and then collect the results
A = gather(A);

back to the CPU

A: You will need to buy the parallel computing toolbox. (using parfor).
This is a well known limitation of matlab where some of the underlying functions do not paralellize across multiple cores (not threads). A quick ballpark is to look at how much CPU matlab uses and multiply that by the number of COREs you have in your pc (this should get you to somewhere around 100%).
If you want to utilize your computers GPU, parallel computing toolbox is the only way to do so.
From mathworks

This really depends on what you are doing. For some code MATLAB can only utilize a single core of a single processor, for other code, MATLAB will automatically utilize all available cores (and maybe processors). It really depends on the underlying functions. Some things cannot be easily parallelized. Sometimes you can help MATLAB with things like parfor loops. Other times you might need something like MPI. Still other times there really is nothing you can do.


text:
Q: Binning files based on the values in python I am trying to bin the values into some custom bins for my data. The Coulmn1 in the dataframe consists of a large set of random numbers ranging from 1.4 to 1.9.
Suppose the initial dataframe looks like this:
Index    Col1
1        1.4678
2        1.5001
3        1.5795
4        1.5234
...      ......
98       1.6754
99       1.6399
100      1.4910

What I want to do is to bin the numbers that fall within +/- 0.002 of the bins listed below. i.e., I want to bin all the data that fall within 1.458 and 1.462 for the first bin. The output should look like this
Index    Col1       Bin_names
1        1.4678      NaN
2        1.5001      1.50
3        1.5795      1.58
4        1.5234      NaN
...      ......      ....
98       1.6754      NaN
99       1.6399      1.64
100      1.4910      NaN

I tried the code below, but it bins all the data between 1.46 to 1.48 in one bin, which is not what I want.
bins = [1.46,1.48,1.5,1.52,1.54,1.56,1.58,1.60,1.62,1.64,1.66,1.68,1.70]
df['Bin_names'] = pd.cut(df['Column1'], bins, labels=['1.48','1.5','1.52','1.54','1.56','1.58','1.60','1.62','1.64','1.66','1.68','1.70'])

How can I bin the data based on my requirement?

A: By default, the boundary of pd.cut() contains the right edge, so you can start with the label '1.46'.
import pandas as pd
import numpy as np
import random
random.seed(10)

df = pd.DataFrame({'Col1':[round(random.uniform(1.450, 1.700),4) for i in range(100)]}, index=np.arange(1,101,1))

bins = [1.46,1.48,1.50,1.52,1.54,1.56,1.58,1.60,1.62,1.64,1.66,1.68,1.70]
labels = ['1.46','1.48','1.50','1.52','1.54','1.56','1.58','1.60','1.62','1.64','1.66','1.68']

df['Bin_names'] = pd.cut(df['Col1'], bins, labels=labels,right=False)
df.sort_values('Col1', inplace=True)
df2 = df.groupby('Bin_names').agg(list)
df3 = df2['Col1'].apply(pd.Series)
df3['cnt'] = df3.count(axis=1, numeric_only=True)
df3

       0    1   2   3   4   5   6   7   8   9   10  11  cnt
Bin_names
1.46    1.4611  1.4611  1.4657  1.4662  1.4700  1.4742  1.4782  1.4799  NaN NaN NaN NaN 8
1.48    1.4832  1.4835  1.4874  1.4891  1.4901  1.4912  1.4914  1.4916  1.4946  NaN NaN NaN 9
1.50    1.5015  1.5061  1.5104  1.5114  1.5125  1.5187  NaN NaN NaN NaN NaN NaN 6
1.52    1.5209  1.5257  1.5286  1.5299  1.5319  1.5329  1.5369  NaN NaN NaN NaN NaN 7
1.54    1.5415  1.5435  1.5454  1.5476  1.5503  1.5532  1.5535  1.5551  1.5572  1.5583  1.5587  1.5590  12
1.56    1.5603  1.5620  1.5639  1.5642  1.5654  1.5700  1.5723  1.5725  1.5742  NaN NaN NaN 9
1.58    1.5800  1.5802  1.5813  1.5834  1.5847  1.5872  1.5918  1.5929  1.5945  1.5957  1.5961  1.5962  12
1.60    1.6003  1.6005  1.6008  1.6033  1.6043  1.6122  1.6134  1.6145  1.6155  1.6183  1.6187  NaN 11
1.62    1.6215  1.6281  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 2
1.64    1.6420  1.6439  1.6444  1.6519  1.6533  1.6545  1.6553  1.6559  NaN NaN NaN NaN 8
1.66    1.6610  1.6638  1.6650  1.6674  1.6745  1.6776  NaN NaN NaN NaN NaN NaN 6
1.68    1.6853  1.6869  1.6882  1.6922  1.6923  1.6956  1.6991  NaN NaN NaN NaN NaN 7


text:
Q: Probabilistic sampling of non-adjacent cells in a raster - R I'd like to sample non-adjacent cells from a raster using the raster cell values as their inclusion probability.
Here is an example of sampling cells from a raster which can result in adjacent cells being selected.
set.seed(1)
library(raster)
r <- raster(matrix(runif(2500), nrow = 50, ncol = 50))
plot(r)

cells = sample(1:ncell(r), 100, prob=r[], replace=FALSE)

cell.centers = xyFromCell(r, cells)

plot(r)
points(cell.centers, pch = 19)

I realize with large sample sizes it would be nearly impossible to avoid selecting adjacent cells. In practice the number of samples I will be making is always going to be much smaller than the number of available cells. I just want to avoid including adjacent cells. I guess I could sample iteratively and remove cells once they are chosen..but that seems obtuse. Any help appreciated.


text:
Q: tell html doc not to load js if mobile device I'm cheekily seeking a line or two of code on the fly here:
Could someone be kind enough to provide code to place in the head section of html doc that says if mobile then do not load JS?
This is being used in conjunction with the following CSS media query:
<link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="m/styles_mobile.css" />

So I'm looking for a piece of code that is based on the same rule: media="only screen and (max-device-width: 480px)"
Would be very grateful

A: Now it's possible to use window.matchMedia
if (window.matchMedia("(min-width: 480px)").matches) {
  document.write('<script type="text/javascript" src="foo.js"><\/script>');
}

https://developer.mozilla.org/docs/Web/API/Window/matchMedia
http://caniuse.com/#feat=matchmedia

A: You can do it like this.

*

*Test the screen width and height to see if it is a mobile device.

*Load in scripts using JavaScript.

What you can do is this:
var scripts = ["foo.js",       //Put all your scripts here.
               "bar.js"];

if(screen.width <= 480){
    for(var i=0;i<scripts.length;i++){
              //-with jQuery (one line!)-
        $("head").append('<script type="text/javascript" src="'+scripts[i]+'"><\/script>');
                 //-or jQuery free-
        var scriptEle = document.createElement("script");
        scriptEle.setAttribute("type","text/javascript");
        scriptEle.setAttribute("src",scripts[i]);
        document.getElementsByTagName("head")[0].appendElement(scriptEle);
    }
}

Notice it is screen.width <= 480.

A: Given: "if mobile then do not load JS", and presuming "mobile" is defined by screens with a width of 480 pixels or less, then something like the following should work:
<script>
if (screen && screen.width > 480) {
  document.write('<script type="text/javascript" src="foo.js"><\/script>');
}
</script>

That will add the script element only if the screen is greater than 480 pixels wide.
The CSS rule in the OP is:
<... media="only screen and (max-device-width: 480px)" ...>

which will target screens of 480 pixels or less, which is contrary to to the first statement. Therefore change > to <= if the script should run on small screens and not run on larger ones.

A: I'm not sure how the previous answers would go with retina displays. I would do something like:
if( /Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent))
 document.write('<script type="text/javascript" src="foo.js"><\/script>');

snippet from here

A: The best way to do it would be to add it around whole the actual mobile script inside the "foo.js" file. The DOM will have trouble loading the  tag if you suddenly append it.
if (screen && screen.width > 480) {
 // Whole your script here
}

Instead of:
if (screen && screen.width > 480) {
  document.write('<script type="text/javascript" src="foo.js"><\/script>');
}


text:
Q: android retrieving large string from HttpGet I have an httpclient class i created. Within it i have a static method, "retrieveHttpGet(String url)", that returns a JSON object.
I'm using my own web API as the endpoint to retrieve data. Everything works fine when i'm retrieving a few lines of text. I'm trying to retrieve far more data though. When i try to pull around 20k characters of text i get the following errors
java.net.SocketException: Socket closed
at libcore.io.Posix.recvfromBytes(Native Method)
at libcore.io.Posix.recvfrom(Posix.java:131)
at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)
at libcore.io.IoBridge.recvfrom(IoBridge.java:513)
at java.net.PlainSocketImpl.read(PlainSocketImpl.java:489)
at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:241)
at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
at org.apache.http.impl.io.AbstractSessionInputBuffer.read(AbstractSessionInputBuffer.java:134)
at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:161)
at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:159)
at java.io.InputStreamReader.read(InputStreamReader.java:244)
at java.io.BufferedReader.fillBuf(BufferedReader.java:130)
at java.io.BufferedReader.readLine(BufferedReader.java:390)

Here is my the method i'm attempting to use
public static JSONObject retrieveHttpGet(String url)
{

DefaultHttpClient httpclient = new DefaultHttpClient();

// Prepare a request object
HttpGet httpget = new HttpGet(url);
httpget.setHeader("Content-type", "application/json");

// Execute the request
HttpResponse response;
try {
    response = httpclient.execute(httpget);
    // Examine the response status
    Log.i("Praeda",response.getStatusLine().toString());

    // Get hold of the response entity
    HttpEntity entity = response.getEntity();
    // If the response does not enclose an entity, there is no need
    // to worry about connection release

    if (entity != null) {
        InputStream inputStream = null;
        String result = null;
        response = httpclient.execute(httpget);

        inputStream = entity.getContent();

        result = convertStreamToString(inputStream);
        inputStream.close();
        // Transform the String into a JSONObject
        JSONObject jsonObjRecv = new JSONObject(result);
        // Raw DEBUG output of our received JSON object:
    //  Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");

        return jsonObjRecv;
    }

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

return null;
}

private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         *
         * (c) public domain: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }


text: Q: deploying local WAR in test environment without teamcity I have a JAVA application that is built using Maven with Spring and Hibernate . My project uses TeamCity to generate the new WAR whenever any code change is commited into SVN.I need to find an alternative to using teamcity. i.e. , we need to be able to deploy the local WAR into the test environment(so that Testers can do their job) without help of teamCity. I have tried replacing the TeamCity WAR with the local WAR , but that is not working . Any suggestions would be welcome .


text:
Q: extends Animal> Generics , can it be used as a single paramenter rather than a collection (arraylist etc) I have been asked to use "? extends" , but asked to pass a single parameter but not as list. Can anybody help me I can write something like below method. Whatver I have studied from Generics i guess ? extends can bee used with collection objects, not a single object.
public void verify(<? extends Account> account) {}

in method i need to check what subtype is passed and then send appropriate command on another object
any help would be appreciated.
Thanks.

A: Maybe your question is not quite clear, but i think that you've been asked to provide method that can accept and work with the Interface Account, so if you use Polymorphism, in the body all you need to do is via type-checking (can be considered as not a good idea) and cast so the logic be able complete the actions according to Accounts.
Update:
Sometimes it is a sign that either class hierarchy or the code that uses it (your method) may need to be refactored or restructured. But often there will be no refactoring / restructuring that avoids the problem.
    What I do is such cases - Clearly your Interface Account (or some extension thereof) needs a call method that each implementer of the interface can code to polymorphically perform this task  by his own needs -- seems the only OO-sound approach! For these you can use Interface segregation principle.

A: Yes, you can do that, it is very simple:
public void verify(Account account);

Now, you can hand in anything that extends Account.
class Account {}
class Account2 extends Account{}

verify(new Account2()); // works like a charm!

Types in Java are already covariant so you do not need any wildcard things. You cannot use wildcards here, but you don't have to.

A: If it is design you can try State Design Pattern .  This is design that can be helpful:
The classes and objects participating in this pattern are:
Context  (Account)
defines the interface of interest to clients
maintains an instance of a ConcreteState subclass that defines the current state.
State  (State)
defines an interface for encapsulating the behavior associated with a particular state of the Context.
Concrete State  (RedState, SilverState, GoldState)
each subclass implements a behavior associated with a state of Context


text:
Q: Sort multidimensional array by choosing the last 10 records I need to sort this array by number, then I need to choose the last 10 records from highest to lowest.
    function compressArray(original) {

      var compressed = [];
      // make a copy of the input array
      var copy = original.slice(0);

      // first loop goes over every element
      for (var i = 0; i < original.length; i++) {

        var myCount = 0;
        // loop over every element in the copy and see if it's the same
        for (var w = 0; w < copy.length; w++) {
          if (original[i] == copy[w]) {
            // increase amount of times duplicate is found
            myCount++;
            // sets item to undefined
            delete copy[w];
          }
        }

        if (myCount > 1) {
          var a = new Object();
          a.value = original[i];
          a.count = myCount;
          compressed.push(a);
        }
      }

      return compressed;
    };

Result:
 [{ name: 'Peter', number: 166 },
  { name: 'Frank', number: 165 },
  { name: 'Ana', number: 149 },
  { name: 'Robert', number: 150 },
  { name: 'Jordi', number: 162 },
  { name: 'Alan', number: 168 },
  { name: 'Carlos', number: 174 },
  { name: 'Carena', number: 159 },
  { name: 'Bruce', number: 167 },
  { name: 'Edison', number: 159 },
  { name: 'Paloma', number: 145 },
  { name: 'Devoto', number: 162 },
  { name: 'Julia', number: 150 },
  { name: 'Reina', number: 153 },
  { name: 'Karen', number: 163 },
  { name: 'Violet', number: 170 },]

I need this result with the last 10 records..
[ 'Carlos',
      'Violet',
      'Alan',
      'Bruce',
      '......',
      '......',
      '......',
      '......',
      '......',
      '......',]

A: .sort, .slice(-10), .reverse() and .map()

var array = [{ name: 'Peter', number: 166 },  { name: 'Frank', number: 165 },  { name: 'Ana', number: 149 },  { name: 'Robert', number: 150 },  { name: 'Jordi', number: 162 },  { name: 'Alan', number: 168 },  { name: 'Carlos', number: 174 },  { name: 'Carena', number: 159 },  { name: 'Bruce', number: 167 },  { name: 'Edison', number: 159 },  { name: 'Paloma', number: 145 },  { name: 'Devoto', number: 162 },  { name: 'Julia', number: 150 },  { name: 'Reina', number: 153 },  { name: 'Karen', number: 163 },  { name: 'Violet', number: 170 }];

var result = array.sort((a, b) => a.number - b.number)
                  .slice(-10)
                  .reverse()
                  .map(n => n.name)

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

A: To sort the array by decreasing number, do this:
array.sort((a, b) => b.number - a.number)

You can then get the 10 largest elements in decreasing order by slicing the first 10 elements:
array.sort((a, b) => b.number - a.number)
     .slice(0, 10)

Snippet:

let array =
 [{ name: 'Peter', number: 166 },
  { name: 'Frank', number: 165 },
  { name: 'Ana', number: 149 },
  { name: 'Robert', number: 150 },
  { name: 'Jordi', number: 162 },
  { name: 'Alan', number: 168 },
  { name: 'Carlos', number: 174 },
  { name: 'Carena', number: 159 },
  { name: 'Bruce', number: 167 },
  { name: 'Edison', number: 159 },
  { name: 'Paloma', number: 145 },
  { name: 'Devoto', number: 162 },
  { name: 'Julia', number: 150 },
  { name: 'Reina', number: 153 },
  { name: 'Karen', number: 163 },
  { name: 'Violet', number: 170 }];

let sort = array.sort((a, b) => b.number - a.number).slice(0, 10);

console.log(sort);

If you want only the names in the output, map the elements to their names:
array.sort((a, b) => b.number - a.number)
     .slice(0, 10)
     .map(e => e.name);

Snippet:

let array =
 [{ name: 'Peter', number: 166 },
  { name: 'Frank', number: 165 },
  { name: 'Ana', number: 149 },
  { name: 'Robert', number: 150 },
  { name: 'Jordi', number: 162 },
  { name: 'Alan', number: 168 },
  { name: 'Carlos', number: 174 },
  { name: 'Carena', number: 159 },
  { name: 'Bruce', number: 167 },
  { name: 'Edison', number: 159 },
  { name: 'Paloma', number: 145 },
  { name: 'Devoto', number: 162 },
  { name: 'Julia', number: 150 },
  { name: 'Reina', number: 153 },
  { name: 'Karen', number: 163 },
  { name: 'Violet', number: 170 }];

let sort = array.sort((a, b) => b.number - a.number)
                .slice(0, 10)
                .map(e => e.name);

console.log(sort);

A:  const result = original.sort((a, b) => a.number - b.number).slice(-10).reverse();

A: There is a much simpler solution:
//if duplicates are OK
function compressArray(array) {
    return array
             .sort((a,b) => b.number - a.number )
             .map(result => result.name);
             .slice(0,10)
}

Or, if duplicates are NOT OK. Remove them first

A: You can do it with .sort and .slice
try:
arr.sort((a, b) => b.number - a.number);
let new_arr = arr.slice(0, 10);


text:
Q: When a literal is passed to the constructor through a member function, why is the value not assigned to the member of the class? I am a beginner in C++. I am working on constructors. I am writing a simple a railway ticket booking program. Here is my code:
#include <iostream>
#include <stdlib.h>
using namespace std;
class Ticket
{
    char* name;
    long PNR;

    Ticket(char *pname, long pnr):name(pname),PNR(pnr)
    {
    }

public:
    Ticket()
    {
        name = NULL;
        PNR=0;
    }

    void booking()
    {
        char *n;
        n= new char[25];
        cout << "Enter Your Name: ";
        cin  >> n;
        Ticket(n,12345);
        cout << "Your Ticket is Booked." << endl;
    }

    void status()
    {
        long num;
        cout << "Enter PNR: ";
        cin >> num;
        if (num == PNR)
            cout << "Ticket is confirmed" << endl;
        else
            cout << "Ticket is not confirmed" << endl;
    }

    void print()
    {
        cout << "Your PNR is " << PNR << endl;
        cout << "The PNR is alloted to " << name << endl;
    }
};

using namespace std;

int main()
{
    int option;
    Ticket pass1;

book:
    cout << "Select an option: " << endl;
    cout << "1. Booking\t2. Status\t3.Print Info" << endl;
    cin >> option;

    switch(option)
    {
    case 1:
        pass1.booking();
        break;
    case 2:
        pass1.status();
        break;
    case 3:
        pass1.print();
        break;
    default:
        cout << "Invalid Entry. Exiting" << endl;
        break;
    }

    cout << "Do you want to check another ticket?" << endl;
    cout <<"1. Yes\t2. No" << endl;
    cin >> option;

    switch(option)
    {
    case 1:
        goto book;
        break;
    case 2:
    default:
        cout << "Exiting" << endl;
        exit(0);
    }

return 0;
}

In the member function, booking(), I call the constructor and pass n and 12345. However, n is passed to the constructor is saved to the member variable "name" but 12345 is not saved to the member variable "PNR". I did not find any error in the code. Why is this happening?

A: Ticket(n,12345); is creating a temporary Ticket and then discards it.  It does not set the member variables for the currect Ticket.  To set the variables booking() should look like
void booking()
{
    name = new int[25]
    cout << "Enter Your Name: ";
    cin  >> name;
    PNR = 12345;
    cout << "Your Ticket is Booked." << endl;
}

I would suggest that you use a std::string instead of a char array as you need to remember to delete the array in the destructor and you need to implement a copy constructor and an assignment operator.  If you use a std::string then all of the defaults will work for you.

A: Ticket(n,12345);

does not re-call the constructor for the current element, it creates a temporary Ticket initialized with (n,12345) and immediately discards it.
In general, you can only construct an object once. After construction completes, you cannot call a constructor for that object again.
Instead you can just assign to your member variables by using their name:
void booking() {
    PNR = 42;  // This will change the member PNR of the current instance
    // ...
}


text:
Q: Angular app with custom JS file runs differently on localhost vs on server I have this simple angular app: janev.ga with a custom JS file for the countdown (I am using the classycountdown script).
THE PROBLEM: when I run it locally everything loads great, however, once I deployed it to the server I realized it doesn't work the same as my localhost testing. What I mean by that is when I try to access it online, it would never load the JS script on the first go, even though there are no errors. I have to refresh the page and only then would the countdown script start working...
The way I use it in the component is by declaring it in angular.json (the custom.js file):

"scripts": [
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/bootstrap/dist/js/bootstrap.min.js",
              "src/assets/js/custom.js",
              "src/assets/js/jquery.classycountdown.min.js",
              "src/assets/js/jquery.classycountdown.js",
              "src/assets/js/jquery.knob.js",
              "src/assets/js/jquery.throttle.js"
            ]

, then I use it in the component like this:

declare const myDate: any;

export class AppComponent implements OnInit {

  myDate = myDate()[0];
  scnds = (myDate()[0] * 86400) - myDate()[1];
  toSec = {
    seconds: this.scnds
  }
}

And this is the custom.js:

function myDate(){
  var rightNow = new Date();
  // var theDate = rightNow.toISOString().slice(0,10).replace(/-/g,"");
  var goLiveDate = new Date("08/22/2020");
  var Result = Math.round(goLiveDate.getTime() - rightNow.getTime()) / (1000*3600*24);
  var toTheSecond = (rightNow.getHours() * 3600) + (rightNow.getMinutes() * 60) + (rightNow.getSeconds());
  return [Result.toFixed(), toTheSecond];
}

$(document).ready(function() {
          var remainingSec = $('.countdown').data('remaining-sec');
          $('.countdown').ClassyCountdown({
        theme: "flat-colors-very-wide",
        end: $.now() + remainingSec
    });
    });

Can anyone suggest what may the problem be? Any input would be appreciated.
Thanks!


text:
Q: when connecting to remote desktop connection using kali linux my computer doesnt allow me to connect but xrdp works fine When connecting Kali to a remote desktop connection it connects but when I use remote desktop connection on windows 10 I get an error saying I cannot establish a connection. does anyone know what the problem is?
remote desktop cant connect for the following reasons: 1-remote access to the server is not enabled. 2- the remote computer is turned off. 3-the remote computer is not available on the network. --Make sure that remote access is turned on and connected to the network, and that remote access is enabled. –

A: It's likely that you're not running an RDP server on your Kali system.
This is perfectly reasonable because Kali is a specialist distribution used for professional security work such as pentesting. You wouldn't want an RDP service exposing such a system to other devices on a network.


text:
Q: How to save video recorded with MediaRecorder API to php server? I can record a video with the webcam, play the resulting blob on the browser and download it on the local machine, but when i save the file to the server it is unreadable. I have tried sending the chunks to the server and concatenate them there, and also sending the whole blob, but the result is the same (unreadable video).
I first read the blobs with a FileReader(), which gives a base64 result, then send it to the server, where i base64_decode() it and save it to a folder.
JS code:
var reader = new FileReader();
reader.readAsDataURL(chunks[index]);
reader.onload = function () {
  upload(reader.result, function(response){
    if(response.success){
      // upload next chunk
    }
  });
};

on the server:
$json = json_decode( $request->getContent(), true );
$chunk = base64_decode( $json["chunk"] );
// all chunks get
file_put_contents("/uploadDirecotry/chunk".$json['index'].".webm", $json["chunk"]);

When all chunks are uploaded:
for ($i = 0; $i < $nrOfChunks; $i++) {
  $file = fopen("/uploadDirectory/chunk".$i.".webm", 'rb');
  $buff = fread($file, 1024000);
  fclose($file);

  $final = fopen("/processed/".$video->getFileName()."-full.webm", 'ab');
  $write = fwrite($final, $buff);
  fclose($final);

  unlink("/uploadDirectory/chunk".$i.".webm");
}

I don't know what i am doing wrong. I've been trying for more than a week to make it work, but it won't. Please help!

A: you have to save decoded chunk
instead of this
file_put_contents("/uploadDirecotry/chunk".$json['index'].".webm", $json["chunk"]);

use this
file_put_contents("/uploadDirecotry/chunk".$json['index'].".webm", $chunk);

Also i suggest, please open final file before your "for loop" in write mode and close it after loop, instead of reopen every time in "for loop".


text:
Q: corr.bias parameter in Random forest regression model in R I'm using the regression model of random forest in R and I found the parameter corr.bias which according to the manual is "experimental", my data is nonlinear and I just wonder if setting this parameter to true can enhance the results, plus I don't know exactly how it works for nonlinear data, so I really appreciate if someone can explain to me how this correction bias works in the random forest package and if it can enhance my regression model or not.

A: The short answer is that it performs a simple correction based on a linear regression on the actual and fitted values.
From regrf.c:
/* Do simple linear regression of y on yhat for bias correction. */
if (*biasCorr) simpleLinReg(nsample, yptr, y, coef, &errb, nout);

and the first few lines of that function are simply:
void simpleLinReg(int nsample, double *x, double *y, double *coef,
          double *mse, int *hasPred) {
/* Compute simple linear regression of y on x, returning the coefficients,
   the average squared residual, and the predicted values (overwriting y). */

So when you fit a regression random forest with corr.bias = TRUE the model object returned will contain a coef element which will simply be the two coefficients from the linear regression.
Then when you call predict.randomForest this happens:
## Apply bias correction if needed.
yhat <- rep(NA, length(rn))
names(yhat) <- rn
if (!is.null(object$coefs)) {
   yhat[keep] <- object$coefs[1] + object$coefs[2] * ans$ypred
}

The non-linear nature of your data probably isn't necessarily relevant, but the bias correction may be very poor if the relationship between the fitted and actual values is very far from linear.
You can always fit the model and then plot the fitted vs actual values yourself and see whether a correction based on a linear regression would help or not.


text:
Q: Bypassing using OAuth for GSuite Mails Is there a way for me to bypass the need to use OAuth for me to send out emails using the G-Suite platform in my application
I am still able to send out using the Microsoft 365 platform but some of my clients will not move to 365 and prefer G-Suite

A: You can use a service account. You will need to have the admin of the domain configure domain wide delegation to an account on the domain.
Once delegation is configured you can then use your code to impersonate a user on the domain and send emails on their behalf.  This is what i normally do with sa a system designed for sending email conversation mails.   When a user creates a new account the system could send an email conformation email. On behalf of say noreply@yourdomain.com
Your issue is going to be with the fact that your clients are the ones who own the domain so your going to have to get the google workspace admin for your client to set this up for you.
The other option would be to use standard oauth2 and authorize a user on the domain and send emails on their behalf.
The issue with that is going to be your application will need to be verified with one of the highest protected scopes. Your app will need to go though a security audit before it is verified.   Last I checked that audit will cost you  $15k-75k


text:
Q: JDBS string for connecting to a PDB database table? I have a Oracle container DB SID orcl and pluggabel DB named pdb1. pdb1 has a table named customers. I am able to make the connection to database but I want to connect to a database table.
Below is the jdbc url string I am able to construct:
jdbc:oracle:thin:@localhost:1521/pdb1

I am using this string in a scripted sql connector. What parameter has to be included in this url string to connect to the table?

A: You don't connect to a table but to a database's schema.
The database is specified by the connection string and the schema by the user's name.

A: Refer to the Youtube videos and quickstart guides. For all resources related to Oracle JDBC, refer to www.oracle.com/jdbc


text:
Q: VBA: Finding a number inside a larger number with Instr Our data exports at work have an annoying habit of comma separating distinct numeric identifiers, which excel interprets as a single long number.
To try and find if a specific number buried in there, I tried experimenting with the Instr function, but I encountered a problem.
Sub arrayTest()

arrTest = Array("11", "22", "33", "44")
arrTest2 = Array("1111", "1111", "1111", "1111")

For j = 0 To UBound(arrTest)
    For i = 0 To UBound(arrTest2)
        If InStr(1, CStr(arrTest(j)), CStr(arrTest2(i))) > 0 Then Debug.Print j, i
    Next i
Next j

End Sub

This code produces nothing, but I'm not quite sure why!
Is there a way to use Instr in this way? My latest idea was to try using CStr to force the numbers to act as strings, even though they already are! But still it doesn't seem to want to work.

A: You need to flip the INSTR inputs:
InStr(1, CStr(arrTest2(i)), CStr(arrTest(j)))

String to be searched is before the search string.

Sub arrayTest()

arrTest = Array("11", "22", "33", "44")
arrTest2 = Array("1111", "1111", "1111", "1111")

For j = 0 To UBound(arrTest)
    For i = 0 To UBound(arrTest2)
        If InStr(1, CStr(arrTest2(i)), CStr(arrTest(j))) > 0 Then Debug.Print j, i
    Next i
Next j

End Sub


text:
Q: Django-React authentication: limit users who can obtain simpleJWT tokens I have two React frontends for my backend: the first one is used by all users, the second one is an admin panel that can only be used by is_staff users.
What is the best way to limit access using simplejwt tokens?
I have overridden TokenObtainPairSerializer to include additional fields like 'is_staff'.
So I have two questions:

*

*is just checking the is_staff field on the frontend safe enough? Doesn't seem to me like a good idea.

*if I want to create a second API URL entry for admin authentication and override authentication logic on the backend side to only issue tokens to staff users. What method/class exactly should I override to change this? Is this a good idea?

A: The is_staff flag can be used for visual checks on the frontend, but views restricted to users with such permissions must be protected on the backend.
Assuming that you are using the Django Rest Framekwork, the best way of protecting your views is to use permissions, or more precisely, custom permissions.
from rest_framework import permissions

class IsStaffUser(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.user and request.user.is_staff

and them
from rest_framework.permissions import IsStaffUser

class StaffViewModelViewSet(viewsets.ModelViewSet):
    permission_classes = (IsStaffUser,)

more content about that can be found on:
Django Rest Framework Staff Only Permissions
Django Rest Framework Custom Permissions Per View
Django Rest Framework Permissions

A: Create Permission classes for django views to give access to them for users that are allowed and disallow users that are not allowed.
For example, your current logic states that is_staff users should only be allowed to login to Admin portal. It can be done easily by simply adding a permission class which allowes or disallows user to login to your admin portal. If you are using single JWTAPI for both, you should use a middleware on this API to detect where the data came from as _requests.META contains this data. You can detect if user is allowed all in backend using this META data.

A: encode is_staff in jwToken and when the user send a request with jwToken, decode it in the backend and check if is_staff user then based on this attribute you can do what you ever want.


text:
Q: Auto-repeating count down timer in ReactiveCocoa I'm new to ReactiveCocoa and there is a problem I couldn't yet find a way to solve. I have a network request in my app which returns data to be encoded in a QR code that will be valid for only 30 seconds. The network request returns a RACSignal and I send the data to be encoded in that signal to my view model. In the view model I map that data to a QR image and expose it as a property in my view model interface. After I create the QR image, I want to update a timeLeftString property that says "This code is valid only for 30 seconds" but the seconds will change as time progresses, and after that 30 seconds complete, I want to make another request to fetch another QR code data that will be valid for 30 seconds more and after that completes another request the fetch data that will be valid for 30 seconds...up until the screen is dismissed. How do I go about implementing this?
Currently I have this to get the data:
- (RACSignal *)newPaymentSignal
{
    @weakify(self);
    return [[[[APIManager sharedManager] newPayment] map:^id(NSString *paymentToken) {

        ZXMultiFormatWriter *writer = [ZXMultiFormatWriter writer];
        ZXBitMatrix *result =
            [writer encode:paymentToken format:kBarcodeFormatQRCode width:250 height:250 error:nil];

        if (!result) {
            return nil;
        }

        CGImageRef cgImage = [[ZXImage imageWithMatrix:result] cgimage];
        UIImage *image = [UIImage imageWithCGImage:cgImage];
        return UIImagePNGRepresentation(image);
    }] doNext:^(NSData *data) {
        @strongify(self);
        self.qrImageData = data;
    }];
}

and this for timer
- (RACSignal *)timeRemainingSignal
{
    @weakify(self);
    return [[[RACSignal interval:0.5 onScheduler:[RACScheduler scheduler]]  //
        startWith:[NSDate date]]                                            //
        initially:^{
            @strongify(self);
            self.expiryDate = [[NSDate date] dateByAddingTimeInterval:30];
        }];
}

The flow is: get data from the api, start the timer, and when the time is up make a new request to get new data and start timer again..and repeat this forever.
1- How do I start the timer after I get data from the API?
2- How do I make this flow repeat forever?
3- How do I stop the timer before 30 seconds complete and start the flow from the beginning if the user taps a button on the user interface?
4- I have an expiryDate property which is 30 seconds added to current date because I thought I will take the difference of expiryDate and [NSDate date] to decide whether the time is up - is there a better way to implement this?
5- How do I break the flow when it's repeating forever and unsubscribe from everything when the screen is dismissed (or, say, when user taps another button)?
thanks so much in advance for the answers.

A: I think the missing piece of the puzzle is the very useful flattenMap operator. It essentially replaces any nexts from its incoming signal with nexts from the signal returned by it.
Here's one approach to solving your problem (I replaced your newPaymentSignal method with a simple signal sending a string):
- (RACSignal *)newPaymentSignal
{
    return [[RACSignal return:@"token"] delay:2];
}

- (void)start
{
    NSInteger refreshInterval = 30;

    RACSignal *refreshTokenTimerSignal =
        [[RACSignal interval:refreshInterval onScheduler:[RACScheduler mainThreadScheduler]]
            startWith:[NSDate date]];

    [[[[refreshTokenTimerSignal
        flattenMap:^RACStream *(id _)
        {
            return [self newPaymentSignal];
        }]
        map:^NSDate *(NSString *paymentToken)
        {
            // display paymentToken here
            NSLog(@"%@", paymentToken);

            return [[NSDate date] dateByAddingTimeInterval:refreshInterval];
        }]
        flattenMap:^RACStream *(NSDate *expiryDate)
        {
            return [[[[RACSignal interval:1 onScheduler:[RACScheduler mainThreadScheduler]]
                startWith:[NSDate date]]
                takeUntil:[refreshTokenTimerSignal skip:1]]
                map:^NSNumber *(NSDate *now)
                {
                    return @([expiryDate timeIntervalSinceDate:now]);
                }];
        }]
        subscribeNext:^(NSNumber *remaining)
        {
            // update timer readout here
            NSLog(@"%@", remaining);
        }];
}

Every time the outer refreshTokenTimerSignal fires, it gets mapped to a new newPaymentSignal, which in turn when it returns a value gets mapped to an expiry date, which is used to create a new "inner" timer signal which fires every second.
The takeUntil operator on the inner timer completes that signal as soon as the outer refresh timer sends a next.
(One peculiar thing here was that I had to add a skip:1 to the refreshTokenTimerSignal, otherwise the inner timer never got started. I would have expected it to work even without the skip:1, maybe someone better versed in the internals of RAC could explain why this is.)
To break the flow of the outer signal in response to various events, you can experiment with using takeUntil and takeUntilBlock on that too.


text:
Q: How to set HDInsight's input/output paths to point to Azure Storage Vault (ASV) in local storage emulator? I am trying to create a simple map/reducer job for hdinsight but I am having trouble with connecting job in local hdinsight hadoop cluster to local azure storage emulator via ASV://
Sample code like this:
var hadoop = Hadoop.Connect();
HadoopJobConfiguration config = new HadoopJobConfiguration();
config.InputPath = @"asv://127.0.0.1:10000/devstoreaccount1/testcontainer/input";
config.OutputFolder = "asv://127.0.0.1:10000/devstoreaccount1/testcontainer/output";
hadoop.MapReduceJob.Execute<Mapper1>(config);

or
var hadoop = Hadoop.Connect();
HadoopJobConfiguration config = new HadoopJobConfiguration();
config.InputPath = @"asv://testcontainer/input";
config.OutputFolder = "asv://testcontainer/output";
hadoop.MapReduceJob.Execute<Mapper1>(config);

where testcontainer is an existing container in local emulator's blob storage.
When running this code I get a StreamingException "Process failed ('Streaming Job Failed!')"
And see the following error in console output:
packageJobJar: [] [/C:/Hadoop/hadoop-1.1.0-SNAPSHOT/lib/hadoop-streaming.jar] C: \Users\user1\AppData\Local\Temp\1\streamjob6525516867576872971.jar tmpDir=null
13/08/26 12:30:51 INFO util.NativeCodeLoader: Loaded the native-hadoop library
13/08/26 12:30:51 WARN snappy.LoadSnappy: Snappy native library not loaded
13/08/26 12:30:51 INFO mapred.JobClient: Cleaning up the staging area hdfs://loc alhost:8020/hadoop/hdfs/tmp/mapred/staging/user1/.staging/job_201308221229_0010
13/08/26 12:30:51 ERROR security.UserGroupInformation: PriviledgedActionExceptio n as:user1 cause:org.apache.hadoop.mapred.InvalidInputException: Input path does  not exist: hdfs:/devstoreaccount1/testcontainer/input
13/08/26 12:30:51 ERROR streaming.StreamJob: Error Launching job : Input path do es not exist: hdfs:/devstoreaccount1/testcontainer/input

Streaming Command Failed!

Any hints?

A: You can use one of the following paths to access local storage emulator.
wasb://testcontainer@storageemulator/input
wasb:///input (when storage emulator is set as the default File System)
asv:///input (when storage emulator is set as the default File System, asv is obsolete, not recommended)


text:
Q: Is it possible to express $\int\frac{dx}{e^x-x}$ in terms of special functions? In a differential equation I am solving, the final result had an integral of $$\int\frac{dx}{e^x-x}.$$ This is non-elementary, and I was wondering if I could get rid of the integral by using some special functions.
Is there any hope in doing this? It seems that Wolfram Alpha isn't able to do it.

A: For an approximation of$$I=\int\frac{dx}{e^x-x}$$ a series solution would be dangerous. However, you can approximate the integrand using the $[n,n]$ corresponding Padé approximant $P_n(x)$. This would write
$$\frac{1}{e^x-x}=\frac {1+\sum_{k=1}^n a_n\,x^n }{1+\sum_{k=1}^n b_n\,x^n }$$ Computing the roots and factoring
$$\frac{1}{e^x-x}=\frac{a_n}{b_n}\,\frac {\prod_{k=1}^n (x-r_k)}{\prod_{k=1}^n (x-s_k)}$$ Using partial fraction decomposition
$$\frac{1}{e^x-x}=\sum_{k=1}^n \frac {c_k}{x-s_k}$$
$$I=\int\frac{dx}{e^x-x}=\sum_{k=1}^n c_k \log(x-s_k)$$ will, as usual, lead to some arctangents and logarithms.
To show the quality of the approximation over a limited range, consider the norms
$$\Phi_n=\int_0^{2e} \left(\frac{1}{e^x-x}-P_n\right)^2\,dx$$
$$\left(
\begin{array}{cc}
n & \Phi_n \\
 2 & 1.06864\times 10^{-4} \\
 3 & 8.82719\times 10^{-5} \\
 4 & 8.62984\times 10^{-8} \\
 5 & 2.08495\times 10^{-9} \\
 6 & 1.11514\times 10^{-12} \\
\end{array}
\right)$$
Doing the work for $n=2$
$$P_2(x)=\frac {1-\frac{1}{3}x+\frac{1}{36}x^2 } {1-\frac{1}{3}x+\frac{19}{36}x^2 }=\frac {(x-6)^2}{19 x^2-12 x+36 }$$
$$P_2(x)=\frac 1{19}\left(1+\frac{a^2-12 a+36}{(a-b) (x-a)} -\frac{b^2-12 b+36}{(a-b) (x-b)}\right)$$ where
$$a=\frac{6}{19} \left(1-3 i \sqrt{2}\right)\qquad \text{and} \qquad b=\frac{6}{19} \left(1+3 i \sqrt{2}\right)$$
So
$$\int P_2(x)\,dx=\frac{x-6}{19}+\frac{306}{361} \sqrt{2} \tan ^{-1}\left(\frac{19
   x-6}{18 \sqrt{2}}\right)-$$ $$\frac{108}{361} \log
   \left(19 x^2-12 x+36\right)$$
Computing  $\int_0^t$, a few numbers
$$\left(
\begin{array}{ccc}
t & \text{approximation} & \text{"exact"}\\
 0.5 & 0.47817 & 0.47817 \\
 1.0 & 0.84296 & 0.84308 \\
 1.5 & 1.06760 & 1.06834 \\
 2.0 & 1.19279 & 1.19499 \\
 2.5 & 1.26069 & 1.26511 \\
 3.0 & 1.29726 & 1.30445 \\
\end{array}
\right)$$
Edit
Suppose that you need the integral around a given point $x=a$. Doing the same, we would have
$$P_2(x)=\frac{\alpha_0+\alpha_1(x-a) +\alpha_2(x-a)^2} { 1+\beta_1(x-a) +\beta_2(x-a)^2}$$
$$\alpha_0=\frac{1}{e^a-a}\quad \alpha_1=-\frac{e^a+1}{2 \left(e^a+2\right) \left(e^a-a\right)}\quad \alpha_2=\frac{e^a}{12 \left(e^a+2\right) \left(e^a-a\right)}$$
$$\beta_1=\frac{e^a a+a+e^a+e^{2 a}-4}{2 \left(e^a+2\right)
   \left(e^a-a\right)}\quad \beta_2=\frac{e^a \left(-a+e^a+12\right)+6}{12 \left(e^a+2\right)
   \left(e^a-a\right)}$$ and the integral would be easy to compute using the same procedure to obtain (with $t=x-a$)
$$\frac{\alpha_2 }{\beta_2}t+\frac{ \left(2 \alpha_0 \beta_2^2-\alpha_1 \beta_1 \beta_2+\alpha_2 \beta_1^2-2 \alpha_2
   \beta_2\right)}{\beta_2^2 \sqrt{4 \beta_2-\beta_1^2}}\tan ^{-1}\left(\frac{\beta_1+2 \beta_2 t}{\sqrt{4
   \beta_2-\beta_1^2}}\right)+$$ $$\frac{(\alpha_1 \beta_2-\alpha_2 \beta_1)}{2 \beta_2^2} \log
   \left(\beta_1 t+\beta_2 t^2+1\right)$$
For example, using $a=\pi$ and integrating between $\frac \pi 2$ and $\frac {3\pi}2$, the above will give $0.257755$ while the solution is $0.258772$; this corresponds to a relative error of $0.39$%.
Be sure that we could do much better.


text:
Q: What are the available snowflake editions? If I read the documentation, it says that there are 4 editions. But in some of the blogs and articles, I see that there is a premier edition also. Is premier edition really available?
Overview of Editions

*

*Standard Edition

*Enterprise Edition

*Business Critical Edition

*Virtual Private Snowflake (VPS)

A: There was just a renaming some time ago. The current editions are the ones you mentioned and can be found here https://docs.snowflake.com/en/user-guide/intro-editions.html :-)
When I remember correctly in the past it was Standard, Premier, Enterprise, Business Critical and Virtual Private Snowflake. The difference between Standard and Premier was the level of support. The higher support-level is now also offered within Standard and thus Premier isn't necessary anymore. (A hint can be found at the very bottom in the footnote of the link above ;-)


text:
Q: Python - Trying to identify the lowest unused number in list of folders My office has folders listed 01200001, 01200002, etc. I am trying to return the lowest unused value from our list.
Here's my script so far:
import os

def Exst(yr, i):
    exst = [n for n in os.listdir("P:/20" + str(yr)) if '01' + str(yr) + str(i) in n][0]
    print(exst)

for i in range(0001, 9999):
    try:
        Exst(20, i.zfill(4))
    except:
        print("01" + str(yr) + str(i).zfill(4))
        break

I am getting the initial 01200001 value, but the loop doesnt seem to be incrementing until failure. In my except statement, I am trying to read the value that the try loop stopped working on.
I'm very new to Python, so please excuse my ignorance.

A: You want to search through existing folders, and return the first one that doesn't exist. So say you have
folders = os.listdir(...)

You can do a very simple implementation like this:
for i in range(1, 10000):
    if f'01{yr}{i:04d}' not in folders:
        return i

This will format the folder name for each index i and return the first index that's not in folders. When you format the index, be sure to use the format spec 04d, so you always get a four character string, with zero instead of space padding.
But that method is inefficient: it performs a linear search for each index. A better way might be to sort the directory contents, find the index of the first match, and step along until you find a gap:
def find_min_index(yr):
    folders = os.listdir(...)
    folders.sort()
    try:
        start = folders.index(f'01{yr}0001')
    except ValueError:
        return 1
    expected = 2
    for expected, actual in enumerate(folders[start + 1:], start=2):
        if f'01{yr}{expected:04d}' != actual
            break
    return expected


text:
Q: Skimage rgb2gray reduces one dimension I am trying to convert multiple RGB images to grayscale. However, I am loosing one dimension
# img is an array of 10 images of 32x32 dimensions in RGB
from skimage.color import rgb2gray
print(img.shape) # (10, 32, 32, 3)
img1 = rgb2gray(img)
print(img.shape) # (10, 32, 3)

As you can see, though the shape of img is expected to be (10, 32, 32, 1), it is coming out as (10, 32, 3).
What point am I missing?

A: This function assumes the input to be one single image of dims 3 or 4 (with alpha).
(As your input has 4 dimensions, it's interpreted as single image of RGB + Alpha; not as N images of 3 dimensions)
If you got multiple images you will need to loop somehow, like this (untested):
import numpy as np
from skimage.color import rgb2gray
print(img.shape) # (10, 32, 32, 3)

img_resized = np.stack([rgb2gray(img[i]) for i in range(img.shape[0])])


text:
Q: Any way to know if UITextField is in the view's hierarchy? I am creating a UITextField-A inside an inputAccessoryView and when I call [UITextField-A becomeFirstResponder], it would not work.  However, if I do it with a delay of 1 sec, it would work.  From what I searched, it is because the UITextField is not in the view's hierarchy yet.  So is there a way to know so I do not need to use the 1sec delay alternative?  Is there a UITextFieldDidAppearInViewHierarchy or somekind in the SDK?

A: UIView offers a didMoveToSuperview method that you could abuse to do this.


text:
Q: Basic defensive programming
Possible Duplicate:
Favorite (Clever) Defensive Programming Best Practices

I am always advised by some programmers to pay concentration to easy debugging. What is defensive programming and to which extend should it be considered while practicing?
And one more important question: is there any key things to consider while coding and what are they?

A: Have a look at

*

*Defensive programming

*Case Study – Defensive
Programming

*The art of defensive programming

Defensive programming is the idea that
  the developer makes as few assumptions
  as absolutely necessary. In addition,
  the developer preemptively creates
  code that anticipates not only
  potential problems but also
  specification changes.

A: As a rule of thumb -- if you catch yourself thinking "this will always be true", write ASSERT( condition) in that place. That is probably the core of what defensive programming should be ;).

A: If defensive programming meant only one thing , that should be use assert extensively.
Here is a good article about when and where to use assert.

There are many situations where it
  is good to use assertions. This
  section covers some of them:
* Internal Invariants
* Control-Flow Invariants
* Preconditions, Postconditions, and Class Invariants

A: http://en.wikipedia.org/wiki/Defensive_programming
Defensive programming means, that you check if a file exists and if you have the permissions to open it instead of just trying to open it and catching any eventual exceptions.
(Just an example)


text:
Q: Prove that, if $A, B$ are normed vector spaces then $(A\times B, \|\cdot \|)$ is a normed vector space. I would like to understand what I must prove. Can you help me with this?
Question: Prove that, if $A, B$ are normed vector spaces then $(A\times B, \|\cdot \|)$ is a normed vector space.
Note: Note that $A, B$ are infinite-dimensional normed vector spaces.
My question: First, I must prove 8 properties of vector space, then how do I formalize, ie, how do I define what I want to prove? I want to prove that this vector space is only normalized with the sum, maximum and Euclidean norm. How do I prove that these norms are equivalent in a infinite-dimensional space like this? How do I define what I want to prove?
The norms mentioned are

*

*sum $\|(x,y)\|=\|x\|_A+\|y\|_B$;

*maximum $\|(x,y)\|= \max(\|x\|_A,\|y\|_B)$;

*euclidian $\|(x,y)\|=\sqrt{\|x\|_A^2+\|y\|_B^2}$;

Is there any way to prove the equivalence between this norm, than I can use just one to prove that $(A\times B, \|\cdot\|)$ is a normed space instead prove for these three norms?
I would like some help to understand the statement and correctly define everything I have to prove. Thank you in advance for any help.

A: I think the following should work. Let $\pi_A\colon A\times B\to A$ and $\pi_B\colon A\times B\to B$ the projections on the spaces $A$ respectively $B$. Observe, these are linear mappings.
Define a norm on $A\times B$ by $$ \|x\|_{A\times B} := \|\pi_A(x)\|_A+\|\pi_B(x)\|_B.$$
Then one can easily show, that it fulfills all three axioms of a norm. Of course, it is not the only one.
For example, we would like to show, that $\|(x,y) \|_\max:=\max(\|x\|_A,\|y\|_B)$ and $\|(x,y) \|_1:=\|x\|_A+\|y\|_B$ are equivalent.
If $\|x\|_A\geq \|y\|_B$, then we have $\|(x,y) \|_\max=\|x\|_A$
$$
\|(x,y) \|_\max=\|x \|_A\leq \|(x,y) \|_1=\|x\|_A+\|y\|_B\leq 2\|x\|_A=2\|(x,y) \|_\max.
$$
Hence, $\|(x,y) \|_\max\leq  \|(x,y) \|_1\leq 2\|(x,y) \|_\max$


text:
Q: Apache choose folder based on url parameter and keep url I'd like to have a way to access folders on my server based on the name given in the url as a parameter.
Let's say my website is www.site.com
I'd like to access custom folders under the main directory by sending a parameter on the url but without having a redirect changing the url.
So I'd provide the folder in the parameter: www.site.com/dev1
This way people wouldn't have to remember the full url be aware of it.
my base folder as per the vhost is /var/www/developers
the subfolders are dev1, dev2, dev3 and so on.
Under dev1/2/3 there is a folder called Portal.
-/var/www/developers
--/var/www/developers/dev1
----/var/www/developers/dev1/Portal
------/var/www/developers/dev1/website/Portal

my current .htaccess is:
RewriteEngine On

RewriteCond %{DOCUMENT_ROOT}/$1/website/Portal  -f
RewriteRule ^([^/]*)/?$ /$1/website/Portal [L]

Whilst it is working, it keeps changing my url to www.site.com/dev1/Portal

A: That is happening because mod_dir is adding a trailing slash after directory portal.
Have your rule like this by having a trailing slash in your rule:
RewriteEngine On

RewriteCond %{DOCUMENT_ROOT}/$1/website/Portal -d
RewriteRule ^([^/]+)/?$ /$1/website/Portal/ [L]


text:
Q: custom errors in asp I am trying to do an error page which redirect to it whenever an error occurs.
This is my code:
              <customErrors defaultRedirect="Error.aspx" mode="On" />

which is working fine now how can I get the error message too on my error page
Example: Error - Index Error

A: You would need to get the last error that occurred (programmatically) and display it in the page. You can do that like this (in Error.aspx):
protected void Page_Load(object sender, EventArgs e)
{
     Exception ex = Server.GetLastError();
     lblError.Text= ex.Message;
     Server.ClearError();
}

Where lblError is a Label control defined in your page just for the purpose of displaying the error messages.
See here for more details.

A: protected override void OnError(EventArgs e)
{
  HttpContext ctx = HttpContext.Current;

  Exception exception = ctx.Server.GetLastError ();

  string errorInfo =
     "
Offending URL: " + ctx.Request.Url.ToString () +
     "
Source: " + exception.Source +
     "
Message: " + exception.Message +
     "
Stack trace: " + exception.StackTrace;

  ctx.Response.Write (errorInfo);
  ctx.Server.ClearError ();

  base.OnError (e);
}

Read more about ASP.NET Custom Error Pages


text:
Q: Regular Expression Match And Compare Captured Groups I'm trying to match some strings of the pattern:
event = sometext1 name = prefix sometext2

I want to match all cases that sometext1 and sometext2 are different. How should I do it with regular expression? Thanks!

A: You can use this regex:
event += +(\w+) +name+ = +\w+ +((?!\1)\w+)\b

RegEx Demo

A: Use a backreference like this:
^event = ([^\s]+) name = prefix (?!\1).+$

Debuggex Demo


text:
Q: Does the inequality of repeated limits at a certain point confirm the limit to not exist at that particular point while dealing in two variables In two variable functions we know that if limit exists at a certain point through all the possible paths and if repeated limits at that particular points exist then the two repeated limits are always equal.
So can we say that if repeated limits exists at some point but are not equal then the general limit of that function will never exist at that particular point....
Thanks in advance for helping me with this one.


text:
Q: PowerMockito tests moved from JDK 1.6 to JDK 1.7 are getting constraint violations We have some tests that had been working fine with JDK 1.6.  We're now moving to JDK 1.7.  These tests work fine in Eclipse.  When we run these tests from our Ant build, we're seeing errors like this:
junit.framework.TestListener: addError(<testmethodname>, loader constraint violation:
when resolving overridden method
"com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(Lorg/w3c/dom/Node;)Ljava/lang/Object;"
the class loader (instance of org/powermock/core/classloader/MockClassLoader) of the current class,
com/sun/xml/bind/v2/runtime/unmarshaller/UnmarshallerImpl, and its superclass loader (instance of <bootloader>),
have different Class objects for the type
com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(Lorg/w3c/dom/Node;)Ljava/lang/Object; used in the signature)

We were using PowerMockito 1.5 when we first saw this.  I just tried upgrading to 1.5.4 and all the relevant dependencies, and that resulted in no change.
This shows the class annotations we're using:
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({ "javax.xml.*", "org.xml.sax.*" })
@PrepareForTest(<classundertest>.class)
public class <classundertest>Test extends MockServiceBase {

What might be the problem here?

A: Last night I finally found the workaround for this.  The key was to add additional package masks to the "@PowerMockIgnore" annotation.  Just about the first thing I tried was adding "com.sun.xml.".  I had thought that didn't make any difference, but I think it simply fixed the tests that referred to that package.  The remaining references were to "com.sun.org.", and I didn't realize that.  When I finally also added "com.sun.org.*", it fixed the remaining tests.


text:
Q: Collision of Discs and Snooker Kicks I woke up this morning thinking about spinning discs. Could someone verify whether my reasoning below is correct?
Problem 1
Suppose have two identical uniform discs constrained to move in a plane. Set disc $A$ spinning about its centre of mass, clockwise viewed from above. Now collide it with disc $B$.
Assume that friction is the only force acting, and the collision is elastic. I believe that I should be able to work out qualitatively what happens from conservation of linear and angular momentum.
The friction will provide a torque causing $B$ to spin anticlockwise about its centre of mass. Let $L$ be the line joining the centre of $A$ and $B$ at the moment of collision. But then by conservation of angular momentum $B$ must deviate to the right of $L$ after collision. And then by conservation of linear momentum disc $A$ will move to the left of $L$.
The other option for conserving angular momentum would be for the disc A to start spinning faster, but this is ruled out by conservation of energy. Correct?
Note: this effect is observed in snooker when left hand side is imparted to the cue ball.
Problem 2
Now suppose that the discs are stood on end on a table and we do the same experiment, assuming no friction between table and disc. Then conservation of angular momentum must cause the first disc to jump in the air upon collision, by the same reasoning as before. Correct?
Note: I guess this is the origin of the "kick" in snooker.
So really understanding how to prevent snooker kicks is the subtle problem of understanding precisely how much angular momentum is transferred between the balls. You ideally want to minimise this (i.e. have almost frictionless ball collisions, compared with the friction between cloth and ball).


text:
Q: Data handling of list + details + edit views in a EmberJS app I'm building an EmberJS app which needs to have three components. A list of items, a detailed view of each item and an edit view of each item. I haven't found any good explanation or example of how to manage the data in this particular case.
You can find a simplified and cleaned out example of what I've got right now at this gist: https://gist.github.com/2390740
What I'd like to avoid is having two copies of the data, but the only way I've been able to get the data into the detailed view is by making a copy of it, which is far from ideal.
Is there some way to reference an item in the array in the ListController from DetailController? That way when the item is updated in the detailed view the list view is automatically updated with the changes.
What I would like to achieve is that the ListController loads a list with basic information about each item, and then the DetailController loads all the available info for the selected item. If the client side data store could be the same for both the list and the detailed view, the DetailController wouldn't have to load the detailed info again if the user returns to an item which already has been loaded. Another benefit is that the list view would already be up to date if the user changed anything and then returns to the list.
Note: I know that the edit view is missing in this example, I'm just trying to get the data binding between the detailed view and the list to work first.

A: I do exactly this in my feed reader ember application.
The way to do this is have a detailController with a content property.
Bind all your detail view stuff to the detailController.  Selecting an item in the listcontroller should set the content property of the detailcontroller to that item.  Done!


text:
Q: d3.jzoom from same scale lavel not working properly I am using d3.zoom for my map. For some reason that I don't understand at some specific scale level zoom function is not working properly. And just on the right side of the map??? Thre is some kind of translation to the right and I can not pan any more my map.
This is js of my svg map.

import * as d3 from "d3"; export default {
name: "KartaHrvatske",
props: ["name"],
mounted(){
    var svg = d3.select("#map")
    const zoom = d3.zoom()
                   .translateExtent([[0,0],[10000000,8200000]])
                   .scaleExtent([1, 10])
                   .on("zoom", zoomed)

    svg.call(zoom)

    function zoomed({transform}){
        svg.select("#wrap").attr("transform", transform)
    }
} }

I am puting gif capture of my map, the left side zooming which is working ok

And the right side of the map which have some kind of translation

Does anyone have idea why this is happening and what can I do? I am using vue framework.


text:
Q: Вылетает ошибка: InvalidTokenError: Invalid token specified: Cannot read property 'replace' of undefined В моём приложении после регистрации пользователя, при входе на страницу пользователя вылетает ошибка:

InvalidTokenError: Invalid token specified: Cannot read property
  'replace' of undefined

В частности из-за jwt-decode:
import React, { Component } from 'react'
import jwt_decode from 'jwt-decode'
class Profile extends Component {
constructor(props) {
  super(props)
  this.state = {
    name: '',
    email: '',
    errors: {},
  }
}

componentDidMount() {
  const token = localStorage.usertoken
  const decoded = jwt_decode(token)
  this.setState({
    name: decoded.name,
    email: decoded.email
  })
}

A: Я бы дал небольшую рекомендацию по поводу хранилища. Если в метод getItem() интерфейса Storage передать ключ в качестве параметра, то метод вернет значение, лежащее в хранилище по указанному ключу. Возвращаемым значением является строка DOMString, содержащая значение для соответствующего ключа.  Если ключ не существует, то будет возвращено значение null.
// Ваш способ получения значения из хранилища
const oldTokenGetter = localStorage.usertoken;
// Рекомендуемый способ получения значения из хранилища
const newTokenGetter = localStorage.getItem('usertoken');

Конечно, это не ошибка, ведь в Storage значения помещенных ключей хранятся как проперти объекта и Вы получите свое значение по имени.
Советы и рекомендации оставим и перейдем к полученной ошибке:

InvalidTokenError: Invalid token specified: Cannot read property 'replace' of undefined

Кроется в пакете jwt-decode. Можно найти в гите следующее ишшуе: JWT InvalidTokenError: Invalid token specified Там в комментариях имеется подсказка, как избежать такой ошибки. В вашем случае нужно поступить так (добавить проверку, что значение имеется):
componentDidMount() {
  const token = localStorage.getItem('usertoken');

  if (token) {
    const decoded = jwt_decode(token);
    this.setState({
      name: decoded.name,
      email: decoded.email,
    });
  }
}

Увы, но судя по исходникам такая проблема имеется и кроется в следующем модуле либы: base64_url_decode.js, который вызывается из основного модуля (index.js)


text:
Q: Does index data count against the free tier data quota in Cloud Firestore? Cloud Firestore has a quota of 1 GiB/day in the free tier. Does data in indexes count against that quota? I know that indexes have their own limits, but here I'm just concerned about their actual data usage.
An example: Let's assume I have 900 MB data (documents & collections) in Firestore. I also have many indexes that take up 200 MB on the storage medium. Now do these indexes now push me over the limit of 1 GiB/day for data?

A: Yes, the limit includes the size of any indexes.  From the documentation:

You are charged for the amount of data that you store in Cloud
  Firestore, including storage overhead. The amount of overhead includes
  metadata, automatic indexes, and composite indexes.


text:
Q: I have a problem with display link the link is not forwording to 1.jsp
this code is not working properly
<display:column property="in" sortable="true" href="1.jsp" paramid="1.jsp"/>

thanx

A: Clicking on this link will not go to 1.html but to 1.jsp as you have defined href="1.jsp".
You have defined paramid="1.html" but paramId takes the name of parameter which you want to send to the href url
i.e. if you want 1.jsp?paramName=paramValue then you will define paramId="paramName"
Read the display:column documentation again to understand it better.


text:
Q: How do I change the appearance of messages in OMNeT++? In the manual it says the following:

To customize the appearance of messages in the graphical runtime environment, override the getDisplayString() method of cMessage or cPacket to return a display string.

I don't understand what this means. I have custom images and I was able to change the icon of nodes with the line below in my simple module.
@display("i=misc/train-stationCopy");

I have the line below in my message class but it does not work and generates error
@display("i=misc/train");

What am I missing? Sorry I'm new to omnet++ and c++.

A: Add this to your .msg file. This will enforce the generation of the getDisplayString() function in the *_msg.h file.
const string displayString @override = "i=misc/train";


text:
Q: component.find an aura:id item created in aura:iteration I am building a menu component.
One menu-item is a sub-menu with list of opportunities, this list is created with aura:iteration over a list of opportunities.
When selecting a menu or a sub-menu, I need to make it look selected (change css attribute). For this to happen, I need to find this menu item in my controller.
If I add id attribute to my item markup and use the event attribute on my controller (event.currentTarget.id), I can catch the item itself and change it's style, this works:
MARKUP

<aura:iteration items="{!v.opportunities}" var="opp">

            {!opp.Name}

</aura:iteration>

CONTROLLER
openItemFromMenu: function(component, event, helper) {
    // get the id
    var oppId = event.currentTarget.id;
    // choose it (select menu)
    var selectedItemNew = component.find(oppId);
    selectedItemNew.style = "background: rgb(216, 237, 255);"
}

PROBLEM
when I try to change the menu selected not from the click of the item (event that is triggered from another page) - I have added an event handler to change the menu item, and I send the opportunity id through that event. Then (after adding aura:id to my item, I am trying to find this menu item of this oppId with component.find in my controller - this does not work:
CHANGED MARKUP
add:
<aura:handler name="eventSelectMenuItem" event="c:myEvent" action="{!c.openItemFromMenu}" />
change:

CHANGED CONTROLLER
openItemFromMenu: function(component, event, helper) {
    // get the id from the event
    var oppId = event.getParam("recordId");
    // choose it (select menu)
    var selectedItemNew = component.find(oppId);
    selectedItemNew.style = "background: rgb(216, 237, 255);"
}

QUESTION
Does component.find for aura:id within an aura:iteration suppose to work?
If not - is there a workaround?
If it does suppose to work - what am I doing wrong?

A: aura:id must be a literal value. As such, you can't use an expression in aura:id (it will be treated as literal text). Instead, you can use the element's id via document.getElementById:
var selectedItemNew = document.getElementById(oppId);

A: First problem is that we cannot use expression while assigning aura:id. Aura:id need to be static.
so your first change is

in js you can do
    openItemFromMenu: function(component, event, helper) {
        // get the id from the event
        var oppId = event.getParam("recordId");
        // choose it (select menu)
        var selectedItemsNew = component.find('link').getElements();
        if(Array.isArray(selectedItemsNew)){
            var selectedItemNew = selectedItemsNew.find(function (oneItem){
return oppId === selectedItemsNew.id})
           if(selectedItemNew){
              selectedItemNew.style = "background: rgb(216, 237, 255);"
           }
        } else if(selectedItemsNew){
          if(oppId === selectedItemsNew.id){
             selectedItemNew.style = "background: rgb(216, 237, 255);"
          }
        }

    }

Instead of adding style directly you can create a class and use

$a.util.addclass()

A: I don't know if it will work for you, but what worked for me was just assigning the same static aura:id to each element in the iteration, and then when you use component.find() it will return an array of all the elements.


text:
Q: Print automático após HTML estar carregado com AngularJS Ao clicar em um botão para a impressão de um relatório, este deverá consultar com o AngularJS algumas informações na base de dados e logo executar o comando para a impressão ($window.print()) depois que a página já estiver carregada com as devidas informações.
Quando tento fazer isto, ele vai para a visualização de impressão antes da página esteja carregada por completo. É certo que simplesmente o usuário esperar a mesma carregar e clicar em imprimir poderia resolver mas, no meu caso, a impressão automática ficaria bem mais interessante.
Necessito que o comando $window.print() seja executado somente depois que as devidas informações já estiverem na página.
Como faço esta verificação?
---- Editado:
Existe um service específico onde faz a consulta dos dados de um determinado funcionário e uma verificação referente (r.sucesso) sobre a consulta. Este código encontra-se dentro do controlador correspondente da tela em específico.
funcionarioService.getListagem(self.funcionarioId, function (r) {
        if (r.sucesso) {
            self.funcionario = r.conteudo;

            // Estranhamente desta forma soluciona meu problema
            // Acredito que este é executado após o carregamento total da página,
            // mas não encontrei nenhuma confirmação a respeito.
            window.setTimeout(function() {
                window.print()
            }, 1);
        }
    });

---- Editado[2]:
Este link fala a respeito do motivo desta solução proposta funcionar mas não ficou muito claro a explicação.

A: A resposta encontrada
window.setTimeout(function() {
    window.print()
}, 0);

é válida, pois não apenas de acordo com este link que eu tinha colocado, mas nesta outra resposta é colocado:

Async invocations, such as those from setTimeout, do indeed generate a new callstack.

onde traduzido seria algo do tipo que setTimeout gera uma nova pilha para invocações assíncronas, sendo executada após a até então a última pilha.


text:
Q: Change event didn't work for selectfield? i am getting struck with sencha touch select field change event. Usual change event is working fine. but in case option values like this,
{
     xtype: 'selectfield',
     label: 'Choose one',
     options: [{text: 'First Option',  value: 1},
               {text: 'First Option', value: 2},
               {text: 'Third Option',  value: 3}],
     listeners : {
          change : function (selectField, newValue, oldValue)
          {
               console.log(newValue);
          }
     }
}

When this case values are different but display values are same, change event didn't work. Please help to finish this issue.

A: This is issue with Sencha. you can check this link
https://www.sencha.com/forum/showthread.php?304198-Select-field-not-firing-change-event-on-same-text-but-different-value.
But If You have a need to do this then you can do with this way, write this in launch function.
Ext.override(Ext.field.Input, {
        setValue: function (newValue) {
            var oldValue = this._value;

            this.updateValue(this.applyValue(newValue));

            newValue = this.getValue();
            this.onChange(this, newValue, oldValue);

            return this;
        }
    });


text:
Q: store image into a folder in netbeans I am using a FileChooser for selectiong image from the system.Now I want to store the image into db.For this I have created a new folder image in the project,and my idea is load the folder with the opened images renamed like  img1,img2...and store this path into the db, at a time one image.
I used the code below for getting the image name
String name = jFileChooser1.getSelectedFile().getAbsolutePath();

But I dont know how to store the image into the folder.Hope anyone will help to solve this.

A: I don't see the point of storing the images into your project jar. It would make more sense to save it into the system. But then again, why even do that?
Just store the image directly to the database. To do that just do this
PreparedStatement ps=con.prepareStatement("insert into imgtable values(?)");
FileInputStream fin=new FileInputStream(fileFromChooser);
ps.setBinaryStream(1,fin,fin.available());

int i=ps.executeUpdate();
System.out.println(i+" records affected");

UPDATE
Saving to File system. You need to specify the path in this line of code
ImageIO.write(image, "jpg",new File("C:\\path\\to\\destination\\" + file.getName()));

import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;

public class SaveImageFile {

    public SaveImageFile() {
        final JFrame frame = new JFrame("Save Image");

        JButton saveImage = new JButton("Browse");
        saveImage.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        "JPG, GIF, and PNG Images", "jpg", "gif", "png");
                chooser.setFileFilter(filter);
                int returnVal = chooser.showOpenDialog(frame);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = chooser.getSelectedFile();
                    System.out.println("You chose to open this file: "
                            + file.getName());
                    BufferedImage image;
                    try {
                        image = ImageIO.read(file);
                        ImageIO.write(image, "jpg",new File("C:\\path\\to\\destination\\" + file.getName()));
                    } catch (IOException ex) {
                        Logger.getLogger(SaveImageFile.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        });
        frame.add(saveImage);
        frame.setLayout(new GridBagLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                SaveImageFile saveImageFile = new SaveImageFile();
            }
        });
    }
}

A: The following code selects image and saves it into a folder. For more follow this link How to save image in folder and path to database
 JFileChooser chooser=new JFileChooser();
 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
 int res=chooser.showOpenDialog(ImageTutorial.this);
if(res==JFileChooser.APPROVE_OPTION)
{
file=chooser.getSelectedFile();
String path=file.getAbsolutePath();
ImageIcon image=new ImageIcon(file.getAbsolutePath());
Rectangle rec=imagelbl.getBounds();
Image scaledimage=image.getImage().getScaledInstance(rec.width,rec.height,Image.SCALE_SMOOTH);
image=new ImageIcon(scaledimage);
imagelbl.setIcon(image);
imagename.setText(file.getName());
 }else
  {
  JOptionPane.showMessageDialog(null,"No new image selected");
  }


text:
Q: Create hierarchical multidimensional array based on number of consecutive symbols at start of strings I'm not sure that the title is correct as it's hard to explain.
I want to convert a 1 dimensional array into a multidimensional array based on each array's hashtag count.
So basically I want this.
[
    0 => "# Grandparent #1"
    1 => "# Grandparent #2"
    2 => "## Parent #2-1"
    3 => "### Child #2-1-1"
    4 => "## Parent #2-2"
    5 => "### Child #2-2-1"
    6 => "### Child #2-2-2"
    7 => "## Parent #2-3"
    8 => "## Parent #2-4"
    9 => "# Grandparent #3"
    10 => "## Parent #3-1"
]

To something like this
[
    [
        'name' => 'Grandparent #1'
    ],
    [
        'name' => 'Grandparent #2',
        'children' => [
            [
                'name' => 'Parent #2-1',
                'children' => [
                    [
                        'name' => 'Child #2-1-1',
                    ]
                ]
            ],
            [
                'name' => 'Parent #2-2',
                'children' => [
                    [
                        'name' => 'Child #2-2-1'
                    ],
                    [
                        'name' => 'Child #2-2-2'
                    ]
                ]
            ],
            [
                'name' => 'Parent #2-3',
            ],
            [
                'name' => 'Parent #2-4',
            ],
        ],
    ],
    [
        'name' 'Grandparent #3',
        'children' => [
            [
                'name' => 'Parent #3-1'
            ]
        ]
    ]
]

My code:
Data set is minimal reproducible example.
There can also be a infinite amount of # after the previous.
The 2nd hashtags (#2-1-1) are used to provide clarity, not part of the issue.
$array = [
    "# Grandparent #1",
    "# Grandparent #2",
    "## Parent #2-1",
    "### Child #2-1-1",
    "## Parent #2-2",
    "### Child #2-2-1",
    "### Child #2-2-2",
    "## Parent #2-3",
    "## Parent #2-4",
    "# Grandparent #3",
    "## Parent #3-1",
];
function structure($lines, $target = 1) {
    $data = [];
    $parent = 0;
    $i = 0;
    foreach($lines as $line) {
        $current = strlen(preg_split('/\s+/', $line)[0]);
        if ($current == $target) {
            $parent = $i;
            $data[$parent]['name'] = $line;
        }
        if ($current != $target) {
            $data[$parent]['children'][] = $line;
        }
        $i++;
    }
    // I tried placing structure function here again but it gives me errors
    // structure($data[$parent]['children'], $target + 1);
    return $data;
}

$data = structure($array);

I've got the Grandparent working but I can't seem to get it to go over the rest. I've tried putting the loop in side itself to make it search the other children but it will just run infinitely. And I can't put a foreach inside a foreach and so on because the amount of hashtags can be whatever length.

A: I didn't have much time to study this, but this is what I came up with...

*

*loop through the array of lines

*separate the sequence of hash symbols from the member name

*measure the length of the hash symbol string and compare it against the current level

*for every instance of a "parent" on a given level, create a reference variable and push it into the output array (tree)

*everytime you encounter a new "parent" on a given level, the old reference must be destroyed and the new reference declared

*when recursion is necessary, ONLY pass direct descendants into the recursive call

*the recursive call needs to be conditionally called at the end of the loop so that unprocessed descendants are handled

Code: (Demo)
function recurse(array $lines, int $level = 1): array
{
    $tree = [];
    $directDescendants = [];
    foreach ($lines as $line) {
        [$hashes, $name] = explode(' ', $line, 2);
        $depth = strlen($hashes);
        if ($depth === $level) {
            if ($directDescendants) {
                $parent['children'] = recurse($directDescendants, $level + 1);
            }
            $directDescendants = [];      // reset collection of direct descendants
            unset($parent);               // destroy reference
            $parent = ['name' => $name];  // name the member
            $tree[] = &$parent;           // push the reference variable into the tree
        } elseif ($depth > $level) {
            $directDescendants[] = $line; // collect only direct descendants of current level parent member
        }
    }
    if ($directDescendants) {
        $parent['children'] = recurse($directDescendants, $level + 1);
    }
    return $tree;
}

var_export(recurse($array));


text:
Q: How to wrap multiple dll in a single dll
Possible Duplicate:
Merging .net managed dlls

I create a test project in which I referenced a dll from some other project. When I build my test project, I see different dll for test project and the referenced dll. I want to wrap both dll's in a single dll.
How can I do it.

A: Take a look at ILMerge:
http://www.microsoft.com/downloads/en/details.aspx?familyid=22914587-b4ad-4eae-87cf-b14ae6a939b0&displaylang=en
http://www.codeproject.com/KB/dotnet/mergingassemblies.aspx
With ILMerge you can merge a bunch of assemblies by running the command like:
ilmerge /out:MergedAssembly.dll ProjectAssembly1.dll ProjectAssembly2.dll ProjectAssembly3.dll
This will merge 3 assemblies into a single one.


text:
Q: Encoding Issue in R htmlParse XML I try to scrape a website but can't handle this encoding issue:
# putting together the url:
search_str <- "allintitle:amphibian richness OR diversity"
url <- paste("http://scholar.google.at/scholar?q=",
             search_str, "&hl=en&num=100&as_sdt=1,5&as_vis=1", sep = "")

# get content and parse it:
doc <- htmlParse(url)

# encoding isssue, like here..
xpathSApply(doc, '//div[@class="gs_a"]', xmlValue)

  [1] "M Vences, M Thomas… - …  of the Royal  …, 2005 - rstb.royalsocietypublishing.org"
  [2] "PB Pearman - Conservation Biology, 1997 - Wiley Online Library"
  [3] "D Vallan - Biological Conservation, 2000 - Elsevier"
  [4] "LB Buckley, W Jetz - Proceedings of the Royal  …, 2007 - rspb.royalsocietypublishing.org"
  [5] "Mà Rodríguez, JA Belmontes, BA Hawkins - Acta Oecologica, 2005 - Elsevier"
  [6] "TJC Beebee - Biological Conservation, 1997 - Elsevier"
  [7] "D Vallan - Journal of Tropical Ecology, 2002 - Cambridge Univ Press"
  [8] "MO Rödel, R Ernst - Ecotropica, 2004 - gtoe.de"
# ...

any pointers?
> sessionInfo()
R version 2.15.1 (2012-06-22)
Platform: x86_64-pc-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=German_Austria.1252  LC_CTYPE=German_Austria.1252
[3] LC_MONETARY=German_Austria.1252 LC_NUMERIC=C
[5] LC_TIME=German_Austria.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] RCurl_1.91-1.1 bitops_1.0-4.1 XML_3.9-4.1

loaded via a namespace (and not attached):
[1] tools_2.15.1

> getOption("encoding")
[1] "native.enc"

A: This worked to some degree for me
doc <- htmlParse(url,encoding="UTF-8")
head(xpathSApply(doc, '//div[@class="gs_a"]', xmlValue))
#[1] "M Vences, M Thomas… - …  of the Royal  …, 2005 - rstb.royalsocietypublishing.org"
#[2] "PB Pearman - Conservation Biology, 1997 - Wiley Online Library"
#[3] "D Vallan - Biological Conservation, 2000 - Elsevier"
#[4] "LB Buckley, W Jetz - Proceedings of the Royal  …, 2007 - rspb.royalsocietypublishing.org"
#[5] "MÁ Rodríguez, JA Belmontes, BA Hawkins - Acta Oecologica, 2005 - Elsevier"
#[6] "TJC Beebee - Biological Conservation, 1997 - Elsevier"

thou
xpathSApply(doc, '//div[@class="gs_a"]', xmlValue)[[81]]

was displaying incorrectly on my windows box for example.
switching to Font DotumChe using GUI preferences however showed it displaying correctly so it may just be a display issue not a parsing one.


text:
Q: wxPython installation on ubuntu 16.04 taking very long time I am trying to install wxPython on ubuntu 16.04 for python3 using pip3, but after downloading the requirements it stuck in installing it. I have installed the required development packages and their dependencies as mentioned here.

A: It takes a long time to build, be patient and it will probably make it through if the needed library dependencies are installed.  You can use the --verbose flag on pip to see what it is doing along the way.
Alternatively, there are already wheel files available for Ubuntu 16.04, see https://wxpython.org/pages/downloads/

A: As suggested by RobinDunn use Linux Wheels:
pip install -U \
    -f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-16.04 \
    wxPython

A: sudo apt install python3-wxgtk4.0
package in Ubuntu 20.04 which will get you version 4.0.7. Works also 22.04


text:
Q: Стилизация checkbox в JSP Есть страничка с стилизированым средствами CSS3 checkbox.
В таком коде работает нормально:

    <input type = "checkbox" name = "agree" id="flag_choice" required>

А вот в таком варианте с тегом JSP (сами теги работают исправно) значок галочки уже не отображается:

    <form:checkbox id="flag_choice" path="agreementDTO"/>

Подскажите пожалуйста в чем проблема.
Вот сам CSS:
#checkbox {
    display: inline-block;
    vertical-align: middle;
}

#flag_choice {
    width: 20px;
    height: 20px;
    display: none;
}

.agree_checkbox_label {
    display: inline-block;
    font-size: 13px;
}

.agree_checkbox_label:before {
    content: "";
    width: 16px;
    height: 16px;
    margin-left: 90px;
    margin-right: 8px;
    margin-top: -5px;
    border-radius: 3px;
    box-shadow: inset 0px 2px 3px 0px rgba(0, 0, 0, .3), 0px 1px 0px 0px
rgba(255, 255, 255, .8);
    background-color: white;
    border: 1px solid green;
    display: inline-block;
    font-size: 13px;
    position: absolute;
}

#flag_choice:checked + .agree_checkbox_label:before {
    content: "\2713";
    text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
    font-size: 15px;
    color: green;
    text-align: center;
    line-height: 15px;
}

JSP генерирует вот такой HTML (не понятно почему 2 инпута):

    <input id="flag_choice" name="agreementDTO" required="true"
      type="checkbox" value="true">
    <input type="hidden" name="_agreementDTO" value="on">

A: Решение вопроса следующее:
#flag_choice:checked + .agree_checkbox_label:before

(тут выбор следующего элемента).
заменен на:
#flag_choice:checked ~ .agree_checkbox_label:before

(тут выбор всех элементов такого типа среди дочерних элементов #checkbox)
спасибо Mikhail Vaysman