text:
Q: End-to-End Reactive Streaming RESTful service I have read this post and I don't know if it is a stupid question. I am completely newbie in reactive programming.
The question is very simple: supposing I have a fully-reactive back-end, how can I stream to browser (a large text, for instance), and print each chunk to the user as soon as they come from server?
Probably I am missing some important conceptual points, but all I need to know is: Can I send small parts of data (from server to browser), with one single HTTP GET (? or not) request? The key is: can I write those small parts, until the whole data is sent?
Thanks for any help. I really tried google before, but I always get information about other concepts (like websockets, long-polling, react.js), that I think it is not the case.
EDIT: I'am not asking for a specific API ou library. I just want to understand the concept, for example: "You CANNOT do this with HTTP protocol, period!" or "This has NOTHING to do with Reactive Programming, you are confused about what stream really means. See 'something_else.js' ".
EDIT2: I did a small rest controller using spring-mvc (spring-boot) with this method:
@RequestMapping(value = "/flush", method = RequestMethod.GET)
public void flushTest(HttpServletResponse response) {

    response.setContentType("text/html");
    response.setStatus(SC_OK);

    try (ServletOutputStream outputStream = response.getOutputStream()) {
        for (int i = 0; i < 3; i++) {
            String chunk = "chunk_" + i;
            outputStream.print(chunk);
            outputStream.flush();
            response.flushBuffer();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

In the browser, only the whole response arrived, even using the flushBuffer. After some research, that this could be a TOMCAT issue, I changed my pom.xml including undertow:
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>

With default configurations:
server.undertow.accesslog.enabled=true
server.undertow.accesslog.dir=target/logs
server.undertow.accesslog.pattern=combined
server.compression.enabled=true
server.compression.min-response-size=1l

At this moment, using debug in my IDE, each chunk was being written after the flushBuffer.
So, I believe this could be a TOMCAT configuration. Long story short, I know there are a lot of things to help me on "streaming solutions", and thanks for all the comments, but my problem was a little bit more conceptual.

A: There is a protocol on top of HTTP which allows delivery of a server response in smaller, ready-to-be-consumed, chunks to the browser using HTTP transport. It's called SSE (Server Sent Events) or EventSource, here is pretty thoroughly assembled article on the topic.
There are other means to stream data using the HTTP protocol. One such alternative is JSON streaming, in which you write partial responses on the wire from the server and consume the JSON chunks when they arrive. On the consuming side a popular library is called Oboe.js, on the server side you basically need to write the partial data on the response wire when you want to sent it, or when it's available.
For both approaches Rx is useful for handling the streaming logic on the server side. You model the pieces as a stream (handle errors, etc.) and eventually, in the Subscriber, you write the single emissions on the wire, closing the response when the Observable is finished.
On the client side, the EventSource events can be wrapped in a new Observable (via Rx.Observable.create()) and processed further as a stream. Also Oboe.js events can be converted into Observables (via Rx.Observable.fromEvent().


text:
Q: Por quê minha matriz está se reescrevendo? Estou querendo criar uma matriz quadrada de ordem N (N é lido), porém ao entrar no loop, minhas matrizes ficam se reescrevendo e assumindo sempre o último número que digitei.
Já tentei alterar o range, trabalhar com indexadores, mas não obtive êxito.
ordem_matriz = int(input("Digite a ordem da matriz (max 10): "))

matriz = [[0] * ordem_matriz] * ordem_matriz

for i in range(len(matriz)):
    for j in range(len(matriz)):
        matriz[i][j] = int(input(f"Digite o vetor [{i}][{j}]: "))
        print(matriz) # isto aqui é só para o controle do que está acontecendo

Eu esperava que ele fosse preenchendo cada matriz, um por um, mas ele assume, neste caso, nas 3 matrizes, o valor que digitei. No fim eles acabam se reescrevendo. Como perceptível no 1 de tornando 4 na última linha.
Digite a ordem da matriz (max 10): 3

Digite o vetor [0][0]: 1
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

Digite o vetor [0][1]: 2
[[1, 2, 0], [1, 2, 0], [1, 2, 0]]

Digite o vetor [0][2]: 3
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Digite o vetor [1][0]: 4
[[4, 2, 3], [4, 2, 3], [4, 2, 3]]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Projective lines over $\mathbb{Q}$ and $\mathbb{Z}$ I read on this Wikipedia page (about projective lines over rings) that "Similarly, a homography of $P(\mathbb{Q})$ corresponds to an element of the modular group, the automorphisms of $P(\mathbb{Z})$."
Now, a homography of the projective line $P(\mathbb{Q})$ is an element of $\mathbf{PGL}_2(\mathbb{Q})$ (invertible $(2 \times 2)$-matrices over $\mathbb{Q}$, modulo scalars), while elements of the modular group are elements of $\mathbf{SL}_2(\mathbb{Z})$ ($(2 \times 2)$-matrices over the integers with determinant $1$).
Is this correct ?
As homographies are determined up to a scalar, their determinants are determined up to a square of an integer (well, actually of a rational number), so how can this statement work ?

A: This line in the Wikipedia article is incorrect and I have deleted it. You are correct that $PGL_2(\mathbb{Q})$ is the correct group of homographies and is strictly larger than the modular group $PSL_2(\mathbb{Z})$, e.g. the homography $x \mapsto 2x$ corresponding to the matrix $\left[ \begin{array}{cc} 2 & 0 \\ 0 & 1 \end{array} \right]$ is not in $PSL_2(\mathbb{Z})$ because its determinant is not a square.
This whole Wikipedia article is strange. It feels like it was written by one person with idiosyncratic tastes and indeed if you scroll down to the external links you can find out who that person likely was...


text:
Q: Rsync file list slow - including dry runs I have been backing up a server over rsync (v3.0.6) for a while. I noticed that it takes about 20 minutes just to get the incremental file list (I am using the whole file flag). I am excluding three files, if I take these out it only takes a second to start syncing. There are only 319 files (689 if you count the directories that get skipped). Any thoughts or ideas? Pattern matching shouldn't be this slow?
rsync -vvnWr --exclude='aaa.tar.gz' --exclude='bbb.tar.gz' -exclude='ccc.tar.gz' --include='*.tar.gz' --exclude='*' --delete -e "ssh -p 34577 -i /root/.ssh/backup_rsa" root@xxx.xxx.xxx.xxx:/backup/cpbackup/daily/ /backup/jarvis/cpanel/$((($(date +\%-d)-1)/7+1))/*

Sample output
[sender] showing file ddd.tar.gz because of pattern *.tar.gz
[sender] showing file eee.tar.gz because of pattern *.tar.gz
[sender] hiding directory fff.0 because of pattern *
[sender] showing file ggg.tar.gz because of pattern *.tar.gz
...

The output is the same with our without exclusions, obviously it skips the ones I list. With exclusions there are long pauses between each of these. I changed the IP and filenames.
Thanks!

A: I just figured it out, must have needed to sleep on it. I am missing one of the hyphens in an exclude. It must have been reading it as additional parameters without causing any syntax errors, with the -c checksum flag being the one probably causing it to slow down.
Thanks everyone for reading!

A: The main reason this is so slow is because you've disabled most of the optimisations that rsync has to offer. You're almost at the stage of copying all the included files on every run.
Why? You've mandated --whole-file instead of allowing rsync to generate differences. You're also not copying the timestamp with -t or -a, so rsync has to read each file on the local and remote systems to determine if the checksums match.
Try this instead
rsync --dry-run -vvtr \
    --exclude='aaa.tar.gz' --exclude='bbb.tar.gz' -exclude='ccc.tar.gz' --include='*.tar.gz' --exclude='*' \
    --delete --delete-during \
    -e "ssh -p 34577 -i /root/.ssh/backup_rsa" \
        root@xxx.xxx.xxx.xxx:/backup/cpbackup/daily/ \
        /backup/jarvis/cpanel/$((($(date +\%-d)-1)/7+1))/


text:
Q: what's the alternative solution of tornado's "write" in django? I am using django 1.4. I am moving codes from tornado to django. There is self.write() at the end of a class. What 's the alternative solution to self.write()? HttpResponse? There is only one template page
so Do I need to response to other page? can I just call response? or render_to_response to the template page again to wrape data to the page? Is write() same with HttpResponse()?
Hey, guys. there are many "?" above, But I only have one problem. An alternative solution of tornado's "write()" in django.
thx for ur time.
The code in tornado looks like:
class DataHandler(tornado.web.RequestHandler):
    ...
    val = ...
    self.write(val)

Maybe in django?
def DataHandler(request):
    ...
    val = ...
    return HttpResponse(val)

Is that clear about my question?

A: HttpResponse is typically used if you wish to return non-template responses.
To render templates, use render from django.shortcuts, for example:
from django.shortcuts import render

def some_handler(request):
    context_for_template = {}
    return render(request, 'template_name.html', context_for_template)

From Tornado's documentation, write seems to be able to automatically convert a dictionary to JSON. HttpResponse does not do that by default, you should look at Creating a JSON response using Django and Python if it is part of your use case.

A: the HttpResponse module
from django.http import HttpResponse

def current_datetime(request):
    now = datetime.datetime.now()
    html = "It is now %s." % now
    return HttpResponse(html)


text:
Q: SelectAll Textbox Text I am using these following code. I want to when I select all text in the textbox it tells me but I don't know why it's not working. please give me some help. Please give some code so that I can use this when I select all text in the textbox text it tells me
if (textBox1.SelectAll() == true)
        {
            MessageBox.Show("You have selected all text in the textbox");
        }

It will tell me: Operator == cannot be applied to operands of type void and bool

A: Couldn't you simply check whether or not TextBox.SelectionLength == TextBox.Text.Length?
http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.selectionlength.aspx
You comparison fails because you're comparing the text with the return value of the SelectAll method which is void(it returns nothing since it just applies the selection).

A: Because
textBox1.SelectAll()

returns nothing or return type is void
just use
textBox1.SelectAll();

If you want to check if all text is selected or not check
if(textBox1.SelectedText == textBox1.Text)
{
     MessageBox.Show("You have selected all text in the textbox");
}

OR
if(TextBox.SelectionLength == TextBox.Text.Length)
{
     MessageBox.Show("You have selected all text in the textbox");
}

A: if(textBox1.SelectedText==textBox1.Text)
{
}

A: Only use
textBox1.SelectAll();

When this method is executed all the text in text box will be selected. You don't need to compare it with true. TextBox.SelectAll() return type is void. Comparing a boolean with void will give error off course.

A: I think you want to add an event handler for the TextBox.SelectionChanged event and in it, compare the TextBox.SelectedText to the TextBox.Text

A: I think you should use the GotMouseCapture Event Here the code it works fine for me.
 private void textBox_GotMouseCapture(object sender, MouseEventArgs e)
    {
        textBox.SelectAll();
        textBox.Focus();
    }


text:
Q: Problem with columns when importing file with Pandas I have a problem when importing text files on Pandas. There is no problem with columns when I open the file in the text, but when I open it with Pandas, I can't split the columns and Jupiter-notebook recognizes it as one column. I want to have three columns with the title 'Z 'H' and 'err'.what will give me when I open the saved file
data= np.genfromtxt('/path/hubel.dat')
df=pd.DataFrame(data)
df.columns= ['Z', 'H', 'err']
df_groupby_err=df.groupby("err")
for err, H  in df.groupby("err"):
    if err<20:
        print( )
        print( H )
        print( )
f=open("hubble_error_edited-2.txt", "w")
for err, H in df.groupby("err"):
    if err<20:
        f.write("\n"+str(H)+""+ "\n")
f.close()
data= pd.read_csv("/path/hubble_error_edited-2.txt" )

A: You can try to add a blank space in the separator parameter :
data= pd.read_csv("/path/hubble_error_edited-2.txt", sep=' ')


text:
Q: How to get the forwarding status and number? I want to read the phone setting to see if forwarding is enabled or not. And if it is
enabled then I want to get the number that calls are forwarded to. I DO NOT want to use
"PhoneStateListener" because the forwarding can be activated before my app installation.
What is the solution?

A: You can make a broadcast call and register it and try to get the outgoing call as shown below :
public class CallBroadcastReceiver extends BroadcastReceiver
{
    public static String numberToCall;
    public void onReceive(Context context, Intent intent) {
        Log.d("CallRecorder", "CallBroadcastReceiver::onReceive got Intent: " + intent.toString());
        if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
            numberToCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
            Log.d("CallRecorder", "CallBroadcastReceiver intent has EXTRA_PHONE_NUMBER: " + numberToCall);
        }

    }
}


text:
Q: Why does mysql_query() print an error? I am just starting with C and the MySQL C API. I am using mysql_query() to create a table. According to the manual, the function usage is int mysql_query(MYSQL *mysql, const char *stmt_str), and the function returns 0 if successful or non-zero on error. However, whether I use if (mysql_query()) or if ! (mysql_query()), the program always prints to stdout, "Error 0:". Also, in either case, the program does create the database and table.
#include <my_global.h>
#include <mysql.h>

int main (int argc, char **argv)
{
    MYSQL *connection;

    const char DATABASE[] = "test";
    const char HOSTNAME[] = "localhost";
    const char USERNAME[] = "root";
    const char PASSWORD[] = "123456";

    connection = mysql_init(NULL);

    if (connection == NULL)
    {
        printf("Error %u: %s\n", mysql_errno(connection), mysql_error(connection));
        exit(1);
    }

    if (mysql_real_connect(connection, HOSTNAME, USERNAME, PASSWORD, NULL, 0, NULL, 0) == NULL)
    {
        printf("Error %u: %s\n", mysql_errno(connection), mysql_error(connection));
        exit(1);
    }

    if (mysql_query(connection, "DROP DATABASE IF EXISTS test"))
    {
        printf("Error %u: %s\n", mysql_errno(connection), mysql_error(connection));
        exit(1);
    }

    if (mysql_query(connection, "CREATE DATABASE test"))
    {
        printf("Error %u: %s\n", mysql_errno(connection), mysql_error(connection));
        exit(1);
    }

    if (mysql_select_db(connection, DATABASE))
    {
        printf("Error %u: %s\n", mysql_errno(connection), mysql_error(connection));
        exit(1);
    }

    /* The problem that I do not understand is happening in the statement below.
     * It seems that a successful query returns zero, so I should not see "Error 0:"
     */
    if (mysql_query(connection, "CREATE TABLE jobs (id int(11) NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL, PRIMARY KEY (id), UNIQUE KEY name_index (name)) ENGINE=InnoDB DEFAULT CHARSET=utf8"));
    {
        printf("Error %u: %s\n", mysql_errno(connection), mysql_error(connection));
        exit(1);
    }

    mysql_close(connection);
}

A: You simply have put a semicolon ; at the end of the if statement so the code between the curly braces gets always executed!!!
Take away the ; and everything will work as expected

A: This is not completely clear from the man page, but my guess would be that the return code of the function is the error code. So you'd have to capture that return value in a variable and then print the value of that variable in case of an error.


text:
Q: Seeing high CPU spikes in MapBox using SQLite3_Step I'm currently getting a tiling issue in MapBox and it looks like a bottleneck issue with the following code:
rc      = sqlite3_step(pStmt);

in the following function:
- (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args

As you can see in the screenshot below, this issue can sometimes take up to 2-3 seconds to complete:

I have noticed that my code seems to perform this function in bursts. So the CPU will drop to about 10% before spiking up to 100+%. During the time it spikes the MapTiles are drawn, however, before this the map drawing comes to a complete stop. This can happen 2-3 times before the tiles are all drawn.
Has anyone seen this issue before? Not sure if it's my CoreData calls interrupting the MapBox ones?
Any help is much appreciated.

A: Check out the 1.5.0 version, released just today, which improves disk caching performance and might address this for you.


text:
Q: One interface take all the IP addresses and the other one use none I built my first custom kernel and have a few problem with it (see this other post).
I configured with /etc/network/interfaces one ip address on each physical interface of the computer. The commande ip a show the IP addresses on each interfaces.
debian@debian:~$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: enp7s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 64:70:02:11:67:a4 brd ff:ff:ff:ff:ff:ff
    inet 192.168.5.1/24 brd 192.168.5.255 scope global enp7s0
       valid_lft forever preferred_lft forever
    inet6 fe80::6670:2ff:fe11:67a4/64 scope link
       valid_lft forever preferred_lft forever
3: enp0s25: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast state DOWN group default qlen 1000
    link/ether 00:1c:c0:94:71:d1 brd ff:ff:ff:ff:ff:ff
    inet 192.168.5.2/24 brd 192.168.5.255 scope global enp0s25
       valid_lft forever preferred_lft forever
    inet6 fe80::21c:c0ff:fe94:71d1/64 scope link
       valid_lft forever preferred_lft forever
debian@debian:~$

debian@debian:~$ cat /etc/network/interfaces
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
allow-hotplug enp7s0
#iface enp7s0 inet dhcp
iface enp7s0 inet static
address 192.168.5.1/24

allow-hotplug enp0s25
#iface enp0s25 inet dhcp
iface enp0s25 inet static
address 192.168.5.2/24

debian@debian:~$

enp0s25 = intel interface
enp7s0 = realtek interface
The problem is the following :

*

*When I connect an ethernet cable to the intel interface (driver e1000e), i can ping both ip addresses (even if the other interface is down).

*When I connect an ethernet cable to the realtek tp-link interface (driver r8169), i can't ping any  of the ip addresses (including the IP associated to it). The interface goes up when a cable is connected to it.
I searched a bit and I can't find a similar problem to mine.
Do you know why there is a difference between what linux is prompting and what really happen with the interfaces ?
Edit : The problem is not related to the custom kernel, it also appear in the default Debian 4.19 kernel version. But they were working like a charm with a with a PfSense.
Edit 2 : The current route table (can change after the networking service is restarted and the realtek interface is upped before the intel interface).
debian@debian:~$ ip route
192.168.5.0/24 dev enp0s25 proto kernel scope link src 192.168.5.2
192.168.5.0/24 dev enp7s0 proto kernel scope link src 192.168.5.1
debian@debian:~$


text:
Q: iPhone users does not connect to StrongSwan VPN, while Android and Windows 10 users do? I have a StrongSwan VPN that for some reason unknown to me cannot connect iOS users to my VPN server.
A few quick notes:

*

*My StrongSwan server is front for VPN clients who connects to my network. I used WireGuard for my backend site-to-site routing.

*All StrongSwan VPN users are validated against a FreeRadius server.

*StrongSwan clients are assigned an IP on the 192.168.201.0/24 subnet, while WireGuard backbone net is running on the 192.168.200.0/24 subnet.

*All clients are also handed a public IPv6 address belonging to a /48 subnet assigned to me.
I run StrongSwan on Ubuntu 20.04 and my configuration file is located in the /etc/swanctl/config/ folder and is included by default due to filename ends on .conf.
The content are as follows:
# Default VPN server settings for all connections
conn-defaults {
    local_addrs = PUBLIC_IPV4, PUBLIC_IPV6

    local {
      auth = pubkey
      certs = vpn-ecdsa.cer
      id = vpn.example.com
    }

    version = 2
    send_certreq = no
    send_cert = always
    unique = never
    fragmentation = yes
    encap = yes
    dpd_delay = 60s

    rekey_time = 0s
}

# Default login method
eap-defaults {
  remote {
   auth = eap-radius
   id = %any
   eap_id = %any
  }
}

connections
{
  # Generic Android configuration that is extended further down.
  #
  # Works with StrongSwan VPN client for Android
  conn-unix : conn-defaults, eap-defaults {
    children {
      net {
        local_ts = 0.0.0.0/0, ::/0
      }

      net-unix : child-defaults {
      }

      esp_proposals = aes128gcm128-x25519
    }

    proposals = aes128-sha256-x25519
  }

  # All Windows klients matches this rule as username validation
  # is done by 'eap_start = yes' in strongswan.conf.
  #
  # Works with Windows 10 built-in VPN client.
  conn-windows : conn-defaults, eap-defaults {
    children {
      net {
        local_ts = 0.0.0.0/0, ::/0
      }

      esp_proposals = aes256-sha256-prfsha256-modp1024
    }

    proposals = aes256-sha256-prfsha256-modp1024
    pools = IkeVPN-site-ipv4, IkeVPN-site-ipv6

  }

  # A very similar configuration to Windows clients
  # configuration, except iOS uses 2048 bit keys,
  # while Windows uses 1024 bit keys.
  #
  # Does NOT work in its current state.
  conn-ios : conn-defaults, eap-defaults {
    children {
      net {
        local_ts = 0.0.0.0/0, ::/0
      }

      esp_proposals = aes256-sha2_256
      pools = IkeVPN-site-ipv4, IkeVPN-site-ipv6

    }

    proposals = aes256-sha256-prfsha256-modp2048
  }

  # Android users is matched against this connection as they are
  # running the app StrongSwan VPN client. Username is passed in the
  # 'id' field to StrongSwan VPN server.
  conn-unix-site : connections.conn-unix {
    remote {
      id = *@site.example.com
    }
    pools = IkeVPN-site-ipv4, IkeVPN-site-ipv6
  }
}

pools
{
   IkeVPN-site-ipv4 {
      addrs = 192.168.201.0/24
      dns = 192.168.200.1
   }

   IkeVPN-site-ipv6 {
      addrs = 2001:db8:cafe::/97
      dns = 2001:db8::1
   }
}

My configuration is created using the structure given from the following webpage:
https://wiki.strongswan.org/projects/strongswan/wiki/Strongswanconf#Referencing-other-Sections
The reason why I use it is due to avoiding to repeat same configuration settings across all my connection profiles.
If you are not familiar to this setup the following configuration for conn-ios this should be considered equivalent:
conn-ios {
   # Obtained from conn-default
   local_addrs = PUBLIC_IPV4, PUBLIC_IPV6

   local {
      auth = pubkey
      certs = vpn-ecdsa.cer
      id = vpn.example.com
   }

   version = 2
   send_certreq = no
   send_cert = always
   unique = never
   fragmentation = yes
   encap = yes
   dpd_delay = 60s

   rekey_time = 0s

   # Obtained from eap-defaults
   remote {
      auth = eap-radius
      id = %any
      eap_id = %any
   }

   # Obtained from original conn-ios profile above.
   children {
      net {
         local_ts = 0.0.0.0/0, ::/0
      }

      esp_proposals = aes256-sha2_256
      pools = IkeVPN-site-ipv4, IkeVPN-site-ipv6
   }

   proposals = aes256-sha256-prfsha256-modp2048
}

The server certificate listed in the conn-default section is a ECDSA certificate obtained from Let's Encrypt using Acme.sh.
The encryption values for proposalsand esp_proposals in the iOS configuration is taken from the hint in: https://wiki.strongswan.org/projects/strongswan/wiki/AppleClients.
When testing all combinations of Android or Windows users connects without any issues, but when somebody tries to login using iPhone the connection then stalls.
Output from log when an iPhone tries to connect is as follows:
10[IKE] CLIENT_IPV4 is initiating an IKE_SA
10[CFG] received proposals: IKE:AES_CBC_256/HMAC_SHA2_256_128/PRF_HMAC_SHA2_256/MODP_2048, IKE:AES_CBC_256/HMAC_SHA2_256_128/PRF_HMAC_SHA2_256/ECP_256, IKE:AES_CBC_256/HMAC_SHA2_256_128/PRF_HMAC_SHA2_256/MODP_1536, IKE:AES_CBC_128/HMAC_SHA1_96/PRF_HMAC_SHA1/MODP_1024, IKE:3DES_CBC/HMAC_SHA1_96/PRF_HMAC_SHA1/MODP_1024
10[CFG] configured proposals: IKE:AES_CBC_128/HMAC_SHA2_256_128/PRF_HMAC_SHA2_256/CURVE_25519
10[IKE] no matching proposal found, trying alternative config
10[CFG] received proposals: IKE:AES_CBC_256/HMAC_SHA2_256_128/PRF_HMAC_SHA2_256/MODP_2048, IKE:AES_CBC_256/HMAC_SHA2_256_128/PRF_HMAC_SHA2_256/ECP_256, IKE:AES_CBC_256/HMAC_SHA2_256_128/PRF_HMAC_SHA2_256/MODP_1536, IKE:AES_CBC_128/HMAC_SHA1_96/PRF_HMAC_SHA1/MODP_1024, IKE:3DES_CBC/HMAC_SHA1_96/PRF_HMAC_SHA1/MODP_1024
10[CFG] configured proposals: IKE:AES_CBC_256/HMAC_SHA2_256_128/PRF_HMAC_SHA2_256/MODP_1024
10[IKE] no matching proposal found, trying alternative config
10[CFG] selected proposal: IKE:AES_CBC_256/HMAC_SHA2_256_128/PRF_HMAC_SHA2_256/MODP_2048
10[IKE] remote host is behind NAT
10[ENC] generating IKE_SA_INIT response 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(CHDLESS_SUP) N(MULT_AUTH) ]
10[NET] sending packet: from PUBLIC_IPV4[500] to CLIENT_IPV4[6452] (456 bytes)
06[NET] received packet: from CLIENT_IPV4[13549] to PUBLIC_IPV4[4500] (512 bytes)
06[ENC] unknown attribute type INTERNAL_DNS_DOMAIN
06[ENC] parsed IKE_AUTH request 1 [ IDi N(INIT_CONTACT) IDr CPRQ(ADDR MASK DHCP DNS ADDR6 DHCP6 DNS6 DOMAIN) N(ESP_TFC_PAD_N) N(NON_FIRST_FRAG) SA TSi TSr N(MOBIKE_SUP) ]
06[CFG] looking for peer configs matching PUBLIC_IPV4[vpn.example.com]...CLIENT_IPV4[PRIVATE_CLASS_A_ADDRESS]
06[CFG] selected peer config 'conn-ios'
06[IKE] initiating EAP_IDENTITY method (id 0x00)
06[IKE] received ESP_TFC_PADDING_NOT_SUPPORTED, not using ESPv3 TFC padding
06[IKE] peer supports MOBIKE
06[IKE] authentication of 'vpn.example.com' (myself) with ECDSA-256 signature successful
06[IKE] sending end entity cert "CN=vpn.example.com"
06[IKE] sending issuer cert "C=US, O=Let's Encrypt, CN=R3"
06[ENC] generating IKE_AUTH response 1 [ IDr CERT CERT AUTH EAP/REQ/ID ]
06[ENC] splitting IKE message (2816 bytes) into 3 fragments
06[ENC] generating IKE_AUTH response 1 [ EF(1/3) ]
06[ENC] generating IKE_AUTH response 1 [ EF(2/3) ]
06[ENC] generating IKE_AUTH response 1 [ EF(3/3) ]
06[NET] sending packet: from PUBLIC_IPV4[4500] to CLIENT_IPV4[13549] (1236 bytes)
06[NET] sending packet: from PUBLIC_IPV4[4500] to CLIENT_IPV4[13549] (1236 bytes)
06[NET] sending packet: from PUBLIC_IPV4[4500] to CLIENT_IPV4[13549] (500 bytes)
11[JOB] deleting half open IKE_SA with CLIENT_IPV4 after timeout

iPhone users are connecting using the built-in VPN client using the following settings:

*

*Type IKEv2

*Description: VPN server

*Server: vpn.example.com

*Remote id: vpn.example.com

*Local id: BLANK

*Username and password authentication.

*Username: user@site.example.com

*Password: ItIsASecret
Does anyone know why the connection stalls for iOS users when it has loaded the conn-ios profile?
UPDATE
And we have liftoff! :-)
As per advice from @ecdsa I have switched the certificate to a 2048-bit RSA certificate.
My Radius server gets called. User authentication succeeds and client gets assign ip-adresse. I am happy. :-)
My configuration for conn-ios is now:
  conn-ios : conn-defaults, eap-defaults {

    # Overriding defaults from 'conn-default'
    local {
      auth = pubkey
      certs = vpn-rsa.cer
      id = vpn.example.com
    }

    children {
      net {
        local_ts = 0.0.0.0/0, ::/0
      }

      esp_proposals = aes256-sha256
    }

    pools = IkeVPN-site-ipv4, IkeVPN-site-ipv6
    proposals = aes256-sha256-prfsha256-modp2048
  }

Everything else is as-is from my initial configuration.

A: As we can see in the log, the client doesn't support RFC 7427 (otherwise, hash algorithm notifies would get exchanged during IKE_SA_INIT), which defines flexible signature-based authentication.
While IKEv2 also supports ECDSA without that extension, RFC 4754 only added limited support for it (only the three NIST curves may be used and each has a specific hash algorithm assigned). So it's possible Apple clients  only accept/use ECDSA if configured explicitly in a configuration profile (there is an option CertificateType that can be set to e.g. ECDSA256).
If using configuration profiles is not an option, the only alternative is to use RSA server certificates, at least until Apple implements support for RFC 7427 in their IKEv2 client.


text:
Q: Nested calculation of sum with Sqlite query I have
a Sqlite Database with the following Schema:
CREATE TABLE User (
  ID_User integer PRIMARY KEY AUTOINCREMENT,
  Name text
);

CREATE TABLE Payment (
  ID_Payment integer PRIMARY KEY AUTOINCREMENT,
  ID_Advancer integer,
  Amount integer NOT NULL DEFAULT 0,
  Title text,
  Datetxt text
);

CREATE TABLE PayersUser (
  ID_User integer,
  ID_Payment integer
);

http://sqlfiddle.com/#!5/931dc2/1
Meaning of the Schema:

*

*A User kann make a payment (entries Payment.ID_Advancer, Payment.ID_Advancer) henceforth called asset.

*This asset is divided between zero or more Users (entries PayersUser.ID_User,PayersUser.ID_Payment) henceforth called stake.

*The debt of a User is the sum of his stakes.

*The sum for a User is the sum of his asset - his debt.

I want
to select the resulting sum of Payments Users did.
SELECT <...> AS `sum`, `User`.`Name` FROM <...>;

| sum | User.Name |;
|=====|===========|;
|18.33| A         |;
|23.33| B         |;
|-11.6| C         |;

Exemplary procedure:

*

*Get a List of User.ID_User with User.name from Table User.

*For every User.ID_User in that List I do the following:

*

*calculate the assetsOfAUser by
SELECT SUM(Payment.Amount) as assetsOfAUser WHERE Payment.ID_Advancer == User.ID_User;

*calculate the debtsOfAUser by

*

*get a ListSELECT Payment.ID_Payment WHERE Payment.ID_Advancer == User.ID_User without dublicates

*for every Payment.ID_Payment as myPaymentID in that List do:

*

*get the corresponding Payment.Amount asmyPaymentAmount`

*get the count of PayerUser.ID_User as countOfPayers where Payment.ID_Payment = myPaymentID

*calculate stakeOfAUser = (PaymentAmount/countOfPayers)

*calculate debtsOfAUser = SUM( stakeOfAUser )

*calculate sumOfAUser = (assetsOfAUser - debtsOfAUser)

*return a List sumOfAUser as sum, User.name
Example
INSERT INTO User (`Name`) VALUES ('A');
INSERT INTO User (`Name`) VALUES ('B');
INSERT INTO User (`Name`) VALUES ('C');
INSERT INTO User (`Name`) VALUES ('D');
INSERT INTO User (`Name`) VALUES ('F');

INSERT INTO Payment (`ID_Advancer`,`Amount`,`Title`)
  VALUES ('1', '20', 'Test1');
INSERT INTO Payment (`ID_Advancer`,`Amount`,`Title`)
  VALUES ('1', '5', 'Test2');
INSERT INTO Payment (`ID_Advancer`,`Amount`,`Title`)
  VALUES ('2', '30', 'Test3');

INSERT INTO PayersUser (`ID_User`,`ID_Payment`) VALUES (1, 1);
INSERT INTO PayersUser (`ID_User`,`ID_Payment`) VALUES (2, 1);
INSERT INTO PayersUser (`ID_User`,`ID_Payment`) VALUES (3, 1);
INSERT INTO PayersUser (`ID_User`,`ID_Payment`) VALUES (3, 2);

Should Result in:
| sum               | User.Name |;
|===================|===========|;
| +20+5-(20/3)      | A         |;
|    30-(20/3)      | B         |;
|     0-(20/3)-(5/1)| C         |;

*

*User A made a Payment of 20 and 5: [+5][+20]

*User A is one of three Users that the Payment "Test1" of 20 is divided between: [-(20/3)]

*User B made a Payment of 30: [+30]

*User B is one of three Users that the Payment "Test1" of 20 is divided between: [-(20/3)]

*User C made no Payment: [+0]

*User C is one of three Users that the Payment "Test1" of 20 is divided between: [-(20/3)]

*User C is the only User (one of one) that the Payment "Test2" of 5 is divided between: [-(5/1)]

I tried
Inner Joins and inline views in the sqlite requests.
Also loading parts of Data and calculate the sum in php.
But no matter what, it always got to complex and incomprehensible for me to get a result.
http://sqlfiddle.com/#!5/931dc2/1

I am Using php PDO. A solution with more Logic in php would be also ok.
My Priorities are

*

*It is Working

*Easy to understand and maintainable


text:
Q: getting value of selected checkbox from datatable in jsp I'm using Java EE.
Here's my JSP:
<form  method="POST" enctype="multipart/form-data"action="<c:url value="submitSelected"/>">

                id
                name
                <input type="checkbox" id="checkall" />

            <c:forEach var="category" items="${categoryList}">

                    <c:out value="${category.id}"/>
                    <c:out value="${category.name}"/>
                    <input type="checkbox" name="selectedCategory" value="${category.id}" />

            </c:forEach>

        <button type="submit" id="select" >submit</button>

</form>

Here's my JS:

I get my checkbox values in my servlet using:
String checkboxValues[] = request.getParameterValues("selectedCategory");

I'm using datatable in my JSP. My problem is if my JSP displays more than 1 page and I select some rows from those pages, my servlet only get values only from displayed page. How do I get all the selected values from the servlet? And if I use the checkall checkbox, how do I get all values from the servlet?

A: JSP is quite a straightforward technology. Any server-side paging which is done in JSP is usually managed by the programmer. JSP doesn't assist you with pagination.
Usually programmers do elaborate orchestration to make pagination work (like passing around parameters like currentPage, totalPages, rowsPerPage etc. and then filtering few rows that will be displayed on the page. They also give hyperlinks for page numbers and more hyperlinks for Previous page and Next page links).
From the code snippet that you have shared, it looks like all rows from categoryList are displayed. If categoryList has 1000 rows, all 1000 rows will be displayed in the same page.
For pagination to work, there should be some servlet or struts Action where the categoryList is managed. Only few rows which are relevant to the current page number should be loaded into that array list.
Considering all this, you can understand that even stuff like 'check-all' would have to be managed by the developer using a fair bit of coding.
Whenever the user clicks to navigate away from a page, you may have to append the category ids corresponding to the selected check-boxes to the URL for the next page, and then on the server maintain an array list of selected category ids. You would also have to clear this list if the user performs a new search and so on.


text:
Q: How to display select options based on value in Angular I want to display some options in a select list based on data in an object. For example if the data property is 0 i want to display a select option as 0 , with option to change to 1, vice versa. However in the html, no option value is played in the field. What am i doing wrong?
Here is my code:

            Set Visibility
            <select *ngIf="category.isVisible === 0" class="form-select" id="isVisible" formControlName="isVisible">
                <option selected value="0">Hidden</option>
                <option value="1">Visible</option>
            </select>
            <select *ngIf="category.isVisible === 1" class="form-select" id="isVisible" formControlName="isVisible">
                <option selected value="1">Visible</option>
                <option value="0">Hidden</option>
            </select>

Here is an example of an object i am passing to the html/view:
{
    "id": 10023,
    "product": "nike tiempo trainers",
    "price": 55.00,
    "isVisible": 1
}

A: Not suggest doing your approach manually, but would suggest that just provide the category.isVisible value to FormControl. The reactive form will handle it.
<select class="form-select" id="isVisible" formControlName="isVisible">
  <option value="0">Hidden</option>
  <option value="1">Visible</option>
</select>

Solution 1: Patch value to FormControl.
Note: This approach is not suggested if the category object is got from API.
this.form = this.fb.group({
  isVisible: [this.category.isVisible],
});

Solution 2: Patch value to FormControl.
this.form.controls.isVisible.patchValue(this.category.isVisible);

Solution 3: Patch category object to FormGroup.
Note: Do consider this approach when you want to bind the whole object to the form group instead of binding each property to form control one by one.
this.form.patchValue(this.category);

Sample StackBlitz Demo


text:
Q: Is there a way to run a command after a specified command Im trying to find a way to run a simple echo command after i run a separate command.
In this specific case I am trying to run a command like
echo 'dont forget to add the newly created app to settings'
after i run
python manage.py createapp newAppName

A: That's what happens naturally if you write one statement after the other. In a script, write:
python manage.py createapp newAppName
echo 'dont forget to add the newly created app to settings'

If you're typing the commands interactively you might want them on one line. Use ;:
python manage.py createapp newAppName; echo 'dont forget to add the newly created app to settings'

Or use && to only run echo if manage.py succeeds:
python manage.py createapp newAppName && echo 'dont forget to add the newly created app to settings'


text:
Q: Is 42 in the French Premier League the maximal number of points possible to be relegated? This is Saturday night mathematics, yet, it is not an absurd exercise
The French premier league has 20 teams. After 38 matches (all teams meeting each other twice), the last 3 by point total are relegated to the next division.
Points are acquired by the following rule: win 3, draw 1, lose 0.
The heuristic rule is that 43 is the magic number, namely a teams reaching 43 points will not be relegated. My question is, is this true? Of course the number comes from historical observation, not a computation, but the real threshold number is in principle computable.

A: By no means! If each team wins once and loses once against each opponent, then every team will end up with 57 points, and the relegated teams will be decided by goal difference.
If you don't want goal difference to be a factor, then have three of the teams exchange one of their wins for a draw. These teams will end up on 55 points, and will all be relegated.


text:
Q: How to pass proporty of a class define in model as URL action paramter I received the following error message:

Compiler Error Message: CS0746: Invalid anonymous type member
  declarator. Anonymous type members must be declared with a member
  assignment, simple name or member access.

from the following line:
<a href="@Url.Action((string)ViewBag.RequeryAction, (string)ViewBag.Vertical, new {  filters.size ="medium"})

How can I pass the filter properties to the controller?

I have defined the following types:
class Filters {
     string Layout;
  `  bool onlyBlack
}

