text:
Q: Laravel query order with order_details using id Stuck on this.
I use this same query without Id to get all the successfully get all this data.
$orders = $this->order
    ->with('orderDetails', 'orderDetails.product')
    ->today()
    ->get();

Relationships
Order:
public function orderDetails(){
    return $this->hasMany('App\OrderDetail', 'order_id');
}

OrderDetail:
 public function order()
{
    return $this->belongsTo('App\Order', 'order_id', 'id');
}

public function product()
{
    return $this->belongsTo('App\Product', 'id_products', 'id');
}

But trying to use the same thing to get data for a particular order doesn't return the order_details.
   public function invoice(Request $request, $id)
  {
    $ordered = $this->order
        ->find($id)
        ->with('orderDetails', 'orderDetails.product');

   return response()->json($ordered);
  }

Why is it behaving differently when passed an id?

A: Try to use just this way:
$ordered = $this->order->find($id);

return response()->json($ordered);

The laravel already turned to relationships based on no mapping that you enter in the model.
In this case, your orderDetails in your response will look like this:
Order: {
Id: "1",
Xpto: "whatever",
OrderDetails: {
Id: "1"
}
}

A: When you use find the query is executed before other directives. You need to be using where:
$ordered = $this->order
    ->where('order_id', $id)
    ->with('orderDetails', 'orderDetails.product')
    ->get();


text:
Q: How to remove iframe highlight border on focus? Wondering if it's possible to remove the dotted border that appears on focus of an iframe embedded within a page? The iframe contains a form that is tabbed to from some input boxes on the page that contains it. The focus border looks unsightly and would like to get rid of it. Have tried setting frameborder to 0 within the iframe, adding a hidefocus attribute and setting the border and outline to 0 through CSS to no avail. Any help would be greatly appreciated!

A: if iframe is not on the same domain, it is not possible

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find the direction in which a function does not change at a point? I have a function $f(x, y)$ and a point $P = (x_{0}, y_{0})$. I need to find the direction $\vec{u} = (a, b)$, among four options, in which the functon $f$ does not change. How can I do that?
UPDATE: So I just calculate $D_{\vec{u}} f(x_{0}, y_{0}) = f_{x} (x_{0}, y_{0}) \cdot a + f_{y} (x_{0}, y_{0}) \cdot b$ and look in which of the given directions it is zero, right?

A: Compute the vector $$\mathbf v = \begin{bmatrix}
-\frac{\partial f}{\partial y} (x, y) \\
\frac{\partial f}{\partial x} (x, y)
\end{bmatrix}.
$$
The instantaneous rate of change of $f$ in the direction $\mathbf v$ (at $(x, y)$) will be zero.


text:
Q: What is the default height of an HTML button? I want to make my button height just a slight bit bigger than the default, but I don't know what the default is. I want to make it dynamic, preferably using % or vh/vw, so that it looks good on every device. I also want to know the %/vw/vh that is default.
I used chrome to find the height of the body tag, in relation to the button height, and then I set the button height to 9vh with css, but this didn't work, the body's height just increased. I then set the body height to 100%, but this didn't make a difference.
My code:
.choice{
    width: calc(50vw - 12px);
    height: 25vh;
    text-align: center;
    line-height: 1em;
    font-size: 3.5vh;
    overflow: hidden;
    white-space: nowrap;
}

button, input[type="submit"]{
  -webkit-transition-duration: 0.4s;
  transition-duration: 0.4s;
  cursor: pointer;
  background-color: #0099FF;
  color: #FFFFFF;
  border-radius: 2px;
  border: 2px solid #0099FF;
  margin: 2px;
  height: 9vh;

}

button:hover, input[type="submit"]:hover{
    background-color: #FFFFFF;
    color: #000000;
}

I expected it to look the same as it would when the code would be like this ( I removed the height attribute in the button, input[type="submit"] section, but the buttons were extremely large instead!:
.choice{
    width: calc(50vw - 12px);
    height: 25vh;
    text-align: center;
    line-height: 1em;
    font-size: 3.5vh;
    overflow: hidden;
    white-space: nowrap;
}

button, input[type="submit"]{
  -webkit-transition-duration: 0.4s;
  transition-duration: 0.4s;
  cursor: pointer;
  background-color: #0099FF;
  color: #FFFFFF;
  border-radius: 2px;
  border: 2px solid #0099FF;
  margin: 2px; /* height used to be specified below */

}

button:hover, input[type="submit"]:hover{
    background-color: #FFFFFF;
    color: #000000;
}

A: I can't help but think that this is a poorly posed question.

*

*Why do you want the button height to be "slightly bigger than default"? Presumably, you'd either want a fixed height, or a dynamic height that responds to the screen size. I fail to understand why you'd want an arbitrary size based upon HTML's default values. The default height of the button will be dependent on the font size anyways.

*If you don't set a body height, then it will be determined by the size of it's children. If you have a body tag with so set height, and then add a button with 9vh, your body will also be 9vh.
Edit:
If you're aiming to have the button have dynamic height based upon the body, then you need to set a body height, and then set the button's height to a percentage of its parent. E.g. body height set to "100vh", and button height set to "70%" or something to that effect.


text:
Q: Two players game, problem I have this type of problem: two boys have to divide 10 playstation games. The strategy is that first one choose a game, then the second another and so on, by having a common goal to be both "the most happy they can". Obviously the two boys have different tastes about the games, so for each game they could have different utility. I want to ask if a problem like that could be solved with Game Theory, and if yes which part of Game Theory I have to look at. Since it is very long theory, and less time ahahah.
Thanks to all, have a nice week :)


text:
Q: webpack рендер .png помогите с Webpack. не рендерит *.png
собирает в dist оно не отображает на странице . куда смотреть ?

<img src="<%=require('../../images/img.png').default%>"/>

A: Попробуйте так.

A: Решено . возможно кому-то поможет :
был пробел в пути "/> после <%= require....


text:
Q: How to send JS object as JSON correct? I have the following JS Object:
json =
            {
                "category_id": category,
                "subcategory_id": subcategory,
                "offer_type": type_offer,
                "features": []
            };

I tried to send this object as JSON like:
$.ajax({
            type: 'POST',
            url: '/add',
            data: json,
            success: function (data) {
            },
            contentType: "application/json",
            dataType: 'json'
        });

Is it right? Or I need to make some preparations before?
Now I use this part of code:
formObj = $("#form_add").serialize();

var json = {};

var wrapperObj = {json: json, form: formObj};

    $.ajax({
                type: 'POST',
                url: '/add',
                data: JSON.stringify(wrapperObj),
                success: function (data) {
                   // TODO
                },
                contentType: "application/json",
                dataType: 'json'
            });

Is it right way? When I package two object inside one and after stringify?

A: You need to use JSON.stringify to make it a valid json
$.ajax({
            type: 'POST',
            url: '/add',
            data: JSON.stringify(json),
            success: function (data) {
            },
            contentType: "application/json",
            dataType: 'json'
        });

A: You can also use jQuery short-hand methods.
$.post('/add', json).done(function() {
     // Handle response here
  });

A: I think you should use JSON.stringify first:
$.ajax({
            type: 'POST',
            url: '/add',
            data: JSON.stringify(json),
            success: function (data) {
            },
            contentType: "application/json",
            dataType: 'json'
        });


text:
Q: Cannot add roles to a group in keycloak-admin-client Technology.

*

*java11

*springboot 2.7.2

*docker quay.io/keycloak/keycloak:19.0.2

Prerequisite.

*

*realmService.create(); // 大元のRealmなので先頭に実行

*clientScopeService.create(); // clientに設定するのでclientsServiceより先に実行

*clientsService.create();

*realmRoleService.create();

*groupService.create(); // group に roleを設定するのでrealmRoleServiceより後に実行

 // groupService.create()
 public void create() {

        for (GroupEnum groupEnum : GroupEnum.values()) {
            GroupRepresentation groupRepresentation = new GroupRepresentation();
            groupRepresentation.setName(groupEnum.getName());

            List<String> roles = Lists.newArrayList();
            roles.add(RoleEnum.READ.getName());
            roles.add(RoleEnum.WRITE.getName());

            groupRepresentation.setRealmRoles(roles);
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

            getGroupsResource().add(groupRepresentation);
        }

    }

After creating the realm role in No4.
When I try to add a realm role while creating a group in No5, I cannot.
Confirmed that the role has been added before attempting to add it to the group.
Confirming that realm roles can be added to groups in the keycloak GUI.


text:
Q: How to create undirected (i)graph in R for protein-interaction data with tissue information? I am new to bioinformatics in general and would really appreciate some help and tips with the project Im working on.
My data of protein-protein interactions is stored in a table (in MySQL) with binary information about tissue-specificity. Now I am trying to create an undirected graph with igraph in R, but could not understand what type of data structure I should use without losing the tissue-information (Adjacency matrix, edge list..?).
Thank you in advance!
The data itself about 200k rows, but here is an example of the structure:

symbol1
symbol2
adipose_tissue
adrenal_gland
amygdala
bone

POT1
PRMT7
0
0
0
0

CNBP
HNRNPAB
1
1
1
1

TRIAP1
BAG3
1
1
1
1

NR5A1
RALY
0
1
0
0

TPI1
CCDC8
1
1
1
1

MRPS22
BARD1
0
0
0
1

TOP2A
CCDC8
0
0
0
1

MYH9
TRIM72
0
0
0
0

ATXN7
TAF12
1
0
0
1

PSEN1
STT3B
1
1
1
1

ATP5F1
TSG101
1
1
1
1

BRCA1
UTP4
0
0
1
1

A: Bioinformatics apart, this is a question of data-wrangling in igraph. Igraph is capable of building graph-objects from both matrices and lists in many formats, so one should avoid too much pre-conversion. I suggest you build your graph using graph_from_data_frame()
I assume that the data structure described above is relational and therefore basically already an edge-list of relations between proteins uniprot2 and uniprot2. This mockup sample-data would then mimics your data-structure.
data <- data.frame(uniprot1 = c('Q94X','Q95X','Q435','QUUU','0982'),
                   uniprot2 = c('QUUU','Q94X','Q95X','Q95X','Q94X'),
                   symbol = c('Symbol A', 'Symbol B', 'Symbol C','Symbol D',' Symbol E'),
                   adipose_tissue = c(1,0,0,1,1),
                   bone=c(0,0,0,1,1))

To keep variables other than just the relational edges between vertices, you can either create them alongside your graph-objects, or add and manipulate them later manually.
Attributes naturally belong either to vertices or to edges. A veracity-attribute in your data would be a protein name, size or other characteristic. An edge-attribute would be the relational strength, type, or any other characteristic of the link between two proteins. If your graph would have a veracity called understandable_name_of_protein you'd access it like so:
V(g)$understandable_name_of_protein
Edge-attributes follow the same principle through E(g)$attribute. When you load the example data above, all your edge-attributes should jump right into your graph like this:
# Build an undirected graph using the edges described in `data`
g <- graph_from_data_frame(data, directed=FALSE)
# Check sure that data was correctly imported as edge-attributes
E(g)$bone
# Add the edge-attribut `color` which will be displayed when plotting the graph
E(g)$color <- ifelse(E(g)$bone == 0, 'green','black')
# plot to see the graph with the bone-attribute visible as edge-color
plot(g)


