text:
Q: HTTP to HTTPS redirect, nginx configuration is causing infinite request to HTTPS Hi I am new to Nginx and looking some help to redirect my http request to https.
I have two configuration on load balance with port 80 and 444 at Linode cloud system.
If request comes from https then load balancer if sending request to my serving tomcat after terminating SSL to LB.
If request comes from http then load balancer is sending to my nginx server which is redirecting request to https.
I see whenever, I start my nginx server, I see continues logs in my tomcat server of redirect url even no one is hitting my http url. I have following complete nginx.conf file.
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
            listen       80 ;
            server_name  example.com;
            #return 301 https://$server_name$request_uri;
            rewrite  ^ https://$server_name/$request_uri permanent;
            root         /usr/share/nginx/html;

            # Load configuration files for the default server block.
            include /etc/nginx/default.d/*.conf;

            location =/ {
                 }

            error_page 404 /404.html;
                location = /40x.html {
            }

            error_page 500 502 503 504 /50x.html;
                location = /50x.html {
            }
        }

Same configuration works perfectly, if I put IP address in place of actual domain name.
Following are the curl results based on location and I see in after redirecting from HTTPS location header is showing https://example.com/login which is doing correctly
# curl -i http://example.com
HTTP/1.1 301 Moved Permanently
Server: nginx/1.6.3
Date: Fri, 29 Jan 2016 07:43:54 GMT
Content-Type: text/html
Content-Length: 184
Connection: close
Location: https://example.com/

<title>301 Moved Permanently</title>

301 Moved Permanently

nginx/1.6.3

# curl -i https://example.com
HTTP/1.1 302 Found
Server: Apache-Coyote/1.1
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-XSS-Protection: 1; mode=block
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Set-Cookie: JSESSIONID=C3B65BD4E015F05705B585F5F8D70074; Path=/; Secure; HttpOnly
Location: https://example.com/login
Content-Length: 0
Date: Fri, 29 Jan 2016 07:44:03 GMT
Connection: close

#curl -i https://example.com/login
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-XSS-Protection: 1; mode=block
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Set-Cookie: JSESSIONID=6B30D6D70672A99F13B2F441B2F2150E; Path=/; Secure; HttpOnly
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-US
Transfer-Encoding: chunked
Date: Fri, 29 Jan 2016 07:44:18 GMT
Connection: close

Please suggest me what I am missing here.

A: To simply redirect all requests to port 80 to https, use the following configuration. No further lines are required, and might skip the purpose of the server:
server {
    listen 80 default_server;
    server_name _;
    rewrite  ^  https://$host$request_uri permanent;
}

This way, whichever host or even IP address will be forwarded to the https counterpart. If you are sure there'll be only one destination host, you may use it instead of the $host variable (do not enter a / afterwards):
    rewrite ^  https://example.com$request_uri permanent;

It'd be even better if you use return:
    return 301 https://example.com$request_uri;
    # or
    # return 301 https://$host$request_uri;

Since this is the only purpose of this server block, remove all other directives, like root, location, error_page and include.
Beware of additional files at /etc/nginx/conf.d/*.conf or /etc/nginx/sites-enabled/*.conf, they may overwrite these settings.
Reload nginx configuration and test. I suggest using cURL — here's the expected result:
$ curl -i http://example.com
HTTP/1.1 301 Moved Permanently
Server: nginx/1.8.0
Date: Wed, 27 Jan 2016 17:33:45 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: https://example.com/

<title>301 Moved Permanently</title>

301 Moved Permanently

nginx/1.8.0

Look and copy the Location: header content, then test again using cURL (use -k if you use a self-signed certificate):
curl -i https://example.com

The result should be from your tomcat application, and NOT another redirect to the same page. If the result is the same (safe from the date), then your LB is probably sending the https requests back to nginx, causing a loop.
Please note that the tomcat application may also be forwarding to https if it doesn't understand it's behind a proxy (the LB). In this case, you'll need to setup the application config to properly understand this (let me know if this is the case).

A: I see that my Nginx server is exposed on public IP using port:80 and it was receiving traffic from unwanted hosts.
Since I had a default configuration in Nginx server block which was redirecting my all incoming http:80 traffic from any host to my tomcat on https:443, thats why I saw tons of logs in my tomcat server.
I had to add below configuration to my /etc/nginx.conf to redirect port:80 traffic to https if request is coming from my domain only.
if ($host ~ ^(example.com|www.example.com)$) {
         return 301 https://$server_name$request_uri;
}


text:
Q: Retreiving the element position using xpath for each and every element with in the same parent I have multiple table elements with in a same chapter. Also i have multiple chapters . I want to name each table like (Table : chapter# . Table#). The xml file looks like this
<bookmap>
   <chapter>

This is first table of first chapter

This is second table of first chapter

   </chapter>
   <chapter>

This is first table of second chapter

This is second table of second chapter

   </chapter>
</bookmap>

Here i need XPATH expression to fetch the table number . Am getting the chapter number like "count(preceding:chapter)+1". In the same way am trying to get the XPATH expression for Table number.How can i acheive this?

A: Use preceding-sibling:
count($table/preceding-sibling::table)+1

Assuming your table element is stored in $table

redpajama_set_name: RedPajamaStackExchange


text:
Q: Build reusable Animation component with react-spring without rendering a wrapper element I'd like to build a re-usable animation component with react-spring.
Here's what I have so far:
codesandbox
const Fade = ({
  show,
  as = "div",
  children
}: {
  show: boolean;
  as?: keyof JSX.IntrinsicElements;
  children: React.ReactNode;
}) => {
  const transitions = useTransition(show, null, {
    from: { position: "absolute", opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 },
    unique: true
  });

  const AnimatedComponent = animated[as];

  return (
    <>
      {transitions.map(({ item, key, props }) => {
        if (!item) {
          return null;
        }

        return (
          <AnimatedComponent key={key} style={props}>
            {children}
          </AnimatedComponent>
        );
      })}
    </>
  );
};

However, there's now an issue where the animation components introduces a "side-effect", adding a "div" wrapper around the child I want animated.
This causes styling issues in existing components that would require lots of changes.
So as a workaround, I attempted to use animated as a function, and pass children as a non-instantiated react element. But then there's noticeable jank and animation doesn't complete and stops mid-way through at times, e.g., inspect the animated element, and notice that the opacity tends to stop at 0.98883393 rather than at 1.
codesandbox
const Fade = ({
  show,
  children
}: {
  show: boolean;
  children: React.ReactElement;
}) => {
  const transitions = useTransition(show, null, {
    from: { position: "absolute", opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 },
    unique: true
  });

  // Here's the change. We wrap children in a functional component and clone
  // children inside
  const AnimatedComponent = animated(({ style }) =>
    React.cloneElement(children, { style })
  );

  return (
    <>
      {transitions.map(({ item, key, props }) => {
        if (!item) {
          return null;
        }

        return (
          <AnimatedComponent key={key} style={props}>
            {children}
          </AnimatedComponent>
        );
      })}
    </>
  );
};

I've noticed that introducing extra "div" wrappers seems to be a side-effect with some of these animation-based libraries like react-spring and framer-motion
Is there a suggested way to build re-usable animation components with react-spring that doesn't come with the side-effect of introducing extra DOM elements

A: This is an old version of react-spring and things have changed since then so it's hard to troubleshoot exactly why you have this odd behaviour with opacity that doesn't reach 1.0. Nonetheless, you also have a warning in the console about updating an unmounted component and the key property is always undefined so I'm not sure you're using transitions correctly. But since that api documentation is no longer around, it's hard to troubleshoot.
Nonetheless, I CAN tell you that it is not necessary to add an extra wrapper element around your animated content. In the first case, you're explicitly telling react-spring to add an element (animated.XXX) which it of course does. In your second (broken) example, there is no wrapper and I think you could get that to work if you looked into how to use useTransition in that old version.
You should know however that react-spring, when at its best, uses a ref to update elements outside of React. That's why all the basic HTML elements supplied by animated(animated.div, animated.span etc...) have this wrapper behaviour that you have seen. If you use animated to wrap your own component, you basically have two choices:

*

*Make sure your custom component can hold a ref and supply any given ref from animated to it (use forwardRef). Now your component will not rerender all the time but only once, and updates will be handled outside of React. With this method YOU are given the possibility to determine which element you want to give the ref to (instead of react-spring using a wrapper to simplify this for you).

*Don't make your custom component take a ref and accept that your component will be rerendered once on every animation frame (this is what happens in your example, log each render to verify this). This is suboptimal from a performance point of view, but would still work.

So to sum up, this doesn't explain the oddity with the  opacity, but it does explain why react-spring prefers to have a wrapper component to work with, because then it can guarantee that it can animate all the content of that element in an efficient way. Luckily enough, react-spring also gives you the option to choose the element type you want.


text:
Q: How can I tell that threads in ThreadPoolExecutor are done? I am writing code where I need to make sure that no threads are currently running in a thread pool before I commit results (to avoid losing data I should have put in the commit). For that, I'm using:
while (_executor.getActiveCount() > 0)
{
  try
  {
    Thread.sleep(10); // milliseconds
  }
  catch (InterruptedException e)
  {
    // OK do nothing
  }
}

But a colleague pointed out in review that the doc for getActiveCount states:

*

*Returns the approximate number of threads that are actively

*executing tasks.

So, is there a risk I would get out of the while loop while there are still active threads in the pool? If so, what would be the correct way to wait for all my worker threads to be done?
Edit: To give some more context: this is an online system, where the task that contains the executor service is left running indefinitely. Work comes in via a messaging system, is put on a thread in the executor, which doesn't need any synchronization, and works come out into another queue for the messaging system. I don't want to kill the executor to wait for completion of tasks.

A: You might want to consider using a CompletionService (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CompletionService.html).
A CompletionService wraps an ExecutorService and returns a Future when tasks are submitted.  By maintaining a list of these Futures, you can see if the jobs that you're waiting on have completed.  It also has the additional advantage that you can have others use the same ExecutorService since you have some means of accounting,

A: _executor.awaitTermination(); should do the job. Now, it won't actually wait for the threads to shutdown, but rather it would wait for all available tasks to terminate.
You could also provide keepAliveTime to a thread pool constructor to instantly terminate idle threads:
ExecutorService executor = new ThreadPoolExecutor(0, 10, 0L /* keepAlive */,
        TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

A: To notify a thread that it should clean up and terminate, use the interrupt method.
t.interrupt();
and it is good to print or have log of your errors from catch block.