class Image {
    Filters filter;
    double height;
}

A: You can't declare a property name with a dot in it. filter.size is not a valid name.
Use this instead:
<a href="@Url.Action((string)ViewBag.RequeryAction, (string)ViewBag.Vertical, new { filtersSize ="medium"})


text:
Q: Javascript - accessing single name value pair not working Can anyone tell me why this is not working?
var fieldsValid = {
    registerUserName: false,
    registerEmail: false,
    registerPassword: false,
    registerConfirmPassword: false
};

function showState () {
    var str = "
registerUserName: " +  fieldsValid[registerEmail] + "
" ;
    document.getElementById('showstate').innerHTML = str;
}

showState();

There is no output into my div.

A: Use quotes around the property name because otherwise, registerEmail is treated as a variable containing the property name, not a property name:
var str = "
registerUserName: " +  fieldsValid['registerEmail'] + "
" ;

Or use the . syntax without quotes:
var str = "
registerUserName: " +  fieldsValid.registerEmail + "
" ;

MDN Working With Objects is a good resource, relevant to this.
For future debugging, observe the console (F12) in your browser.

A: Let's say you have someObject.
someObject[johndoe] Returns the item in someObject that has johndoe's value (since here it is a variable) as index.


text:
Q: Radio Button Alignment in flutter I am a newbie in flutter. I wanted to Align the radio buttons. i.e Radio button should be Aligned Column wise whatever the text is there.
I am using Column widget then Row Widget in it but getting the below result.