text:
Q: Homology of a boundary in ambient manifold Let $M$ be a compact oriented $m$-dimensional manifold with a boundary $N \neq \emptyset$. Then $N$ is a closed oriented $m-1$-dimensional manifold.
Is it always true that the homology class $[N]_M$ has to vanish in $H_{m-1}(M, \mathbb Z)$?

A: If $M$ is a compact oriented $m$-dimensional manifold with non-empty boundary $N$, then the image of the fundamental class of $[N]$ with respect to the natural inclusion $i(n)=n$ lives in $H_{m-1}(M)$, not in top homology of $M$ (you wrote $n$ but I assume you meant to write $m$). I think it is true that the image will always be zero, since it is a boundary. If you assume that everything is smooth and you work with real coefficients, then the image will be zero by Stokes theorem. More concretely, if you have a closed $m-1$ form $\omega$, then $\int_N \omega = \int_{\partial M} \omega = \int_M d\omega=0$, hence the image of $[N]$ is zero.


text:
Q: Memcached does not respect ordering of tuples I am using memcached through pylibmc. I am saving a tuple with four elements:
(A, B, C, D)

And reading the same key returns a different order:
(B, C, D, A)

My codebase is complicated, so the problem could be something else. I would like to know if there is a known issue with memcached and tuples before I spend more time investigating this.

A: It won't be memcached causing the problem as all it stores is the raw data it's sent. It doesn't understand data structures within the values it stores and certainly doesn't mess around with them.
pylibmc could feasibly cause the problem if its serialization/deserialization logic was flawed, but I would be absolutely amazed if this was the case.
If you want to rule pylibmc out, you could serialize the data yourself before passing it on directly to memcached (by perhaps using something like the json or cPickle libraries).


text:
Q: are .appspot google app engine sites restricted in crawl / search engine rankings? i'm not recieving any hits on sites with "*.appspot.com" addresses. I've set up google webmaster and everything. Are you required to have a custom domain to show up in google search indexes?

A: You don't need a custom domain to show up in google search.
There are many examples of ranking sites, for example: https://www.google.de/#q=fix+the+road


text:
Q: Will leaving MySqlConnection idle cause it to timeout? I'm currently developing game server, that uses MySQL for storage.
The question is: if I will leave MySQL Connection to idle I think it will cause it to timeout?
If yes would it be wise and possible to turn off connection idle timeout?
Or maybe I should before every query check it out if connection hasn't been closed and open it again?
But then another question arises: Should I use async methods or create new thread that would be responsible for MySQL, in order to not pause main thread because then all the sync between players would be interrupted?

A: It depends on your server settings but you must anticipate that MySQL connections will eventually be terminated for being idle. The amount of time that elapses before they're considered dead varies considerably.
The normal practice here is to use a connection pool that automatically recovers from connection-related errors by creating a new connection and retrying the query.
Most database drivers will return a very specific exception if you're operating on a closed connection. These can be caught and handled accordingly.


text:
Q: NLog - Configure log file name from appsettings in web.config What i want is to pull the Log File path from my Web.config appsettings section.
The scenario is that, the deployment team would replace all the files while deployment except the web.config. Hence even if i set up my NLog Config File, it would be replaced in the next deployment and all my settings would be lost.
Is there a way that I could read the appsettings from my config and use it to set my log file path?
<target xsi:type="File" name="FileLog" fileName="PULL_LOG_PATH_FROM_WEB_CONFIG/${shortdate}.log">

A: Use NLog.Extended and use
${appsetting:key1}.
So
<target xsi:type="File" name="FileLog" fileName="${appsetting:key1}/${shortdate}.log" />

See docs for ${appsetting}
update: this is currently only supported for ASP.NET and not for ASP.NET Core. See issue for ASP.NET Core: https://github.com/NLog/NLog/issues/2334


text:
Q: Magento 2 code to get Magento 1 product detail via rest api I would like to use Magento 1 rest api to get the product details in Magento 2.
Can anybody help me out on magento 2 code for getting the product details from magento 1.
http://devdocs.magento.com/guides/m1x/api/rest/introduction.html


text:
Q: Swap letters in a string I need to swap letters in a string with the following rules:

*

*A is replaced by T

*T is replaced by A

*C is replaced by G

*G is replaced by C

For example: ACGTA should become TGCAT
What would be the best way to resolve this?

A: Searching for java "A to T, T to A" found this suggestion:
String sequence = "AATTTCTCGGTTTCAAT";
sequence = sequence.replace("A", "t")
                   .replace("T", "a")
                   .replace("C", "g")
                   .replace("G", "c")
                   .toUpperCase();
System.out.println(sequence);

This is a simple and concise solution that works for your specific situation and will have acceptable performance if your DNA strings are relatively short. For a more general solution for handling large amounts of data you should iterate over the characters one by one and build a new string. Or as polygenelubricants pointed out - consider a storage format that only uses 2 bits per base instead of 16.

A: I would go for a more general solution like this:
public String tr(String original, String trFrom, String trTo) {
  StringBuilder sb = new StringBuilder();

  for (int i = 0; i < original.length(); ++i) {
    int charIndex = trFrom.indexOf(original.charAt(i));
    if (charIndex >= 0) {
      sb.append(trTo.charAt(charIndex));
    } else {
      sb.append(original.charAt(i));
    }
  }

  return sb.toString();
}

Calling the function like this would give the result you need:
tr("ACGTA", "ATCG", "TAGC")

So the function is pretty much the same as unix tr utility:
echo ACGTA | tr ATCG TAGC

A: Like I explained yesterday, Strings are immutable, you can't change a String, you have to create a new one and replace the old one.
You can solve your problem like this:
String s = "ACGTA";
StringBuilder sb= new StringBuilder();
for (char c:s.toCharArray()) {
  switch(c) {
    case 'A': sb.append('T');break;
    case 'T': sb.append('A');break;
    case 'C': sb.append('G');break;
    case 'G': sb.append('C');break;
    default: //handle error here -> invalid char in String
  }
}
s = sb.toString();

The advantage of this solution is that you just don't create too many String objects (every 'replace' operation creates a new String and this can kill performance if you have to revert a lot of dna sequences)

Here is more performant version based on the very helpful comments from polygenelubricants and rsp:
String s = "ACGTA";
char[] reverse = new char[s.length()];
for (int i = 0; i < reverse.length; i++) {
  switch(s.charAt(i)) {
    case 'A': reverse[i] = 'T';break;
    case 'T': reverse[i] = 'A';break;
    case 'C': reverse[i] = 'G';break;
    case 'G': reverse[i] = 'C';break;
    default: //handle error here -> invalid char in String
  }
}
s = new String(reverse);

A: DNA has a small alphabet. You can use a lookup table, replacing some statements with a simple array indexing.
This approach:

*

*Traverses the sequence only once.

*Eliminates the conditional statements.

*Can be stable in terms of letter case, which is sometimes used to communicate information in DNA sequences.

*Can handle IUPAC ambiguity codes.

*Can handle gaps.

*Can easily provide a reverse complement.

First, you need a lookup table.
private static final String COMPLEMENT_TABLE
  // 0123456789ABCDEF0123456789ABCDEF
  = "                                " // 0-31
  + "             -                  " // 32-63
  + " TVGH  CD  M KN   YSAABWXR      " // 64-95
  + " tvgh  cd  m kn   ysaabwxr      "; // 96-127
  //  ABCDEFGHIJKLMNOPQRSTUVWXYZ

private static final byte[] COMPLEMENT_TABLE_BYTES
  = COMPLEMENT_TABLE.getBytes( StandardCharsets.US_ASCII );

Then, you can find the complement's bases by a simple table lookup.
public static byte[] complement( byte[] sequence ) {
    int length = sequence.length;
    byte[] result = new byte[ length ];

    for ( int i = 0; i < length; ++i ) {
        result[i] = COMPLEMENT_TABLE_BYTES[ sequence[i] ];
    }

    return result;
}

If desired for convenience with small sequences, you can provide a method that accepts and returns a String.
public static String complement( String sequence ) {
    byte[] complementBytes = complement(
      sequence.getBytes( StandardCharsets.US_ASCII ));
    return new String( complementBytes, StandardCharsets.US_ASCII );
}

The reverse complement can be computed in the same loop.
public static byte[] reverseComplement( byte[] sequence ) {
    int length = sequence.length;
    byte[] result = new byte[ length ];

    for ( int i = 0; i < length; ++i ) {
        result[ (length - i) - 1] = COMPLEMENT_TABLE_BYTES[ sequence[i] ];
    }

    return result;
}

public static String reverseComplement( String sequence ) {
    byte[] complementBytes = reverseComplement(
      sequence.getBytes( StandardCharsets.US_ASCII ));
    return new String( complementBytes, StandardCharsets.US_ASCII );
}

Using your example sequence:
public static void main(String[] args) {
    String sequence = "ACGTA";

    String complementSequence = complement( sequence );
    System.out.println( String.format(
       "complement(%s) = %s", sequence, complementSequence ));

    String reverseComplementSequence = reverseComplement( sequence );
    System.out.println( String.format(
      "reverseComplement(%s) = %s", sequence, reverseComplementSequence ));
}

We get this output:
complement(ACGTA) = TGCAT
reverseComplement(ACGTA) = TACGT


text:
Q: Adding more threads to program resulted in longer execution time for calculating trapezoidal integration I am working on a multi-threaded numerical integration program using the trapezoidal rule.
I have a struct which contains six items:
typedef struct trapezoidalIntegrationThread{
    float a;
    float b;
    int n;
    float h;
    double res;
    float elTime;
}threadParams;

a is the left end point, b is the right end point, n is the number of trapezoids, h is the height, res is the result calculated within compute_with_pthread, and finally, elTime is the elapsed time for compute_with_pthread for benchmarking.
Here is my code in main:
int n = NUM_TRAPEZOIDS;
float a = LEFT_ENDPOINT;
float b = RIGHT_ENDPOINT;

pthread_t masterThread;
pthread_t slaveThread[NUM_THREADs];
threadParams *trapThread;

for(i = 0; i < NUM_THREADs; i++) {
    trapThread = (threadParams *) malloc(sizeof(threadParams));
    trapThread->a = a;
    trapThread->b = b;
    trapThread->n = n;
    trapThread->h = (b - a) / (float) n;

    if (pthread_create(&slaveThread[i], NULL, compute_using_pthreads, (void *) trapThread) != 0) {
        printf("Looks like something went wrong..\n");
        return -1;
    }
}

for(i = 0; i < NUM_THREADs; i++) {
    pthread_join(slaveThread[i], NULL);
}

pthread_exit((void *) masterThread);