A: When tasks are submitted to the executor, they return Futures, which indicate when they complete. That is the preferred mechanism to use.
You can use JDK ExecutorService shutdown/awaitTermination.

A: Use case: need to cleanup thread-locals in pool threads upon their completion and this cleanup can take long (e.g. connection close). Only after that the main thread can continue.
A worker thread can register itself in some collection. For that override start() and run() and pass a custom thread factory to ThreadPoolExecutor:
class MyThreadFactory implements ThreadFactory {

    @Override
    public Thread newThread(final Runnable r) {
        return new MyThread(r);
    }
...

class Some {
    void waitAllThreads() {
        Thread worker;
        while ((worker = workerThreads.poll()) != null) {
            worker.join();
        }
    }
    ...

class MyThread extends Thread {

    @Override
    public synchronized void start() {
        if (getState() == State.NEW) {
            some.workerThreads.offer(this);
        }
        super.start();
    }

    @Override
    public void run() {
        try {
            super.run();
        } finally {
            some.workerThreads.remove(this);
        }
    }

    ...


text: Q: Zeta function for Gaussian integers I read somewhere that there exists a zeta function for Gaussian integers that involves a combination of the Riemann zeta function and the Dirichlet beta function. Unfortunately, I have lost my source and and searching on internet on this subject does not yield the desired results. Can anyone give me such a definition for Gaussian integers, and possibly some articles I can read on the subject?


text:
Q: Showing Edit / Delete buttons for each row in a GWT CellTable? I have a cell table showing some data. For each row, I want to have two columns which contain edit / delete buttons. When each button is clicked, it should be able to notify a listener which button was clicked (and preferably also be able to pass in the object that row is associated with).
How can I do this? Specifically, I know how to render a button, but how can I process the on-click event and pass in the object which the user clicked to edit or delete?

A: This is the standard approach:
myTable.addCellPreviewHandler(new Handler<MyObject>() {

    @Override
    public void onCellPreview(CellPreviewEvent<MyObject> event) {
        if ("click".equals(event.getNativeEvent().getType())) {
            if (event.getColumn() == 0 || event.getColumn() == 1) {
                MyObject object = event.getValue();
                Window.alert("Column clicked: " + event.getColumn());
            }
        }
    }

});

This is a more efficient solution, because you only have one handler attached to a table, instead of trying to attach a handler to each button in each row.

A: I think you can make a foreach through all the rows in the celltable (I never worked with celltables)
And then you can add your own ClickHandler to the Button.
Something like that (not tested):
final int row = myrow; // add the row value or a object identifier or similar
Button delete_button = new Button("delete");
    delete_button.addClickHandler(new ClickHandler(){
    @Override
    public void onClick(ClickEvent event) {
        // Insert your delete funciton
        delete(row);
   }
});

You mentioned a Listener, Listener are depreciated, use Handler instead.


text:
Q: No internet connection, how to restore to default I have no internet, no icon, and just nothing. This maybe was after few manipulations when i was trying to solve problems with usb modem, which wasn't working properly, which i did a long ago. And now after month later i started my ubuntu, and Currently my ubuntu have no internet connection, on windows internet works fine, can't uninstall ubuntu because there is a lot of staff. ifconfig shows:
Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:515 errors:0 dropped:0 overruns:0 frame:0
TX packets:515 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:115214 (115.2 KB) TX bytes:115214 (115.2 KB)

All Settings -> Network Showing Error Message "The system network services are not compatible with this version"
What is wrong, how can i fix this, Have no idea on how to fix this, Please Help!!!

A: Found the solution, actually one line of code did the job gksu "service network-manager start" from answer @hexafraction


text:
Q: Raphael.js Animate Texts around circle This fiddle will kind of explain it all:
http://jsfiddle.net/Mirodil/Ww2ud/
http://jsfiddle.net/Mirodil/Ww2ud/3/
I'm trying to animate this texts around circle. Each text has its own rotation angle degree. When i try to rotate them around circle, first text loses its rotation angle degree and second time rotate.
How can i rotate texts around circle without losing rotation angle degree?

A: Thank you @Neil. This example helped me to solve my issue. Working example in the bellow link.
http://jsfiddle.net/Mirodil/XTDpF/


text:
Q: Login com ActiveDirectory Estou tentando realizar a conexão com AD. Porém o erro é exibido:

Warning: ldap_connect(): Could not create session handle: Bad
  parameter to an ldap routine in C:\Program Files
  (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\my portable
  files\ad\ad.php on line 8
      Could not connect to LDAP server.

Alguém saberia as possíveis causas para essa falha na conexão?
<?php
$ldap_server = "192.168.2.1/nomeservidor";
$dominio = "DOMINIO/";
$user = $dominio."administrador";

echo $user;

$ldap_porta = "389";
$ldap_pass   = "minhasenha";
$ldapcon = ldap_connect($ldap_server, $ldap_porta) or die("Could not connect to LDAP server.");

if ($ldapcon) {
  $bind = ldap_bind($ldapcon, $user, 'minhaSenha');
  if ($bind) {
    echo "LDAP bind successful…";
  }
  else {
    echo "LDAP bind failed…";
  }
}
?>

Agradeço desde já.

A: Tente usar a sua url de conexão assim:
$ldap_server = "ldap://192.168.2.1/nomeservidor";
Ou então, coloque o número da porta após o ip:
192.168.2.1:porta
Referência:
http://php.net/manual/pt_BR/function.ldap-connect.php


text:
Q: Run Time error - earn for money I tried to solve the UVA problem Earn For Money ID: 12614
on my IDE I get a correct answer for all cases
but when I submitted on the uva online judge I get a run time error
there is my code
import java.util.Scanner;

class Main{

/**
 * UVAonlineJudge
 */
public static void main(String[] args) {
    Main e = new Main();
    Scanner scan = new Scanner(System.in);
    final int T = scan.nextInt();
    for(int i=0 ; i < T ; i++){
         int N = scan.nextInt();
        int[] array = new int[N];
        String line = scan.nextLine();
        int j = 0;
        for(String num : line.split(" ")){
            array[j] = Integer.parseInt(num);
            j++;
        }
        int m= i+1;
        System.out.println("Case "+ m + ": " + e.getMax(array));

    }
    scan.close();
}
int getMax(int[] array){
    int first_max = array[0];
    for(int i=1 ; i < array.length ; i++){
        if(array[i] >first_max){
            first_max = array[i];
        }
    }
    return first_max;
}

}

A: I think you will be getting
Exception in thread "main" java.util.NoSuchElementException
NoSuchElementException is thrown by the nextElement() method of an Enumeration to indicate that there are no more elements in the enumeration.
Check here for more on  No Such Element Exception
So intead of directly using scan.nextInt() , first use hasNextInt() to check wheather an element is present or not
I'll also suggest you to use BufferedReader Class to take inputs.


text:
Q: asp.net and javascript please advise I am completely new to JavaScript and I am having some problems.
My mission is to create a Mouseover and mouseout script which i am having some difficulty with,
My aspx code is

and my code behind c# is
 if ((e.Row.RowType.ToString() != "Header") && (e.Row.RowType.ToString() != "Footer"))
 {
      ImageButton ib = (ImageButton)e.Row.Cells[3].Controls[0];
      ib.Attributes.Add("onmouseover", "ShowToolTip(this);");
      ib.Attributes.Add("onmouseout", "hideToolTip();");

I have no idea what is next.. please help

A: You can directly add these events to img_tool in aspx :

Plus, if you want to access your controls (web controls or html elements) in code behind, you have to add attribute runat="server" :

A: try something like this
if ((e.Row.RowType.ToString() != "Header") && (e.Row.RowType.ToString() != "Footer"))
  {
  ImageButton ib = (ImageButton)e.Row.Cells[3].Controls[0];
  ib.Attributes.Add("onmouseover", string.Format("ShowToolTip('{0}');", ib.ClientId));
  ib.Attributes.Add("onmouseout", string.Format("hideToolTip('{0}');", ib.ClientId));
  }


text:
Q: Removing diy tag Can the diy tag be removed?
I don't see how that would be a good tag for anyone to use.
Unless there is a diy language / pattern / whetever I don't know about.

A: That was definitely a meta tag and is now removed.


text:
Q: How to convert Complex CSV to JSON? I have CSV file which contains many fields and strings.
Here is that CSV file:
https://drive.google.com/file/d/1GVLvTqRv80Gfg1fvBYNx0z5xIiiLCHUo/view?usp=sharing
I want the proper JSON format. When I try with normal functions of python I get some fields in below form:

But I want "population_mesh" and other similar fields in Array (Not String)
-> One more thing is that I also want "population", "intervention", and "Outcomes" fields in array form.
Below is the sample target JSON file
https://drive.google.com/file/d/1Y7oGVyOG777APVqOsLBxc9eSd38pDMbc/view?usp=sharing
Actually I tried to convert "population" and other similar fields to array of strings but some string having quotes identified as a part of JSON jormat but escape character has to be put to make exactly like target JSON.


text:
Q: can't get flex to recognize keyword strings I'm trying to write a syntax highlighter for C programming language using flex. My problem is that the program stops reading input when it reaches any keyword pattern and somehow gets stuck. (the keyword definition rule is the very first rule defined in the rules section) I have no idea on why this is happening and the regex for keywords seems to like fine.
this is the code:
%{
#include <stdio.h>
#include <string.h>
enum token_type{
    KEYWORD,
    ID,
    INTEGER,
    FLOAT_NUMBER,
    SOME_CHARACTER,
    SOME_STRING,
    SPECIAL_CHARACTER,
    COMMENT,
    MULTILINE_COMMENT,
    ENDING_DOUBLE_QUOTE
};
int yy_left_integer;
double yy_left_double;
char* yy_left_string;

%}

%x in_multiline_comment
%x in_string
%option noyywrap
%%

"auto"|"int"|"const"|"short"|"break"|"long"|"continue"|"double"|"struct"|"float"|"unsigned"|"else"|"switch"|"for"|"signed"|"case"|"register"|"default"|"sizeof"|"char"|"return"|"do"|"static"|"void"|"enum"|"typedef"|"goto"|"volatile"|"extern"|"union"|"if"|"while"   {yy_left_string = yytext; return KEYWORD;}

"/*" BEGIN(in_multiline_comment);

"//"[^ \n]* {yy_left_string = yytext; return COMMENT;}

[a-zA-Z_][a-zA-Z0-9_]* {yy_left_string = yytext; return ID;}

(("0x")[+-]?[0-9A-F]+) | ([+-]?[0-9]+) {yy_left_integer = atoi(yytext); return INTEGER;}

([+-]?[0-9]*\.[0-9]+)(E[+-]?[0-9]+)? {yy_left_double = atof(yytext); return FLOAT_NUMBER;}

\" {BEGIN(in_string);}

<in_string>{
[\\.?] {yy_left_string = yytext; return SPECIAL_CHARACTER;}
[^\"\\]* {strncpy(yy_left_string, yytext + 1, strlen(yytext -1)); return SOME_STRING;}
\"  {yy_left_string = yytext; BEGIN(INITIAL); return ENDING_DOUBLE_QUOTE;}
}

\\(.?) {yy_left_string = yytext; return SPECIAL_CHARACTER;}

\'[^ \']?\' {yy_left_string = yytext; return SOME_CHARACTER;}

<in_multiline_comment>{
    "*/" {yy_left_string = yytext; BEGIN(INITIAL); return MULTILINE_COMMENT;}
    ^[*\n]+
    "*"
    "\n"    yylineno++;
}
[\n] {yylineno++;}
[\t\v] {}
. {yy_left_string = yytext;}
%%
int main(int argc, char** argv)
{
    int token;
    if(argc > 1){
        if(!(yyin = fopen(argv[1], "r"))){
        perror(argv[1]);
        return 1;
        }

    }
    FILE* highlighted_html_file = fopen("highlighted.html", "w");
    if(highlighted_html_file == NULL){
        printf("error opening file\n");
        return 1;
    }
    while(token = yylex()){
        if(token == KEYWORD){fprintf(highlighted_html_file,"%s ", yy_left_string);}
        else if(token == ID){fprintf(highlighted_html_file," %s ", yy_left_string);}
        else if(token == INTEGER){fprintf(highlighted_html_file, " %d ", yy_left_integer);}
        else if(token == FLOAT_NUMBER){fprintf(highlighted_html_file, "%f", yy_left_double);}
        else if(token == SPECIAL_CHARACTER){fprintf(highlighted_html_file,  " \"%s ", yy_left_string);}
        else if(token == SOME_STRING){fprintf(highlighted_html_file, " \"%s", yy_left_string);}
        else if(token == ENDING_DOUBLE_QUOTE){fprintf(highlighted_html_file,  "\"");}
        else if(token == SOME_CHARACTER){fprintf(highlighted_html_file,  " \"%s ", yy_left_string);}
        else if(token == COMMENT || token == MULTILINE_COMMENT){fprintf(highlighted_html_file, " %s", yy_left_string);}
        else {fprintf(highlighted_html_file, "%s", yy_left_string);}
    }
}

A: The enum token_type KEYWORD has the value 0, and your loop terminates if your token is 0.
Change
enum token_type{
    KEYWORD,

to be:
enum token_type{
    KEYWORD = 1,

and this problem will disappear.

A: As well as I know you should not copy "yytext" to your variables simply using variable assignment. You should copy it using strdup or something like that.
Also, the following code is awful:
<in_string>{
[\\.?] {yy_left_string = yytext; return SPECIAL_CHARACTER;}
[^\"\\]* {strncpy(yy_left_string, yytext + 1, strlen(yytext -1)); return SOME_STRING;}

What is means? This means that if you process \a, then you will do "yy_left_string = yytext". I. e. now yy_left_string is "char*" pointing to some memory internal to flex. Let's assume then you process normal char, say, z. Now you do "strncpy(yy_left_string,...)". So, you pass yy_left_string (i. e. pointer to some flex-internal memory!!!) to strncpy. So, you write some data into flex internals. This can break everything. And you don't even know if yy_left_string has enough space to store all yytext characters. So, you can easily fall into segmentation fault.
Do you understand how memory in C works? Do you understand pointers etc? Do you understand string handling in C?
Also, I am not sure in all info I provided about yytext. I. e. I am not sure that yytext is really should not be stored in your vars. And I am not sure that it is bad idea to write to memory pointed by yytext. Read flex docs to get all this info.
(Also, your tag "flex" is wrong, because it is about other flex.)


text:
Q: Flask('application') versus Flask(__name__) In the official Quickstart, it's recommended to use __name__ when using a single module:

*... If you are using a single module (as in this example), you should use __name__ because depending on if it's started as
  application or imported as module the name will be different
  ('__main__' versus the actual import name). ...

However, in their API document, hardcoding is recommended when my application is a package:

So it's important what you provide there. If you are using a single
  module, __name__ is always the correct value. If you however are
  using a package, it's usually recommended to hardcode the name of your
  package there.

I can understand why it's better to hardcode the name of my package, but why not hardcoding the name of a single module? Or, in other words, what information can Flask get when it receives a __main__ as its first parameter? I can't see how this can make it easier for Flask to find the resources...

A: __name__ is just a convenient way to get the import name of the place the app is defined.  Flask uses the import name to know where to look up resources, templates, static files, instance folder, etc.  When using a package, if you define your app in __init__.py then the __name__ will still point at the "correct" place relative to where the resources are.  However, if you define it elsewhere, such as mypackage/app.py, then using __name__ would tell Flask to look for resources relative to mypackage.app instead of mypackage.
Using __name__ isn't orthogonal to "hardcoding", it's just a shortcut to using the name of the package.  And there's also no reason to say that the name should be the base package, it's entirely up to your project structure.


text:
Q: Segue not working, cell not selecting Evening,
I have managed to section my table alphabetically (:D) but now the cells do not select.
The idea is that the first view presents a list of words. A word is then selected and that leads to a detail view featuring a glossary. But, the cell doesn't select (turns grey not blue?) and the segue in storyboard running from prototype cell to new view doesn't do anything (clicking a cell in simulator doesn't cause the segue).
Does anyone have a suggestion?
I have included my code below, with the prepareforsegue code ready for when needed.
Thanks guys :)
@interface RCViewController ()

@end

@implementation RCViewController

static NSString *CellIdentifier = @"Cell Identifier";

@synthesize fruits;

-(NSDictionary *)alphabetizedFruits:(NSArray *)fruitsArray {
NSMutableDictionary *buffer = [[NSMutableDictionary alloc]init];

for (int i=0; i <fruits.count; i++) {
    NSString *fruit = [fruits objectAtIndex:i];
    NSString *firstLetter = [[fruit substringToIndex:1]uppercaseString];

    if ([buffer objectForKey:firstLetter]) {
        [(NSMutableArray *)[buffer objectForKey:firstLetter]addObject:fruit];
    }
    else {
        NSMutableArray *mutableArray = [[NSMutableArray alloc]initWithObjects:fruit, nil];
        [buffer setObject:mutableArray forKey:firstLetter];
    }
}
NSArray *keys = [buffer allKeys];
for (int j; j<keys.count; j++) {
    NSString *key = [keys objectAtIndex:j];
    [(NSMutableArray *)[buffer objectForKey:key]sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
}
NSDictionary *result = [NSDictionary dictionaryWithDictionary:buffer];
return result;
 }

 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSArray *keys = [self.alphabetizedFruits allKeys];
return [keys count];
}

 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *unsortedKeys = [self.alphabetizedFruits allKeys];
NSArray *sortedKeys = [unsortedKeys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSString *key = [sortedKeys objectAtIndex:section];
NSArray *fruitsForSection = [self.alphabetizedFruits objectForKey:key];
return  [fruitsForSection count];
 }

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

NSArray *unsortedKeys = [self.alphabetizedFruits allKeys];
NSArray *sortedKeys = [unsortedKeys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSString *key = [sortedKeys objectAtIndex:[indexPath section]];
NSArray *fruitsForSection = [self.alphabetizedFruits objectForKey:key];
NSString *fruit = [fruitsForSection objectAtIndex:[indexPath row]];

[cell.textLabel setText:fruit];

return cell;
 }

 -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section    {
NSArray *keys = [[self.alphabetizedFruits allKeys]sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSString *key = [keys objectAtIndex:section];
return key;
}

 -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:@"showDetail"]) {
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    detailViewController *destViewController = segue.destinationViewController;
    destViewController.word = [fruits objectAtIndex:indexPath.row];
}
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

NSString *path = [[NSBundle mainBundle]pathForResource:@"words" ofType:@"plist"];
NSArray *wordsDictionary = [NSArray arrayWithContentsOfFile:path];
self.fruits = [wordsDictionary valueForKey:@"Word"];

self.alphabetizedFruits = [self alphabetizedFruits:self.fruits];

[self.tableView registerClass:[UITableViewCell class]   forCellReuseIdentifier:CellIdentifier];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

A: you need to add the didSelectRowAtIndexPath method:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // confirm cell is being selected
    NSLog(@"didSelectRowAtIndexPath");

    // perform the segue by getting the cell selected and passing it to the prepareForSegue method
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [self performSegueWithIdentifier:@"showDetail" sender:cell];
}


text:
Q: Windows 2003 DNS subdomains We have a purely internal DNS setup to resolve multiple nics for eash host, i.e. -

*

*mailserver01-sm 1.1.1.1 remote access and AD connectivity (service management)

*mailserver01-data 2.2.2.2 mail routing

*mailserver01-bk 3.3.3.3 backup connectivity

My question is this can I frig DNS by having sub domains of -sm, -data, & -bk under the FQDN ?
so that the following each appear under the relevant subdomains:-

*

*mailserver01-sm.datacenter.int

*mailserver01-data.datacenter.int

*mailserver01-bk.datacenter.int

instead of:-

*

*mailserver01.-sm.datacenter.int

*mailserver01.-data.datacenter.int

*mailserver01.-bk.datacenter.int

A: Having any part of an FQDN starting or ending with a hypen is not a supported configuration. You can create a zone starting or ending in -, but it's really not recommended.
Also, records within that zone (i.e. A or CNAME) that start with a - will not work with most DNS resolvers, as - is usually reserved for flags.
You can use _ however.
Refer to RFC 1035, section 2.3.1 (although it's been revised by RFC 1123 to permit starting with a digit rather than an alpha)


text:
Q: ldd output showing shared object file whose function is not called I ran ldd command on an executable created by Open MPI. It shows a reference to libpthread.so
Using LD_PRELOAD variable I created my own implementation of pthread_create, but from the it output it seems that MPI implementation is not calling pthread_create as I had expected.
Why does ldd show pthread so file in output if it is not being used?
does Open MPI not use a separate MPI thread for every node to implement the functionality?

A: MPI uses processes, not threads. So no, Open MPI will not use a separate MPI thread per node.

A: If the binary is not linked with --as-needed then it will acquire a reference to every library given on the link command line, regardless of whether it is actually needed. Pass -Wl,--as-needed to gcc in order to have it pass the option to ld.


text:
Q: Tried to synchronously call function from a different thread When I try to formate date using dayjs or when I try to format currency using Intl.NumberFormat()
I've got the following error
Code sample

Could anyone help with this?


text:
Q: EF Core insert null value to nullable column that has default value I am curious about specific scenario in SQL when using EF Core.
For example there is a column that allows null and at the same time has defalut value, it is unusual situation but that is not the issue here.
Question is about technical possibility.
[SomeId] [uniqueidentifier] NULL DEFAULT (newsequentialid())

And in Application there is Entity(Code First) which has appropriate Property
public Guid? SomeId { get; set; }

The problem is how to Insert this Entity into DB so that SomeId would have Null value. Because even when property is Null, Database will override it with default value.
This can be done with pure sql by explicitly assigning null to column but it seems that the same can't be done with EF, or am I wrong ?
EDIT:
To elaborate more
public class ExampleTable
{
    [Key]
    int Id { get; set; }

    string Name { get; set; }

    Guid? SomeId { get; set; }
}

In Seed method for example:
var record1 = new ExampleTable
{
    FirstName = "Carson"
}
var record2 = new ExampleTable
{
    FirstName = "Carson",
    SomeId = null
}
context.ExampleTableSet.Add(record1);
context.ExampleTableSet.Add(record2);
context.SaveChanges(record);

record 1 and 2 are the same since SomeId is nullable Guid?, and in both cases after Submiting SomeId in database gets real value from newsequentialid.
Is there any way to keep SomeId Null in database as well.

A: I'm not sure if I understand the question fully, but by modifying your declaration you can set the default value. On creation of a record, 'SomeId' will default to NULL
    public class ExampleTable
    {
        public ExampleTable()
        {
            SomeId = null;
        }

        public Guid? SomeId { get; set; }
    }


text:
Q: Vim: Limit upwards search by one directory I have the following file structure:
.
├── main
└── src
    └── main.c

If I'm editing the file main.c and use the command
:echo findfile(expand('%:t:r'),";")

Vim prints main. But if main does not exist then findfile will keep searching upwards until the root directory / and that can take a long time.
Is there a way to limit the upward search ";" to one directory? I'm looking for something similar to **2 which sets the maximum downward search level to 2.

A: While you cannot limit the upward search to one directory, you can instead specify the starting path to be up one directory relative to where you are now and then search downward only a directory:
:echo findfile(expand('%:t:r'),"../**1")

This works well for the sample question. Higher upward directories (../../../../**4) would become tedious to specify, and would have the detriment of searching in the opposite order (top-down rather than bottom-up), though I'm not sure there's a better way.

A: To limit the upward search level to one I ended up using expand('%:p:h'):
execute "echo findfile(expand('%:t:r'),';".expand('%:p:h')."')"

or use getcwd:
execute "echo findfile(expand('%:t:r'),';".getcwd()."')"


text:
Q: Android Expand and collapse for recyclerview is not working as expected I am developing an app with expandable Recyclerview. But expansion is not working as expected. Nothing works  if I click on any item that is in collapsed state after expanding another item. I want to collapse the previously expanded item automatically if click any other item.
Please see my code for the same :
final boolean isExpanded = position==mExpandedPosition;
holder.expandableLayout.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
if (isExpanded) {
    previousExpandedPosition = position;

}
holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        mExpandedPosition = isExpanded ? -1:position;
        notifyItemChanged(previousExpandedPosition);
        notifyItemChanged(position);

    }
});

Please correct me if anything is wrong with my implementation.

A: As i guess you're just notifying your current item that something has but not the older one which is already expanded which is causing the problem so apply changes as following.
....
holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int previousSelectedPosition = mExpandedPosition;
        mExpandedPosition = isExpanded ? -1:position;

        notifyItemChanged(position); // here we notified our current item
        if (previousSelectedPosition != -1)
           notifyItemChanged(previousSelectedPosition); // here we notified past item
    }
});
....

A: You don't need a "previousExpandedPosition":
private int mExpandedPosition = -1;
@Override
    public void onBindViewHolder(MyAdapter.MyViewHolder holder, final int position) {
        String str = mData.get(position);
        holder.mText.setText(str);

        final boolean isExpanded = position == mExpandedPosition;
        holder.expandableLayout.setVisibility( isExpanded ? View.VISIBLE : View.GONE);
        holder.itemView.setActivated(isExpanded);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mExpandedPosition = isExpanded ? -1 : position;
                    notifyDataSetChanged();
                }
            });
    }


text:
Q: AJAX is successfully posting variables which are not visible in $_POST been scratching my head for hours on this one,
I have the below JQuery code that watches for a change in the select with the name of "CategoryID".  It then posts the value of the "CategoryID" select to a PHP processor script which queries MySQL for the sub categorys and returns the updated options and populates the "SubCategoryID" select.
In the PHP processor script if I var_dump($_POST) at the top of the script I get an empty POST array.  I've also tried dumping the $_REQUEST but still empty print_r() gives the same empty array
However the script runs fine and retrieves the correct data from the db and populates the web page.
I can even change the script and save the "CategoryID" to the DB and it populates it with the correct value...
As a relative nubee to JS for my own understanding how is this possible.
I have looked at some of the other questions posted but none of them give a solution
    $(document).ready(function() {  $('select[name="CategoryID"]').change(function() {
    var selectedCategoryID = $('select[name="CategoryID"] option:selected').val();
    var selectedSubCategoryID = $('select[name="SubCategoryID"] option:selected').val();
    $.ajax({
      method: "POST",
      url: '/../_JQuery/PHPProcessorScript.php',
      data: { CategoryID : selectedCategoryID, SubCategoryID : selectedSubCategoryID },
      cache: false
    }).done(function(data) {
      $("select[name=SubCategoryID]").html(data);
    })
  })
})

PHP Processor script
var_dump($_POST); exit; // Returns an empty array with no ajax values

// If I remove exit the script returns the  expected result so the ajax values are being parsed somehow...
$_POST['CategoryID'] = trim($_POST['CategoryID']);
    $_POST['SubCategoryID'] = trim($_POST['SubCategoryID']);
if (empty($_POST['CategoryID'])) {
    print '<option value="">select a category first</option>';
}

if (!empty($_POST['CategoryID'])) {
    if (ctype_digit($_POST['CategoryID'])) {
        if (strlen($_POST['CategoryID']) <= 11) {
            $DBConnection = new database_connector();
            $PS1SQL = 'SELECT
                        ID,
                        Description
                       FROM db_table
                       WHERE
                        CategoryID = :CategoryID';
            $Statement = $DBConnection->Prepare($PS1SQL);
            $Statement->bindParam(':CategoryID', $_POST['CategoryID'], PDO::PARAM_INT);
            $Statement->Execute();
            if ($PS1RS = $Statement->fetchAll(PDO::FETCH_ASSOC)) {
                $PS1RS = array_merge(array(000 => array('ID' => 0, 'Description' => 'choose a sub category')), $PS1RS);
                foreach ($PS1RS as $Key => $SubCategory) {
                    if ($_POST['CategoryID'] == $SubCategory['ID']) {
                        $SubCategoryList .= "<option value=\"$SubCategory[ID]\" selected=\"true\">$SubCategory[Description]</option>\n";
                    } else{
                        $SubCategoryList .= "<option value=\"$SubCategory[ID]\">$SubCategory[Description]</option>\n";
                    }
                }
                print $SubCategoryList;
            } else {
                print '<option value="" selected="true">Oops! no sub categorys available</option>';
            }
        }
    }


text:
Q: JSON url not working I want to call json array from the server
This line works fine for me
JSONObject json = JSONfunctions.getJSONfromURL("http://midsweden.gofreeserve.com/fetch.php");

but when i try to fetch using my sharedprefences class it does not work and cme with force to to stop , here is that code
 JSONObject json = JSONfunctions.getJSONfromURL("http://midsweden.gofreeserve.com/fetch.php?identifier="
                + Test.this.myprefs.getEmail());

In eclipse it doesn't point any error i mean missing of var deceleration but it doesn't work . Any suggestion ???
Here is what i am seeing in the logcat
05-02 19:49:53.569: ERROR/AndroidRuntime(20721): Uncaught handler: thread main exiting due to uncaught exception
05-02 19:49:53.688: ERROR/AndroidRuntime(20721): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.droidnova.android.howto.optionmenu/com.droidnova.android.howto.optionmenu.Test}: java.lang.NullPointerException
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2621)
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at android.app.ActivityThread.access$2200(ActivityThread.java:126)
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1932)
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at android.os.Looper.loop(Looper.java:123)
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at android.app.ActivityThread.main(ActivityThread.java:4595)
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at java.lang.reflect.Method.invokeNative(Native Method)
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at java.lang.reflect.Method.invoke(Method.java:521)
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at dalvik.system.NativeStart.main(Native Method)
05-02 19:49:53.688: ERROR/AndroidRuntime(20721): Caused by: java.lang.NullPointerException
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at com.droidnova.android.howto.optionmenu.Test.onCreate(Test.java:37)
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2544)
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     ... 11 more
05-02 19:49:53.778: ERROR/ActivityManager(97): fail to set top app changed!
05-02 19:49:58.048: ERROR/PackageInstallationReceiver(248): Remove /data/local/tmp/com.droidnova.android.howto.optionmenu.apk Fail!
05-02 19:51:41.418: ERROR/AndroidRuntime(20746): ERROR: thread attach failed
05-02 19:51:42.818: ERROR/AndroidRuntime(20754): ERROR: thread attach failed
05-02 19:51:43.438: ERROR/AndroidRuntime(20762): Uncaught handler: thread main exiting due to uncaught exception
05-02 19:51:43.448: ERROR/AndroidRuntime(20762): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.droidnova.android.howto.optionmenu/com.droidnova.android.howto.optionmenu.Test}: java.lang.NullPointerException
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2621)
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     at android.app.ActivityThread.access$2200(ActivityThread.java:126)
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1932)
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     at android.os.Looper.loop(Looper.java:123)
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     at android.app.ActivityThread.main(ActivityThread.java:4595)
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     at java.lang.reflect.Method.invokeNative(Native Method)
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     at java.lang.reflect.Method.invoke(Method.java:521)
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     at dalvik.system.NativeStart.main(Native Method)
05-02 19:51:43.448: ERROR/AndroidRuntime(20762): Caused by: java.lang.NullPointerException
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     at com.droidnova.android.howto.optionmenu.Test.onCreate(Test.java:37)
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2544)
05-02 19:51:43.448: ERROR/AndroidRuntime(20762):     ... 11 more
05-02 19:51:45.178: ERROR/ActivityManager(97): fail to set top app changed!
05-02 19:51:54.428: ERROR/AndroidRuntime(20772): ERROR: thread attach failed
05-02 19:51:55.818: ERROR/AndroidRuntime(20780): ERROR: thread attach failed
05-02 19:51:56.528: ERROR/AndroidRuntime(20788): Uncaught handler: thread main exiting due to uncaught exception
05-02 19:51:56.538: ERROR/AndroidRuntime(20788): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.droidnova.android.howto.optionmenu/com.droidnova.android.howto.optionmenu.Test}: java.lang.NullPointerException
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2621)
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     at android.app.ActivityThread.access$2200(ActivityThread.java:126)
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1932)
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     at android.os.Looper.loop(Looper.java:123)
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     at android.app.ActivityThread.main(ActivityThread.java:4595)
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     at java.lang.reflect.Method.invokeNative(Native Method)
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     at java.lang.reflect.Method.invoke(Method.java:521)
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     at dalvik.system.NativeStart.main(Native Method)
05-02 19:51:56.538: ERROR/AndroidRuntime(20788): Caused by: java.lang.NullPointerException
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     at com.droidnova.android.howto.optionmenu.Test.onCreate(Test.java:37)
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2544)
05-02 19:51:56.538: ERROR/AndroidRuntime(20788):     ... 11 more
05-02 19:51:58.658: ERROR/ActivityManager(97): fail to set top app changed!
05-02 19:55:31.438: ERROR/AndroidRuntime(20809): ERROR: thread attach failed
05-02 19:55:38.148: ERROR/AndroidRuntime(20820): ERROR: thread attach failed
05-02 19:55:41.638: ERROR/PackageInstallationReceiver(248): Remove /data/local/tmp/com.droidnova.android.howto.optionmenu.apk Fail!
05-02 20:15:28.608: ERROR/wpa_supplicant(139): Set_key: Wrong Key
05-02 20:15:28.608: ERROR/wpa_supplicant(139): Set_key: Wrong Key
05-02 20:15:28.608: ERROR/wpa_supplicant(139): Set_key: Wrong Key
05-02 20:15:28.608: ERROR/wpa_supplicant(139): Set_key: Wrong Key
05-02 20:15:28.608: ERROR/wpa_supplicant(139): Set_key: Wrong Key
05-02 20:15:29.648: ERROR/wpa_supplicant(139): prepare_filter_struct: type=5
05-02 20:15:32.728: ERROR/wpa_supplicant(139): prepare_filter_struct: type=5

More more detail here is the Test class
public class Test extends ListActivity  {
     Prefs myprefs = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        JSONObject json = JSONfunctions.getJSONfromURL("http://midsweden.gofreeserve.com/fetch.php?identifier="
            + Test.this.myprefs.getEmail());

        try{

            JSONArray  earthquakes = json.getJSONArray("earthquakes");

            for(int i=0;i<earthquakes.length();i++){
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject e = earthquakes.getJSONObject(i);

                map.put("id",  String.valueOf(i));
                map.put("name", "Earthquake name:" + e.getString("name"));
                map.put("password", "Magnitude: " +  e.getString("password"));
                mylist.add(map);
            }
        }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }

        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.test,
                        new String[] { "name", "magnitude" },
                        new int[] { R.id.item_title, R.id.item_subtitle });

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
                Toast.makeText(Test.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();

            }
        });
    }

And here is the share preferences class
package com.droidnova.android.howto.optionmenu;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class Prefs {

    private SharedPreferences _prefs = null;
    private Editor _editor = null;
    private String _useremailaddress = "Unknown";
    private String _serverurl = "http://chinar.gofreeserve.com/db.php";

    public Prefs(Context context) {
        this._prefs = context.getSharedPreferences("PREFS_PRIVATE", Context.MODE_PRIVATE);
        this._editor = this._prefs.edit();
    }

    public String getValue(String key, String defaultvalue) {
        if (this._prefs == null) {
            return "Unknown";
        }

        return this._prefs.getString(key, defaultvalue);
    }

    public void setValue(String key, String value) {
        if (this._editor == null) {
            return;
        }

        this._editor.putString(key, value);

    }

    public String getEmail() {
        if (this._prefs == null) {
            return "Unknown";
        }

        this._useremailaddress = this._prefs.getString("emailaddress", "noidea");
        return this._useremailaddress;
    }

    public String getServer() {
        if (this._prefs == null) {
            return "http://chinar.gofreeserve.com";
        }

        this._serverurl = this._prefs.getString("serverurl", "http://chinar.gofreeserve.com/");
        return this._serverurl;
    }

    public void setEmail(String newemail) {
        if (this._editor == null) {
            return;
        }

        this._editor.putString("emailaddress", newemail);
    }

    public void setServer(String serverurl) {
        if (this._editor == null) {
            return;
        }
        this._editor.putString("serverurl", serverurl);
    }

    public void save() {
        if (this._editor == null) {
            return;
        }
        this._editor.commit();
    }
}

A: You are getting NullPointerException because (most probably) your myprefs is null.
Where do you initialize this field?
Anyhow, for saving references, instead of creating your own solution, you should look at Shared Preferences.

A: Your myPrefs var is null
 public class Test extends ListActivity  {
 Prefs myprefs = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listplaceholder);
    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

 //myprefs can only be null at this point, you need this line or an equivalent for your Prefs class:
 myprefs = PreferenceManager.getDefaultSharedPreferences(this);

    JSONObject json = JSONfunctions.getJSONfromURL("http://midsweden.gofreeserve.com/fetch.php?identifier="
        + Test.this.myprefs.getEmail());

API:
getDEfaultSharedPrefs()
or
getSharedPrefs()
EDIT
Ah yes your using some custom preferences class, so you have to instantiate this class.
  // Your choice of
  Prefs myprefs = new Prefs();
  Prefs myprefs = new Prefs(this);
  Prefs myprefs = new Prefs(getApplicationContext());

getApplicationContext()
or if he method your looking to use is static:
  Prefs.getEmail();

Have a read of this: Top Ten Java Errors (Number 10 and Number 1!)

A: You have a null pointer exception in your code:
Caused by: java.lang.NullPointerException
05-02 19:49:53.688: ERROR/AndroidRuntime(20721):     at com.droidnova.android.howto.optionmenu.Test.onCreate(Test.java:37)

Fix this so at the very least your application will run.


text:
Q: Django - can someone explain saving model info to a db works in a MVC framework? So I have a model class a form class and a views class.
I am having a hard time effectively explaining to someone how it works in the sense of a MVC framework. I am new to django and I have followed the documentation however, i cannot seem to explain it well enough.
To my understanding you create the model, which you pass into your form to create a form, then pass that into your view when you render onto an html page through context then you wait for a user to hit a submit button which returns the info via POST and then you catch that data in your view and go through the necessary steps to save the data. Am I missing anything?

A: In python models.py and the forms together are the controller in MVC since they contain the program logic and control saving objects in the DB, views.py file is showing the content of data, so it's the View. The Model is what django ORM handles for us. It stores the data and handles load/stores in the DB.


text:
Q: how can I toggle the mousewheel behavior in Tilix? I'm using Tilix as a terminal on Ubuntu 20.04 (Focal).
At the moment, I have two shells opened (two instances of bash) in a split window, both working, but:

*

*one has a scrollbar and responds to "mousewheel up/mousewheel down" by scrolling upwards/downwards,

*the other has no scrollbar and responds to the mousewheel by going up/down in my shell's command history.

$ tilix --version
Versions
    Tilix version: 1.9.1
    VTE version: 0.60
    GTK Version: 3.24.20

Tilix Special Features
    Notifications enabled=0
    Triggers enabled=0
    Badges enabled=1

Question

*

*What can I toggle, that would re-activate the "scroll mode" on the second shell window?

*Is it a Tilix toggle, or a bash toggle? (I would be surprised if it were the latter, but you never know)


text:
Q: Appending text to each item in list I would like to add the word days to appear after each item in my list (each item is a numpy.int64) such that each item appears followed by the word days (e.g 6 days).
This is what I have tried so far
medians =  closing_deals.groupby(['origin'])['days_to_close'].median().values
median_labels = [m + 'days' for m in medians]

Here is my data
array([ 9, 11,  7, 27, 13, 42, 35, 10,  9, 23, 17])

This is the error message I am receiving

TypeError: ufunc 'add' did not contain a loop with signature matching
  types dtype

A: You can't concatenate int with string using +, but you can use string formatting to get the output you are looking for. For example:
medians = [9, 11, 7, 27, 13, 42, 35, 10, 9, 23, 17]
labels = [f'{m} days' for m in medians]
print(labels)
# ['9 days', '11 days', '7 days', '27 days', '13 days', '42 days', '35 days', '10 days', '9 days', '23 days', '17 days']

# For Python 3 versions before 3.6, use '{} days'.format(m) instead of the f string


text:
Q: Conditions for a supremum of a set. Suppose a function $f(x)$ is continuous on $[a, b]$ and there exists, $x_0 \in (a, b)$ such that $f(x_0) > 0$. And then define a set,
$$A = \{ a \le x < x_0 \space | \space f(x) = 0   \}$$
We say $c = \sup A$
Does $c$ necessarily have to suffice that $f(c) = 0$ ? ?  Why/ why not?
I am confused about sets so this will be helpful!

A: Yes, provided that $A$ is not empty: Since $c$ is the supremum of $A$, we find a sequence $(x_n)\subset A$ of elements of $A$ converging to $c$. Since each number $x_n$ is an element of $A$, we must have $\color{blue}{f(x_n)=0}$. Since $f$ is $\color{green}{\text{continuous}}$, we conclude
\begin{align*}
f(c)=f\left(\lim_{n\to\infty} x_n\right)\color{green}=\lim_{n\to\infty}f(x_n)\color{blue}=\lim_{n\to\infty}0=0.
\end{align*}


text:
Q: How can I grep JSON record with specific values in Linux Lets say I have this in the same file:
{
  "city": "NY",
  "car": "ford",
  "whatever": "whatever",
  "whatever": "whatever",
  "day": "friday",
  "mood": "good",
  "whatever": "whatever",
  "whatever": "whatever",
}
{
  "whatever": "whatever",
  "city": "NY",
  "car": "ford",
  "day": "monday",
  "whatever": "whatever",
  "whatever": "whatever",
  "whatever": "whatever",
  "mood": "good",
  "whatever": "whatever",
}

How can I grep only that record in which I have "day": "monday"?
I've have actually tried a lot of different ways, for example grep -Po '{[^*]+\n.+day\": \"monday.+[^*]}'
So eventually I want to get this:
{
  "whatever": "whatever",
  "city": "NY",
  "car": "ford",
  "day": "monday",
  "whatever": "whatever",
  "whatever": "whatever",
  "whatever": "whatever",
  "mood": "good",
  "whatever": "whatever",
}

A: Try to use jq to parse the JSON file, for example having this file:
[{
    "city": "NY",
    "car": "ford",
    "whatever": "whatever",
    "day": "friday",
    "mood": "good"
}, {
    "whatever": "whatever",
    "city": "NY",
    "car": "ford",
    "day": "monday",
    "mood": "good"
}]

If you just want to get the dictionary having the day equal to monday:
jq '.[] |  select(.day | contains("monday"))' file.json

It will return:
{
  "whatever": "whatever",
  "city": "NY",
  "car": "ford",
  "day": "monday",
  "mood": "good"
}


text:
Q: how can I see images with NohanaImagePicker pod file? I am using swift 3 and use NohanaImagePickerpod file to select multiple images and its working well the problem is that I want to see selected Images in collection view and i will receive fatal Error in this line
        cell.imageforCV.image =  ViewController.imgArray[indexPath.row]

I used static variation for imgArray
here is my codes
import UIKit
import Photos
import NohanaImagePicker

class ViewController: UIViewController , NohanaImagePickerControllerDelegate , UICollectionViewDelegate , UICollectionViewDataSource {

static var imgArray = [UIImage]()
static var imgCount = Int()
@IBOutlet weak var imageCollectionView: UICollectionView!
var images = [ PHAsset]()
@IBAction func gallery(_ sender: UIButton) {

 let picker = NohanaImagePickerController()
    picker.delegate = self
    present(picker, animated: true, completion: nil)
    picker.maximumNumberOfSelection  = 200
    print("\(picker)")

}
 func nohanaImagePickerDidCancel(_ picker: NohanaImagePickerController) {
    print("Canceled")
    picker.dismiss(animated: true, completion: nil)
}

   func nohanaImagePicker(_ picker: NohanaImagePickerController, didFinishPickingPhotoKitAssets pickedAssts :[PHAsset]) {
    print("Completed\n\tpickedAssets = \(pickedAssts)")
    picker.dismiss(animated: true, completion: nil)
    performSegue(withIdentifier: "back", sender: self)
    let numberOfImages = pickedAssts.count
    print("\(numberOfImages)")

    ViewController.imgCount = pickedAssts.count

    var phAssetArray : [PHAsset] = []

    for i in 0..<pickedAssts.count
    {
        ViewController.imgArray.append(self.getAssetThumbnail(asset: pickedAssts[i]));
    }
    let size = CGSize(width: 50, height: 50)
    let options = PHImageRequestOptions()

    let manager : PHCachingImageManager =  PHCachingImageManager()

    manager.startCachingImages(for: phAssetArray,
                                                  targetSize: size,
                                                  contentMode: .aspectFill,
                                                  options: options)

    imageCollectionView.reloadData()
              }

func getAssetThumbnail(asset: PHAsset) -> UIImage {
    var retimage = UIImage()
    print(retimage)
    let manager = PHImageManager.default()
    manager.requestImage(for: asset, targetSize: CGSize(width: 50.0, height: 50.0), contentMode: .aspectFit, options: nil, resultHandler: {(result, info)->Void in
        retimage = result!
    })
    print(retimage)
    return retimage
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return ViewController.imgArray.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = imageCollectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! imageCell

    print(ViewController.imgArray.count)
    print(indexPath.row)
    print(ViewController.imgArray[indexPath.row])

    cell.imageforCV.image =  ViewController.imgArray[indexPath.row]

    return cell

}

   override func viewDidLoad() {
         super.viewDidLoad()

         imageCollectionView.reloadData()

         self.imageCollectionView!.dataSource = self
         self.imageCollectionView!.delegate = self

    let picker = NohanaImagePickerController()

    // Set the maximum number of selectable images

    // Set the cell size
    picker.numberOfColumnsInPortrait = 2
    picker.numberOfColumnsInLandscape = 3

    // Show Moment
    picker.shouldShowMoment = true

    // Show empty albums
    //        picker.shouldShowMoment = shouldShowEmptyAlbum = true

    // Hide toolbar
    picker.shouldShowEmptyAlbum = true

    // Disable to pick asset
    picker.canPickAsset = { (asset:Asset) -> Bool in
        return false
    }

    // Color
    ColorConfig.backgroundColor = UIColor.white
   }

A: use following function
    func getAssetThumbnail(asset: PHAsset) -> UIImage {
    let manager = PHImageManager.default()
    let option = PHImageRequestOptions()
    var thumbnail = UIImage()
    option.version = .original
    option.isSynchronous = true
    manager.requestImage(for: asset, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in thumbnail = result! })
    return thumbnail
}

Lets take First asset as
    let phAsset = pickedAssts.first


text:
Q: LINQ subquery question Can anybody tell me how I would get the records in the first statement that are not in the second statement (see below)?
from or in TblOrganisations
where or.OrgType == 2
select or.PkOrgID

Second query:
from o in TblOrganisations
 join m in LuMetricSites
 on o.PkOrgID equals m.FkSiteID
 orderby m.SiteOrder
 select o.PkOrgID

A: If you only need the IDs then Except should do the trick:
var inFirstButNotInSecond = first.Except(second);

Note that Except treats the two sequences as sets. This means that any duplicate elements in first won't be included in the results. I suspect that this won't be a problem since the name PkOrgID suggests a unique ID of some kind.
(See the documentation for Enumerable.Except and Queryable.Except for more info.)

A: Do you need the whole records, or just the IDs? The IDs are easy...
var ids = firstQuery.Except(secondQuery);

EDIT: Okay, if you can't do that, you'll need something like:
var secondQuery = ...; // As you've already got it

var query = from or in TblOrganisations
            where or.OrgType == 2
            where !secondQuery.Contains(or.PkOrgID)
            select ...;

Check the SQL it produces, but I think it should do the right thing. Note that there's no point in performing any ordering in the second query - or even the join against TblOrganisations. In other words, you could use:
var query = from or in TblOrganisations
            where or.OrgType == 2
            where !LuMetricSites.Select(m => m.FkSiteID).Contains(or.PkOrgID)
            select ...;

A: Use Except:
var filtered = first.Except(second);


text:
Q: Ограничить количество страниц в пагинации подскажите пожалуйста, каким образом ограничить пагинацию на странице.
На данный момент количество страниц выходит за рамки экрана. Как сделать, что бы было четкое представление информации
Имеется контроллер:
@GetMapping("/ondock")
public String ondockGet(Model model, Principal principal,
                        @RequestParam(value = "page", required = false, defaultValue = "0") Integer page) throws IOException, ParseException {
    Page<Cargo> cargos = cargoService.cargoOndockPage(PageRequest.of(page, 10));
    model.addAttribute("cargos", cargos);
    model.addAttribute("numbers", IntStream.range(0, cargos.getTotalPages()).toArray());
    return "ondock";
}

и HTML кусок:

 0}">

A: Очевидно, нужно скрывать какие-то номера страниц)
Возможно, проще это будет сделать через стили, возможно, например, так:
if(cargos.getTotalPages() > 10) {
    model.addAttribute("numbers",
        IntStream.range(
            page > 5 ? (page - 5) : 0,
            (cargos.getTotalPages() - page) > 5 ? (page + 5) : cargos.getTotalPages()
        ).toArray());
}
else {
    model.addAttribute("numbers", IntStream.range(0, cargos.getTotalPages()).toArray());
}


text:
Q: How to wait till an audio clip is loaded? I'm quite a newbie in JAVA and I am trying to read a clip. Here is my code :
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;

public class TestClipBis {
protected static AudioFormat audioFormat;

public static void main(String[] args) throws Exception {

// Specification of the sound to play
// No control. We assume that the sound can be played on audio system
//File soundFile = new File("chimes.wav");
File soundFile = new File("test.wav");
InputStream is = new FileInputStream(soundFile);
InputStream bufferedIn = new BufferedInputStream(is);
//AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);
AudioInputStream sound = AudioSystem.getAudioInputStream(bufferedIn);

audioFormat = sound.getFormat();
System.out.println(audioFormat);

// Loading the sound into the memory (a Clip)
DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
System.out.println(info);
//Clip clip = (Clip) AudioSystem.getClip();
Clip clip = (Clip) AudioSystem.getLine(info);

System.out.println("Sound frame lenght : "+sound.getFrameLength());
System.out.println("Clip FrameLength before opening : "+clip.getFrameLength());
System.out.println("Clip will open - "+info);
System.out.println("Info format : "+info.getLineClass());

// Check before this line that everything is in memory
// Yes, but how ?
clip.open(sound);
System.out.println("Clip is open");
System.out.println("Clip FrameLength after opening : "+clip.getFrameLength());
// Due to a bug in Java Sound,
// we explicitly out of the VM when the sounds stop
clip.addLineListener(new LineListener() {
  public void update(LineEvent event) {
    if (event.getType() == LineEvent.Type.STOP) {
        System.out.println("Methode de sortie");
      event.getLine().close();
      System.exit(0);
    }
  }
});

// Playing the clip
clip.start();

System.out.println("IsActive : "+clip.isActive());
//clip.close();

 }
}

My problem is how to be sure that the clip is loaded in memory before opening and playing it ? With the above code, when I open and play the sound file, I have few seconds of playing but never the same length, randomly, and never the full song.
Or should I use something else than a clip to play a song? But I want to "move" into the song and not only streaming it from the start to the end.
Edit:
Ok, I tried few things. First, I tried to see if the "ByteArrayOuptputStream" was written. I had a "println" in the loop and yes, all is written but it don't fix the problem.
Then, when I open the clip, I tried to add the parameters : audioformat, bytearray, startpoint, bufferlength. Nothing better.
Then, I noticed that when the sounds stop, the method to exit was used. So, I tried to "mute" that method (with comment signs). The result is different : it read the file but the sound is jerky. And when I check the CPU use, it's around 100%. Is it a first clue to guess what's the problem ?
I tried to make a loop that indicates the frameposition after the start : all the frames are read but the sound is still jerky.
I also tried the thead.sleep before and after the start method : nothing better.
So, here is the code I use. Many code parts are between "comment quotes" because they are try, unsuccessfull...
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;

public class TestBufferedClip {
protected static AudioFormat audioFormat;
public static ByteBuffer buffer;

public static void main(String[] args) throws Exception {

// Specification of the sound to play
// No control. We assume that the sound can be played on audio system
//File soundFile = new File("chimes.wav");
File soundFile = new File("test.wav");
FileInputStream fis = new FileInputStream(soundFile);

ByteArrayOutputStream baos = new ByteArrayOutputStream((int)soundFile.length());

byte[] buf = new byte[1024];
int n = 0;
int loop = 0;
while ((n=fis.read(buf))>=0) {
    baos.write(buf);
    buf=new byte[1024];
    System.out.println("Loop = "+loop);
    loop+=1;
}
byte[] ba = baos.toByteArray();
System.out.println("ByteArray size : "+ba.length);
ByteArrayInputStream bais = new ByteArrayInputStream(ba);

//AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);
AudioInputStream sound = AudioSystem.getAudioInputStream(bais);
audioFormat = sound.getFormat();
System.out.println(audioFormat);

// Loading the sound into the memory (a Clip)
DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
System.out.println("Info :"+info);
//Clip clip = (Clip) AudioSystem.getClip();
Clip clip = (Clip) AudioSystem.getLine(info);

System.out.println("Sound frame lenght : "+sound.getFrameLength());
System.out.println("Info format : "+info.getLineClass());

// Check before this line that everything is in memory
// Yes, but how ?
clip.open(audioFormat, ba, 0, ba.length);
//clip.open(sound);
System.out.println("Clip is open");
System.out.println("Clip FrameLength after opening : "+clip.getFrameLength());
// Due to a bug in Java Sound,
// we explicitly out of the VM when the sounds stop
/*
clip.addLineListener(new LineListener() {
  public void update(LineEvent event) {
    if (event.getType() == LineEvent.Type.STOP) {
        System.out.println("Methode de sortie");
      event.getLine().close();
      System.exit(0);
    }
  }
});
*/

// Playing the clip
System.out.println("Before thread sleep");
try {
    Thread.sleep(31000);
} catch (InterruptedException e){
    e.printStackTrace();
}
System.out.println("After thread sleep");

clip.start();

System.out.println("IsActive : "+clip.isActive());
/*
while (clip.isActive()==true) {
    System.out.println("Position = "+clip.getFramePosition());
}
*/
//clip.close();

}
}

@Phil Freihofner :
I thought about your solution to read and discards data until I reach my "start" point. You wrote "In order to start at a point within the audio file, using a SourceDataLine, you would have to read and discard data from the audio input line until you got to the desired starting spot". How do you do that ? When I use the "SourceDataLine" method, my start method is a loop with a line.write(bytes, 0, bytesreads); to point the sound on the speakers.
So, how do you just read and discard ? I didn't find any "read" method with the line.

A: javax.sound.sampled supports two objects for playing back audio. The Clip, as you are using, has to be loaded completely into memory before one can play it back. On the plus side, it is also easy to position the playback to start from within the Clip, either using microseconds or frame position.
I see no benefit from first loading the sound into a byte buffer. That is a redundant level of buffering for Clips. I'd only do it if you were trying to do DSP or something else that requires getting to the data, something beyond the Clip's built in ability to set a start point.
If you are able to preload the possible audio choices as Clips before they are selected, that might be the best solution, as long as you don't run out of RAM.
The other option for playback is a SourceDataLine. It reads and plays back the file on a per-buffer basis. Thus, it can start up quicker than an unloaded Clip (no need to load the entire file into memory first). However, once the Clip is preloaded, the Clip will play back without having to do repeated file loads.
In order to start at a point within the audio file, using a SourceDataLine, you would have to read and discard data from the audio input line until you got to the desired starting spot. You can do this by counting frames (the format will tell you the number of bytes per frame). This reading and discarding would disrupt timing a bit, but my experience has been that reading and discarding audio data is a couple of orders of magnitude faster than playback, since playback involves blocking queues to keep the output at the required frame rate.
Check the Java Sound Tutorials for more info, which includes links to the Clip and SourceDataLine APIs.
Here is an example of the loading of a Clip:
File soundFile = new File("test.wav");
AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);
DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(sound);

The data from test.wav should now be in RAM. All that other stuff you have using byte buffers and buffered lines is unnecessary.
When you are ready to play, use clip.setMicrosecondPosition(long milliseconds) to set your sound to start at the desired location, (not needed if you are starting from the beginning, unless you've already played the Clip, in which case the position will be where it was when you stopped). Then use clip.start() to commence playing.
IMPORTANT NOTE: playback will end prematurely if the program running it exits. One way to test this is to put a Thread.sleep(long milliseconds) command after the clip.start(), where the value of milliseconds is longer than the length of the clip. But that is not a real solution, just a diagnostic to prevent the program from closing the clip playback thread. You should be handling keeping the program running from the main threads, not the thread with the audio playback.

A: First read whole into a byte buffer. Do this by copying all content from file to ByteArrayOutputStream. This way you will have whole media content in memory. Now you can wrap array from ByteArrayOutputStream.toByteArray() into ByteArrayInputStream and provide that pure in-memory stream as audio input stream.


text:
Q: a defined dictionary gets undefined when i dict trough it I have an funtion that makes a get request to an server and the server respond to it and i need to check the status code but when i use the key of the responded dict i get the log that its undefined, but when i do this in the console i do get the status code.
function check_object(time_link_check){
        var x = $.get(time_link_check);
        //1
        console.log(x)
        //2
        console.log(x.status)
    }

*

*

Object {
  readyState: 1,
  getResponseHeader: getResponseHeader(e),
  getAllResponseHeaders: getAllResponseHeaders(),
  setRequestHeader: setRequestHeader(e, t),
  overrideMimeType: overrideMimeType(e),
  statusCode: statusCode(e),
  abort: abort(e),
  state: state(),
  always: always(),
  catch:
    catch (e),
  …
}

*undefined


text:
Q: Bibtex: How to start numbering citations from only a specific page? In my thesis, I am using \bibliographystyle{IEEEtran} so that the references will be ordered in the order of their appearance. In my Acknowledgements (which comes well before the introduction chapter), I need to cite some journal. Hence the first citation in the introduction chapter will not start from '1'! I need bibtex to start numbering only from the introduction chapter. Any help to resolve this issue?

A: With every call to \cite, LaTeX writes to the .aux file. All we have to do is mimic \cite without this writing feature:

\documentclass{article}

\usepackage{filecontents}
\begin{filecontents*}{\jobname.bib}
\@article{lorem,author={Lorem Ipsum}}
\@article{ipsum,author={Ipsum Lorem}}
\end{filecontents*}

\makeatletter
% Partly taken from http://mirrors.ctan.org/macros/latex/unpacked/latex.ltx
\newcommand{\citenocite}[1]{%
  \@ifundefined{b@#1}{\hbox{\reset@font\bfseries ?}
    \G@refundefinedtrue
    \@latex@warning
      {Citation `#1' on page \thepage \space undefined}}
    {\mbox{[\csname b@#1\endcsname]}}}
\makeatother

\begin{document}

\citenocite{ipsum} \cite{lorem} \cite{ipsum}
\bibliographystyle{IEEEtran}
\bibliography{\jobname}

\end{document}


text:
Q: Istio virtualservice uri match not working I am new to kubernetes and istio. On GKE, I have created ingress-gateway and two virtual services. The first one is frontend-gateway that routes to hipstershop and the second one is dummyservice which route to my hello world server. But when I call with
curl -v http://35.223.232.224/dummy

, it shows Cannot GET /dummy error.I'm sure my dummyservice is working since I have tested with Loadbalancer external IP.But I can call to hipstershop with http://ingress_ip. Can someone please help me?
Here is my istio config file
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: frontend-gateway
spec:
  selector:
    istio: ingressgateway # use Istio default gateway implementation
  servers:
  - port:
      number: 80
      name: http
      protocol: HTTP
    hosts:
    - "*"
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: dummy-ingress
spec:
  hosts:
  - "*"
  gateways:
  - frontend-gateway
  http:
  - match:
    - uri:
        exact: /dummy
    route:
    - destination:
        host: dummyservice
        port:
          number: 80

---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: dummy-ingress2
spec:
  hosts:
  - "*"
  gateways:
  - frontend-gateway
  http:
  - match:
    - uri:
        exact: /dummy2
    route:
    - destination:
        host: dummyservice
        port:
          number: 80

---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: frontend-ingress
spec:
  hosts:
  - "*"
  gateways:
  - frontend-gateway
  http:
  - route:
    - destination:
        host: frontend
        port:
          number: 80

A: My dummyservice node.js server is only serving on "/" url. So the error 404 returning is not from ingress but from my node.js server.Changing my base route in node server solved the issue.
'use strict';

const express = require('express');

// Constants
const PORT = 80;
const HOST = '0.0.0.0';

// App
const app = express();
app.get('/dummy', (req, res) => {
  res.send('Hello world\n');
});

app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);

A: FYI : Kaili and Jaeger can be installed with Istio and can give you information about traffic in your service mesh


text:
Q: Explain this margin logic for leftBarButtonItem, rightBarButtonItem, titleView Can anyone explain to me where the margins you see in this screen shot below are coming from? I want the red, green and blue rectangles to all fit next to each other in both screen layouts, landscape and portrait. Instead I see inexplicable margins between the views.
// Setup Left Bar Button item
UIBlankToolbar* tools = [[[UIBlankToolbar alloc] initWithFrame:CGRectMake(0, 0, 115, 44)] autorelease];
tools.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[tools setBackgroundColor:[UIColor greenColor]];
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:tools] autorelease];

...

// Setup Right Bar Button Item
UIBlankToolbar* tools = [[[UIBlankToolbar alloc] initWithFrame:CGRectMake(0, 0, 100, 44)] autorelease];
[tools setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
[tools setBackgroundColor:[UIColor redColor]];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:tools] autorelease];

...

// Setup Title View
self.navigationItem.titleView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 44)] autorelease];
self.navigationItem.titleView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self.navigationItem.titleView setBackgroundColor:[UIColor blueColor]];

What I see with this code:

What really perplexes me is that the margins between views become BIGGER as the space available becomes smaller? I don't understand why they are there, nor why they behave counter to what I expect from margins.
Thanks!

A: The navigation bar has minimum margins between its items that it enforces and that's why you can't get rid of the margins.
Explaining your specific code is not very hard either: 115+100+50 = 265 and the width of the screen is 320, so the navigation bar has 55 pixels to use as margins. The left item is left aligned, the right item is right aligned and the middle item is centered.
So the margins you get in portrait makes perfect sense.
What you're seeing in landscape is due to your flexible width. You're not supposed to have flexible width on items in a navigation bar, so the behavior when doing that is undefined, i.e., the bug is in how you use the navigation bar and not in the navigation bar itself.
What's happening is that the new size for the right item is calculated first. It grows from 100 to 100+(480-320) = 260. Then the middle item's size is calculated and it seems like it just takes all the size available to it. When it's time for the left item to be calculated it actually shrinks since the right and middle item has taken all the space, so when the navigation bar enforces the margins the pixels are taken from the left item.
The actual algorithm may differ. After all it's closed source and I'm trying to explain undefined behavior, but looking at the produced margins that seems to be what's happening.
Anyway, you're app should never rely on undefined behavior, as undefined behavior may change between versions and break it. What you should do is create your own custom view and add it as a subview of the navigation bar. Then you'll handle margins within your view the way you want to.
yourView = [[YourView alloc] initWithFrame:(UIInterfaceOrientationIsPortrait(interfaceOrientation)) ? CGRectMake(0, 0, 320, 44) : CGRectMake(0, 0, 480, 44)];
yourView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self.navigationController.navigationBar addSubview:yourView];


text:
Q: Cache convention and overriding I've made a convention that allow caching of all entites by default.
But for some entites I want to remove caching. I thought about using
AutoMappingOverriding but I don't know if it is possible to say
NoCache in AutoMappingOverriding.
Thanks,

A: Using another slightly related post I came up with the following:
// setup caching
var typesToIgnoreForCaching = new Type[] { typeof(Type1ToNotCache), typeof(Type2ToNotCache) };
var typesToCache = typeof(IEntity).Assembly.GetTypes().Where(t => config.ShouldMap(t)
            && !typesToIgnoreForCaching.Contains(t)).ToList();
 var cacheOverride = new CacheOverride();
 cacheOverride.DoOverrides(m, typesToCache);

The CacheOverride class is as follows:
class CacheOverride : PersistenceOverride<object>
{
    public override Action<AutoMapping<T>> MyOverride<T>()
    {
        return am =>
        {
            am.Cache.ReadWrite();
        };
    }
}

Where the PersistenceOverride class is:
abstract class PersistenceOverride<I>
{
    public void DoOverrides(AutoPersistenceModel model, IEnumerable<Type> Mytypes)
    {
        foreach (var t in Mytypes.Where(x => typeof(I).IsAssignableFrom(x)))
            ManualOverride(t, model);
    }

    private void ManualOverride(Type recordType, AutoPersistenceModel model)
    {
        var t_amt = typeof(AutoMapping<>).MakeGenericType(recordType);
        var t_act = typeof(Action<>).MakeGenericType(t_amt);
        var m = typeof(PersistenceOverride<I>)
                .GetMethod("MyOverride")
                .MakeGenericMethod(recordType)
                .Invoke(this, null);
        model.GetType().GetMethod("Override").MakeGenericMethod(recordType).Invoke(model, new object[] { m });
    }

    public abstract Action<AutoMapping<T>> MyOverride<T>() where T : I;
}

Essentially, all this does is go through the list of entities in your domain, via reflection, and manually override each entity with your convention caching strategy. You just need to add whichever types you don't want caching to typesToIgnoreForCaching.
Also, you'll need to modify the typesToCache line so that it corresponds to however you've set up your domain.
Thanks to Tom for the code to produce an Action<AutoMapping<T>>


text:
Q: How to Merge multiple records from the concatenated column I have multiple columns that has to be concatenate. I did it using a function. Next I need to merge multiple row into a single record separated by comma. I have a reference number (Sr#).
In the below image you can see how I concatenate the columns to a single column. we can see the duplicates in the row 4,5 and 6,7. I need help to understand how to merge those records with ref to sr#.
select Sr.sr#, a.created ||' // ' ||a.OWNERLASTNAME||' // ' ||a.OWNERFIRSTNAME||' // ' ||a.DESCRIPTION||' // ' ||a.activitystatus||' // ' ||a.ACTIVITYSUBSTATUS||' // ' ||a.closeddate as Dispatch_comments

From smaxtable

Please show me the solution to this. Thank you

A: If I understood you correctly, you want to "concatenate" distinct values of dispatch_comments value. If that's so (presuming you're on Oracle, as you tagged the question with Oracle-SQLDeveloper tag), one option is to

*

*get distinct dispatch_comments values (which means you'll have to take only one, e.g. MIN value of sr#

*"concatenate" them using listagg. If resulting string exceeds 4000 characters, you'll need xmlagg instead

WITH your_query AS
  (SELECT
        sr.sr#,
        a.created
        || ' // '
        || a.ownerlastname
        || ' // '
        || a.ownerfirstname
        || ' // '
        || a.description
        || ' // '
        || a.activitystatus
        || ' // '
        || a.activitysubstatus
        || ' // '
        || a.closeddate AS dispatch_comments
    FROM smaxtable
  ),
temp AS
  -- in order to get distinct DISPATCH_COMMENTS, take just one (e.g. MIN) sr#
  (SELECT MIN(sr#) sr#,
          dispatch_comments
    FROM your_query
    GROUP BY dispatch_comments
  )
-- finally, aggregate DISPATCH_COMMENTS
SELECT sr#,
       LISTAGG(dispatch_comments, ', ') WITHIN GROUP(ORDER BY NULL) result
FROM temp
GROUP BY sr#


text:
Q: Finding eigenvalues of the linear map of differentiation on polynomial sets I have the following question:

Let $\mathbf{P_2}$ denote the vector space of real polynomials of degree at most two, and let $\mathbf{L}:\mathbf{P_2}\rightarrow\mathbf{P_2}$ be the linear map $\mathbf{L}f=f', $(the derivative of $f$). What are the eigenvalues of $\mathbf{L}$?

I got since the linear map takes $$\begin{pmatrix} \alpha \\ \beta\\ \gamma \end{pmatrix}\rightarrow \begin{pmatrix} 0 \\ 2\alpha \\\beta \end{pmatrix}$$We have $$\begin{pmatrix} 0 \\ 2\alpha \\\beta \end{pmatrix}=\lambda\begin{pmatrix} \alpha \\ \beta\\ \gamma \end{pmatrix}$$
This only will have a solution without $\alpha=\beta=\gamma=0$, when $\lambda=0$
Is this correct? Just making sure my reasoning is sound.

A: Hint: A base for $\mathbf{P_2}$ is $\{1,x,x^2\}$ and the derivatives are
$$1\longmapsto 0,$$
$$x\longmapsto 1,$$
$$x^2\longmapsto 2x.$$
Then the matrix of the transformation is
$\left(\begin{array}{ccc}
0&1&0\\
0&0&2\\
0&0&0
\end{array}\right).$
The characteristic matrix is
$\left(\begin{array}{ccc}
x&-1&0\\
0&x&-2\\
0&0&x
\end{array}\right)$, whose determinant is the characteristic polynomial
$$\chi(x)=x^3,$$
with a  triple zero $\lambda=0$.
These are the matrix's eigenvalues.
The only non trivial eigenvector is
$\left(\begin{array}{c}
1\\
0\\
0
\end{array}\right)$, since
$$\left(\begin{array}{ccc}
0&1&0\\
0&0&2\\
0&0&0
\end{array}\right)
\left(\begin{array}{c}
1\\
0\\
0
\end{array}\right)=0
\left(\begin{array}{c}
1\\
0\\
0
\end{array}\right)
.$$
Remark:
Here a polynomial $a+bx+cx^2$ is manipulated by is components conventionally as  $\left(\begin{array}{c}a\\ b\\ c\end{array}\right)$.

A: Yes, correct.
$0=\lambda\alpha\ \implies\ $ either $\lambda=0$ or $\alpha=0$.
If $\lambda=0$, we get $2\alpha=0$ and $\beta=0$.
If $\lambda\ne 0$ then $\alpha=0$ and hence $2\alpha=\lambda\beta \implies \beta=0$ and also $\beta=\lambda\gamma\implies \gamma=0$. So this case won't give an eigenvector.


text:
Q: Generate a new dataframe from a function in R I'm kinda new to R and I'm trying to make a simple function that would take a sample of n observations from each of the groups in the df:
df <- data.frame(var1=c(rnorm(50,50,10)),b=letters[1:2])

The idea is to get 2 new df with a sample of n observations from eahc group (a or b).
I've tried this:
random_sample_groups <- function(aorb){
  df_out <- df %>%
    filter(group == "aorb") %>%
    sample_n(10)
}

I don't know how to tell R that df_out are dataframes...
Your help will be appreacited, thanks!!

A: dplyr and the tidyverse in general are built primarily around interactive use, so they use techniques (e.g. "masking") to make it simpler to access columns within a data frame. To use the same functions programmatically can entail some extra work.
Here, we can make the function group by a column we specify using the "embrace" or "curly curly" operator {{ }}, which makes it possible for the function to access that column name as it exists inside the environment of the function, and to replicate the same kind of behavior you would normally expect from dplyr.
Here are two useful articles that explain more of the theory and necessity for this.
https://dplyr.tidyverse.org/articles/programming.html
https://rlang.r-lib.org/reference/topic-data-mask.html
library(dplyr)
random_sample_groups <- function(my_df, n, grouping){
  my_df %>%
    group_by( {{grouping}} ) %>%
    sample_n(n) %>%
    ungroup()
}

set.seed(42)
random_sample_groups(df, 2, b)

# A tibble: 4 × 2
   var1 b
  <dbl> <chr>
1  45.0 a
2  43.4 a
3  52.9 b
4  48.2 b