Code is here
 Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Row(
                children: [
                  Radio(value: 1, groupValue: 'null', onChanged: (index) {}),
                  Text('Radio button 1')
                ],
              ),
              Row(
                children: [
                  Radio(value: 1, groupValue: 'null', onChanged: (index) {}),
                  Text('Radio 2')
                ],
              ),
              Row(
                children: [
                  Radio(value: 1, groupValue: 'null', onChanged: (index) {}),
                  Text('Test')
                ],
              ),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Row(
                children: [
                  Radio(value: 1, groupValue: 'null', onChanged: (index) {}),
                  Text('RB 1')
                ],
              ),
              Row(
                children: [
                  Radio(value: 1, groupValue: 'null', onChanged: (index) {}),
                  Text('Btn Radio 2')
                ],
              ),
              Row(
                children: [
                  Radio(value: 1, groupValue: 'null', onChanged: (index) {}),
                  Text('Rad 3')
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }

A: You can use the below lines I hope this will help you

Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Expanded(
              child: Row(
                children: [
                  Radio(
                      value: 1, groupValue: 'null', onChanged: (index) {}),
                  Expanded(
                    child: Text('Radio button 1'),
                  )
                ],
              ),
              flex: 1,
            ),
            Expanded(
              child: Row(
                children: [
                  Radio(
                      value: 1, groupValue: 'null', onChanged: (index) {}),
                  Expanded(child: Text('Radio 2'))
                ],
              ),
              flex: 1,
            ),
            Expanded(
              child: Row(
                children: [
                  Radio(
                      value: 1, groupValue: 'null', onChanged: (index) {}),
                  Expanded(child: Text('Test'))
                ],
              ),
              flex: 1,
            ),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Expanded(
              flex: 1,
              child: Row(
                children: [
                  Radio(
                      value: 1, groupValue: 'null', onChanged: (index) {}),
                  Expanded(child: Text('RB 1'))
                ],
              ),
            ),
            Expanded(
              flex: 1,
              child: Row(
                children: [
                  Radio(
                      value: 1, groupValue: 'null', onChanged: (index) {}),
                  Expanded(child: Text('Btn Radio 2'))
                ],
              ),
            ),
            Expanded(
              flex: 1,
              child: Row(
                children: [
                  Radio(
                      value: 1, groupValue: 'null', onChanged: (index) {}),
                  Expanded(
                    child: Text('Rad 3'),
                  )
                ],
              ),
            ),
          ],
        ),
      ],
    ),