I am basically creating the number of threads defined in NUM_THREADS (let's assume this value is 4). I am allocating how much memory the struct needs, and setting the pre-defined values of:
#define LEFT_ENDPOINT 5
#define RIGHT_ENDPOINT 1000
#define NUM_TRAPEZOIDS 100000000
#define NUM_THREADs 8   /* Number of threads to run. */

Next, I create my pthreads, and call the compute_using_pthreads function:
void *compute_using_pthreads(void *inputs)
{
    double integral;
    int k;
    threadParams *args = (threadParams *) inputs;
    unsigned long p_micros = 0;
    float p_millis = 0.0;
    clock_t p_start, p_end;

    float a = args->a;
    float b = args->b;
    int n = args->n;
    float h = args->h;

    p_start = clock();

    integral = (f(a) + f(b))/2.0;

    for (k = 1; k <= n-1; k++) {
        integral += f(a+k*h);
    }

    integral = integral*h;

    p_end = clock();
    p_micros = p_end - p_start;
    p_millis = p_micros / 1000;

    args->res = integral;
    args->elTime = p_millis;
}

I ran this program and compared it against a non-multithreaded function:
double compute_gold(float a, float b, int n, float h)
{
    double integral;
    int k;

    integral = (f(a) + f(b))/2.0;

    for (k = 1; k <= n-1; k++) {
        integral += f(a+k*h);
    }

    integral = integral*h;

    return integral;
}

So here are the results:
Run-time of compute_gold:
~3000 ms

Run_time of compute_with_pthread:
Using 1 thread: ~3000 ms

Using 2 threads: ~6000 ms

Using 4 thrads: ~12000 ms

....

So for some reason, the more threads I added, the execution took n-threads more time to execute. I can't for the life of me figure out why this is happening, as I am quite new to C programming =/


text:
Q: LU-factorization with OpenMP seems to slow, need advice I have written a code which performs LU-factorization with OpenMP. I feel like the code is performing too slow. The computer I am working on have 16 cores and the time for 16 threads is 12.5s and for 4 threads 14.3s. This is the section of the code where the parallelization is happening. I am new to C programming and feel like I am missing something that is slowing the multithreading down.
    /*__Initialize lock__*/
omp_lock_t lock[n];

for(i=0;i<n;i++)
   omp_init_lock(&lock[i]);

/*___Create theads____*/
#pragma omp parallel private(i,j,k,thread) num_threads(nThreads)
{
  thread=omp_get_thread_num();
  #pragma omp for schedule(static)
  for(i=0;i<n;i++) omp_set_lock(&lock[i]);
  if(thread==0)
    omp_unset_lock(&lock[0]);

  for(i=0;i<n;i++){
    div=1/U[i][i];
    #pragma omp for schedule(static)
      for(j=i+1;j<n;j++)
         L[j][i]=U[j][i]*div;

    #pragma omp for schedule(static)
      for(j=i+1;j<n;j++){
        for(k=i;k<n;k++)
           U[j][k]=U[j][k]-L[j][i]*U[i][k];
        if(j==i+1)
           omp_unset_lock(&lock[i+1]);
      }
}
}

A: Based on the code that you have provided it seems to me that you do not need any lock whatsoever, try the following parallel version:
#pragma omp parallel num_threads(nThreads)
{
  for(int i=0;i<n;i++){
      div=1/U[i][i];
      #pragma omp for schedule(static)
      for(j=i+1;j<n;j++)
         L[j][i]=U[j][i]*div;

      #pragma omp for schedule(static)
      for(int j=i+1;j<n;j++){
        for(int k=i;k<n;k++)
           U[j][k]=U[j][k]-L[j][i]*U[i][k];
      }
}


text:
Q: Kendo AutoComplete set custom CSS class instead of the default? Kendo Autocomplete input has default class named k-input.
I would like to ask, how can I set complete custom class (width, height, etc) for these input?
I tried to find some informations in documentation but without luck:
http://docs.telerik.com/kendo-ui/api/javascript/ui/autocomplete#fields-options
Could somebody tell me how can I do it please?
Thanks for any advice.

A: Try this:
$("#yourElementsId").removeClass("k-input");

A: Assuming that the id of your autocomplete is countries do:
var ac = $("#countries").kendoAutoComplete({
    ...
}).data("kendoAutoComplete");
// Setting width
ac.wrapper.css("width", "300px");
// Setting height
ac.input.css("height", "3em");

Or using CSS for setting height:
#countries {
    height: 3em;
}

NOTE You can also set the height using only CSS but you cannot set the width only to one autocomplete. The CSS would be:
span.k-widget.k-autocomplete.k-header {
    width: 500px;
}


text:
Q: Generate color palette from image in PHP I need to create color palette with PHP. I use code like this:
for ($x = 0; $x < $this->width; $x += $level) {
    for ($y = 0; $y < $this->height; $y += $level) {
        $index = imagecolorat($this->workingImage, $x, $y);
        $rgb = imagecolorsforindex($this->workingImage, $index);
        $color = $this->getClosestColor($rgb["red"], $rgb["green"], $rgb["blue"]);
        $hexarray[] = $this->RGBToHex($color[0], $color[1], $color[2]);
    }
}

How can I do it? For any picture I need at least 10 colors. I am tried to use another methods, pixelate image before receiving color palette, but it is not helping for me.

A: Unfortunately you have mixed up your starting image with your incorrect results and your desired results, so I have separated it out as image.png below:

Now, I plan to use pnmquant which is part of the NetPBM package which is available precompiled and ready to install on most platforms from SourceForge.
So, first I need to convert your PNG to NetPBM's PPM format for the pnmquant tool to work - I'll use pngtopnm for that. Then I want to extract the colours as a swatch and enlarge the swatch so you can see something bigger than the extracted 21 pixels -I'll use ImageMagick for that, and I want to make a text representation of it so you can see the numbers, and I'll use ImageMagick for that.
pngtopnm image.png | pnmquant 21 | pnmtopng > result.png

convert image.png pnm:- | pnmquant 21 | convert - -unique-colors -scale 400x swatch.png

convert image.png pnm:- | pnmquant 21 | convert - -unique-colors -depth 8 txt:

# ImageMagick pixel enumeration: 21,1,65535,srgb
0,0: (65278,9766,2827)  #FE260B  srgb(254,38,11)
1,0: (65278,15163,2570)  #FE3B0A  srgb(254,59,10)
2,0: (65535,10794,5140)  #FF2A14  srgb(255,42,20)
3,0: (65535,11565,5140)  #FF2D14  srgb(255,45,20)
4,0: (65278,11308,5140)  #FE2C14  srgb(254,44,20)
5,0: (65535,11822,5140)  #FF2E14  srgb(255,46,20)
6,0: (65278,11822,5140)  #FE2E14  srgb(254,46,20)
7,0: (65278,19532,3341)  #FE4C0D  srgb(254,76,13)
8,0: (65278,20817,3855)  #FE510F  srgb(254,81,15)
9,0: (65278,16962,5140)  #FE4214  srgb(254,66,20)
10,0: (65535,20303,4369)  #FF4F11  srgb(255,79,17)
11,0: (65278,20817,4626)  #FE5112  srgb(254,81,18)
12,0: (63479,33410,28270)  #F7826E  srgb(247,130,110)
13,0: (62451,56540,55769)  #F3DCD9  srgb(243,220,217)
14,0: (62708,61166,59110)  #F4EEE6  srgb(244,238,230)
15,0: (62451,62708,62965)  #F3F4F5  srgb(243,244,245)
16,0: (65278,63736,62965)  #FEF8F5  srgb(254,248,245)
17,0: (62194,65278,65535)  #F2FEFF  srgb(242,254,255)
18,0: (65278,64250,63736)  #FEFAF8  srgb(254,250,248)
19,0: (65535,65535,65535)  #FFFFFF  white
20,0: (65278,65278,65278)  #FEFEFE  srgb(254,254,254)

As regards PHP, you can shell out and exec the command-line tools above, or look at the source code and adapt to PHP.


text:
Q: Busy-waiting Future in Rust Tokio I want to implement a Future that busy-waits on its completion.
According to this link, this is one option
impl Future for Delay {
    type Output = &'static str;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>)
        -> Poll<&'static str>
    {
        if Instant::now() >= self.when {
            println!("Hello world");
            Poll::Ready("done")
        } else {
            // Ignore this line for now.
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    }
}

What I am worried about is this future starving out other tasks. Is it guaranteed that if I call wake inside the Future that returns Pending, that this wake will execute as a last item after epol, timers, and any other wakes called before?
Is this the good way to implement busy-wait Future?


text:
Q: Re-export third party definitions in typescript npm module We have a private npm logging module based on pino and using typescript. We are compiling and publishing to npm. When importing the module into an application, we get the errors:
node_modules/@scope/logging/lib/index.d.ts(1,23): error TS2688: Cannot find type definition file for 'pino'
node_modules/@scope/logging/lib/index.d.ts(2,23): error TS7016: Could not find a declaration file for module 'pino'. 'C:/app/node_modules/pino/pino.js' implicitly has an 'any' type. Try `npm install @types/pino` if it exists or add a new declaration (.d.ts) file containing `declare module 'pino';`

package.json
{
  "name": "@scope/logging",
  "version": "1.0.0",
  "main": "lib/index.js",
  "typings": "lib/index.d.ts",
  "dependencies": {
    "pino": "4.16.1"
  },
  "devDependencies": {
    "@types/pino": "4.7.1",
    "typescript": "2.8.3"
  }
}

tsconfig.json:
{
  "compileOnSave": true,
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "moduleResolution": "node",
    "inlineSources": true,
    "inlineSourceMap": true,
    "declaration": true,
    "outDir": "lib",
    "baseUrl": ".",
    "typeRoots": ["node_modules/@types"],
    "paths": {
      "*": [
        "node_modules/*",
        "src/types/*"
      ]
    },
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "allowSyntheticDefaultImports": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true
  },
  "typeAcquisition": {
    "enable": true
  },
  "include": ["src/**/*"],
  "exclude": [
    "**/*.spec.ts",
    "node_modules",
    "src/**/node_modules"
  ]
}

lib/index.ts
import * as pino from 'pino';

const isProduction = process.env.NODE_ENV === 'production';
const logLevel = process.env.LOG_LEVEL ? process.env.LOG_LEVEL.toLowerCase() : (isProduction ? 'warn' : 'debug');

const logOpts: pino.LoggerOptions = {
  safe: true,
  level: logLevel,
  prettyPrint: !!isProduction,
};

export const logger = (category: string): pino.Logger => {
  return pino({
    name: category,
    ...logOpts,
  });
};

After compiling with tsc, here are the output files:
lib/index.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const pino = require("pino");
const isProduction = process.env.NODE_ENV === 'production';
const logLevel = process.env.LOG_LEVEL ? process.env.LOG_LEVEL.toLowerCase() : (isProduction ? 'warn' : 'debug');
const logOpts = {
    safe: true,
    level: logLevel,
    prettyPrint: !!isProduction,
};
exports.logger = (category) => {
    return pino(Object.assign({ name: category }, logOpts));
};

lib/index.d.ts
/// <reference types="pino" />
import * as pino from 'pino';
export declare const logger: (category: string) => pino.Logger;

Now after publishing, I require this module as a dependency and import it:
app/index.ts
import { logger } from '@scope/logging';
const log = logger('Application');

log.info('Working');

The error leads me to believe I need to include @types/pino/index.d.ts in my module when compiling, but I don't see how to do that.

A: I think the answer is to include @types/pino as a dependency in the package.json of the module, so it's installed alongside the logging module when used in the application. It feels weird to include types as a dependency, but it has to be installed automatically and peerDependency doesn't do that.


text:
Q: yii filter in two cgrdiview with same model I have two cgridview that using same model.
When I use filters, the textfield names are the same (model class).
It's possible modify this name?
example:
$model1 = new ClassName;
$model2 = new ClassName;
if(isset($_GET['cgrdiview_1'])) {
    $model1->attributes = $_GET['cgrdiview_1'];
}
if(isset($_GET['cgrdiview_2'])) {
    $model2->attributes = $_GET['cgrdiview_2'];
}

Instead I have:
$_GET['model_class']

for both cgridview

A: Yes, It is possible by adding an id field.
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
The id attribute is most used to point to a style in a style sheet, and by JavaScript (via the HTML DOM) to manipulate the element with the specific id.
If you check the Yii API Documentation for CGridView You can see that you can set an id field for the CGridview.
In your view, change the CGridview code to contain the following:
'id' => 'cgridview_1'

This code needs to be added at the top of your gridview. For example:
$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'cgridview_1',
    'dataProvider'=>$dataProvider,
    'columns'=>array(
        'title',          // display the 'title' attribute
        'category.name',  // display the 'name' attribute of the 'category' relation
        'content:html',   // display the 'content' attribute as purified HTML
        array(            // display 'create_time' using an expression
            'name'=>'create_time',
            'value'=>'date("M j, Y", $data->create_time)',
        ),
        array(            // display 'author.username' using an expression
            'name'=>'authorName',
            'value'=>'$data->author->username',
        ),
        array(            // display a column with "view", "update" and "delete" buttons
            'class'=>'CButtonColumn',
        ),
    ),
));