A: You can compare the widget I use according to the screen. you can do them with Flexible or Expanded
 Container(
     child: Column(
      children: [
        Row(
          children: [
            Flexible(
              flex: 1,
              child: Row(
                children: [
                  Radio(
                      value: 1, groupValue: 'null', onChanged: (index) {}),
                  Expanded(
                      child: Text(
                    'Radio button 1',
                    maxLines: 2,
                  ))
                ],
              ),
            ),
            Flexible(
              flex: 1,
              child: Row(
                children: [
                  Radio(
                      value: 1, groupValue: 'null', onChanged: (index) {}),
                  Text('Radio 2')
                ],
              ),
            ),
            Flexible(
              flex: 1,
              child: Row(
                children: [
                  Radio(
                      value: 1, groupValue: 'null', onChanged: (index) {}),
                  Text('Test')
                ],
              ),
            ),
          ],
        ),
        Row(
          children: [
            Flexible(
              flex: 1,
              child: Row(
                children: [
                  Radio(
                      value: 1, groupValue: 'null', onChanged: (index) {}),
                  Text('RB 1')
                ],
              ),
            ),
            Flexible(
              flex: 1,
              child: Row(
                children: [
                  Radio(
                      value: 1, groupValue: 'null', onChanged: (index) {}),
                  Text('Btn Radio 2')
                ],
              ),
            ),
            Flexible(
              flex: 1,
              child: Row(
                children: [
                  Radio(
                      value: 1, groupValue: 'null', onChanged: (index) {}),
                  Text('Rad 3')
                ],
              ),
            ),
          ],
        ),
      ],
    ),
  )