A: I solved my problem with custom filter in each column:
$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'cgridview_2',
    'dataProvider' => $data,
    'filter' => $filter,
    'columns'=>array(
        array(
            'name' => 'column1',
            'filter' => CHtml::textField("cgridview2[column1]", $filter->column1),
        ),
        array(
            'name' => 'column2',
            'filter' => CHtml::textField("cgridview2[column2]", $object->column2),
        ),


text:
Q: TOTAL vs Aggr in QlikView I'm trying to understand how TOTAL and Aggr work in QlikView. Could someone please explain the difference between the two examples below, and if possible please illustrate with a SQL query?
Example1:
Max({<Field1=>} Aggr(Sum({<Field2={'Value'}, Field1=>} StuffCount), Field1))

Example2:
Max({<Field1=>} TOTAL Aggr(Sum({<Field2={'Value'}, Field1=>} StuffCount), Field1))

A: Not sure what you mean with and SQL query in this example. Anyway, imagine you have this list of Customers (CustomerID) and Sales (Sales):
CustomerID/ Sales

*

*Customer1  25

*Customer2  20

*Customer1  10

*Customer1  5

*Customer1  20

*Customer3  30

*Customer2  30

Then you want to show it on a pivot table with dimension CustomerID and two expressions:

*

*Max(Aggr(Sum(Sales), CustomerID)) // this will show 60 for the first customer, 50 for the second and 30 for the third one

*Max(TOTAL Aggr(Sum(Sales),CustomerID)) //this will show 60 in every row of your table (which is the maximum sum of sales among all customers)

So basically AGGR creates a temporal list of whatever you put in the first function input (in this case sum(Sales)) using the dimension of the second (CustomerID). Then you can perform operations on that list (such as Max, Min, Avg...). If you write TOTAL and use the expression in a pivot table, then you 'ignore' the dimensions that might be affecting the operations.
Hope it helps

A: TOTAL keyword is useful in charts/pivot tables. It applies the same calculation on every datapoint in the chart/pivot, with independence of dimentions.
Therefore - if you put your expression into pivot table - 1st option may display different values per cell (if the Aggr is rellevant) when the 2nd will result in same values.
Aggr function allows making double aggregations (avg of sum, max of count etc..) on different group by bases.


text:
Q: HighCharts Drilldown issue in pie Can someone tell me why this chart is rendering properly in drill up? The code is wrapping arc3d. I have provided the code and also the JFiddle for reference. When you click on the graph it drills down perfectly but while drilling up the graph is not rendering properly. it holds the color of the drilled slice.
(http://jsfiddle.net/subhasispatra/np0bn3ps/)
$(function () {
Highcharts.setOptions({
    lang: {
        drillUpText: '<Back'
    }
});
Highcharts.wrap(Highcharts.SVGRenderer.prototype, 'arc3d', function (proceed) {
    var result = proceed.apply(this, [].slice.call(arguments, 1));
    result.fadeIn = result.show;
    return result;
});

$('#container').highcharts({
    "plotOptions": {
        "pie": {
            "point": {
                "events": {
                    "click": function () {
                        if (this.options != undefined && this.options != null && this.options.url != null && this.options.url.length > 0) location.href = this.options.url;
                        else return;
                    }
                }
            },
                "dataLabels": {
                "enabled": true,
                    "style": {
                    "fontWeight": "bold",
                        "fontFamily": "Arial",
                        "fontSize": "10"
                },
                    "color": "#000000"
            },
                "shadow": true,
                "curson": "pointer",
                "depth": 30,
                "allowPointSelection": true,
                "showInLegend": true
        }
    },
        "drilldown": {
        "series": [{
            "id": "Draft",
                "data": [{
                "name": "15-21 DAYS",
                "url": "http://www.google.com",
                "y": 1
            }, {
                "name": "22-30 DAYS",
                "url": "http://www.google.com",
                "y": 1
            }]
        }, {
            "id": "Canceled",
                "data": [{
                "name": "15-21 DAYS",
                "url": "http://www.google.com",
                "y": 0
            }, {
                "name": "22-30 DAYS",
                "url": "http://www.google.com",
                "y": 1
            }]
        }],
            "drillUpButton": {
            "relativeTo": "spacingBox",
                "theme": {
                "style": {
                    "fontSize": "7pt"
                }
            },
                "y": 0,
                "x": 0
        }
    },
        "series": [{
        "name": "SERIES",
            "data": [{
            "drilldown": "Draft",
            "name": "Draft",
            "y": 2
        }, {
            "drilldown": "Canceled",
            "name": "Canceled",
            "y": 1
        }]
    }],
        "yAxis": {
        "title": {
            "style": {
                "color": "#000000",
                    "fontSize": "10"
            }
        },
            "labels": {
            "style": {
                "fontWeight": "normal",
                    "color": "#000000",
                    "fontFamily": "Arial",
                    "fontSize": "10"
            }
        }
    },
        "title": {
        "text": "Orders created in last 30 days"
    },
        "legend": {
        "itemStyle": {
            "fontWeight": "normal",
                "color": "#000000",
                "fontFamily": "Arial",
                "fontSize": "10"
        },
            "layout": "vertical",
            "align": "left",
            "verticalAlign": "middle"
    },
        "chart": {
        "renderTo": "container",
            "options3d": {
            "enabled": "true",
                "alpha": 40,
                "beta": 0,
                "depth": 40
        },
            "backgroundColor": "rgba(255, 255, 255, 0.1)",
            "type": "pie"
    },
        "credits": {
        "enabled": false
    },
        "xAxis": {
        "title": {
            "style": {
                "color": "#000000",
                    "fontSize": "10"
            }
        },
            "labels": {
            "style": {
                "fontWeight": "normal",
                    "color": "#000000",
                    "fontFamily": "Arial",
                    "fontSize": "10"
            }
        }
    }
});

});

A: The problem is due to 3D rendering. Disable 3D options and it'll work fine.


text:
Q: np.linalg.norm AxisError: axis 1 is out of bounds for array of dimension 1 I want to use np.linalg.norm to calculate the norm of a row vector, and then use this norm to normalize the row vector, as I wrote in the code. I give an initial value to the vector x, but after I run this code I always get:

AxisError: axis 1 is out of bounds for array of dimension 1

So I'm confused and don't know what's the problem. Here is my code:
import numpy as np

def normalizeRows(x):
    x_norm = np.linalg.norm(x, axis=1, keepdims=True)
    x_normalized = x / x_norm

    return x_normalized

x = np.array([1, 2, 3])
print(normalizeRows(x))

And here is the error:
---------------------------------------------------------------------------
AxisError                                 Traceback (most recent call last)
<ipython-input-16-155a4cdd9bf8> in <module>
     10
     11 x = np.array([1, 2, 3])
---> 12 print(normalizeRows(x))
     13
     14

<ipython-input-16-155a4cdd9bf8> in normalizeRows(x)
      4
      5 def normalizeRows(x):
----> 6     x_norm = np.linalg.norm(x, axis=1, keepdims=True)
      7     x_normalized = x / x_norm
      8

<__array_function__ internals> in norm(*args, **kwargs)

d:\programs\python39\lib\site-packages\numpy\linalg\linalg.py in norm(x, ord, axis, keepdims)
   2558             # special case for speedup
   2559             s = (x.conj() * x).real
-> 2560             return sqrt(add.reduce(s, axis=axis, keepdims=keepdims))
   2561         # None of the str-type keywords for ord ('fro', 'nuc')
   2562         # are valid for vectors

AxisError: axis 1 is out of bounds for array of dimension 1

Could somebody tell me why this is wrong and how to fix it? Thanks!

A: This gives you axis error because your array is a 1d array, and since :
"In a multi-dimensional NumPy array, axis 1 is the second axis. When we're talking about 2-d and multi-dimensional arrays, axis 1 is the axis that runs horizontally across the columns" quoted from link
All you have to do is change your axis to 0
import numpy as np

def normalizeRows(x):
    x_norm = np.linalg.norm(x, axis=0, keepdims=True)
    x_normalized = x / x_norm

    return x_normalized

x = np.array([1, 2, 3])
print(normalizeRows(x))

[0.26726124 0.53452248 0.80178373]


text:
Q: java.lang.IllegalArgumentException: Invalid format This code:
DateTimeParser[] parsers = { DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss zzz").getParser(),
DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss").getParser(), DateTimeFormat.forPattern("dd/MM/yyyy HH:mm").getParser(),
DateTimeFormat.forPattern("HH:mm").getParser() };
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();

Session session;
DateTime dTime = null;
Calendar calendar;

try{
    if (completedTime != null && !completedTime.equalsIgnoreCase("")){
        LocalDateTime jt = LocalDateTime.parse(completedTime, formatter);
        LocalDateTime dt;
        LocalDateTime retDate;

produces the error:

java.lang.IllegalArgumentException: Invalid format: "09/05/2015 04:00:00 GDT" is malformed at " GDT"
  at the LocalDateTime jt = LocalDateTime.parse(completedTime, formatter); line

I can't for the life of me work out why it is failing.  I am pretty sure it is something simple, but I haven't spotted it.

A: You may want to refer to this thread (or one of the many others like it).  My best advice would be to try cutting to only one "z" in your parser.

A: First thing to note:
What is "GDT"? The website http://www.timeanddate.com/time/zones/ does not yield an answer. So if it really exists and is not a typo then what is your locale? Remember that time zone names and abbreviations are highly localized.
Second: The count of pattern symbols "z" is okay - for classes like SimpleDateFormat etc. - see its documentation. Either four letters for the full name or less than four letters for the abbreviation:

General time zone: Time zones are interpreted as text if they have
  names. Text: For formatting, if the number of pattern letters is 4 or
  more, the full form is used; otherwise a short or abbreviated form is
  used if available. For parsing, both forms are accepted, independent
  of the number of pattern letters.

But you use Joda-Time. Its documentation clearly states:

Zone names: Time zone names ('z') cannot be parsed.

I have verified this non-support using the newest Joda-Time version 2.7 by following code:
    DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss z").withLocale(Locale.GERMANY);
    DateTime dt = formatter.parseDateTime("09/05/2015 04:00:00 MESZ");
    System.out.println("Joda-Time: " + dt);
    // Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "09/05/2015 04:00:00 MESZ" is malformed at "MESZ"

Of course, "MESZ" is correct and must be interpreted as Europe/Berlin in context of given german locale.
However, since version update (2.2) the same code set to Locale.US works for some timezones names like "EDT", "PST" etc., see also this commit. So we can finally say, the parsing support of Joda-Time for timezone names and abbreviations is best to say very limited. Once again, what is your Locale? If it is not US then I can understand why you get the exception. And you will also get an exception for the input "GDT" even if we consider it as valid due to the limited capabilities of Joda-Time-parser.

A: You need to manually specify a mapping from timezone abbreviation to timezone. For example:
    return new DateTimeFormatterBuilder()
                .appendPattern("dd/MM/yyyy HH:mm:ss ")
                .appendTimeZoneShortName(UK_TIMEZONE_SYMBOLS)
                .toFormatter();

Here UK_TIMEZONE_SYMBOLS is a Map<String,DateTimeZone> which contains our view of timezone names (so BST is British summer time, not Bangladesh standard time)
Here's how we build ours:
public static Map<String, String> buildTimeZoneSymbolMap(Locale locale) {
    Map<String, String> timeZoneSymbols = Maps.newLinkedHashMap();
    for (String[] zoneInfo : DateFormatSymbols.getInstance(locale).getZoneStrings()) {
        String timeZone = zoneInfo[0];
        if (!timeZoneSymbols.containsKey(zoneInfo[2])) {
            timeZoneSymbols.put(zoneInfo[2], timeZone);
        }
        if (zoneInfo[4] != null && !timeZoneSymbols.containsKey(zoneInfo[4])) {
            timeZoneSymbols.put(zoneInfo[4], timeZone);
        }
    }
    timeZoneSymbols.put("UTC", "GMT");
    return timeZoneSymbols;
}

public static Map<String, DateTimeZone> buildDateTimeZoneSymbolMap(Locale locale) {
    return Maps.transformValues(buildTimeZoneSymbolMap(locale), input -> DateTimeZone.forTimeZone(TimeZone.getTimeZone(input)));
}

public static final Map<String, DateTimeZone> UK_TIMEZONE_SYMBOLS = ImmutableMap.copyOf(buildDateTimeZoneSymbolMap(Locale.UK));


text:
Q: Посчитать сумму Есть код, который генерирует список. Данные берутся из форм. При нажатии на кнопку add
Внизу должно появляться суммированное значение всех чисел последнего элемента списка, что у меня не получилось. Пробовал разные варианты но результат один. Что я делаю неправильно.

    <form>
        <input type="text" name="text1" value="Some text" class="ai" id="ai" >
        <input type="text" name="number1" value="Some numbers" class="qu" id="qu">
        <input type="text" name="number2" value="Some numbers" class="pr" id="pr">
        <input type="button" name="add" value="Add" class="add" id="add">
    </form>

A: function totalPrice(){
  var z = 0;
  var elems = document.querySelectorAll('.price');
  for (var i = 0; i < elems.length; i++) {
    var itemPrice = +elems[i].innerHTML;
    z += itemPrice;
  }
  price.innerHTML = z;
}

Ну, и как обычно:
"из форм" - множественное число. id="pr" - повторяется? Нельзя.


text:
Q: How to make Clojure tests stop tests running in case one of them failed? I just would like to make the command lein test fail right once the first one test case fails.

A: Not an exact answer, but if you are working on a single problematic test, I use the "focus" feature of lein-test-refresh.  Very cool plugin.
https://github.com/jakemcc/lein-test-refresh

A: I use eftest as a better alternative to default clojure.test runner:
How to use?
From the REPL https://github.com/weavejester/eftest#fast-failure
user=> (run-tests (find-tests "test") {:fail-fast? true})

or using lein plugin https://github.com/weavejester/eftest#plugin


text:
Q: Can't print index and sum of an array I have homework. I have to make a program which can input the length of an array with the value in it. After I click the "process" button, the program will make an output of index and value with the result sum and average from the array.

I'm stuck and couldn't print the index and the value to the multiple textbox below process button.
I'm expecting the output will look like this:

Here's the code which I'd been successful write so far:
namespace ArrayProcess
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void process_Click(object sender, EventArgs e)
        {

            int sum = 0;
            string ind = "index";
            string message;
            int count = Convert.ToInt32(inputArray.Text);
            int[] varray = new int[count];
            for (int i=1; i <= count; i++)
            {
                varray[i] = Convert.ToInt32(Interaction.InputBox(message="enter the value of array number "+i));
                sum += varray[i];
            }
            boxSum.Text = Convert.ToString(sum);
        }
    }
}

Please, help me.

A: Here is the code for you  (boxAvg is for average)
namespace ArrayProcess
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void process_Click(object sender, EventArgs e)
        {

            int sum = 0;
            string ind = "index";
            string message;
            int count = Convert.ToInt32(inputArray.Text);
            int[] varray = new int[count];
            for (int i=1; i <= count; i++)
            {
                varray[i-1] = Convert.ToInt32(Interaction.InputBox(message="enter the value of array number "+i));
                sum += varray[i-1];
            }
            //Refer your list box here to add newly added values to the list
            boxSum.Text = Convert.ToString(sum);
            boxAvg.Text = Convert.ToString(sum / count);  //calculate the average
        }
    }
}

A: Given that the array already has data :
private void Display()
{
    var columnHeader1 = "Index    Value\n";
    multilineTextBox1.Text =
        columnHeader1 +
        string.Join("\n", vArray.Select((x,i)=> $"{i+1,5}    {x,5}"));

    boxSum.Text = vArray.Sum();
    boxAvg.Text = vArray.Average();

    var columnHeader2 = "Index    Value    Histogram\n";
    multilineTextBox2.Text =
        columnHeader2 +
        string.Join("\n", vArray.Select((x,i)=> $"{i+1,5}    {x,5}    {new String('*', x)}"));
}

*

*String.Join(separator, string[]), To join each row with a Carriage return/Line feed.

*.Select((x,i)=> (...), To get each elment of the array an its index.

*$"", For the easy string interpolation

*{i+1,5}, To display the index i padded on 5 char.

*new String('*', x)}, To create a string of N time the same char.

Console demo


text:
Q: TCP Server/Client - How to send user input and send back the same message from the server? I want my client to send a message to the server and the server send back the message received
but there is an issue with my client because It never reach the close() statement because of readLine()
therefore it just hangs there, what can I do to make it work ?
Server :
import java.net.*;
import java.io.*;
public class Server{
    public static void main(String[] args){
        try{
            ServerSocket server=new ServerSocket(3535);
            while(true){
                Socket socket=server.accept();
                BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));

                String message=in.readLine();
                System.out.println(message);

                out.print(message);
                out.flush();

                in.close();
                out.close();
                socket.close();
            } }
        catch(Exception e){
            System.out.println(e);
            e.printStackTrace();
        }
    }
}

Client :
import java.net.*;
import java.io.*;
public class Client{
    public static void main(String[] args){
        try{
            BufferedReader user_in =new BufferedReader(new InputStreamReader(System.in));
            while(true){
                Socket socket=new Socket("localhost",3535);
                BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));

                out.print(user_in.readLine());
                out.flush();

                String message_from_server = in.readLine();
                System.out.println("Message from server : " + message_from_server);

                out.close();
                in.close();
                socket.close();
            }

        }
        catch(Exception e){
            System.out.println(e);
            e.printStackTrace();
        }
    }
}

A: The "problem" lies in readLine() in the server.
This is wanted behavior. BufferedReader implements readLine() in a way so that it blocks until it receives either one of: '\n', '\r', carriage return followed by a line feed, or an EOF
The client is sending neither of them.
Instead of using the print() method of PrintWriter, you could use println().


text:
Q: K-means clustering on text data? For simpler understanding I am explaining with smaller example.
I have 2 sets :

I have 10 unique string ids. id1,id2,id3,id4,id5... id10

I have 3 unique c-ids: cid1,cid2,cid3

There is a mapping between 2 sets but not within the values of same sets.

The mapping is say :

id1 : cid1,cid2

id2 : cid3

id3 : cid1
... so on..

I need to cluster set of ids(strings) against cids(strings) and vice a versa.

Right now I have created a csv file like below.  (similar to sparse)

id1 , cid1

id1 , cid2

id3 , cid3

.

.

I run the k-means in Weka but not sure if this is the right way. All those ids are actually features / attributes which do not have any specific order. But the way I am representing , the columns are treated as attribute values. How can I convert it into features?

A: For kmeans you have to create equal length vectors. One possible way is - given there are three unique Ids cid1, cid2 and cid3 so you create a vector of length 3 each taking a binary value (0 or 1) denoting the absence or presence of that unique id.
id => [cid1, cid2, cid3]

i.e. above examples can be written as:
id1,1,1,0
id2,0,0,1
id3,1,0,1
...

Then I think you can cluster using kmeans. I do not know the semantics of Ids here so can't really comment on how well will it cluster.

A: Since you are willing to try any other tool that will do the clustering, I recommend taking a look at SPMF.

SPMF is an open-source data mining mining library written in Java,
  specialized in pattern mining.
It is distributed under the GPL v3 license.
It offers implementations of 89 data mining algorithms for:
sequential pattern mining, association rule mining, itemset mining,
  sequential rule mining, clustering. The source code of each algorithm
  can be integrated in other Java software.
Moreover, SPMF can be used as a standalone program with a simple user
  interface or from the command line.

You can download the GUI program or the source code from here
Documentation and data-set description can be found on this page.

For KMeans the program accepts only integer values (there is a workaround for strings) separated by single spaces and also it assumes that all rows have the same length.
1 2 3 4
1 6 8 8
1 2 3 3
2 4 5 5
4 7 8 7
7 6 8 9
4 4 3 3
2 2 5 5
7 5 5 5
5 6 8 9

The output file format is defined as follows. Each line is a cluster and lists the vectors contained in the cluster. A vector is a list of double values separated by "," and between the "[" and "]" characters.
cluster 1: [1.0,2.0,3.0,4.0][1.0,2.0,3.0,3.0][2.0,4.0,5.0,5.0][4.0,4.0,3.0,3.0][2.0,2.0,5.0,5.0]
cluster 2: [7.0,6.0,8.0,9.0][1.0,6.0,8.0,8.0][4.0,7.0,8.0,7.0][5.0,6.0,8.0,9.0]
cluster 3: [7.0,5.0,5.0,5.0]

However if your data-set has only a few distinct strings a "find and replace" will do the job.
In any other case you can use R