text:
Q: Flask beginner - error logging So I have a flask app which is going to run a website on Apache (mod_wsgi). However, it keeps crashing, and the Apache error logs are not recording anything.
While there is some documentation here http://flask.pocoo.org/docs/0.12/errorhandling/#logging-to-a-file  , I have no idea where to put any of the code.
Here is the app code, incidentally. It's crashing due to some permission issues with the method it's calling (needs data from a secure server), but that's not the point.
from model import InputForm
from flask import Flask, render_template, request
from compute import compute

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    form = InputForm(request.form)
    if request.method == 'POST' and form.validate():
            result = compute(form.A.data, form.B.data)
    else:
        result = None

    return render_template('view.html', form=form, result=result)

if __name__ == '__main__':
    app.run(debug=True)

(ignore the indentation issues)

A: Apache will log anything Flask logs to stdout/stderr. The issue is that Flask itself is not logging anything when it is an internal application error. For a start, temporarily add:
app.debug = True

after app is created in the first place. You need it there as app.run() is not used in mod_wsgi. That will cause errors to show in the browser.
Then go find the Flask config setting to tell it to always log application errors to stdout/stderr. Make sure you remove that setting of app.debug when work that out.


text:
Q: Downloadable link for MS Access file I am stuck in creating a link for ".mdf" MS-Access file through which the file can be downloaded. I have gone through many similar questions and their answers but no luck. I tried to use anchor tag in simple html file but didn't work.
Later I tried classic asp script, but that also not worked. Classic ASP script is given below
<%
const adTypeBinary = 1

    'Set the content type to the specific type that you are sending.
     Response.ContentType = "application/octet-stream"
     Response.AddHeader "Content-Disposition", "attachment; filename=labels.mdf"

     set objStream = Server.CreateObject("ADODB.Stream")
     objStream.open
     objStream.type = adTypeBinary
     'objStream.LoadFromFile(strFilePath & strFile)
     objStream.LoadFromFile(server.MapPath("labels.mdf"))

    response.binarywrite objStream.Read

    objStream.close
    Set objStream = nothing

%>

Note: We are using classic ASP as a server side language, so you consider if necessary in example.

A: I think because the mdf file is being used. As I know *.mdf is sql server database file.. so Its impossible to get "it" as long as SQL server is running and serve the related database. this is my suggestion :

*

*Detach the related database

*Make sure you have read access to the related folder


text:
Q: How to migrate wordpress from xampp windows to ubuntu I am trying to move my wordpress site from local xampp, windows machine to ubuntu server.
I have tried exporting database from xampp panel. Moved all wordpress files to apache directory and imported database. Used selects from this article:
https://blog.templatetoaster.com/move-wordpress-localhost-to-live-server/
to change urls to current server.
UPDATE wp_posts SET post_content = REPLACE(post_content, 'http://127.0.0.1/directory', 'http://server_ip/directory');
UPDATE wp_options SET option_value='http://server_ip/directory' WHERE option_name='home';
UPDATE wp_options SET option_value='http://server_ip/directory' WHERE option_name='siteurl';
All images on site should work and all pages but only home page and admin works but when I try to click on other pages I get error:
"The requested URL /directory/page1/ was not found on this server."
And all images don't show.


text:
Q: Return variable from within Laravel Excel Import Code Below, basic example, but I want to return errors (see commented out if statement after the import ). How would I pass variables from the 'import' class back to the controller?
Controller:
public function resultsImport(Request $request)
{
    //validate the xls file
    $this->validate($request, array('student_results_import_file' => 'required'));

    if($request->hasFile('student_results_import_file')){
        $extension = File::extension($request->student_results_import_file->getClientOriginalName());
        if ($extension == "xlsx" || $extension == "xls" || $extension == "csv") {

            Excel::import(new StudentResultsImport, $request->file('student_results_import_file'));
// if $ignore_count>0 --> do stuff
            return redirect('/baadmin/students')->with('flash_message', ['success','Results Imported Successfully','Student file "'. $request->student_results_import_file->getClientOriginalName() .'" imported successfully!']);
        } else {
            return redirect('/baadmin/students')->with('flash_message', ['error','Results Import Failed','Student file "'. $request->student_results_import_file->getClientOriginalName() .'" import failed. File is a '. $extension .' file. Please upload a valid xls/csv file.']);
        }
    }
}

Import
public function collection(Collection $rows)
{
    set_time_limit(300);
    $ignore_count = 0;

    foreach ($rows as $row) {
        if ($row[8] != '') {
        //import
        }
        else {
        $ignore_count++;
        //$ignore_count is just a simple example, ultimately would probably have an array of the various errors detected on the various rows
        }
    }
}

A: Managed to find the appropriate answer in the documentation, referring to 'Getters':
https://docs.laravel-excel.com/3.1/architecture/objects.html#getters
eg:
namespace App\Imports;

use App\User;
use Maatwebsite\Excel\Concerns\ToModel;

class UsersImport implements ToModel
{
    private $rows = 0;

    public function model(array $row)
    {
        ++$this->rows;

        return new User([
            'name' => $row[0],
        ]);
    }

    public function getRowCount(): int
    {
        return $this->rows;
    }
}

After doing the import, we can request the state with the getter.
$import = new UsersImport;
Excel::import($import, 'users.xlsx');

dd('Row count: ' . $import->getRowCount());


text:
Q: Reconciling Different Vapor Pressure Definitions In describing vapor pressure, I have often heard the following intuition: Assume a closed container that is partially filled with water. Above the water lies a vacuum. The water will vaporize until the pressure exerted on the surface of the water no longer allows the water to leave the solution. Is this even correct?
From Wikipedia, vapor pressure is defined as "the pressure exerted by a vapor in thermodynamic equilibrium with its condensed phases (solid or liquid) at a given temperature in a closed system." From this equilibrium perspective, the vapor pressure is reached when the rate of vaporization is equal to the rate of condensation.
From the first definition, is the building pressure really forcing the water molecules down to an appreciable extent? Or is vapor pressure simply a convenient way of describing such an equilibrium.


text:
Q: Why is hexbin grid distorted in polar stereo projection I am trying to understand why a hexbin plot in a north or south polar stereo projection shows squashed hexagons, even though the area of the grid is square and the projection is approximately equal area.
I've tried both north and south polar stereo projections using basemap.
import numpy as np
from numpy.random import uniform
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

fig = plt.figure(figsize=(12,10)) # width, height in inches
ax =fig.add_axes([-0.02,0.1,0.74,0.74])

m = Basemap(epsg='3413',lon_0=0.,resolution='l',width=6000000,height=6000000)

m.drawcoastlines()

m.drawmapscale(0.,90.,0.,90.,1000)

npts=2000
lats = uniform(60.,80.,size=npts)
lons = uniform(0.,360.,size=npts)
data = uniform(0.,4800.,size=npts)

x,y=m(lons, lats)

thiscmap=plt.cm.get_cmap('viridis')

p=m.hexbin(x,y,C=data,gridsize=[10,10],cmap=thiscmap)

plt.show()

A: I don't know why you get squashed hexagons. But you can adjust the hexagon shape by setting appropriate values of gridsize. Here I modify your code and get better plot.
import numpy as np
from numpy.random import uniform
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

fig = plt.figure(figsize=(12,10)) # width, height in inches
ax =fig.add_axes([-0.02, 0.1, 0.74, 0.74])

# North polar stereographic projection epsg='3413'; ***large areal distortion***
#m = Basemap(epsg='3413', lon_0=0., resolution='c', width=6000000, height=6000000)

# 'laea':  Lambert Azimuthal Equal Area
# Thematic mapping with ground surface data should be plotted on 'equal-area' projection
m = Basemap(projection='laea', lon_0=0., lat_0=90, resolution='l', width=6000000, height=6000000)

m.drawcoastlines(linewidth=0.5)

m.drawmapscale(0.,90.,0.,90.,1000)  # 1000 km?

npts = 2000
lats = uniform(60.,80.,size=npts)  # not cover N pole
lons = uniform(0.,360.,size=npts)  # around W to E
data = uniform(0.,4800.,size=npts)

x,y = m(lons, lats)

thiscmap = plt.cm.get_cmap('viridis')

# To get 'rounded' hexagons, gridsize should be specified appropriately
# need some trial and error to get them right
#p=m.hexbin(x, y, C=data, gridsize=[10,10], cmap=thiscmap)  # original code
m.hexbin(x, y, C=data, gridsize=[16,11], cmap=thiscmap)     # better

plt.colorbar()  # useful on thematic map

plt.show()

The projection you use (epsg:3413) is stereographic projection which has large areal distortion. More appropriate projection for thematic mapping in this case is Lambert Azimuthal Equal Area.
The resulting plot:


text:
Q: mergeMap cancels previous HTTP calls I have a dialog that when opened dispatches an action to preload data for form controls inside the dialog. The action is picked up by an effect that in turn returns an array of new actions to preload the data for each id in the array that is passed to the original action.
@Effect()
preloadReferenceData$ = this.actions$
  .ofType(PRELOAD_REFDATA)
  .pipe(
    map((action: PreloadRefData) => action.payload),
    mergeMap(ids => {
      const actions: Action[] = [];
      ids.forEach((id) => actions.push(new LoadRefDataForId(id)));
      return actions;
    })
  );