text:
Q: Method is not properly working when ASP.NET GridView Index gets changed I have a method which is executed when the page is loaded and when the page of the gridview is changed. This method imports the data, as well setting the rowspans.
The data import is working on every site but the Rowspan only gets set on the first page.This is my C# Code:
 protected void grdvProductChurn_DataBound()
{
    for (int rowIndex = grdvProductChurn.Rows.Count - 2; rowIndex >= 0; rowIndex += -1)
    {
        GridViewRow gvRow = grdvProductChurn.Rows[rowIndex];
        GridViewRow gvPreviousRow = grdvProductChurn.Rows[rowIndex + 1];
        for (int cellCount = 0; cellCount <= gvRow.Cells.Count - 8; cellCount++)
        {
            if (gvRow.Cells[cellCount].Text == gvPreviousRow.Cells[cellCount].Text)
            {
                if (gvPreviousRow.Cells[cellCount].RowSpan < 2)
                {
                    gvRow.Cells[cellCount].RowSpan = 2;
                }
                else
                {
                    gvRow.Cells[cellCount].RowSpan = gvPreviousRow.Cells[cellCount].RowSpan + 1;
                }
                gvPreviousRow.Cells[cellCount].Visible = false;
            }
        }
    }

    if (grdvProductChurn != null)
    {
        GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal);
        TableHeaderCell left = new TableHeaderCell();
        left.Text = "";
        left.ColumnSpan = 2;
        row.Cells.Add(left);

        TableCell totals = new TableHeaderCell();
        totals.ColumnSpan = grdvProductChurn.Columns.Count - 2;
        totals.Text = "Anzahl";
        row.Cells.Add(totals);

    }

}

And this is my asp GridView:
    <asp:GridView ID="grdvProductChurn" runat="server" CellPadding="4" HeaderStyle-BorderStyle="None" autopostback="true"
    BorderColor="#666666" BorderStyle="Solid" AllowPaging="True" AutoGenerateColumns="false" PageSize="30" DataSourceID="DataSource_ProductChurn"
    AllowSorting="True" ForeColor="#666666" CellSpacing="1" DataFormatString="{0:###,###,###,###,###}"
    CaptionAlign="Left"  Width="960px" HeaderStyle-HorizontalAlign="Center" HorizontalAlign="Center" CssClass="GridView2"
    Height="119px" OnRowCreated="grdvProductChurn_RowCreated" onpageindexchanged="grdvProductChurn_PageIndexChanged" >

Then I also have the method for the onpageindexchanged. It gets executed when I change the page, but the rowspan doesn't work.
   public void grdvProductChurn_PageIndexChanged(object sender, EventArgs e)
    {
        grdvProductChurn_DataBound();

    }


text:
Q: Calling super class' async method from async method in extending class I'm writing JavaScript (> ECMAScript 6) and I can't figure how to call a super class' async method in an extending class' method.
This is what I'm trying to do:
class SuperClass {
    constructor(){}

    async method() {
        return;
    }
}

class ExtendClass extends SuperClass {
    constructor() {
        super();
    }

    async method() {
        return super.method();
    }
}

The above won't compile, getting this as error:
SyntaxError: 'super' keyword unexpected here
    at Object.<anonymous> (Path/To/File.js:line:character)

Am I actually trying to do something that isn't possible? Can't seem to Google anything useful..
It does not help to await the call to the super class, it does not help to have different method names - the only thing that helps is making the extending class' method non-async.

A: This is due to the transpilation used in the testing framework, TestCafe (as stated by @Bergi). I will direct the question elsewhere. Thanks for the comments.
UPDATE
This is currently a bug in the TestCafe framework (link to bug).
The workaround is as follows:
async method () {
    return await SuperClass.prototype.method.call(this)
}


text:
Q: SELECT Statement with IF condition MySQL i have a table , it has columns
menu_id , parent_id, controller , action , action_edit , action_view ,

select * from test where
( action like 'my_action.php' or
action_edit like '%my_action.php%' or
action_view like '%my_action.php%'
) AND parent_id !=0 ORDER BY `controller` ASC

When action or action_view or action_edit is home.php -> i want to omit the parent_id !=0 .
I tried using
AND IF(action='home.php' OR action_view='home.php' OR action_edit='home.php',parent !=0,) instead of AND parent_id !=0 but it's giving me a token mismatch error
but not working , thank you in advance :)

A: Try something like this:
select *
from test
where  'home.php' not in (action, action_view, action_edit) or parent_id <> 0) and
       (action like 'my_action.php' or action_edit like '%my_action.php%' or
        action_view like '%my_action.php%'
       )

EDIT:
not in is dangerous with not in.  Let's prevent problems using coalesce():
select *
from test
where  'home.php' not in (coalesce(action, ''), coalesce(action_view, ''), coalesce(action_edit, '')) or parent_id <> 0) and
       (action like 'my_action.php' or action_edit like '%my_action.php%' or
        action_view like '%my_action.php%'
       )

A: maybe you want this?
select * from test where
(( action like 'my_action.php' or
   action_edit like '%my_action.php%' or
   action_view like '%my_action.php%'
 ) AND parent_id !=0)
OR
( action='home.php' OR
  action_view='home.php' OR
  action_edit='home.php')
ORDER BY `controller` ASC

A: Try this:
SELECT * FROM test
  WHERE NOT EXISTS ((SELECT A.* FROM test A)
                   JOIN (SELECT B.* FROM test B WHERE
                         B.action like 'my_action.php'
                         OR B.action_edit like '%my_action.php%'
                         OR B.action_view like '%my_action.php%')
                   ON A.parent_id !=0)
ORDER BY `controller` ASC

A: Hi Finally i have a solution
select * from test where
( action like 'my_action.php' or
action_edit like '%my_action.php%' or
action_view like '%my_action.php%'
) AND parent_id !=0 ORDER BY `controller` ASC

instead of parent_id !=0 i used
and IF(action='home.php' OR action_view='home.php' OR action_edit='home.php',parent=0,parent!=0)
Now its working , thank you for your help guys :) . I posted my answer because i thought it will be a help for future users with the similar problem :)

A: How about :
select * from test where
(( action like 'my_action.php' or
action_edit like '%my_action.php%' or
action_view like '%my_action.php%'
)) AND (parent_id !=0))
ORDER BY `controller` ASC


text:
Q: Azure VM stops working after encrypting C drive? So this is the second time ive run into this. Ive started the process of enabling bitlocker on C drive. It asks for password and i supply one. It then asks to restart and i do. Azure portal shows it as running, but when i try to connect, it shows as the computer being off. Ideas? I really need to get back in there.

A: You cannot simply encrypt an Azure VM by enabling bitlocker.  The only way to encrypt the disk is to go through the Azure Disk Encryption process. This requires storing your encryption keys in Azure Keyvault. While this process enables bitlocker it needs to get the encryption key from keyvault because while the machine is booting you don't have access to the console to enter a password.
If you have enabled bitlocker on a vm, hopefully it has failed on the first verify boot, and if you force a reboot it will work.
If you have skipped the verify step and gone straight to encrypting the disk you will need to mount the disk in another VM and use your recovery key to access the data again.


text:
Q: Build replication from backup not publication source I have an interesting scenario I am trying to find a solution to.
We currently have the current setup.
ProductionDatabase (publisher) is the publication for transnational replication to the following:
  WarehouseDatabase (subscriber)
  NewWarehouseDatabase (subscriber)
My issue is that WarehouseDatabase has had triggers and other SP's added to it.  When I build replication for NewWarehouseDatabase I built it from a backup of ProductionDatabase.  So NewWarehouseDatabase does not have the triggers or SP's that had been added to WarehouseDatabase.
Doing a SQL Compare generated a list that had a lot more things displayed than I really want to manage.
So I thought I can build replication by backing up WarehouseDatabase and restoring to NewWarehouseDatabase and then enabling replication from ProductionDatabase.  Then I thought that will not work as the LSN and other internals that might not sync up for replication to work.
I am wondering if anyone can suggest how I can accomplish this, if you can understand my babbling...
Regards,
GarryB

A: If I understand you question correctly you could use a schema compare tool to generate a script that would be used to insert the extra SPs and triggers into the new datawarehouse DB.
Redgate have a tool like this in their DBA bundle and I think data and schema compare are now functionalities of visual studio.

A: When I need to do something like this, I just use sys.objects. After you restore the NewWarehouseDatabase databse, create a Linked Server on the instance where you have WarehouseDatabase to point to the instance where you have the NewWarehouseDatabase databse. Then write an EXCEPT query using sys.objects. Something like this:
select o.name, s.name
from WarehouseDatabase.sys.objects o
inner join WarehouseDatabase.sys.schemas s on s.schema_id = o.schema_id
where o.type in ('List the types you're interested in')
except
select o.name, s.name
from <LINKEDSERVER>.NewWarehouseDatabase.sys.objects o
inner join <LINKEDSERVER>.NewWarehouseDatabase.sys.schemas s on s.schema_id = o.schema_id
where o.type in ('List the types you're interested in')

This should give you a list of the objects that are in the WarehouseDatabase databse but not in the NewWarehouseDatabase database.


text:
Q: Configure RAID 1 on ThinkServer TS140 I am setting up a server for a business, and one of the specifications that they have set is a RAID 1 configuration for the two drives in the machine (the OS will be installed on this mirror).  One of the mirrored drives will be in a hot swap bay, so that at the end of the day, he can take the bay drive out, put it in a safe, and put another drive in.  The two hot swappable drives will rotate each day.
I am trying to set this up on a Lenovo ThinkServer TS140, but have a two issues:

*

*When I start the server up, I do not get a prompt to configure a RAID array.  I had worked with another server of the exact same model, and would get a prompt to hit CTRL+I to enter the RAID configuration utility.  Do I need to install something first?

*I was wondering if this would be possible using the mainboard RAID (or given the fact that the mainboard never prompts for such), if I need a controller card for this?
The owner of the business says that his current server does this, so I'm going to head over there to examine the old one, but that won't be until 5PM.  I tried contacting Lenovo technical support, but 1) he insisted the option was there when it never prompted for such, and 2) also insisted that I needed Lenovo hard drives to make this work (with or without a controller card).
Thanks in advance.
2016.06.14 Edit:
It is exactly as he described it.  He has a FastTrak TX2300 and a RAID controller.  The drive bay and the internal drive both plug into the controller card, and he just yanks the drive at the end of the day.  I also asked how long he has been doing this, and he said "Just about 10 years."
As far as "Taking out a disk out of a RAID array is no replacement for a proper backup", I didn't say it was.  This is just what he wants to do.  I'm going to recommend he also use NovaBackup to an external hard drive, but this is one of his specifications.

A: No!
This is not a sane approach. At all. Taking out a disk out of a RAID array is no replacement for a proper backup. Among other things, you needlessly put yourself to the risk of a failed recovery due to a bad "primary" disk.

A: Ok, for question 1 on my post, I found that a BIOS setting was misconfigured.  I had to enter Devices > ATA Drive Setup > Configure SATA as - RAID.
As far as question 2, since I was able to set the drives up for RAID 1 in the Configuration Utility, I should be able to set it up how the buyer wants it.  We're going to recommend that he uses NovaBackup to make a backup image to a third drive, which he can rotate out in the hot swap bay.  If, however, he wants it set up the same way, that is the way we're going to do it.