Normally, I use the mergeMap operator to successfully dispatch multiple new actions from an effect, though this is the first time I'm dispatching multiple actions of the same type, and it's the first time I've experienced that the XHR calls get cancelled. I would have suspected the use of switchMap in the case where the XHR calls are cancelled, but not now when I use mergeMap.
These is the content of actions
LoadRefDataForId {payload: "2441", type: "[Refdata] Load RefData"}
LoadRefDataForId {payload: "7612", type: "[Refdata] Load RefData"}
LoadRefDataForId {payload: "9411", type: "[Refdata] Load RefData"}

and this is taken from the network log

The effect that handles the LoadRefDataForId action
@Effect()
loadRefDataForId$ = this.actions$
  .ofType(LOAD_REFDATA_FOR_ID)
  .pipe(
  map((action: LoadRefDataForId) => action.payload),
  switchMap((id) => this.service.loadRefData(id)
    .pipe(
    map((occupations) => {
      return new LoadRefDataForIdSuccessful({ id: id, occupations: occupations } as RefDataPayload);
    }),
    catchError((err, caught) => {
      console.log(caught);
      return caught;
    })
    ))
  );

Why are the XHR cancelled, even though I'm using mergeMap?

A: The cancelations are caused by this effect:
@Effect()
loadRefDataForId$ = this.actions$
  .ofType(LOAD_REFDATA_FOR_ID)
  .pipe(
  map((action: LoadRefDataForId) => action.payload),
  switchMap((id) => this.service.loadRefData(id)
    .pipe(
    map((occupations) => {
      return new LoadRefDataForIdSuccessful({ id: id, occupations: occupations } as RefDataPayload);
    }),
    catchError((err, caught) => {
      console.log(caught);
      return caught;
    })
    ))
  );

By using switchMap in it, you are telling that only the last LoadRefDataForId action that passes through the actions$ stream should be considered/processed.
Change it to:
@Effect()
loadRefDataForId$ = this.actions$
  .ofType(LOAD_REFDATA_FOR_ID)
  .pipe(
  map((action: LoadRefDataForId) => action.payload),
  mergeMap((id) => this.service.loadRefData(id)
    .pipe(
    map((occupations) => {
      return new LoadRefDataForIdSuccessful({ id: id, occupations: occupations } as RefDataPayload);
    }),
    catchError((err, caught) => {
      console.log(caught);
      return caught;
    })
    ))
  );


text:
Q: Metodo recursivo para saber si un elemento pertenece a un array, ¿que me falta? Esto es un método que estoy tratando de hacer de manera recursiva para saber si un elemento pertenece a un arreglo.
public static boolean pertenece(int v[], int n, int elemento) {

    boolean pert = false;
    if (n == v.length) {
        return pert;
    }
    if (v[n] == elemento) {
        pert = true;
        return pert;
    } else {
        pertenece (v, n + 1,elemento);

        return pert;
    }
}

A: En el else tienes que retornar el resultado de la llamada recursiva ya que ahora estas devolviendo false siempre
public static boolean pertenece(int v[], int n, int elemento) {

    boolean pert = false;
    if (n == v.length) {
        return pert;
    }
    if (v[n] == elemento) {
        pert = true;
        return pert;
    } else {
        return pertenece (v, n + 1,elemento);
    }

}


text:
Q: Hibernate Constraint Violation when persisting associated entities I'm developing a Java Spring Web Application for an Online Movie Ticket Service.
A user has a designated amount of points and is allowed to use these points to pay for a part of their tickets. If the user decides to cancel  a transaction his points are reimbursed. These point movements are called PointTransactions.
Transactions are stored in a transactions table and PointTransactions are stored in a pointTransactions table with a reference to the parent transaction.
I am having trouble when persisting a PointTransaction Entity that references a new Transaction Entity on the same method.
Here is the code I am currently using:
@Override
@Transactional
public TransactionDTO confirmCheckout(...) {

    /**Validations removed and parameters simplified to improve readability**/

    Transaction transaction = transactionDao.create(...);
    pointsTransactionDao.create(transaction, ...);

    return new TransactionDTO(transaction);
}

The DAO functions have been duely tested and work independently, however when the above code is run I receive the following exception.
javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:347)
at ar.edu.itba.paw2018b.persistence.PointTransactionsHibernateDaoImpl.create(PointTransactionsHibernateDaoImpl.java:32)

Caused by: org.postgresql.util.PSQLException: ERROR: insert or update on table "pointtransactions" violates foreign key constraint "pointtransaction_transaction_transid_fk"
Detail: Key (transaction)=(23) is not present in table "transactions".

When viewing the code during runtime I can confirm that the Transaction with ID = 23 is the one created in the confirmCheckout() method.
It appears the constraint is violated because the Transaction record is not commited to the DB before the PointTransaction record.
This error began once I changed the PersistenceContext of my EntityManagers from the default to the ExtendedType, the change was pushed by my need to Lazily initialize most of my references. I believe the problem is strongly related to this however I do not have enough of a grasp on Hibernate to infer the best way to tackle the issue.
Below is the code of my Daos and Models.
Thank you for your time.
@Repository
public class TransactionHibernateDaoImpl implements TransactionDao {

    @PersistenceContext(type = PersistenceContextType.EXTENDED)
    private EntityManager em;

    @Override
    public Transaction create(User userId, Screening screeningId, String seat, String food, double price, boolean paid, Timestamp date, String confirmationCode, int status) {
        final Transaction transaction = new Transaction(userId,screeningId,seat,food,price,date,paid,confirmationCode, status);
        em.persist(transaction);
        return transaction;
    }
    public void setEm(EntityManager em) {
        this.em = em;
    }
    /** Unrelated Methods **/
}

.
@Repository
public class PointTransactionsHibernateDaoImpl implements PointTransactionsDao {

    @PersistenceContext(type = PersistenceContextType.EXTENDED)
    private EntityManager em;

    @Override
    public PointTransactions create(User userid, int conversion, Transaction transaction, int price, int reason, Timestamp date)
    {
        final PointTransactions ptransaction = new PointTransactions(userid,conversion,transaction,price, reason, date);
        em.persist(ptransaction);
        return ptransaction;
    }
    public void setEm(EntityManager em) {
        this.em=em;
    }
    /** Unrelated Methods **/
}

.
@Entity
@Table(name = "pointtransactions")
public class PointTransactions {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @SequenceGenerator(sequenceName = "transactions_transid_seq", name = "transactions_transid_seq", allocationSize = 1)
    @Column(name = "pointtransid", nullable = false)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "userid")
    private User userid;

    @Column
    private int conversion;

    @Column
    private Timestamp date;

    @Column
    private int price;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "transaction")
    private Transaction transaction;

    @Column(nullable = false)
    private int reason;

    public PointTransactions(){}

    public PointTransactions(User userId, int conversion, Transaction transaction, int price, int reason, Timestamp date){
        this.userid = userId;
        this.conversion = conversion;
        this.transaction = transaction;
        this.price = price;
        this.reason = reason;
        this.date = date;
    }
    /** Getters and Setters **/
}

.
@Entity
@Table(name = "transactions")
public class Transaction {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @SequenceGenerator(sequenceName = "transactions_transid_seq", name = "transactions_transid_seq", allocationSize = 1)
    @Column(name = "transid", nullable = false)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "userid")
    private User userid;

    @Column(name = "transactiondate",nullable = false)
    private Timestamp date;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "screeningid")
    private Screening screeningid;

    @Column(nullable = false)
    private String seat;

    @Column(name = "fooddetails", length = 1024)
    private String food;

    @Column(nullable = false)
    private double price;

    @Column(nullable = false)
    private boolean paid = false;

    @Column
    private String confirmationCode;

    @Column
    private int status;

    public Transaction(){}

    public Transaction( User userId, Screening screeningId, String seat, String food, double price, Timestamp date, boolean paid, String confirmationCode, int status){
        this.userid = userId;
        this.date = date;
        this.screeningid = screeningId;
        this.seat = seat;
        this.food=food;
        this.price = price;
        this.paid = paid;
        this.confirmationCode = confirmationCode;
        this.status = status;
    }
/** Getters and Setters **/
}

A: you are pretty close on your observation, long story short, PerssitenceContextType.EXTENDED - means you are responsible for managing your stuff ;container will not do it for you.
"Transaction with ID = 23 is the one created in the confirmCheckout() method" - Can you please check the "ID = 23" persist in the DB ?
I guess not, means your changes are not committed in the order or they should or they are not flushed so you end up with " violates foreign key constraint "pointtransaction_transaction_transid_fk" "
Dirty solution[do the stuff yourself] -- that is commit/flush the ID=23 changes,check it persist in the DB and then proceed with rest of the operations.
Here is the long story you were looking for - https://vladmihalcea.com/initialize-lazy-proxies-collections-jpa-hibernate/
sincerely hoping for a movie ticket


text:
Q: NoSuchMethodException: org.springframework.boot.autoconfigure.http.HttpMessageConverters I want to configure Spring application with Hibernate. I tried this:
Main start method:
@Configuration
@EnableWebMvc
public class WebConfig implements WebApplicationInitializer, WebMvcConfigurer {

    private BasicAuthenticationInterceptor basicAuthenticationInterceptor;

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.removeIf(converter -> converter instanceof MappingJackson2XmlHttpMessageConverter);
        converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);
        converters.add(new MappingJackson2XmlHttpMessageConverter(
                ((XmlMapper) createObjectMapper(Jackson2ObjectMapperBuilder.xml()))
                        .enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION)));
        converters.add(new MappingJackson2HttpMessageConverter(
                createObjectMapper(Jackson2ObjectMapperBuilder.json())));
    }

    private ObjectMapper createObjectMapper(Jackson2ObjectMapperBuilder builder) {
        builder.indentOutput(true);
        builder.modules(new JaxbAnnotationModule());
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        builder.defaultUseWrapper(false);
        return builder.build();
    }

    @Override
    public void onStartup(ServletContext container) {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(ContextDatasource.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }

    @Autowired
    public void setBasicAuthenticationInterceptor(BasicAuthenticationInterceptor basicAuthenticationInterceptor) {
        this.basicAuthenticationInterceptor = basicAuthenticationInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(basicAuthenticationInterceptor);
    }

}

Hibernate configuration called from rootContext.register(ContextDatasource.class);:
@SpringBootApplication
@Configuration
@EnableTransactionManagement
public class ContextDatasource {