text:
Q: Serialize and save data to a string I have this code here:
public xml.Sheet Sheet1 { get; set; }

I need to be able to serialize it and save the content in a string. Let's say xml1
I was able to do the deserialization but not the serialization.
The Sheet1 has Properties like:
Sheet1.Root
Sheet1.Controls

The XML file should be:
<Root>
<Control> </Control>
<Control> </Control>
<Control> </Control>
</Root>

<Root>
<Control> </Control>
<Control> </Control>
<Control> </Control>
</Root>

How do I start?
 XmlSerializer ser = new XmlSerializer(Sheet1.GetType());

Edit: my new code is this:
 public void GetContents(ref string xml1, ref string xml2)
        {

            using (var writer = new StringWriter())
            {
                XmlSerializer ser = new XmlSerializer(Sheet1.GetType());
                ser.Serialize(writer, Sheet1);
                xml1 = writer.ToString();
            }

            using (var writer2 = new StringWriter())
            {
                XmlSerializer ser2 = new XmlSerializer(Sheet2.GetType());
                ser2.Serialize(writer2, Sheet2);
                xml2 = writer2.ToString();

            }

        }

Then I call this method:
compare.GetContents(ref xml1, ref xml2);

Now I get the new strings and how can I save them into XML files?

A: Your Sheet class needs to be marked as [Serializable].  Also be aware only public properties and fields will be serialized.
string xml1;
using (var writer = new StringWriter())
{
  XmlSerializer ser = new XmlSerializer(Sheet1.GetType());
  ser.Serialize(writer, Sheet1);
  xml1 = writer.ToString();
}

And to save to a file:
using (var fileWriter = new StreamWriter("filename.xml", Encoding.UTF8))
{
  fileWriter.Write(xml1);
}


text:
Q: how to make seprate login for the admin and others in laravel? i need to make two different login for other users and admin.
i have made two different login controller. For admin i tried to override attemptLogin function
AdminLoginController.php
 public function attemptLogin(Request $request)
    {

        $this->guard()->attempt(
            $this->credentials($request), $request->filled('remember')
        );
        $user = $this->guard()->user();
        $admin = $user->hasRole('admin');

        if($admin){
            return true;
        }
        else{
            return false;
        }

    }

but this make user logged in for both the users admin as well as other user. Thanks in advance!

A: This works for me.
public function attemptLogin(Request $request)
    {

        $this->guard()->attempt(
            $this->credentials($request), $request->filled('remember')
        );
        $user = $this->guard()->user();
        $admin = $user->hasRole('admin');

        if($admin){
            return true;
        }
        else{
            $this->guard()->logout();
            return false;
        }

    }

A: YOu can do a checking for that inside your login action of admin as given below, I am sharing the code which I have used in one of my project. I hope you can understand, i have added comments also
public function login(Request $request){
    if(auth()->user()){
        $user = auth()->user()->toArray();
        $role = Role::where('_id', new \MongoDB\BSON\ObjectID($user["role_id"]))->first();
        if($role) $role = $role->toArray();
        if(!empty($role)){
            // Prevent other users to enter admin area by checking the role
            if(strtolower($role['name']) != 'admin'){
                Auth::logout();
                \Session::flash('errors', 'You are not authorized to access admin area.' );
                return redirect(url('/admin/login'));
            }else{
                return redirect(url('/admin'));
            }

        }else{
            Auth::logout();
            \Session::flash('errors', 'Invalid user role' );
            return redirect(url('/admin/login'));
        }
    }
    return view('admin/index/login');
}

If any users other than admin try to login in admin area, by checking the role force them to logout the system

A: The simplest way is to define new guard and provider in config/auth.php.
    'guards' => [
        'web' => [ // default guard
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'admin',
        ],
    ],

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],

        'admin' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ]
    ],

App/Admin.php class is your admin eloquent class and App/User.php is your user eloquent class. This way assumes that admins and users have got separated table in database. Of course you should also use admin guard in your AdminLoginController by one of two ways:

*

*set protected $guard = 'admin';

*set public function guard(){
        Auth::guard('admin');
    }


text:
Q: Get elements of Series B not in A What is the most efficient way to find the elemens in B that are not in A?
The index column of both sets is to be used for the comparison.  The other column is to be carried with the results.
Here is a sample, keeping in mind that series A and B can get huge:
print a
    c2
c1
o80  a
o81  b

print b
    c2
c1
o83  c
o81  b

Here is the desired result:
print c
    c2
c1
o83  c

After each comparison, the results C will be appended to a running results series.
I can do the job, with combine_first, comparing the results, etc, but it doesn't look elegant and simple and won't scale well.
Any insights from those who are really experienced at this?

A: I would just use logical indexing:
c1 = pandas.Series([1, 2], index=['A', 'B'], name='c1')
c2 = pandas.Series([3, 4, 5], index=['A', 'B', 'C'], name='c2')
c2[~c2.index.isin(c1.index)]

give me:
C    5
Name: c2, dtype: int64


text:
Q: Permanently add to emacs load path I am trying to add "~/" to the emacs load path, because for whatever reason it is not there.  I managed to find the command for adding to the emacs load path:
(add-to-list 'load-path "~/")

When I execute this command the load-path variable contains all the stuff it did before, and "~/" is added to the list.  The problem is when I quit emacs, the next time it starts the "~/" had been removed from the list, the change is not persistent.  How do I add something to the emacs load-path variable permanently?
Adding to the .emacs file won't work here, because the problem is that the .emacs file, which is in the ~/ directory, is not being loaded, so modifying the .emacs file won't fix this problem.

A: I guess there is a typo in phils' comment. The right way should be C-h v user-init-file RET. Maybe you customized this variable in some other places and you forgot. Try changing the value of this variable back to the default.


text:
Q: Logout with JAAS login module The question is a little bit longer than expected. Below is the link to a similar one (3rd post) where I didn't find the answer satisfying.
TL;DR
I am trying to logout using the JAAS Login Module. Here is the brief structure of the project:
LoginService is responsible for instantiating LoginContext when a user wants to log in:
@Service
public class LoginService {

    public UserDTO getUserDTOFrom(Credentials credentials) {
        try {
            LoginContext loginContext = new LoginContext("Login", new JAASCallbackHandler(credentials));
            loginContext.login();
            // construct UserDTO object.
        } catch (LoginException e) {
            LOGGER.error("Login Exception: {}", e.getMessage());
            // construct UserDTO object.
        }
    // return UserDTO object.
}

The LoginController calls the method:
@RestController
@RequestMapping("/login")
public class LoginController {

    private final LoginService loginService;

    @Autowired
    public LoginController(LoginService loginService) {
        this.loginService = loginService;
    }

    @PostMapping
    public ResponseEntity<UserDTO> getUserDTOFrom(@Valid @RequestBody Credentials credentials) {
        UserDTO userDTO = loginService.getUserDTOFrom(userForm);
        // return response that depends on outcome in the login service
    }
}

The issue arises when I want to logout previously logged in user. LoginContext is responsible for calling the logout method in the JAAS Login Module. For instance:
loginContext.logout();
The method in the JAAS Login Module:
public class JAASLoginModule implements LoginModule {

    @Override
    public boolean logout() {
        subject.getPrincipals().remove(usernamePrincipal);
        subject.getPrincipals().remove(passwordPrincipal);
        return true;
    }
}

I don't have the LoginContext in LogoutService and unable to completely clear the previously authenticated subject.
I tried to create a singleton bean to get the same instance of the LoginContext:
@Configuration
public class LoginContextBean {

    @Lazy
    @Bean
    public LoginContext getLoginContext(Credentials credentials) throws LoginException {
        System.setProperty("java.security.auth.login.config", "resources/configuration/jaas.config");
        return new LoginContext("Login", new JAASCallbackHandler(credentials));
    }
}

@Service
public class LoginService {

    private final ObjectProvider<LoginContext> loginContextProvider;

    @Autowired
    public LoginService(ObjectProvider<LoginContext> loginContextProvider) {
        this.loginContextProvider = loginContextProvider;
    }

    public UserDTO getUserDTOFrom(Credentials credentials) {
        try {
            LoginContext loginContext = loginContextProvider.getObject(credentials);
            loginContext.login();
            // construct UserDTO object.
        } catch (LoginException e) {
            LOGGER.error("Login Exception: {}", e.getMessage());
            // construct UserDTO object.
        }
    // return UserDTO object.
    }
}

@Service
public class LogoutService {

    private final ObjectProvider<LoginContext> loginContextProvider;

    @Autowired
    public LogoutService(ObjectProvider<LoginContext> loginContextProvider) {
        this.loginContextProvider = loginContextProvider;
    }

    public void performLogout() {
        LoginContext loginContext = loginContextProvider.getObject();
        try {
            loginContext.logout();
        } catch (LoginException e) {
            LOGGER.error("Failed to logout: {}.", e.getMessage());
        }
    }
}

The solution is not particularly useful, since next / the same user to log in will get NPE on the LoginContext.
I read that HttpServletRequest's getSession().invalidate(); suppose to call the logout() of JAAS or that HttpServletRequest's logout() would do the job. But both methods have no effect. For instance:
@RestController
@RequestMapping("/logout")
public class LogoutController {

    private final LogoutService logoutService;

    @Autowired
    public LogoutController(LogoutService logoutService) {
        this.logoutService = logoutService;
    }

    @DeleteMapping
    public ResponseEntity<Void> deleteJwt(@CookieValue("jwt_cookie") String jwtToken, HttpServletRequest request) throws ServletException {
        request.getSession().invalidate(); // logout() is not called.
        request.logout(); // logout() is not called.
        return getResponse();
    }
}

I want to get the hand on the previously created LoginContext when a user wants to log out but create a new one when another user tries to log in.
Please note that I am not using Spring Security.
EDIT:
One of the ideas was to use a singleton that will hold a Set of login contexts associated with the particular user. And then call and destroy them when the user logs out. A key for such a Set could be a JWT token or user id. After further thinking, it appeared to me that a user might have multiple sessions, and in this case, user id as a key will fail to serve its purpose. The second option is a JWT token, but there is a scenario when the future middleware will issue a new JWT token upon expiration, then my Set will have no way to return a valid login context.

A: After some research, my team decided that JAAS doesn't suit our needs. We are not using the complete functionality it has to offer, and it ties our hands rather than smoothing the developing process.
If you will encounter a similar issue, here is an explanation:
we are using WebSphere 8.5.5 that has the support of JAAS. It is possible to logout, but the price will be tying it to the application server. Considering that in our plans is to move from WebSphere, this implementation is not an option.
The link to one of such guides lies here.
There are two alternatives for the future:

*

*Wrap it in Spring Security since it offers support for JAAS;

*Replace the custom module entirely relying on Spring Security's
functionality.


text:
Q: Elastix inbound call occupied more channels enter image description here
Dear Experts,
I am a newb in Elastix,
I have configured Elastix for all inbound calls forward to mobile numbers via the Elastix queue feature.
it was working fine. but for the last two days, it's making some problems. to fix that, when I am checking the number of channels occupied via core show channels its showing four channels occupied for one inbound call. I have attached a screenshot file. can someone explain to me why the app queue and app dial are down?


text:
Q: Combining Google Directions and Google Places I try to make a search bar on my site, which will use two Google APIs.
Basing on Google API documentation I've written this code.
function calcRoute() {
    //Setting variables for Google Places API request

    var start = 'starting point';
    var end = 'destination point';

    var service;
    var moscow = new google.maps.LatLng(55.749646,37.62368);
    var places = [];

    var request1 = {
        location: moscow,
        radius: '50000',
        query: start
    };

    var request2 = {
        location: moscow,
        radius: '50000',
        query: end
    };

    //Setting variables for Google Directions API

    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();

    //Executing Google Places request

    service = new google.maps.places.PlacesService();
    service.textSearch(request1, callback1);
    service.textSearch(request2, callback2);

    function callback1(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        places[0] = results[0].formatted_address;
    } else {
        document.getElementById("directionsPanel").innerHTML = "
Sorry, directions not found.

";
        return;
    }
}

function callback2(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
    places[1] = results[1].formatted_address;

//Executing Google Directions request

    var request = {
    origin:places[0],
    destination:places[1],
    travelMode: google.maps.DirectionsTravelMode.DRIVING
};

    directionsService.route(request,

function(response, status) {
         if (status == google.maps.DirectionsStatus.OK) {

var myOptions = {
        zoom: 8,
        streetViewControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map(document.getElementById("map_canvas2"), myOptions);
directionsDisplay.setMap(map);

    directionsDisplay.setDirections(response);
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));
  }
  else
  {
  document.getElementById("directionsPanel").innerHTML = "
Sorry, directions not found.

";
  };
});

 //End of Google Directions request

}
else
{
  document.getElementById("directionsPanel").innerHTML = "
Sorry, directions not found.

";
  return;
}
}

//Closing calcRoute() function

}

Here's HTML

    <link href="../images/style.css" rel="stylesheet" type="text/css" />

    <FORM NAME="joe">
      <INPUT TYPE="hidden" NAME="burns" />
    </FORM>

When I test it, chrome js console throws
"Uncaught TypeError: Cannot read property 'innerHTML' of undefined".
However, both two divs are defined and there are no typo errors in their id's.
I think I need a API key for Google Places to work.
Besides that, is there anything else that I need for this code to work properly?

A: This works for me.  I think it has something to do with the way you are initializing things:

Working example

A: Finally, I found the errors that I made.
First error.
I did not pass a necessary argument map when I created a service object.
//Before

service = new google.maps.places.PlacesService();

//After

var myOptions = {
zoom: 8,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

map = new google.maps.Map(document.getElementById("map_canvas2"), myOptions);

service =  new google.maps.places.PlacesService(map);

Second error.
I declared all variables inside a CalcRoute() function
thus making them unreachable for other functions.
So, I had to declare them as global variables.

Third error.
I made two requests to Google Places API at a time.
This created an error.
So, I put a second request in a callback function of a first one.

Here is a final working example.
var map

var directionsDisplay;
var directionsService = new google.maps.DirectionsService();

var placesService;

var moscow = new google.maps.LatLng(55.749646,37.62368);
var start;
var end;

var places = [];

function calcRoute() {

start = 'Domodedovo airport';
end = 'Hotel Balchug Kempinsky';

if(start == '' || end == '')
{
document.getElementById("directionsPanel").innerHTML = "
Sorry, directions not found.

";
return;
}

var myOptions = {
zoom: 8,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas2"), myOptions);

var request1 = {
location: moscow,
radius: '50000',
query: start
};

//Executing Google Places request

placesService =  new google.maps.places.PlacesService(map);
placesService.textSearch(request1, callback1);

}

function callback1(results, status) {

if (status == google.maps.places.PlacesServiceStatus.OK) {
places[0] = results[0].formatted_address;

var request2 = {
location: moscow,
radius: '50000',
query: end
};

placesService.textSearch(request2, callback2);
}

else
{
document.getElementById("directionsPanel").innerHTML = "
Sorry, directions not found.

";
return;
}
}

function callback2(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
places[1] = results[0].formatted_address;

 //Executing Google Directions request

var request = {
origin:places[0],
destination:places[1],
travelMode: google.maps.DirectionsTravelMode.DRIVING
};

directionsService.route(request,

function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {

directionsDisplay = new google.maps.DirectionsRenderer();

directionsDisplay.setMap(map);

directionsDisplay.setDirections(response);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}
else
{
document.getElementById("directionsPanel").innerHTML = "
Sorry, directions not found.

";
};
});

 //End of Google Directions request

}
else
{
  document.getElementById("directionsPanel").innerHTML = "
Sorry, directions not found.

";
  return;
}
}


text:
Q: Define a variable and run as command in Batch file I'm trying to define a line of batch command and run it
I use something like this :
pushd "%WORKSPACE%"
set mycommand = translate.py documentname
%XD%

but it doesn't run at all
Anybody knows how to do it ?

A: I think it would be like:
 pushd "%WORKSPACE"
 set mycommand=translate.py "documentname.py"
 %mycommand%

Hopefully it's like that...


text:
Q: Compression/encryption algorithms output guarantees My question here regards compression/encryption algorithms in general and to me sounds like a complete noobie one. Now, I understand that "in general" "it all depends", but suppose we're talking algorithms that all have reference implementation/published specs and are overall ever so standard. To be more specific, I'm using .NET implementations of AES-256 and GZip/Deflate
So here goes. Can it be assumed that, given exactly the same input, both types of algorithms will produce exactly the same output.
For example, will output of aes(gzip("hello"), key, initVector)) on .NET be identical to that of on a Mac or Linux?

A: AES is rigourosly defined, so given same input, same algorithm, and same key, you will get the same output.
It cannot be said the same for zip.
The problem is not the standard. There IS a defined standard : Deflate stream is IETF RFC 1950, gzip stream is IETF RFC 1952, so anyone can produce a compatible zip compressor/decoder starting from these definitions.
But zip belong to the large family of LZ compressors, which, by construction, are neither bijective nor injective. Which means, from a single source, there are many many ways to describe the same input which are all valid although different.
An example.
Let's say, my input is : ABCABCABC
Valid outputs can be :

*

*9 literals

*3 literals followed by one copy of 6 bytes long starting at offset -3

*3 literals followed by two copies of 3 bytes long each starting at offset -3

*6 literals followed by one copy of 3 bytes long starting at offset -6

*etc.
All these outputs are valid and describe (regenerate) the same input. Obviously, one of them is more efficient (compress more) than the others. But that's where implementation may differ. Some will be more powerful than others. For example, it is known that kzip and 7zip generate better (more compressed) zip files than gzip. Even gzip has a lot of compression options generating different compressed streams starting from a same input.
Now, if you want to constantly get exactly the same binary output, you need more than "zip" : you need to enforce a precise zip implementation, and a precise compression parameter. Then, you'll be sure that you generate always the same binary.

A: AES is defined to a standard, so any conforming implementation will indeed produce the same output.  GZip is a program, so it is possible that different versions of the program will produce different outputs.  I would expect a later version to be able to reinflate the output from an earlier version, but the reverse may not be possible.
As others have said, if you are going to compress, then compress the plaintext, not the cyphertext from AES.  Cyphertext won't compress well as it is designed to appear random.


text:
Q: Finding Probabilities of Distribution Functions I recently turned in an assignment and had an error on it, or so I'm told, I'm not entirely convinced just yet. The problem was as follows:
$$F(x) =\begin{cases}1-\frac{16}{x^2},  & x\ge4 \\ 0, & x<4 \end{cases}$$
There were a number of different things I was to do with this problem. It wasn't until we were finding a few simple probabilities that the confusion set in.
It is my understanding that given $F$ is a distribution function of a random variable $X$, for an event concerning $X$, the probability of the event in terms of $F$ is as follows:
$$
\begin{array}{c|lcr}
\text {Event}& \text{Probability} \\
\hline
X \le a &F(a) \\
X \gt a &1-F(a) \\
X \lt a &F(a-)\\
X \ge a &1-F(a-)\\
X=a &F(a)-F(a-)\\
a\lt X\le b&F(b)-F(a)\\
a\lt X < b&F(b-)-F(a)\\
a\le X \le b&F(b)-F(a-)\\
a\le X < b&F(b-)-F(a-)
\end{array}
$$
where $F(a-)$ and $F(b-)$ represent the left hand limits. (From pg $146$ of Fundamentals of Probability with Stochastic Processes by Saeed Ghahramani)
I was asked to find $P(X \ge 6)$. What I did:
$$P(X \ge 6)=1-F(6-)=1-\frac{16}{36}=\frac{20}{36}=\frac59$$
What my professor had in his solutions (and also another student I spoke with agreed was correct) was:
$$P(X \ge 6)=1-P(X=6)$$
$$P(X=6)=1-\frac{16}{36}=\frac59$$
Thus,
$$P(X \ge 6)=1-\frac59=\frac49$$
What am I missing here? Am I misunderstanding the chart?

A: The function $F(x)$ that you have described is clearly a cumulative distribution function. We have $\Pr(X\ge 6)=\Pr(X\gt 6)=1-F(6)=1-\left(1-\frac{16}{36}\right)=\frac{4}{9}$.
Our cdf is continuous. Thus there is no need to worry about the distinction between $\ge$ and $\gt$: For any $a$, the probability that the random variable is exactly equal to $a$ is $0$.
Remark: Note that $F(x)=\Pr(X\le x)$, and that $F(x)=1-\frac{16}{x^2}$ (for suitable $x$). The mitake in your calculation is a small slip. What you call $F(6-)$ should be $1-\frac{16}{36}$, not $\frac{16}{36}$.
By the way, although $F(6)$ is indeed $\frac{5}{9}$, it is not true that $\Pr(X=6)=\frac{5}{9}$. We have $\Pr(X\le 6)=\frac{5}{9}$, but $\Pr(X=6)=0$.


text:
Q: Is mkdir -p safe to parallelize? I'm writing Makefile rules like this:
out/%.x: ...
    mkdir -p $(@D)/
    ...

I intend to parallelize this Makefile (-j), which will trigger many mkdir -p's to simultaneously.
Is this safe? Or do I need to guard against problems by ensuring mkdir -p only happens once?
(Note that mkdir -p isn't necessarily a single operation at the file system level, unlike mkdir.)

A: The rationale for POSIX mkdir says

Because no error is produced if any path component already exists, the -p option is also useful to ensure that a particular directory exists.

This suggests that parallel use should be safe. I can understand your doubts, given the potential for races, so let's look at an implementation...
In GNU coreutils, the -p option ends up being handled by mkancesdirs, which has a helpful description which should allay your fears:

Ensure that the ancestor directories of FILE exist, using an
     algorithm that should work even if two processes execute this
     function in parallel.

(Instead of immediately acting on errors from mkdir, it tries to chdir into each component directory and only fails if that fails.)
If you're using GNU Make, you could use its secondary expansion to handle directories in the same way as other prerequisites:
.SECONDEXPANSION:

%/:
        mkdir -p $@

out/%.x: $$(@D)/ ...
        ...