    @Bean
    public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
        return new FastJsonHttpMessageConverter();
    }

    @Bean
    @Autowired
    public HttpMessageConverters convertersToBeUsed(FastJsonHttpMessageConverter converter) {
        return new HttpMessageConverters(converter);
    }

    @Bean
    public LocalSessionFactoryBean getSessionFactory() throws NamingException {
        final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(getDataSource());
        sessionFactory.setPackagesToScan(new String[] { "org.datalis.plugin.database.models" });
        sessionFactory.setHibernateProperties(hibernateProperties());

        return sessionFactory;
    }

    @Bean
    public DataSource getDataSource() throws NamingException {
        return (DataSource) new JndiTemplate().lookup("java:/global/production_gateway");
    }

    @Bean
    public PlatformTransactionManager getHibernateTransactionManager() throws NamingException {
        final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(getSessionFactory().getObject());
        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor getExceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    private final Properties hibernateProperties() {
        final Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
        hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MariaDBDialect");

        hibernateProperties.setProperty("hibernate.show_sql", "true");
        hibernateProperties.setProperty("hibernate.format_sql", "true");
        return hibernateProperties;
    }
}

But when I deploy the WAR file I get error:
Caused by: java.lang.NoSuchMethodException: org.springframework.boot.autoconfigure.http.HttpMessageConverters$$EnhancerBySpringCGLIB$$1d90bff9.<init>()
    at java.base/java.lang.Class.getConstructor0(Class.java:3302)

Full error stack:
https://pastebin.com/x30W2aws
Can you give advice where I'm wrong and how to fix the problem?
Do I need to implement the module startup with another configuration?
EDIT:
With Java 8 the code is working without above issue. With latest Java 10 I get the above exception. Do you know what configuration I need to do?

A: According to the Spring Boot release notes, Java 10 is supported by Spring Boot version 2.0.1 and up.  Without a list of your dependencies it's impossible to know if this is the issue, but it does seem like a good place to start.
Are you running Boot v2.0.1 or higher?


text:
Q: How to hide border flickity in Chrome anyone please help, how to hide border flickity slider in chrome. The border just show in Browser Chrome only. may be like this :

or u can visit my blog : aqiqoh-syafaat.blogspot.co.id
thanks

A: To remove the outline from just flickity elements you can add the following css
.flickity-enabled:focus {
    outline: none;
}

As others have said removing this globally is bad for accessibility. If you use the dots or nav features for flickity you would ideally add focus to these elements.

A: Can you please tell exactly where how you can see that border.
Generally this border appears as outline on focus(if), you can set
*:focus{
outline:none;
}

This will remove that blue border from everywhere.
or simply outline:none; on element or its pseudo class
(Use !important if needed.)


text:
Q: Snake. Roll back the coordinates of the snake to impact I can't realize the possibility of continuing the game after a collision. The snake should stop and start moving after clicking on one of the arrow buttons.
In a collision, a window appears about the loss, I need to continue the game.

I press the button and the following happens:

I don't understand how I can save the coordinates of the snake just before the collision.
In the moveTimer_Tick method, all elements move, i.e. new coordinates have already appeared at the head and body, then there is a check for collisions with the wall and body. If they are found, a window appears about the loss.
New snake coordinates are not displayed. But after clicking the "Continue" button, an update occurs and the snake climbs to the border.
The question is: how can I save the coordinates of the snake, before the collision, and after continuing to start with them.
namespace Snake{
    public partial class MainWindow : Window
    {
          //The field on which the snake lives
          Entity field;
          // snake head
          Head head;
          // whole snake
          List<PositionedEntity> snake;
          // apple
          Apple apple;
          //number of points
          int score;
          // Is movement paused
          bool paused;
          //time
          DispatcherTimer moveTimer;

       //constructor form
       public MainWindow()
       {
           InitializeComponent();

           snake = new List<PositionedEntity>();
           //create field 600x600pixels
           field = new Entity(600, 600, "pack://application:,,,/Resources/snake.png");

           //create a timer that runs every 300 ms
           moveTimer = new DispatcherTimer();
           moveTimer.Interval = new TimeSpan(0, 0, 0, 0, 300);
           moveTimer.Tick += new EventHandler(moveTimer_Tick);

       }

       //redraw screen method
       private void UpdateField()
       {
           //update the position of the elements of the snake
           foreach (var p in snake)
           {
               Canvas.SetTop(p.image, p.y);
               Canvas.SetLeft(p.image, p.x);
           }

           //update the position of apple
           Canvas.SetTop(apple.image, apple.y);
           Canvas.SetLeft(apple.image, apple.x);

           //points update
           lblScore.Content = String.Format("{0}000", score);
       }

       //timer tick handler. All movement takes place here.
       void moveTimer_Tick(object sender, EventArgs e)
       {
           // Do not update if movement is paused
           if(paused) {
               return;
           }

           //in the reverse order we move all the elements of the snake
           foreach (var p in Enumerable.Reverse(snake))
           {
               p.move();
           }

           //we check that the head of the snake did not crash into the body
           foreach (var p in snake.Where(x => x != head))
           {
               if (p.x == head.x && p.y == head.y)
               {
                   //we lose
                   moveTimer.Stop();
                   GameOver.Visibility = Visibility.Visible;
                   btnRestart.Visibility = Visibility.Visible;
                   tbScore.Text = String.Format("SCORE: {0}000", score);
                   return;
               }
           }

           //check that the head of the snake did not go out of the field
           if (head.x < 40 || head.x >= 540 || head.y < 40 || head.y >= 540)
           {
               //we lose
               moveTimer.Stop();
               GameOver.Visibility = Visibility.Visible;
               btnRestart.Visibility = Visibility.Visible;
               tbScore.Text = String.Format("SCORE: {0}000", score);
               return;
           }

           //check that the head of the snake crashed into an apple
           if (head.x == apple.x && head.y == apple.y)
           {
               //increase the score
               score++;
               //move the apple to a new place
               apple.move();
               var part = new BodyPart(snake.Last());
               canvas1.Children.Add(part.image);
               snake.Add(part);
           }
           UpdateField();
       }

       private void Window_KeyDown(object sender, KeyEventArgs e)
       {
           // Unpause movement when any key is pressed
           if(paused) {
                paused = false;
           }
           switch (e.Key)
           {
               case Key.Up:
                   head.direction = Head.Direction.UP;
                   break;
               case Key.Down:
                   head.direction = Head.Direction.DOWN;
                   break;
               case Key.Left:
                   head.direction = Head.Direction.LEFT;
                   break;
               case Key.Right:
                   head.direction = Head.Direction.RIGHT;
                   break;
           }
       }

       // "Start"
       private void button1_Click(object sender, RoutedEventArgs e)
       {
           btnStart.Visibility = Visibility.Hidden;
           btnRestart.Visibility = Visibility.Hidden;
           tBNotEnoughPoints.Visibility = Visibility.Hidden;
           score = 0;
           snake.Clear();
           canvas1.Children.Clear();
           // "Game Over"
           GameOver.Visibility = Visibility.Hidden;

           canvas1.Children.Add(field.image);
           apple = new Apple(snake);
           canvas1.Children.Add(apple.image);
           head = new Head();
           snake.Add(head);
           canvas1.Children.Add(head.image);

           moveTimer.Start();
           UpdateField();

       }
       private void btnContinue_Click(object sender, RoutedEventArgs e)
       {
           if (score >= 2)
           {
               GameOver.Visibility = Visibility.Hidden;
               btnRestart.Visibility = Visibility.Hidden;
               score -= 2;
               // Pause movement
               paused = true;
               moveTimer.Start();
               UpdateField();
           }
           else
           {
               tBNotEnoughPoints.Visibility = Visibility.Visible;
           }
       }

       public class Entity
       {
           protected int m_width;
           protected int m_height;

           Image m_image;
           public Entity(int w, int h, string image)
           {
               m_width = w;
               m_height = h;
               m_image = new Image();
               m_image.Source = (new ImageSourceConverter()).ConvertFromString(image) as ImageSource;
               m_image.Width = w;
               m_image.Height = h;

           }

           public Image image
           {
               get
               {
                   return m_image;
               }
           }
       }

       public class PositionedEntity : Entity
       {
           protected int m_x;
           protected int m_y;
           public PositionedEntity(int x, int y, int w, int h, string image)
               : base(w, h, image)
           {
               m_x = x;
               m_y = y;
           }

           public virtual void move() { }

           public int x
           {
               get
               {
                   return m_x;
               }
               set
               {
                   m_x = value;
               }
           }

           public int y
           {
               get
               {
                   return m_y;
               }
               set
               {
                   m_y = value;
               }
           }
       }

       public class Apple : PositionedEntity
       {
           List<PositionedEntity> m_snake;
           public Apple(List<PositionedEntity> s)
               : base(0, 0, 40, 40, "pack://application:,,,/Resources/fruit.png")
           {
               m_snake = s;
               move();
           }

           public override void move()
           {
               Random rand = new Random();
               do
               {
                   x = rand.Next(13) * 40 + 40 ;
                   y = rand.Next(13) * 40 + 40 ;
                   bool overlap = false;
                   foreach (var p in m_snake)
                   {
                       if (p.x == x && p.y == y)
                       {
                           overlap = true;
                           break;
                       }
                   }
                   if (!overlap)
                       break;
               } while (true);

           }
       }

       public class Head : PositionedEntity
       {
           public enum Direction
           {
               RIGHT, DOWN, LEFT, UP, NONE
           };

           Direction m_direction;

           public Direction direction {
               set
               {
                   m_direction = value;
                   RotateTransform rotateTransform = new RotateTransform(90 * (int)value);
                   image.RenderTransform = rotateTransform;
               }
           }

           public Head()
               : base(280, 280, 40, 40, "pack://application:,,,/Resources/head.png")
           {
               image.RenderTransformOrigin = new Point(0.5, 0.5);
               m_direction = Direction.NONE;
           }

           public override void move()
           {
               switch (m_direction)
               {
                   case Direction.DOWN:
                       y += 40;
                       break;
                   case Direction.UP:
                       y -= 40;
                       break;
                   case Direction.LEFT:
                       x -= 40;
                       break;
                   case Direction.RIGHT:
                       x += 40;
                       break;
               }
           }
       }

       public class BodyPart : PositionedEntity
       {
           PositionedEntity m_next;
           public BodyPart(PositionedEntity next)
               : base(next.x, next.y, 40, 40, "pack://application:,,,/Resources/body.png")
           {
               m_next = next;
           }

           public override void move()
           {
               x = m_next.x;
               y = m_next.y;
           }
       }
   }
}

A: There is something to say about the design of your code, but if you don't care and you want a fast (and ugly) solution you can modify your PositionEntity in order to store old coordinates:
   public class PositionedEntity : Entity
   {
       protected int m_x;
       protected int m_y;
       protected int m_oldX;
       protected int m_oldY;

       public PositionedEntity(int x, int y, int w, int h, string image)
           : base(w, h, image)
       {
           m_x = x;
           m_y = y;
           m_oldX = x;
           m_oldY = y;
       }

       public virtual void move() { }
       public virtual void RestorePrevious()
       {
           m_x = m_oldX;
           m_y = m_oldY;
       }

       public int x
       {
           get
           {
               return m_x;
           }
           set
           {
               m_oldX = m_x;
               m_x = value;
           }
       }

       public int y
       {
           get
           {
               return m_y;
           }
           set
           {
               m_oldY = m_y;
               m_y = value;
           }
       }
   }

When you have a collision you should call the RestorePrevious() on the head and on all the rest of the snake


text:
Q: viewResolver with more folders inside of WEB-INF/jsp is not working in spring <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <!--  avoid '???' -->
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp"/>
</bean>

if i create other subfolders under jsp , for instance
/WEB-INF/jsp/reports , /WEB-INF/jsp/insertions
how should i configure now the viewResolver to can resolve these new sub folders??

A: Say you have a jsp test.jsp under /WEB-INF/jsp/reports
From your controller return
@RequestMapping("/helloWorld")
    public String helloWorld(Model model) {
        model.addAttribute("message", "Hello World!");
        return "reports/test";
    }

A: You can configure your the Tiles layout system
    <bean class="org.springframework.web.servlet.view.tiles3.TilesConfigurer" id="tilesConfigurer">
    <property name="definitions">
        <list>
            <value>/WEB-INF/layouts/layouts.xml</value>
            <!-- Scan views directory for Tiles configurations -->
            <value>/WEB-INF/views/**/views.xml</value>
        </list>
    </property>
</bean>

Then you create the views.xml where you have all the routes of your view to link with your ModelAndView in the controller.
views.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE tiles-definitions PUBLIC
    "-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN"
    "http://tiles.apache.org/dtds/tiles-config_2_1.dtd">

     <tiles-definitions>

       <definition name="refreshActivityPlan" extends="basic.ajax-requirejs">
               <put-attribute name="content" value="/WEB-INF/views/common/activity_plan/activityPlanView.jsp"/>
        </definition>

       </tiles-definitions>

Then finally in your controller:
    ModelAndView mav = new ModelAndView("refreshActivityPlan");
    mav = getModelAndView(id, subStep, mav);
    return mav;

A: From your controller return values like reports/xxx or insertions/yyy

A: View resolver picks up the prefix you have configured in XML file or java configuration and it prefixes it with the jsp file name you have provided,
here in this case resolver is looking for /WEB-INF/jsp/test.jsp which is not available.

replace that "test" with "reports/test" while creating ModelAndView
  object.


text:
Q: Migrate ASP.net Identity users to Firebase I am looking for a way to migrate ASP.net Identity users stored in MongoDB (using AspNetCore.Identity.MongoDbCore v 1.0.8 NuGet package) to Firebase Authentication project.
In order to import users using Firebase CLI I need to specify the following parameters:
firebase auth:import ACCOUNT_FILE    \
    --hash-algo=HASH_ALGORITHM         \
    --hash-key=KEY                     \
    --salt-separator=SALT_SEPARATOR    \
    --rounds=ROUNDS                    \
    --hash-input-order=HASH_INPUT_ORDER

Where hash-algo = HMAC_SHA256; rounds = 10000; hash-input-order = SALT_FIRST;
Also, I need to provide the salt along with the password hash in the list of users (JSON file).
Please guide me how can I get the required parameters (hash-key, and salt) in order to successfully migrate the existing users to Firebase Authentication project.
Thanks!
I was able to create a new user in Firebase Authentication project using Firebase Admin API for .Net
and I was able to successfully authenticate the newly created user.
However I am unable to migrate any of the preexisting users that are currently stored in MongoDB.


text:
Q: update a table in designer view in sql server in the same way we do in Oracle SQL We can update a table in designer view in Pl/sql by using following query:
select * from table1 for update

and than by unlocking the designer view and do further changes.
Can we do the same in SQL Server? I tried to do the same in SQL Server than I got an error:

FOR UPDATE clause allowed only for DECLARE CURSOR

Guys any ideas??

A: In Management Studio, right-click the table name in Object Explorer, and choose "Edit Top 200 Rows". If this does not return the row(s) you want to edit, hit Ctrl+3 and this will allow you to modify the query that populates the grid. In all honesty, you should be learning proper DML (update, insert, delete) syntax instead of treating your table like a spreadsheet.
You won't be able to change the schema from the same designer, though; for that you'll have to use right-click > Design. (And again, proper DDL is better than relying on bug-laden and feature-restricted visual designers.)


text:
Q: XSLT: Add text inside html tag Is it possible to add text from a xsl variable to the inside of a html tag something like this?
<xsl:variable name="selected">
   <xsl:if test="@class = 'selected'"> class="selected"</xsl:if>
</xsl:variable>

A: You should not attempt to write this as literal text, instead look at xsl:element and xsl:attribute.  Rough example:
<xsl:element name="li">
    <xsl:attribute name="class">
        <xsl:value-of select="$selected" />
    </xsl:attribute>
</xsl:element>

Full documentation here.

A: Try this:
<xsl:element name="li">
    <xsl:if test="@class = 'selected'">
        <xsl:attribute name="class">
            selected
        </xsl:attribute>
    </xsl:if>
</xsl:element>

Optionally, the xsl:if could be nested in the xsl:attribute, instead of the other way around, if a class="" is desired. As already mentioned, it is unwise to write this as literal text.

A: Note that if you are careful enough to make it its first child, you can use <xsl:attribute> directly inside of your
 tag, instead of using <xsl:element>

    <xsl:if test="$selected">

        <xsl:attribute name="class">selected</xsl:attribute>
    </xsl:if>


text:
Q: AWS EB Apache mod_wsgi configuration I'm using AWS EB Python container.
I wish to change Apache mod_wsgi configuration, but it's automatically overwritten by default setting after EC2 instance reboot. (or, re-deployment of application version).
How can I use my own mod_wsgi configuration smart way?
As I understood, it's overwritten by config.py file in /opt/elasticbeanstalk/hooks folder.

A: This is not elegant way I think, but for someone who can met similar situation.
Try to modify config.py file in /opt/elasticbeanstalk/hooks folder.
You can find APACHE_TEMPLATE variable. Please add your own configuration to this string.
And, upload your new S/W version. That's all.
UPDATE: I found better solution:
- How to force https on elastic beanstalk?


text:
Q: Dnsmasq broken after upgrade to Bionic: works, but takes ~30 seconds to resolve any query my dnsmasq configuration got broken after upgrading to Ubuntu 18.04 from 16.04.

*

*systemd-resolved is enabled and running

*dnsmasq is enabled and running

Any DNS query to the outside world will hang for some 30 seconds before succeeding. Queries to my local hosts (anything.mylocal) will succeed immediately.
If I stop dnsmasq (i.e. service dnsmasq stop), then all DNS queries to the outside world will work immediately (but .mylocal, of course, not).
In: /etc/dnsmasq.conf
listen-address=127.0.0.1
address=/.mylocal/127.0.0.1

In: /etc/NetworkManager/NetworkManager.conf
[main]
...
# dns=dnsmasq
...

Uncommenting the dns= line will prevent ANY dns query.
In: /etc/systemd/resolved.conf
[Resolve]
#DNS=
#FallbackDNS=
#Domains=
#LLMNR=no
#MulticastDNS=no
#DNSSEC=no
#Cache=yes
#DNSStubListener=no

In: /etc/resolv.conf
This file is a link to: ../run/resolvconf/resolv.conf, which contains:
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
# 127.0.0.53 is the systemd-resolved stub resolver.
# run "systemd-resolve --status" to see details about the actual nameservers.

nameserver 127.0.0.53

In: /etc/nsswitch.conf
passwd:         compat systemd
group:          compat systemd
shadow:         compat

hosts:          files mdns4_minimal [NOTFOUND=return] dns myhostname
networks:       files

protocols:      db files
services:       db files
ethers:         db files
rpc:            db files

netgroup:       nis

One noticeable difference with the output of systemd-resolve --status:

*

*With dnsmasq running, the first line in Global reads: DNS Servers: 127.0.0.1

*With dnsmasq stopped, this line is absent, there is no global DNS Server, and the first useful server is defined in  the Link 2 section, which specifies my default gateway (192.168.1.1)

Any help is greatly appreciated :)

A: After a night's sleep ;-) this is what I came up with. I just manually added some public upstream servers (1.1.1.1 is CloudFlare's, 8.8.8.8 is Google's)
In: /etc/dnsmasq.conf:
listen-address=127.0.0.1
address=/.mylocal/127.0.0.1
server=1.1.1.1
server=8.8.8.8

All the remaining files are left as in my question. Both systemd-resolved and dnsmasq are enabled and running.
This makes DNS queries work.
I still do not consider this as the correct answer, because I would prefer to use the DNS provided by the network, but at least it works...


text:
Q: Freemarker - behavior of Built-ins with Iterables I am observing strange behavior with Freemarker.
I have an Iterable in reportModel.affectedJars. It is provided from a graph database - Tinkerpop/Titan.
${iterableHasContent(reportModel.affectedJars)?then("true", "false")}

${reportModel.affectedJars?has_content?then("yes", "no")} has_content

${reportModel.affectedJars?size}

${reportModel.affectedJars}

<#if reportModel.affectedJars?size == 0>

No archives containing CVE vulnerabilities were found.

<#else>
    <#list reportModel.affectedJars.iterator() as file>
        Something...

iterableHasContent is an alternative of ?size.
I would expect this to  be quite consistent, in terms of:
false
no has_content
0

No archives ...

But what is actually happening is:
false
yes has_content
6
--- and no iterations. ---

Which looks like there's some glitch that makes Freemarker think that the Iterable is not empty, but then when iterated, it gives no items. No exception is thrown.
I was trying to debug, but the debugger doesn't stop at the relevant code for some reason.
Is there something I am missing in ?size and ?has_content paradigms that allows this behavior?

A: Don't try do anything with that Iterable, except calling iterator() on it. The problem is that FreeMarker was created before Iterable was introduced, and it sees a pure Iterable (i.e., one which doesn't also implement Collection) as a generic object, rather than some listable thing. (Fixing this without breaking backward compatibility is not possible, though surely there should be a configuration option for it.) This is also where the size 6 comes from; it's the number of items in the hash, which contains its methods and JavaBean properties. Ugh...
So after you got the Itera*tor*, the next thing you will find that it doesn't support ?size. It supports ?has_content though. (This assumes that you are using the default object wrapper, not pure BeansWrapper, which is pure evil.) But if you can, use #list with a nested #else. Something like:
<#list reportModel.affectedJars.iterator() as file>
    Something...
<#else>

No archives containing CVE vulnerabilities were found.

</#list>

or a more real life example:
<#list reportModel.affectedJars.iterator()>

Found some archives containing CVE vulnerabilities:

    <#items as file>
       Something...
    </#items>
<#else>

No archives containing CVE vulnerabilities were found.

</#list>