text:
Q: Why we used ptr and not *ptr in the following code I am confused about the pointer used in this simple c++ code.My doubt is why we didn't used (*ptr) to print the string instead of (ptr). Please can someone help me with it.
#include<iostream>
using namespace std;
int main()
{
  char *ptr[3];
  ptr[0]="OMKAR";
  ptr[1]="GURAV";
  //char *ptr1="HELLO";
  cout<<"Contents of ptr[0]:"<<ptr[0]<<endl;
  cout<<"Contents of ptr[1]:"<<ptr[1]<<endl;
}

A: *ptr[0] will print only the first character ie "O"

so if you use
ptr[0] it will print "OMKAR"

because ptr[n] equivalent to  *(ptr+n)

A: Because
int x;
...
ptr[x]=...;

Is equivalent to
int x;
...
*(ptr+x)=...;

A: The cout takes into consideration what type you give to it.
There are many different overloads of cout, relevant here are the char, char *and ptr which is really char **ptr
In your example you have the following data types

*

*ptr       - char *ptr3 - decays to char **ptr (Array-to-pointer decay)

*ptr[x]    - which is *(ptr+x) or char *

**ptr[x]   - which is **(ptr+x) or char

To find out what each of the follow lines does
std::cout<<"Contents of *ptr[0]:"<<*ptr[0]<<std::endl;
std::cout<<"Contents of ptr[0] :"<<ptr[0]<<std::endl;
std::cout<<"Contents of ptr    :"<<ptr<<std::endl;

when coutis defined something like this (grossly simplified)
class ostream {
    public:
    ostream& operator<< (const void *);
    ostream& operator<< (const char *);
    ostream& operator<< (const char);
};
ostream cout;

Using ADL(Argument-Dependent Lookup) or König Lookup we first need to find what the type is
*ptr[0] -> char    (char)
ptr[0]  -> char *  (pointer to char)
ptr     -> char ** (pointer to pointer to char)
Now ADL finds the most specialized version and uses that

*

*char is not a void *

*char is not a char *

*char is a char

*char * could be a void * // Implicit conversions

*char * is a char *

*which is more specialized than void *

*char * is not a char

*so char * selects its specialized version

*char ** could be a void * // Implicit conversions

*char ** is not a char *

*char ** is not a char

*so char ** uses the void *

so they end up writing
Contents of *ptr[0]:O
Contents of ptr[0] :OMKAR
Contents of ptr    :0x27fe00

A: ptr[n] is equivalent to *(ptr + n), which is already dereferenced. So ptr[0] returns char *, not char ** and std::ostream is cool with that, because it has an operator<< overloaded for it.

A: It's quit simple. char *ptr[3]; there is an array which contains three pointers. ptr[0]="OMKAR"; the first ponter point to "OMKAR", and the second pointer ptr[1] point to "GURAV" ...
When we want print the char string, just cout the ponter.

A: Please excuse the formattting, as I am on my phone.

char *ptr[3]

Is an array of pointers. So when you do
 ptr[1] = "TEXT"

it's setting the pointer to the address of where the string literal "TEXT" is stored in the program.
It's kind of like doing
char *var;
var = "TEXT";

It's just an array containing pointers to char, or in other words, an array of strings.


text:
Q: Returning Option of (Int,Int) in scala from a List[Int,Int] I have a scala List of tuples, sorted in descending order by first element of the tuple.
I tried a few operations as below which can return me few elements from the list or List()
scala> val l = List((95,6),(10,2),(8,5))
l: List[(Int, Int)] = List((95,6), (10,2), (8,5))

scala> l.filterNot({case (x,y)=>x/5<2})
res6: List[(Int, Int)] = List((95,6), (10,2))

scala> l.filterNot({case (x,y)=>x/5<200})
res7: List[(Int, Int)] = List()

I want to write a utility method that can wrap and return Option type of the first element of the List which will be a tuple if filterNot has not emptied the list to List(). If filterNot gives me List(), I just want to return None. If filterNot gives me back a List with items, I want to do Option(l(0)). I can do it with regular if checks and all but I was wondering how do I do it the more functional way?

A: A better alternative would be to use List.find which takes a predicate and returns the first match:
scala> l find { case (x, y) => x / 5 >= 2 }
res5: Option[(Int, Int)] = Some((95,6))

scala> l find { case (x, y) => x / 5 >= 200 }
res6: Option[(Int, Int)] = None

Note I reversed the less than to greater than because we're not negating the predicate.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using Java 8, what is the most preferred and concise way of printing all the lines in a file? What is the most preferred and concise way to print all the lines in a file using the new Java 8?
The output must be a copy of the file, line for line as in:
[Line 1 ...]
[Line 2 ...]

The question pertains to Java-8 with lambdas even though there are ways of doing it in older versions. Show what Java-8 is all about!

A: Here is a simple solution:
System.out.println( new String(Files.readAllBytes(Paths.get("sample.java"))) );

A: This uses the new Stream with a lambda in a try enclosure.
I would say it is the most preferred and concise way because:
1) It will automatically close the stream when done and properly throw any exceptions.
2) The output of this is lazy. Each line is read after the last line is processed. This is also is closer to the original Java streams based file handling spec.
3) It prints each line in a manner that most closely resembles the data in the file.
4) This is less memory intensive because it does not create an intermediate List or Array such as the Files.readAllLines(...)
5) This is the most flexible, since the Stream object provided has many other uses and functions for working with the data (transforms, collections, predicates, etc.)
 try (Stream<String> stream = Files.lines(Paths.get("sample.txt"),Charset.defaultCharset())) {
            stream.forEach(System.out::println);
 }

If the path and charset are provided and the Consumer can take any Object then this works too:
 try (Stream stream = Files.lines(path,charset)) {
            stream.forEach(System.out::println);
 }

With error handling:
 try (Stream<String> stream = Files.lines(Paths.get("sample.txt"),Charset.defaultCharset())) {
            stream.forEach(System.out::println);
 } catch (IOException ex) {
        // do something with exception
 }

A: You don't really need Java 8:
System.out.println(Files.readAllLines(path, charset));

If you really want to use a stream or need a cleaner presentation:
Files.readAllLines(path, charset).forEach(System.out::println);


text:
Q: How to split the result of ND neigbour result using perl? I have an output like this:
IPv6 Address                            Age    Link-layer Addr   State  Circuit
2001::1                                 0      00:30:88:13:28:b9 intf   1/1 vlan-id 100
2001::2                                 62     00:00:00:00:00:00 incmp  1/1 vlan-id 100
2002::1                                 0      00:30:88:13:28:b9 intf   1/1 vlan-id 101
2002::2                                 63     00:00:00:00:00:00 incmp  1/1 vlan-id 101
fe80::201:4ff:fe00:0                    14     00:00:00:00:00:00 incmp  1/1 vlan-id 100
fe80::230:88ff:fe13:28b9                0      00:30:88:13:28:b9 intf   1/1 vlan-id 100
fe80::201:5ff:fe01:0                    60     00:00:00:00:00:00 incmp  1/1 vlan-id 101
fe80::230:88ff:fe13:28b9                0      00:30:88:13:28:b9 intf   1/1 vlan-id 101

from here i want the age column values alone to be stored. How to use split or grep command here ?

A: perl -anE 'next if $. == 1; say "age: $F[1]"' file

to find max age:
use List::Util qw(max);
my $max_age = max map { (split)[1] } `command`;

without modules:
my ($max_age) = sort { $b <=> $a } map { (split)[1] } `command`;

A: This would be easy if your columns were separated by a fixed width (e.g. \t or a certain number of spaces). Assuming they're not, and assuming that you want to read in your file, I'd use a simple regex to pull out the age values, and for each line of the input file (here 'input.txt') push them onto an array called @age.
#!/usr/bin/perl
use strict;
use warnings;
use File::Slurp;
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;

my @input = read_file('input.txt');
shift @input;

my @age;
foreach (@input){
    my (@match) = ($_ =~ /\:\w+\s+(\d+)\s+/);
    push @age, @match;
}

print Dumper (\@age);

Output:
$VAR1 = [
          '0',
          '62',
          '0',
          '63',
          '14',
          '0',
          '60',
          '0'
        ];

UPDATE
Data Dumper just provides a way of visualising what's in a data structure. But if you don't want to use it then just change to:
#!/usr/bin/perl
use strict;
use warnings;

my $input = 'input.txt';
open my $file, '<', $input or die "Can't open $input: $!";

my @age;
while (<$file>){
    my (@match) = ($_ =~ /\:\w+\s+(\d+)\s+/);
    push @age, @match;
}

foreach (@age){
    print "$_\n";
}

Output:
    0
    62
    0
    63
    14
    0
    60
    0

In either case, it doesn't change the way the code works, or the fact that the information is stored in an array called @age


text:
Q: How can I get Word to open in draft view automatically? I am using Word for Mac 2011 (Version 14.1.2) and I would like it to default open files in draft view as opposed to print view.  It is not obvious to me what settings to change to get this result.

A: The views are not set global, but per document. If you open the document and save it in draft view, it will reopen in draft view. Also, once you selected draft on new document, word seems to default to that for new docs on startup.
You can find a whole thread on the topic here:
Microsoft Answers KB: Set Default View to Draft

A: I can't confirm Word 2011, but at least in Word 2013 and 2016, you can add the following macro to your Normal template:
Sub AutoOpen()
    ActiveWindow.View.Draft = True
End Sub

To create new documents in draft view:
Sub AutoNew()
    ActiveWindow.View.Draft = True
End Sub

I had the same question, and found the answer I provided above here.


text:
Q: Can I specify *source* IP address for a JDBC connection? I have a Java application that connects to a database with a JDBC driver. It happens to be a Postgres instance, but I'm looking for a general solution if it exist.
The server on which the application runs has multiple IP address, all in the same subnet. The JDBC connection is established using the 'primary' IP of the server.
I can play with Linux networking stack to have outgoing connections to the database use the secondary IP address.
Is there a way to programatically specify the source IP address will be used to to my JDBC connection?

Context: We want to move the application without touching the database, which has rules restricting IP address it will accept connections from.
The only hack I see would be making an SSL connection, and return a new Socket bound to the secondary IP from a custom SSLSocketFactory.

A: Some googling suggests that it depends on a particular JDBC driver.
For MySQL, it's done via property on the URL:
jdbc:mysql://localhost:3306/sakila?localSocketAddress=123.33.33.33

(See https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html)
In the case of Postgres, looks like your best option is socketFactory URL property - just create plain old sockets, not SSL sockets.
(See https://jdbc.postgresql.org/documentation/head/connect.html#connection-parameters)

A: Following PR add feature to configure localSocketAddress on PostgreSQL JDBC driver: https://github.com/pgjdbc/pgjdbc/pull/2082


text:
Q: Why Http request with Fiddler is blazing fast I wrote a multithread program in c# that crawls a web site, but when I started Fiddler in the background request completed 12x faster, it is really strange for me and when I close Fiddler download rates slows downs. how it is possible please help, (there is no proxy setting for my connection to the ineternet and for Fiddler too) If i can inject the performance of fiddler in my application it would be wonderful, any solution? Is there any magic behind the scenes ?? :)
Thanks

A: The reason is the limit on the number of simultaneous http connections which is ignored when using Fiddler.
I've run into the same behavior while using System.Net.Http.HttpClient to perform multiple (~80) concurrent requests. With Fiddler running, all the requests were completing much faster. Keep-alive was certainly enabled.
I used Wireshark to see what's happening and first thing I noticed that the manner of the http traffic was different. With Fiddler requests were thrown all at once and responses followed nicely grouped as well. Without Fiddler the requests were interleaving with responses.
Secondly, tcpview showed that my code without Fiddler opened only 2 tcp connections to the server. With Fiddler started, the number of connections significanly increased. There were tens of them from my app to Fiddler and then from Fiddler to the server.
It is well known that the http standard recommends the number of http connections should be no more than 2 and it seems the limit is implemented as a default setting in http clients.
In .NET applications we can control the limit with ServicePointManager.DefaultConnectionLimit static property. As an experiment, having it set to 100 made the requests completing with the same time with and without Fiddler.
The setting can also be controlled through app.config:
    <system.net>
    <connectionManagement>
        <add address="*" maxconnection="100" />
    </connectionManagement>
</system.net>

Now, why is the default connection limit not respected while using Fiddler? Looks like the limit is different when an http client uses a proxy and Fiddler does act as a proxy. I did not find much information about the proxy connection limit besides this old article.

A: Can you show some sample code so people can confirm this? Otherwise it'll become wild guessing.
My best guess: Fiddler uses keepalive which will save the trouble of opening the connection over and over again. You can confirm this by disabling both Reuse client connections and Reuse connections to servers: if it's then as slow as usual (or slower), the benefit is gained from keeping the connection alive.


text:
Q: How to tag an artefact in Nexus repository? I want to tag specific artefacts in my Nexus repository and then display the list of such tagged artefacts in Jenkins pipeline as parameters. How can I tag artefacts in Nexus?

A: To tag an artefact you could use a curl command like :
curl -u userToken -X POST "https://your.nexus.url/service/rest/v1/tags/associate/tagName?repository=repoName&group=folder%2Fwhere%2Fyou%2Fwant" -H "accept: application/json"

Where :

*

*tagName is the expected tag

*repoName is your repository.

*%2F in the URL parameter is for a slash, as per URL parameter encoding rules. I tried with a "/" but that didn't work under windows.

This command will tag all artefacts in the folder.


text:
Q: Get placeholder index for jQueryUI Sortable I use jQuery Sortable plugin for sorting a list of pages. Users can rearrange the pages in custom order. However, I want the placeholder box to contain the page number the page will get on release.
If the user has three pages in their list, and rearranges the second page, to the end, the placeholder for page three would show the number three.
How would I go about to do this?

A: Try this :
$("#sortable").sortable({
      placeholder: 'ui-state-highlight ui-sort-position',
      helper: 'clone',
      sort: function(e,ui) {
         $(ui.placeholder).html(Number($("#sortable > li:visible").index(ui.placeholder)+1));
      }
});

will show you the new index (+1) ... working demo here


text:
Q: Error : fork() failed in code generation I am developing one application for my client with IBM Streams v4.2
While compiling, I am getting the following error:

/opt/ibm/InfoSphere_Streams/4.2.0.0/system/impl/bin/spl-code-gen-driver:
  CDISP0139E ERROR: The execution of the code generator failed. The
  error is: fork() failed.

Can anyone help as to where can I look for the actual error?

A: fork() failing generally means the system is overloaded and out of resources.  Try terminating processes that you don't need, and if that doesn't work could you try increasig the memory for the VM and then or restarting the OS?

A: My problem is resolved now. fork() is due to too many processes running.Since I could not make out which process to kill, I restarted the system and immediately compiled the code after it was started.My code was compiled successfully.
For a permanent solution, I reduced the number of parallel threads/chain in the code so that the system does not run out of resources.It worked !!!


text:
Q: How to edit accounts & sync settings for a specific account Under the 'Accounts & Sync' settings graphical OS menu, there are listings of user-configured Google accounts.
Please could someone point me in the right direction to programmatically change the sync settings associated with one of these accounts?
Thanks

A: Those settings use the new AccountManager APIs.  Here's some sample code that shows how to add a new account.  I'd assume that you'd want to get the credentials of one of the existing accounts and simply modify the data.
Unfortunately, I haven't had a chance to try out those APIs yet.

A: Maybe ContentResolver#setIsSyncable() can do what you want.
Perhaps would be better to fire the android.provider.Settings.ACCOUNT_SYNC_SETTINGS intent with either the EXTRA_AUTHORITIES extra set to ["google.com"], or possibly put the extra named "account" as the Account object you got from AccountManager. Then your user can turn their sync on or off for themselves.

A: ContentResolver.setSyncAutomatically(account, authority, true/false): sets whether or not the provider is synced when it receives a network tickle.


text:
Q: Should the reflection coefficient be negative? According to Fresnel's equations for the magnetic field parallel to the surface of a dielectric, the reflection coefficient is this:
$$r_{s}=\frac{\cos\theta^{i}-\frac{n_2}{n_1}\cos\theta^{t}}{\cos\theta^{i}+\frac{n_2}{n_1}\cos\theta^{t}}\tag{R}$$
In all the examples I have found, the magnetic field's direction "looks"(I'm not sure what is the correct term) at the reader (like this)
However, when the magnetic field "looks down", like this
the reflection coefficient I have found is the negative of Fresnel's.
$$r_{s}=\frac{-\cos\theta^{i}+\frac{n_2}{n_1}\cos\theta^{t}}{\cos\theta^{i}+\frac{n_2}{n_1}\cos\theta^{t}}\tag{R}$$ Is this correct or are my calculations wrong? Here the user concludes that this is caused by a phase shift, is that the case here too?

A: If you've changed the direction of the incoming magnetic field $\vec{H}_{\pi 0}$ but kept $\hat{u}_\pi$ pointing in the same direction, then you must have implicitly changed the direction of the incoming electric field $\vec{E}_{\pi0}$ (since $\vec{E} \times \vec{H} \propto \vec{k}$.)   Since the Fresnel coefficient is defined as the ratio of $\vec{E}_{\alpha0}$ to $\vec{E}_{\pi0}$, it makes sense that flipping the sign of the magnetic (and electric) field flips the sign of the Fresnel coefficient;  it's merely a matter of the definitions you choose.


text:
Q: Transforming Huge Database table to Another Table We are migrating lot of data from our old database to new database.
Presently, both of them are actively[writing/reading] used based on flows/activity as migration is in progress.
Here's the real challenge for me now. We have old database table which's still getting used now.

Atleast 1,00,000 new records are getting inserted every day and we
  need to move 6months old data [01-01-2014] to new database.

We are using MySQL in both places. The new table to old table need some logical-transformation of data which will be carried through Java-JDBC, as the table structures and functionality is changed.
What are the ideal steps that I need to follow and taken care to do this transformation as quick as possible without fail.
As per my calculation, we will be migrating atleast 2,00,00,000 records.

Some info:
Presently index exists only on ID column. creation_date exists without index
How to fetch efficiently these records, a better query to fetch??
Efficient way to transform using multi-threading
Efficient way to write the data into new database

A: Since existing records are static they can be converted to the new schema any time after the migration process is signed off.  Specifically, as soon as the new DB is available you can start loading it with old data.  Start with the oldest and work your way forward one day at a time.  Assuming it takes less than twenty four hours to convert one day's data, you can run this process non-stop until you have caught up with today's data.
Thereafter you can continue with a more-or-less parallel run, with two options.  Option "A" is to load each new day's data into the old DB, then run the convertion process to get it into the new DB.  Option "B" is to run the old ETL to load today's source file into the old DB and run the new ETL to load the same soruce file into the new DB.  Option "B" has the advantage of testing your new ETL process, too.
Then on cut-over day you will have at most one day's worth of data to move.
As for the convertion process itself I would suggest you read all the data for one business transaction from the old tables (i.e. a referentially in tact set), convert it, then write it entirely to a set of staging tables in the new schema.  Note not to the live tables themselves but to a parallel set of staging tables.  Then you can write lots of reconciliation checkes against these staging tables.  If there's a problem you can bulk-delete the staging tables without affecting the new DB's data, fix the convertion and re-run.
Once the reconciliation completes successfully you can bulk-copy from the staging to the live tables.  The staging tables can have additional columns to help with reconciliation that you would not want in the live tables (source surrogate ID, for example).  Retain the staging tables for a few months for any post-mortem on your go-live problems.
I know it sounds like all this staging and reconciliation is eating precious time during a cut-over.  And it is, but is nothing compared to the time it will take to post-fix two hundred million rows in an active production system.


text:
Q: Count repeated null values in array I have an array like this:
$items = ['a', 'b', null, null];

I want count [nulls] in this array which is 2.
But: Without replacing them before working with. Like this:
$items = array_replace($items,array_fill_keys(array_keys($items, null),''));

array_count_values($items);

And: Without removing them from the array and put them out of the total. Like this:
count($items) - count(array_filter($items));

I'm trying to know more better solutions.

A: You could array_filter on the null values and count once on the result:
count(array_filter($items, function ($item) { return $item === null; }))

or in PHP 7.4:
count(array_filter($items, fn($item) => $item === null));

Demo: https://3v4l.org/TOHdP

A: Usually the best is to be explicit, so simply iterate over the input array and count:
<?php
$items = ['a', 'b', null, null];
array_walk($items, function($value) use (&$count) {
    if ($value === null)
      $count++;
});
var_dump($count);

The output obviously is:
int(2)

A: You can use array_count_values method. you can use it like this:
- Solution 1
$items = ['a', 'b', null, null];

$counts = 0;
foreach(array_count_values($items) as $item => $counter){
    $counts += $counter;
}
echo count($items) - $counts;

PS: array_count_values() just count string and integers.
- Solution 2
Or you can use array_filter to create null values array and count it.
echo count(array_filter($items, function ($item) {
    return $item === null;
}))

A: No need for array_filter
$items = ['a', 'b', null, null];

echo(count(array_keys($items, null, true))); // Output: 2

Note the third argument must be true if you only want null to be counted, as true means do strict comparison (===)


text:
Q: Eclipse CDT is reporting false erros while using std::index_sequence UPDATED: Added complete example and compiler information
I have Eclipse 2019-03 (4.11.0) with CDT 9.7.0.20190309 and the build-in compiler reports false positive errors while using std::index_sequence in C++17:
#include <gtest/gtest.h>
#include <utility>
#include <array>

class Sample {
public:
    template<std::size_t N >
    std::size_t get_percentage( void ) {
        return N;
    }

    template<std::size_t... Is>
    inline std::array<std::size_t, sizeof...(Is)> calculate_percentages( std::index_sequence<Is...> ) noexcept {
        return { this->get_percentage<Is>()... };
    }
    template<std::size_t N>
    inline std::array<std::size_t, N> get_percentages( void ) noexcept {
        return this->calculate_percentages( std::make_index_sequence<N>() );
    /*           ^^^^^^^^^^^^^^^^^^^^^ : Invalid arguments ' Candidates are: std::array calculate_percentages(std::integer_sequence) ' */
    }
};

TEST( IntegerSequence, InvalidArgumentsError ) {
    Sample test;
    std::array<std::size_t, 5> data = test.get_percentages<5>();
    for( int i = 0; i < 5; i++ ) {
        std::cout << data[i] << std::endl;
    }
}

int main( int argc, char ** argv ) {
    testing::InitGoogleTest( &argc, argv );
    return RUN_ALL_TESTS();
}

But the normal compilation succeeds without any problem.
My CDT GCC Built-in Compiler Settings in
Project Properties -> C/C++ General -> Preprocessor Include Paths, Macros etc. -> Providers is as follows:
${COMMAND} ${FLAGS} -E -P -v -dD -std=c++17 "${INPUTS}"

The same applies for CDT Cross GCC Built-in Compiler Settings.
Rebuilding the index does not helped in there.
The GCC version I am using:
gcc (Ubuntu 8.3.0-6ubuntu1) 8.3.0

Many thanks in advance to anyone willing to help...

A: The problem is caused by the fact that the standard library that comes with gcc 8 and newer uses a new compiler intrinsic called __integer_pack to implement std::make_integer_sequence (and related utilities like std::make_index_sequence).
Eclipse CDT's parser does not currently understand the __integer_pack intrinsic, and therefore it has trouble correctly parsing code that uses std::make_integer_sequence / std::make_index_sequence with these newer gcc versions.
I filed a CDT bug to track adding support for the __integer_pack intrinsic.
Meanwhile, a workaround you could employ is to use gcc 7 or older. If you need gcc 8 or newer to actually build your code, you could still tell Eclipse the look at the standard library headers of e.g. gcc 7 by replacing ${COMMAND} in the mentioned "built-in compiler settings" configuration with g++-7.
UPDATE: The Eclipse bug is now fixed, with the fix targeting CDT's 9.11 release (scheduled to be part Eclipse 2020-03).


text:
Q: Get id's retrieved by data attribute using javascript from li items JavaScript
var sessions = [];
$('.rightDiv').each(function(index) {
    var session = $.trim($(this).text().slice(0, -1)).split("×");
    var sessionData = [];
    for (var i = 0; i < session.length; i++) {
        var ids = $(this).find('li').data('id');
        var s = {
            subjectOrder: i,
            subjectID: ids
        };
        sessionData.push(s);
    }
    var ses = {
        sessionNo: index,
        sessionData: sessionData
    };
    sessions.push(ses);
});

HTML

Counting<button onclick="deleteElement(event)" class="delbtn">×</button>

Priorities" class="delbtn">×</button>

JSON
{"sessionNo":"0","sessionData":[{"subjectOrder":"0","subjectID":"1"},{"subjectOrder":"1","subjectID":"1"}]}

My Problem
What the code above does, is retrieves the session no from the ul class: class="sortable rightDiv session4" and each id of the li from data-id.

In this case it loops fine through the li items, but it only displays the id of the first li element.
It should be:
{"sessionNo":"0","sessionData":[{"subjectOrder":"0","subjectID":"1"},{"subjectOrder":"1","subjectID":"2"}]}

Any idea what's wrong?

A: Since you are using $(this).find('li').data('id');, it will always return the value of first li data attribute.
Use .each() to iterate and create an array
var sessionData = [];

$(this).find('li').each(function (index, elem) {
    sessionData.push({
        subjectOrder: index,
        subjectID: $(elem).data('id')
    });
})

A: change:
var ids  = $(this).find('li').data('id');

to:
var ids  = $(this).find('li').eq(i).data('id');


text:
Q: Too little RAM in Kaa Server I want to run a test with KAA, so I was trying to install the sandbox in my laptop but it has only 4GB in RAM, so when I try to set up the Virtual Machine the system won't let me set up over 1,6GB and the VM won't start.
So I was trying to install in other old laptop so I installed Ubuntu 16,04 and I followed all the step by step instructions in Kaaproyect's WEB. I could do it, but when I try to start the server can't do it. I was checking the Log error and say me that the problem is in the Java's Virtual machine, can't start because only have 2GB in RAM. I need to test a Little application so is it possible change this requirement in the Java machine and start the system?
PS: I can't buy more Ram.

A: I recommend you to use amazon AWS. The basic installation where you can run Kaa is free for one year, and it runs quite well there.


text:
Q: Images sometimes don't load in my web application In my Java web application, the images sometimes fail to appear, instead showing the "broken link" red X symbol. Looking at the Network tab in Chrome's developer tools, I can see that the images are being loaded with a status code of 200 (OK) and the correct content type header. There does not appear to be a content length header, if that matters.
I have not been able to reproduce the issue when I run the application locally from my IDE; it only seems to happen when I run it on the server. My first thought was that it might have something to do with IE's Compatibility View, but the same thing happens whether Compatibility View is on or off, and it also happens in Chrome. I also tried changing some of IE's security settings, since the app is in the Local Intranet Zone when I run it locally, while it is in Trusted Sites when it I run it on the server. That didn't help.
I don't think there is anything unusual about the img tags in the JSP. I am using an older DOCTYPE because it prevents IE 8 from putting a border around the page, and I need to support IE 8. The border is undesirable, but if changing the DOCTYPE would fix the problem, it would be worth it. I realize that the older DOCTYPE puts IE into quirks mode, but changing it to <!DOCTYPE html> didn't seem to help.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<%@page contentType="text/html" pageEncoding="UTF-8"%>

     ...

        ...

If I reload the page, some of the images will reappear, while others will disappear. I typically have to reload the page 4 or 5 times before all the images will appear. Clearing cache and/or cookies didn't seem to help.
There are not a lot of images, typically only 6 or 7 on a page, and they are no bigger than 4kb in size. Some images are GIFs while others are PNGs; both types have the same problem. I am running Tomcat 7 on Java 1.6 both locally and on the server.
Another piece of information, although I'm not sure how it fits into the puzzle: I looked in the folder where IE stores its cached files, and I noticed that the file for one of the images that was not being displayed had a file size of 0. I deleted the file, reloaded the page, and the image appeared. Then I reloaded the page a couple of times until the image disappeared, and looked in the cache directory. Once again, the image file had a size of zero. I'm not sure why that would happen.
I have looked around and seen similar questions, but so far no solution. I've tried to supply all the information that I thought would be relevant, but let me know if there is anything else that might be important. Thanks for your help.


text:
Q: wordpress, unknown collation #224 in table wp_posts.frm I am connecting my wp database via sqlpro and while checking my tables I get unknown collation #224 error. I have tried this advice with no luck.
My wp site gives db connection error. Is there anything I can do to restrore my database?

A: it is local server or hosting, where is your WP ?


text:
Q: How can we prevents a file/folder from being included in the codebase in Angular 12? I have one scenario in which I need to import service files according environment variable. How can we achieve that ? Example is as bellow.
I have two folders with name of dev and prod in which I have service files with same name but different logic. I have one component in which I want to inject that service/dependency according to environment, means If I am creating prod build then service from prod folder should be added in bundle(bundle should not include dev folder services).
Please help me to achieve this scenario.

A: Like for environment.ts, you might be able to use https://angular.io/guide/build#configure-target-specific-file-replacements
"project": {
  "fileReplacements": [
    {
      "replace": "src/environments/environment.ts",
      "with": "src/environments/environment.project-b.ts"
    },
    {
      "replace": "src/app/services/dev/index.ts",
      "with": "src/app/services/prod/index.ts"
    }
  ]
}

index.ts in both dev and prod folder:
import { DbService } from './db.service'
import { ActionsDbService } from './actions.service'
import { ItemsDbService } from './items.service'

export {
  DbService,
  ActionsDbService,
  ItemsDbService
}

and in your other files which import for example ItemsDbService you would import from 'src/app/services/dev'


text:
Q: Read the Message only countable number of times in Spring AMQP I am having an application which receives the message from RabbitMQ. Once the message is consumed and if it encounters some issue. I have set the setDefaultRequeueRejected to true and it is re queuing back.
Now i have scenario, If the message goes back to the queue, again it will be consumed and again re-queues. This has form a kind of cycle.
Now i need to consume the re-queued message only twice (Maintaining kind of a counter) and after that i will push it to ErrorQueue/DeadLetter Queue.
How to maintain such counter ?
Regards,
Chandan

A: RabbitMQ doesn't provide such a mechanism, just a boolean header that indicates the message was redelivered.
If the sender sets a messageId header, you can use a stateful retry interceptor with and the framework will keep track of how many times the same message has been delivered. With a RejectAndDontRequeueRecoverer, the message will be sent to the DLQ (if configured) after retries are exhausted.
If you don't have message ids, you can use a custom MessageKeyGenerator to generate a key for the state from the message itself.


text:
Q: How to calculate the difference in revenue for 2 specific periods from data in a single table? I am using SQL Server 2014 and I have the following T-SQL query which is supposed to calculate the difference in total revenue based on 2 specific periods. The data to perform the computation come from a single SQL Table.
To summarize, I have a column in table T1 called Revenue and another column called Month. I need to find the difference in revenue for Months September 2020 to December 2020 versus September 2019 to December 2019.
My T-SQL query stands as follows:
USE [MyDatabase]

;with cte1 as
(
  SELECT
    sum ([Revenue]) as 'Revenue Sep 19 - Dec 19'
  FROM
    [T1]
  WHERE
    [Month] between '2019-09-01' and '2019-12-01'
),
cte2 as (
  SELECT
    sum ([Revenue]) as 'Revenue Sep 20 - Dec 20'
  FROM
    [T1]
  WHERE
    [Month] between '2020-09-01' and '2020-12-01'
),
cte3 as (
  SELECT
    cte2.[Revenue Sep 20 - Dec 20] as 'Total Revenue',
    'Sep 20 - Dec 20' as 'Period',
    '1' as 'ID'
  FROM
    [cte2]

  UNION ALL

  SELECT
    cte1.[Revenue Sep 19 - Dec 19] as 'Total Revenue',
    'Sep 19 - Dec 19' as 'Period',
    '1' as 'ID'
  FROM
    [cte1]
)
select a.[Total Revenue] - b.[Total Revenue]
from
  (select cte3.[Total Revenue] from [cte3] where cte3.[Period] = 'Sep 20 - Dec 20') a
  JOIN
  (select cte3.[Total Revenue] from [cte3] where cte3.[Period] = 'Sep 19 - Dec 19') b
  ON b.[ID] = a.[ID]

I have based my query on the following: How to calculate between different group of rows of the same table
However, when running my query, I am getting the following error message:

Invalid column name 'ID'.

I can't figure out what I am doing wrong here. Isn't column ID present in the cte3?

A: ID must be present in the select list of both a and b for it to be visible to the join:
from
  (select cte3.ID, cte3.[Total Revenue] from [cte3] where cte3.[Period] = 'Sep 20 - Dec 20') a
  JOIN
  (select cte3.ID, cte3.[Total Revenue] from [cte3] where cte3.[Period] = 'Sep 19 - Dec 19') b
  ON b.[ID] = a.[ID]

A: You query is way more complicated than necessary.
SELECT (SUM(CASE WHEN [Month] between '2020-09-01' and '2020-12-01' THEN [Revenue] ELSE 0 END) -
        SUM(CASE WHEN [Month] between '2019-09-01' and '2019-12-01' THEN [Revenue] ELSE 0 END)
       ) as difference
FROM [T1];

Your version has three CTEs, a UNION ALL, two subqueries, and a JOIN.
Notes:

*

*Do not use single quotes to delimit column aliases.  Only use single quotes for strings and dates.

*Name your column aliases so they don't need to be escaped.  For instance, use underscores instead of spaces.

*Do not use meaningless table aliases such as a and b.  Use meaningful ones, such as t2019.

A: While using SUB QUERY you must mention the Column which you mention in the Join condition also
SELECT A.[TOTAL REVENUE] - B.[TOTAL REVENUE]
FROM
(SELECT CTE3.[TOTAL REVENUE],CTE3.ID FROM [CTE3] WHERE CTE3.[PERIOD] = 'SEP 20 - DEC 20') A
JOIN
(SELECT CTE3.[TOTAL REVENUE],CTE3.ID FROM [CTE3] WHERE CTE3.[PERIOD] = 'SEP 19 - DEC 19') B ON B.[ID] = A.[ID]

A: Try this below code, It will help you
USE [MyDatabase]

select sum([Revenue Sep 20 - Dec 20])-sum([Revenue Sep 19 - Dec 19]) as revenue_diffrence
from
(
SELECT
    [Revenue] as 'Revenue Sep 19 - Dec 19', 0 as 'Revenue Sep 20 - Dec 20'
  FROM
    [T1]
  WHERE
    [Month] between '2019-09-01' and '2019-12-01'

union all
SELECT
    0 as 'Revenue Sep 19 - Dec 19',[Revenue] as 'Revenue Sep 20 - Dec 20'
  FROM
    [T1]
  WHERE
    [Month] between '2020-09-01' and '2020-12-01'
)a


text:
Q: Update Many-to-Many Association with GraphDiff I have the following data model:

My business logic works with detached entities so I'm using GraphDiff to perform updates. I'm having trouble updating the PerfModes/CalcPoints association. Conceptually, Block owns CalcPoints and PerfModes, but CalcPoints can be associated with any number of PerfModes.
I'm trying to do updates at the Block level. The code I came up with doesn't throw any errors (while other attempts did) but neither does it update the PerfModes/CalcPoints association.
container.UpdateGraph(block, map => map
    .OwnedCollection(b => b.HistPoints)
    .OwnedCollection(b => b.CalcPoints)
    .OwnedCollection(b => b.PerfModes, with => with
        .OwnedCollection(p => p.FilterCriterion, with2 => with2
            .OwnedCollection(fc => fc.Filters, with3 => with3
                .AssociatedEntity(f => f.OperatorType)
                .AssociatedEntity(f => f.CalcPoint))))
        .AssociatedCollection(p => p.CalcPoints)
);

I probably don't have a full grasp of EF graphs and GraphDiff. How do I ensure that the many-to-many PerfModes/CalcPoints association gets updated correctly?
EDIT
After looking over andyp's answer, I pulled down the latest version of GraphDiff from GitHub and tried the following mappings:
container.UpdateGraph(block, map => map
    .OwnedCollection(b => b.CalcPoints)
    .OwnedCollection(b => b.PerfModes,
        with => with.AssociatedCollection(pm => pm.CalcPoints)));

This correctly updates my PerfModes/CalcPoints association. I switched back to my original mappings and still saw the issue of the association not updating, so it seems there's a problem with trying to update the entire model at once. I'd be fine with making multiple UpdateGraph calls, but what would be the best way to break them out?
Here's a gist with relevant code and a failing unit test.
I'm inheriting the EF generated container class to create my own context with proxy creation disabled. Does that cause a problem with GraphDiff?

A: As your mappings seemed to be correct, I've tried to reproduce your issue like this:
var calcPoint = new CalcPoint();
var block = new Block
{
    CalcPoints = new List<CalcPoint> {calcPoint},
    PerfModes = new List<PerfMode>
    {
        new PerfMode {CalcPoints = new List<CalcPoint> {calcPoint}}
    }
};

using (var context = new TestDbContext())
{
    context.UpdateGraph(block, map => map
        .OwnedCollection(b => b.CalcPoints)
        .OwnedCollection(b => b.PerfModes,
            with => with.AssociatedCollection(pm => pm.CalcPoints)));

    context.SaveChanges();
}

using (var context = new TestDbContext())
{
    var reloaded = context.Blocks.Include("PerfModes.CalcPoints").Single();
    Assert.AreEqual(1, reloaded.CalcPoints.Count);
    Assert.AreEqual(1, reloaded.PerfModes.Count);
    Assert.AreEqual(1, reloaded.PerfModes[0].CalcPoints.Count);

    Assert.AreEqual(reloaded.CalcPoints[0], reloaded.PerfModes[0].CalcPoints[0]);
}

All entities are simple POCOs with an int key and just IDbSet<T>s on my DbContext. I've neither added anything in OnModelCreating(..) via the fluent API nor used any attributes on the navigation properties.
My code above is working properly, so I've got a couple of suggestions / questions:

*

*Is there anything (significant) you did differently then me above?

*Do you call SaveChanges() after UpdateGraph()? It's not implied!

*Do you have the latest version of GraphDiff? Please note, that the NuGet package is quite outdated, it's better to grab the current source from Github and build it yourself.

*If your problem persists please update your question with the exact scenario that isn't working: please include the state of your DbContext before calling UpdateGraph(), the changes you expect GraphDiff to make and the ones it fails to make.

EDIT:
Your mapping wasn't correct after all, you're mapping Block.CalcPoints twice, once as an owned collection (first call to OwnedCollection(..)) and once as an associated collection (last and only call to AssociatedCollection(..)). So you never told GraphDiff to map PerfModes.CalcPoints and it, in turn, never updates that collection.. ;-)
To ask GraphDiff to do that please move one ) from the end of the line before the last line to the end of the last line and you should be fine (after that your indentation matches the brackets). The correct mapping looks like this (two closing brackets at the end of the last line):
container.UpdateGraph(block, map => map
    .OwnedCollection(b => b.HistPoints)
    .OwnedCollection(b => b.CalcPoints)
    .OwnedCollection(b => b.PerfModes, with => with
        .OwnedCollection(p => p.FilterCriterion, with2 => with2
            .OwnedCollection(fc => fc.Filters, with3 => with3
                .AssociatedEntity(f => f.OperatorType)
                .AssociatedEntity(f => f.CalcPoint)))
        .AssociatedCollection(p => p.CalcPoints))
);


text:
Q: Can a connected second countable manifold have cardinality $>2^{\aleph_0}$?
Can a connected second countable manifold have cardinality $>2^{\aleph_0}$?

From here, a connected Hausdorff manifold must have cardinality $2^{\aleph_0}$. How about if we change the condition "Hausdorff" to "second countable"?

A: Regardless of connectedness: since the manifold $M$ is second-countable, it has a countable atlas (every open covering of a second-countable space admits a countable subcovering). Therefore, it is countable union of subsets homeomorphic to the unit ball of $\Bbb R^n$, whose cardinality is at most $2^{\aleph_0}$.
Therefore its cardinality is $\le \aleph_0\cdot 2^{\aleph_0}=2^{\aleph_0}$.


text:
Q: Marshmallow RelativeLayout behaves strange with alignBaseline On Android 6.0 Marshmallow the positioning of an EditText in relation to an ImageView in a RelativeLayout with the attributes baseline and layout_alignBaseline does not work anymore. The behaviour can even be observed in the layout editor in Android studio. On a real Android Marshmallow device or emulatr the EditText in my case is shift outside the screen and not visible. Do I miss some changes, is it a bug?
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivityFragment">

<ImageView
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:id="@+id/imageView"
    android:src="@drawable/icon_category_geography_raster"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:baselineAlignBottom="true"
    android:background="#00ffff"
     />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/editText"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@id/imageView"
    android:background="#ff0000"
    android:inputType="text"
    android:hint="Hint"
    android:layout_alignBaseline="@id/imageView" />

I have created screenshots of the Layout Editor of Android Studio. The difference between these two screenshots is solely the change of the API level.
I have created a sample project
https://github.com/mikegr/baseline

A: This is bug reported on https://code.google.com/p/android/issues/detail?id=73697&thanks=73697
Since API11 you can simply use  android:baselineAlignBottom="true"
Below API11 you can overwrite getBaseLine().
Update to Android Support Library 23.2.1,  this may solve your problem.


text:
Q: How to highlight a node in D3 via Query String? I have a collapsible D3 Tree which I have modified to work with Angular 4. Everything is working fine.
Script reads the Params in the URL, grab the ID in the params and open the graph until the requested node ( attachment )

URL:
/asset-graph?id=27
In this case ID 27 is the Asset 3 in the graph.
I need to change the colour or highlight the requested node in the graph.
Here is the code I came up with:
.style('fill', (d: any) => {
      // debugger
      let id;
      if (d._children == null && d.children == null) {
        id = d.data.id;
      }
      if (!UtilService.empty(d.children)) {
        id = d.children[0].data.id;
      }
      if (!UtilService.empty(d._children)) {
        id = d._children[0].data.id;
      }
      if (!UtilService.empty(id)) {
        if ( String(this.parentId) === String(id) ) {
          return 'red';
        }
      }
      });

This code works fine and result is ( attached ) - I selected node 2.2

Here is the issue
Same code is showing the wrong highlighted label if node is a parent: ( attached )
Here I change the params in the URL to Asset 3 but the asset 2 got highlighted.

Here is the code re-jigged for typescript.
...
      ngOnInit() {

        this.svg = this.graphHelper.setUp(
                    this.d3,
                    this.width,
                    this.height,
                    this.margin);

        if ( !UtilService.empty(this.treeData) ) {
          this.root = this.d3.hierarchy(this.treeData, (d: any) => {
            return d.children;
          });
          this.root.x0 = this.height / 2;
          this.root.y0 = 0;
          [this.root].forEach(this.collapse);
          this.update(this.root);
        }

        // this.parentId: Coming from params in URL
        this.find (this.root, this.parentId);
      }

      collapse = (d: any) => {
        if (d.children) {
          d._children = d.children;
          d._children.forEach((d1) => {d1.parent = d; this.collapse(d1); });
          d._children.forEach(this.collapse);
          d.children = null;
        }
      }

      find(d, id) {
        if (String(d.data.id) === id) {
          while (d.parent) {
            d = d.parent;
            this.click(d, 'auto'); // if found open its parent
          }
          return;
        }

        // recursively call find function on its children
        if (d.children) {
          d.children.forEach( (da) => { this.find(da, id); });
        } else if (d._children) {
          d._children.forEach( (da) => { this.find(da, id); });
        }
      }

      public update(source) {
        this.treemap = this.d3.tree().size([this.height, this.width]);
        // Assigns the x and y position for the nodes
        this.treeData = this.treemap(this.root);

        // Compute the new tree layout.
        const nodes = this.treeData.descendants();
        const links = this.treeData.descendants().slice(1);

        // Normalize for fixed-depth.
        nodes.forEach((d) => { d.y = d.depth * 180; });

        // ****************** Nodes section ***************************

        // Update the nodes...
        const node = this.svg.selectAll('g.node')
          .data(nodes, (d: any) => {
            return d.id || ( d.id = ++this.i ); }
          );

        // Enter any new modes at the parent's previous position.
        const nodeEnter = node.enter().append('g')
          .attr('class', 'node')
          .attr('transform', (d) => {
            return 'translate(' + source.y0 + ',' + source.x0 + ')';
        })
        .on('click', this.click);

        // Add Circle for the nodes
        nodeEnter.append('circle')
          .attr('class', 'node')
          .attr('r', 1e-6)
          .style('fill', (d: any) => {
              return d._children ? 'lightsteelblue' : '#fff';
          });

        // Add labels for the nodes
        nodeEnter.append('a')
        .append('text')
        .attr('dy', '.35em')
        .attr('x', (d: any) => {
          return d.children || d._children ? -13 : 13;
        })
        .attr('text-anchor', (d: any) => {
          return d.children || d._children ? 'end' : 'start';
        })
        .text( (d: any) => {
          return `${d.data.asset_name.length > LIMIT_LENGTH ? d.data.asset_name.substr(0, LIMIT_LENGTH) + '...' : d.data.asset_name}`;
        });

        // UPDATE
        const nodeUpdate = nodeEnter.merge(node);

        // Transition to the proper position for the node
        nodeUpdate.transition()
        .duration(this.duration)
        .attr('transform', (d) => {
            return 'translate(' + d.y + ',' + d.x + ')';
        });

        // Update the node attributes and style
        nodeUpdate.select('circle.node')
        .attr('r', 4.5)
        .style('fill', (d: any) => {
            return d._children ? 'lightsteelblue' : '#fff';
        })
        .attr('cursor', 'pointer');

        // Remove any exiting nodes
        const nodeExit = node.exit().transition()
          .duration(this.duration)
          .attr('transform', (d) => {
              return 'translate(' + source.y + ',' + source.x + ')';
          })
          .remove();

        // On exit reduce the node circles size to 0
        nodeExit.select('circle')
        .attr('r', 1e-6);

        // On exit reduce the opacity of text labels
        nodeExit.select('text')
        .style('fill-opacity', 1e-6);

        // ****************** links section ***************************

        // Update the links...
        const link = this.svg.selectAll('path.link')
          .data(links, (d: any) => {
            return d.id;
          });

        // Enter any new links at the parent's previous position.
        const linkEnter = link.enter().insert('path', 'g')
          .attr('class', 'link')
          .attr('d', (d: any) => {
            const o = {x: source.x0, y: source.y0};
            return this.diagonal(o, o);
          });

        // UPDATE
        const linkUpdate = linkEnter.merge(link);

        // Transition back to the parent element position
        linkUpdate.transition()
          .duration(this.duration)
          .attr('d', (d: any) => {
            return this.diagonal(d, d.parent);
          });

        // Remove any exiting links
        const linkExit = link.exit().transition()
          .duration(this.duration)
          .attr('d', (d: any) => {
            const o = {x: source.x, y: source.y};
            return this.diagonal(o, o);
          })
          .remove();

        // Store the old positions for transition.
        nodes.forEach((d: any) => {
          d.x0 = d.x;
          d.y0 = d.y;
        });
      }

      diagonal(s, d) {
        const path = `M ${s.y} ${s.x}
                C ${(s.y + d.y) / 2} ${s.x},
                  ${(s.y + d.y) / 2} ${d.x},
                  ${d.y} ${d.x}`;
        return path;
      }

      click = (d, type) => {
        if (d.children) {
            d._children = d.children;
            d.children = null;
          } else {
            d.children = d._children;
            d._children = null;
          }
        this.update(d);
        this.clickMe(d.data.id, type);
      }

      clickMe = (d, type?) => {
        if (type !== 'auto') {
          this.graphSrv.callServer(d);
          this.updateLoader = true;
        }
        this.callback = d;
      }
    }


text:
Q: Websockets closing connection immediately after handshake I am trying to open a secure WebSocket and when connection is open, I want to send JSON request and to wait for response.
Need it for automation BackEnd testing.
But, I try this code and I get

websockets.exceptions.ConnectionClosedError: code = 3000 (registered),
  no reason

My colleague tells me that it seems that I open the connection, do the handshake and then immediately close it! I would like to remain open if it is possible!
This is the code that returns me "error" 3000
import asyncio
import websockets
import ssl
import logging
import time

logger = logging.getLogger('websockets')
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())

serv = 'wss://"adress":"PORT"'
print("1")
ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLSv1_2)
print("2")
json_s = {"msgType":1,"tag":12345,"username":"abc","password":"defghijk"}
print("3")
async def get_msg(uri):
    async with websockets.connect(uri) as ws:
        await ws.send(json_s)
        print("4")
        time.sleep(3)
        print('data sent')
        time.sleep(3)
        resp = await ws.recv()
        print("5")
        time.sleep(3)

    return resp
print("6")

loop = asyncio.get_event_loop().run_until_complete(get_msg(serv))
print("7")
loop.create_task(get_msg(serv))
print("8")
loop.run_forever()
print("9")

I am getting
    1
    2
    3
    6
    4
    data sent
    Traceback (most recent call last):
      File "C:/Users/Korisnik/PycharmProjects/TACHYON/Test/Websockets doc test.py", line 34, in <module>
        loop = asyncio.get_event_loop().run_until_complete(get_msg(serv))
      File "C:\Users\Korisnik\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 608, in run_until_complete
        return future.result()
      File "C:/Users/Korisnik/PycharmProjects/TACHYON/Test/Websockets doc test.py", line 26, in get_msg
        resp = await ws.recv()
      File "C:\Users\Korisnik\PycharmProjects\TACHYON1\venv\lib\site-packages\websockets\protocol.py", line 509, in recv
        await self.ensure_open()
      File "C:\Users\Korisnik\PycharmProjects\TACHYON1\venv\lib\site-packages\websockets\protocol.py", line 812, in ensure_open
        raise self.connection_closed_exc()
    **websockets.exceptions.ConnectionClosedError: code = 3000 (registered), no reason**

Process finished with exit code 1

And I am stuck here...

A: Maybe someone will find this Answer helping
Our server was set-up to get connection "Only" From web browser, so I must put in websocket settings User-Agent and Origin headers!
It looks like this
async with websockets.connect(uri, max_size=None, max_queue=2 ** 5, read_limit=2 ** 20, write_limit=2 ** 20,extra_headers={'User-Agent': 'Safari/537.36', 'Origin': '192.168.1.1'}) as websocketESU:
When I put those extra headers everything works just fine
It takes me 2 moths to find this solution which is absolutely simple!
Thanks everyone for answers!


text:
Q: How to match a username and password set (SharedObject's in AS3) I'm currently saving a username and password in a flash cookie, using SharedObjects.
My question is how do I make usernameField match with passwordField and usernameField2 match with passwordField2. Basically I want to distinguish one login set from another.
package
{

    import flash.display.*;
    import flash.events.*;
    import flash.net.*;
    import flash.text.*;

  public class foo extends Sprite
  {

      public var usernameField:TextField = new TextField();
      public var passwordField:TextField = new TextField();
      public var conPasswordField:TextField = new TextField();
      public var traceOutputField:TextField = new TextField();

      public var saveDataObject:SharedObject = SharedObject.getLocal("test");

      public function foo()
      {
           traceOutputField.width = 500;
           addChild(traceOutputField);

           usernameField.text = "username";
           passwordField.text = "password";
           conPasswordField.text = "password";

           usernameField.y = 50; addChild(usernameField);
           passwordField.y = 100; addChild(passwordField);
           conPasswordField.y = 150; addChild(conPasswordField);

           registerUserInfo(null);
      }

      public function registerUserInfo(evt:MouseEvent):void
      {
           if(passwordField.text == conPasswordField.text)
           {
                  saveDataObject.data.savedUsername = ""+usernameField.text;
                  saveDataObject.flush();
                  traceOutputField.text = "DEBUG " + saveDataObject.size + " / " + saveDataObject.data.savedUsername;

                  saveDataObject.data.savedPassword = ""+passwordField.text;
                  saveDataObject.flush();
                  trace(saveDataObject.size);
           }
           else if(passwordField.text != conPasswordField.text)
           {
                  trace("Passwords do not match");
           }
      }

  }
}

A: try this:
public var saveDataObject:SharedObject = SharedObject.getLocal("test");

public function getUsers():Array{
    var users:Array = saveDataObject.data.users as Array;
    return users;
}

public function saveUserInfo(name:String, pass:String):void{
    var users:Array = getUsers();
    if(!users){
        users = [];
    }
    users.push({username:name, password:pass});
    saveDataObject.data.users = users;
    saveDataObject.flush();
}

Now you can write all kinds of other functionality around this.  example:
public function getPasswordForUser(username:String):String{
    var users:Array = getUsers();
    if(users){
        for (var i:int=0; i<users.length; i++){
            if(users[i].username == username){
                return users[i].password;
            }
        }
    }
    return null;
}

There are many other things that can be done here but this will get you going


text:
Q: Semantic Versioning I want to use Semantic Versioning of an act, but I am not familiar with it and want to learn the professional way. So I have the following problems:

*

*How can I sent version for example to 1.0, if the Fork-Link is deactivated (see Screenshot).

*How is the recomenden workflow for versioning?

*Who does Apify-Versioning correspond with the version number in package.json?

*What does the link 'Delete' actually delete, the whole act, the version or the version-number?

Regards Wulfgäääng

A: Unfortunately, we don't support the Semantic versioning of actors right now.
You can use the current versioning system as you wish but I have summarized the best practices from our point.

*

*There is a limit of 10 versions per actor so you may want to delete some unused ones. If this will be issue for more users, we may increase the limit.

*Explained in the article.

*It doesn't at all.

*It deletes the version - the number and the source code for this particular version. But the builds with this version stay so you can still use them.


text:
Q: How to Integrate BIRT report engine with minimum jars? Currently i have integrated BIRT report engine with my Struts2 Application, which has around 80 Jars and 51MB in Size, Can any body help me to reduce the jars in terms of number or size, i am worried that more jars may occupy more Perm-gen Space and affect on performance.
Thanks

A: BIRT comes with support for all databases. So, keeping only the jars related to our database helps in getting rid of many jars.


text:
Q: How to pass a user's password to puppeteer inside a Firebase callable function? How do I pass in a user's email & password into a function from a Firebase callable function?
I have written a callable function that uses puppeteer to navigate to a user's dashboard page, make a PDF of it, and then store the PDF in Cloud Storage.
My problem is that users must be authenticated to view the page. Without providing authentication, puppeteer just takes a PDF of my login page.
If I hard code in an email and password and toss it to puppeteer like so, then I get the desired dashboard page:
const page = await browser.newPage();

  await page.goto("https:www.somepage.com/auth/signin", {
    waitUntil: "networkidle2",
  });

  email = context.auth.token.email;
  password = "myPassword";

  await page.type("[type=email]", email);
  await page.type("[type=password]", password);
  await page.click("[type=submit");

  await page.waitFor(5000);

  await page.goto("https:www.somepage.com/dashboard", {
    waitUntil: "networkidle2",
  });

I know how to retrieve the current user's email from context, but how do I retrieve the password as well? Is this even possible?
Or, is there a better way to go about this altogether?
I've tried using context and admin, but have read that this is the wrong approach or just plain not possible.
Thank you for any help you can provide and sorry if this question has been answered elsewhere.

A: It's not possible to get a users plaintext, unhashed password from Firebase Auth.  That's considered a security problem.


text:
Q: jQuery - Auto Suggest - focusout() Plunk: http://plnkr.co/edit/iPIW1AvQUrThidzA3bw9?p=preview
The requirement is to create multiple auto-suggest input boxes that show up only when a user starts typing in an input field. Clicking a value from the input box should populate that input with the selected value and hide the auto-suggest.
The code I wrote works until here.
I am also trying to hide the auto-suggest box when a user starts typing, then changes focus to a different inputbox. When I implement focusout() to do that, the click on the suggest dropdown does not work.
Any help is appreciated!

A: The work around is to use focusin() instead of focusout() at least in this case. So, it would look like

$('.autoSelectInput').focusout(function(){
    $autoSelectDropdown.hide(); });


text:
Q: Filemaker Pro 12 Exporting current 'Records being browsed' as Excel on iOS I'm managing a Filemaker Pro 12 solution to create purchase orders and send them via email for the iPad but the iOS Platform doesn't allow to export Excel files.
Currently we are sending the orders as a .pdf file but the warehouse has to manually approve each order. The solution we were thinking of is to send a .csv file attached to an email so that the warehouse has less work.
I'm using 3 different tables to create a order. A table that stores the products, a container table (to set the quantity, discount etc.) and a table for the order itself. So you can for example create three product-A and two Product-B in an order which works fine. My PDF solution uses an extra Layout and works fine. On a PC or Mac you can export Excel files with a script and the "Save Records as Excel" function, but this is not available on iOS, so I'm looking for alternatives.
The script I came up with to send the .csv file via email looks like this:
Set Error Capture [On]
Freeze Window
Go to Related Record [Show only related records; From table "Orders_Container"; Using Layout: "MailLayout" (Orders_Container); New Window]
If( Get (LastError) = 0)
    Sort Records[ Restore; No dialog]
    Set Variable[ $FILE; Value:Get (TemporaryPath ) & "file.csv" ]
    Export Records [No dialog; "$FILE"; Windows(ANSI)]
    Send Mail[Send via E-mail Client; To: "customer@web.com"; Subject: "Order"; "$FILE"]
End If
Close Windows [Current Window]

I tried to use the function "Export Records" but it exports all records of the current customer instead of the 'Records being browsed' which is only available for the PDF export. I've tried to do this but on iOS you can't create a new file to export and I can't come up with something else. I don't want the users to use Menu -> Export -> E-Mail because they will have to enter 3-4 Email addresses each time which is way to time consuming (this also exports all records instead of the ones which are currently being browsed). Is there any way to export the records that are currently open, save those in a .csv file and send a mail with the file attached? Thanks in advance.
EDIT: Ironically after some testing with different scripts, the script I posted here works now correctly.

A: The Export Records function exports the current found set - the same as Records Being Browsed. This indicates that other issues are keeping your script from working.
You might want to look at the Related Record and which set is found. Use a temporarily pause just before the Import Records function is called to see what set is present.
Also, keep in mind that if there is an error with your Go to Related Record call, nothing happens. A record created by a previous export would then remain in place and this then might show a different set of records than you would expect.


text:
Q: Placing an ASP.NET ImageButton inside a TableCell I'm trying to put an imagebutton in a tablecell, but the only property to add anything to a tablecell I know of, is the Text property. And that's for text, only accepting Strings.
How do I add the Imagebutton instance instead?

A: tableCell.Controls.Add(imageButtonInstance);


text:
Q: C# : Keep a windows Form focused over another form (Microsoft.Office.Interop.Excel.Application) In fact, I'm developping an Excel Addin.
My addin is opening a new Windows Form over Excel, and what I'd like to do is :

*

*Disable and remove focus from the excel's window

*Send focus to the new Windows Form

*Keep the new Form over the Excel's Windows

*Re-enable and send back focus to excel's window on Form's closing event

How should I do that ?
Note :: I don't want my new opened form to be on top of all windows but only on top of my excel's window.


text:
Q: The client and server cannot communicate, because they do not possess a common algorithm on Windows Server Web 2008 I am working on a ASP.Net WebForms application. We are using PayFort's Start API for the payment process. The application is running fine on our local machine (Windows 10) but it shows following error when we try to make payment using their API on our deployment server (Windows Server Web 2008).

The client and server cannot communicate, because they do not possess
  a common algorithm.

The documentation on their webpage  (PayFort Start and SSL/TLS) states that they use Tls1.2 for the communication. Their API already contains the code to use Tls1.2 as Security Protocol
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

We've built the application on .Net framework 4.5 since Tls1.2 only supported by .Net 4.5 or later. Needless to mention, our server has .Net Framework 4.5 installed in it.
We've also added the registry values for Tls1.1 and Tls1.2 in the windows registry
Using the SSL Labs tool, we've also confirmed that there are atleast two Cipher suites supported by both servers (our server and PayFort's API Server) (https://api.start.payfort.com)
Cipher suites supported by PayFort's API Server

(Green outlined are those which are common with our server)
Cipher Suites supported by our server

I've also used the Nartac IIS crypto software and it's showing the following info as Best Practices

I'm not sure if it has anything to do with the problem or not, but here are the details of the SSL certificate installed in our server

Can anyone please point out that what we are doing wrong and what should we do in order to communicate with the desired server and make payment from the application deployed on our server as we are doing perfectly on our local machine.

A: Are you using Windows 2008 non R2? TLS 1.2 is not supported on Windows 2008. You have to upgrade to Windows 2008 R2 or above if you need TLS 1.2 support
You can view TLS support for different versions of Windows here:
http://blogs.msdn.com/b/kaushal/archive/2011/10/02/support-for-ssl-tls-protocols-on-windows.aspx


text:
Q: Generic views request handling Django I'm relative new in Django. I want to use generic views like this :
class photogalleryView(generic.ListView):
    template_name = 'xxx/photogallery.html'
    model = Foto
    query = Foto.objects.all()

def get_queryset(self):
    return self.query

and I definitelly don't know how to handle GET or POST request or something like $_SESSION like in PHP, can you please give me some pieces of advice please ?
Thank you very much guys !
for example - I want to handle GET request on this URL:
http://127.0.0.1:8000/photogallery?filter=smth

A: Have a look at the documentation for class based views, if that's what you want to use.
You can add get and post methods to your class, and they will trigger on each respective request.
These methods take a request argument, which can be used to access data from the client, the session, and the logged in user. Check out the docs for details.

A: First, returning the same QuerySet object query = Foto.objects.all() doesn't make much sense and can (and will) get you into trouble when you try to use filters and pagination. If you want to modify your QuerySet manually, do the following:
def get_queryset(self, *args, **kwargs):
    qs = super().get_queryset(*args, **kwargs)
    # modify the qs QuerySet in the way you want
    return qs

In Django, you don't normally use GET or POST. Django handles it for you :)
The example of what you want to achieve is here:
https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-display/#dynamic-filtering
In fact, Django documentation is very nice and comprehensive, at least for the public features.
Pay your attention on the url(r'^books/([\w-]+)/$', PublisherBookList.as_view()), in the example, where ([\w-]+) RegEx group captures some argument (e.g. "smith") which you can later use in your get_queryset method (as self.args[0] in the example).
To understand more about url patterns, read this piece of the documentation:
https://docs.djangoproject.com/en/1.10/topics/http/urls/#named-groups


text:
Q: How to get a newline in Python shell, with a different indentation, without breaking the code I want to this in Python Shell

def get_tweets(xyz) :
 auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
 for j in tweets_for_csv:
  tmp.append(j)
                print(tmp)

But, in the last line, on clicking [Enter], It becomes this

def get_tweets(xyz) :
 auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
 for j in tweets_for_csv:
  tmp.append(j)
        print(tmp)

See the difference in an indentation in the last line of expected and actual code.
Please, help me to do it correctly.

A: I got the answer, by myself. I am a newbie, and also coding after a long time.
Use Backspace, to change indentation. I was aware of this but in the subconscious mind.


text:
Q: Using Numpy where to place conditions on Pandas DataFrame while taking Cumulative Sum I am trying to place a condition on one of the columns in Pandas Dataframe and based on that condition I want to take cumulative sum of another column in the Dataframe. To be more clear here is the example: Suppose my DataFrame df as:
+-----------+--------------+-----+-------------+
|   Date    | daily_return | dir | size_return |
+-----------+--------------+-----+-------------+
| 2/25/2015 |    -0.000681 |  -1 |   -0.000681 |
| 2/26/2015 |      -0.0015 |  -1 |    -0.00218 |
| 2/27/2015 |    -0.003022 |  -1 |   -0.005203 |
| 3/2/2015  |     0.005776 |   1 |    0.005776 |
| 3/3/2015  |    -0.003772 |  -1 |   -0.003772 |
| 3/4/2015  |     -0.00436 |  -1 |    -0.00755 |
+-----------+--------------+-----+-------------+

I've placed a condition on the column dir as long as the value in dir is equal to dir.shift(1) I want to take cumulative sum of column daily_return until dir is not equal dir.shift(1) and when they are not equal I want daily_return equal to size_return.
The code that I used to generate the above table is as follows:
df['size_return'] = np.where(df.dir == df.dir.shift(1),
                             df.daily_return.cumsum(axis=0), df.daily_return)

The problem with the above table is that I can't figure out why in the last two rows if I sum using above line of code daily_return the result is -0.00755, I should be getting -0.00813 (-0.003772 + -0.00436).
There must be an error in my logic written in above code, I can't figure out my mistake?
Second, I do not want value in every row of size_return only last row of filtered data frame based on the condition. To be more clear this is how the final table should be looking:
+-----------+--------------+-----+-------------+
|   Date    | daily_return | dir | size_return |
+-----------+--------------+-----+-------------+
| 2/25/2015 |    -0.000681 |  -1 |             |
| 2/26/2015 |      -0.0015 |  -1 |             |
| 2/27/2015 |    -0.003022 |  -1 |   -0.005203 |
| 3/2/2015  |     0.005776 |   1 |    0.005776 |
| 3/3/2015  |    -0.003772 |  -1 |             |
| 3/4/2015  |     -0.00436 |  -1 |   -0.008132 |
+-----------+--------------+-----+-------------+

A: Check with groupby and cumsum
df.groupby((df.dir==df.dir.shift()).eq(0).cumsum()).daily_return.cumsum()
0   -0.000681
1   -0.002181
2   -0.005203
3    0.005776
4   -0.003772
5   -0.008132
Name: daily_return, dtype: float64

If only keep the last one ,using duplicated
s=(df.dir==df.dir.shift()).eq(0).cumsum()
df['New']=df.groupby(s).daily_return.cumsum().mask(s.duplicated(keep='last'),'')
df
        Date  daily_return  dir  size_return       New
0  2/25/2015     -0.000681   -1    -0.000681
1  2/26/2015     -0.001500   -1    -0.002180
2  2/27/2015     -0.003022   -1    -0.005203 -0.005203
3   3/2/2015      0.005776    1     0.005776  0.005776
4   3/3/2015     -0.003772   -1    -0.003772
5   3/4/2015     -0.004360   -1    -0.007550 -0.008132


text:
Q: How can I map users to roles and execute code accordingly in javascript? I've got 5 user roles ("admin","modifier","manager","projectmanager","readonly") and need to execute different code depending on the specific role (only one role per user). Before I setup users and roles in a databse, I want to make it work and test the functionality in JavaScript. How can I 'connect' the users (hardcoded values) to the right role and execute the code?
Should I use arrays or maybe a switch case?
Something like:
//Declaration
arrAdmin["user1","user5","user9"];
arrModifier["user3","user6","user8"];
arrManager[];
arrProject["user4"];
arrReadOnly["user2","user7","user10","user11"]
...

function executeFunctionality(user){
var userFound = false;
while(userFound == false){
    for(var i=0; i<arrAdmin.length; i++){
        if(user == arrAdmin[i]){
            userFound = true;
            executeAdmin();
        }
    }
    for(var i=0; i<arrModifier.length; i++){
        if(user == arrModifier[i]){
            userFound = true;
            executeModifier();
        }
    }
    for(var i=0; i<arrManager.length; i++){
        if(user == arrManager[i]){
            userFound = true;
            executeManager();
        }
    }
    //etc...
}
}

or a switch case maybe?
switch(user){
"user1" : executeAdmin();
"user2" : executeReadOnly();
"user3" : executeModifier();
"user4" : executeProject();
"user5" : executeAdmin();
// etc ...
}

Thanks in advance!

A: You should definitely put that logic on the server side and deliver content and scripts according to th current user's role, because your JS can be accessed by anyone. It is NOT safe to dal with that on the client side!

A: With a slight modification to this answer you should be able to do something like this:
var dispatcher = {
    "user1": executeAdmin,
    "user3": executeModifier,
    "user4": executeProject,
    "user5": executeAdmin
//...
};

(dispatcher[user] || executeReadOnly)();

Note: if the 'readonly' user role means basic privileges for all users - which seems to be the case in your example - there's no need to map any users to it. Just implement a default scenario that applies to all users (that don't have any extras).

A: This should do
function executeFunctionality(user){
    if(executeUserFunction(arrAdmin, user, executeAdmin)){
        return true;
    }

    if(executeUserFunction(arrModifier, user, executeAdmin)){
        return true;
    }

    if(executeUserFunction(arrManager, user, executeAdmin)){
        return true;
    }
    //etc
    return false;
}

function executeUserFunction(array, user, fn){
    var i;

    for(i = 0; i < array.length; i++){
        if(user == array[i]){
            fn();
            return true;
        }
    }
    return false;
}


text:
Q: Proximity search with Google maps I'm developing a store location application.
Looking up a store, it currently shows the location in googlemaps based on address and zip code.
Now I want to build a function which also shows other shops within 500 meter radius.
To do this, I have to do a proximity search / calculation.
My biggest question, is how I should approach this.
I did find this link, which has some example code. But I'm unsure if I can use the code (and which of the codes I should use). Does anyone have better examples?
Also I'm thinking of adding a new table to the database, which stores the geo code for each store. Do I need more fields than 'id', 'latitude' and 'longitude' ?
UPDATE
I just found this link at phpro.org. It looks like it's just what I need! Has anyone used their examples and can comment upon it?

A: You cant radius search directly with the google maps API, however, you should know (or can figure them out via geocoding their addresses) the latitude and longitude of each point of interest (POI) you want to include in the search.
After this you can use the Great Circle equation to search for proximity, and it turns out to be very fast.  We have implemented this as a stored procedure for the locator service at my work and use it to search through >3500 locations with response times under 0.1 seconds.

A: Some SQL implementations contain geospatial extensions. In those implementations you can directly write a WHERE clause that filters the results by distance from a specified point.
Check the documentation of your SQL implementation. If it has geospatial POINT type, then it makes sense to enter the coordinates as POINTs rather than a lat/lng pair, and consider using that field as a SPATIAL KEY if you're going to be accessing the table mainly by location.


text:
Q: Android VideoView not playing Portrait Orientation THE PLATFORM:
Developing in Eclipse using Android SDK 16.
THE PROBLEM:
I have a VideoView element that is supposed to fill the entire screen in 480x800 (PORTRAIT ORIENTATION) and it plays fine, but will not orient to portrait.  It sticks in landscape mode and the aspect ratio is skewed to fit that way.
WHAT I HAVE ATTEMPTED:

*

*using android:screenOrientation="portrait" in manifest

*using android:orientation="vertical" in the container and the VideoView itself

*using setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); right before I call setContentView

*trying to set the layout width and height to 480dpx800dp instead of fill_parent

*trying to set the VideoView width and height to 480px x 800dp instead of fill_parent

*switching off the auto rotate display

THE XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="480dp"
    android:layout_height="800dp"
    android:background="#000000"
    android:orientation="vertical" >

    <VideoView
        android:id="@+id/opening_video"
        android:layout_width="480dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:layout_height="800dp"
        android:orientation="vertical" />

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/transparent_button"
        android:contentDescription="@string/back_button_desc"
        android:background="@android:color/transparent" />

</RelativeLayout>

THE CODE:
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_start_screen);

        VideoView videoView = (VideoView) findViewById(R.id.opening_video);

        Uri pathToVideo = Uri.parse("android.resource://com.example.consumerengage/" + R.raw.opening_tablet);
        videoView.setVideoURI(pathToVideo);
        videoView.setOnPreparedListener(new OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });

        videoView.requestFocus();
        videoView.start();

       // boolean isPlaying = videoView.isPlaying() ;

       // videoView.stopPlayback();
       // videoView.clearFocus();

       addListenerOnButton();

    }

THE QUESTION:
Nothing I have attempted has been successful.  How can I get my 480x800 video to play in portrait orientation?

A: Are you certain your video is is 480x800 and not 800x480? 800x480 is a standard resolution, if you record a video in portrait with a phone the output will still be 800x480 and to have normal playback the video should be turned 90 degrees. What you are describing is what would happen if you try to play a 800x480 video in a 480x800 videoView. If this is the case you could rotate it with video editing software like Windows Live Moviemaker or iMovie if you are on Mac.

A: You are using dp where you should be using px:

<VideoView
    android:id="@+id/opening_video"
    android:layout_width="480px"
    android:layout_alignParentRight="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true"
    android:layout_height="800px"
    android:orientation="vertical" />

<ImageButton
    android:id="@+id/imageButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/transparent_button"
    android:contentDescription="@string/back_button_desc"
    android:background="@android:color/transparent" />

Or, alternatively (and better) - just use match_parent (or fill_parent):

<VideoView
    android:id="@+id/opening_video"
    android:layout_width="match_parent"
    android:layout_alignParentRight="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true"
    android:layout_height="match_parent"
    android:orientation="vertical" />

<ImageButton
    android:id="@+id/imageButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/transparent_button"
    android:contentDescription="@string/back_button_desc"
    android:background="@android:color/transparent" />

A: Try this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000">

    <VideoView
        android:id="@+id/opening_video"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/transparent_button"
        android:contentDescription="@string/back_button_desc"
        android:background="@android:color/transparent" />

</RelativeLayout>

Hope this helps. And also check your manifest file too.

A: Here's what I ended up doing:
The issue was the OS version.  If it was ICS (4.0) and above, it would play the video on its side, so upon detecting android.os.Build.VERSION.SDK_INT of 14 or greater, I load the video that is built on its side so it plays the right way.
This is a very silly workaround, and I never really got the answer to my question.  The video should not play like that.


text:
Q: Mathematical operation using mutate_each I want to build upon mutate_each / summarise_each in dplyr: how do I select certain columns and give new names to mutated columns? thread. It talks about applying mutate to multiple columns. However, I understand that we can use functions such as sum etc. but I am not sure how I can apply mathematical operations such as addition, multiplication, division and subtraction.
Here are my data:
dput(DF)
structure(list(FY = c(2015, 2016, 2017, 2030, 2015, 2016, 2017,
2030, 2015, 2016, 2017, 2030, 2015, 2016, 2017, 2030, 2015, 2030
), Value = c(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, NA, NA)), .Names = c("FY", "Value"), row.names = c(NA,
18L), class = "data.frame")

Here's my working code to show you what I want:
DF<-DF %>%
  dplyr::group_by(FY) %>%
  dplyr::summarise(Numbers = sum(Value,na.rm = TRUE)) %>%
  spread(FY,Numbers)

DF$`2016`<-DF$`2016` + DF$`2030`/3
DF$`2017`<-DF$`2017` + DF$`2030`/3
DF$`2015`<-DF$`2015` + DF$`2030`/3
DF$`2030`<-NULL

DF <- DF %>%
gather(FY,Values,`2015`:`2017`)

My objective is to use mutate_each() to automate the following lines of code and reduce repetition. I am unsure how I can use mutate to calculate 1/3rd of 2030 column and then add it back to 2016
   DF$`2016`<-DF$`2016` + DF$`2030`/3
    DF$`2017`<-DF$`2017` + DF$`2030`/3
    DF$`2015`<-DF$`2015` + DF$`2030`/3

What can I do to minimize the repetition?

Expected Output after applying above operation:
dput(DF)
structure(list(FY = c("2015", "2016", "2017"), Values = c(62.6666666666667,
66.6666666666667, 70.6666666666667)), row.names = c(NA, -3L), .Names = c("FY",
"Values"), class = c("tbl_df", "tbl", "data.frame"))

A: With dplyr we can group_by FY. Get the sum of each group and add 1/3 rd part of FY 2030 to all the sum.
library(dplyr)
DF %>%
   group_by(FY) %>%
   summarise(Sum = sum(Value, na.rm = TRUE)) %>%
   mutate(NewValue = Sum + Sum[FY == '2030']/3) %>%
   filter(FY != 2030)

#    FY   Sum  NewValue
#  <dbl> <dbl>    <dbl>
#1  2015    44 62.66667
#2  2016    48 66.66667
#3  2017    52 70.66667

A: We can use data.table
library(data.table)
setDT(DF)[FY %in% 2015:2017, .(NewValue = sum(Value, na.rm = TRUE) +
                  sum(DF[FY==2030]$Value, na.rm=TRUE)/3), by = FY]
#     FY NewValue
#1: 2015 62.66667
#2: 2016 66.66667
#3: 2017 70.66667


text:
Q: Select-string apply to multiple lines of input I have a file like:
abc WANT THIS
def NOT THIS
ghijk WANT THIS
lmno DO NOT LIKE
 pqr WANT THIS
...

From which I want to extract:
abc
ghijk
pqr

When I apply the following:
(Select-String -Path $infile -Pattern "([^ ]+) WANT THIS").Matches.Groups[1].Value >$outfile

It only returns the match for the first line:
abc

(adding -AllMatches did not change the behaviour)

A: You may use
Select-String -path $infile -Pattern '^\s*(\S+) WANT THIS' -AllMatches | Foreach-Object {$_.Matches} | Foreach-Object {$_.Groups[1].Value} > $outfile

The ^\s*(\S+) WANT THIS pattern will match

*

*^ - start of a line

*\s* - 0+ whitespaces

*(\S+) - Group 1: one or more non-whitespace chars

* WANT THIS - a literal substring.

Now, -AllMatches will collect all matches, then, you need to iterate over all matches with Foreach-Object {$_.Matches} and access Group 1 values (with Foreach-Object {$_.Groups[1].Value}), and then save the results to the output file.

A: Re-reading the code, its matching them all, but only writing the value of the first match (doh!):
 (Select-String -Path $scriptfile -Pattern "([^ ]+)  WANT THIS").Matches.Groups.Value >$tmpfile

OTOH, it appears that the "captures" in the pattern output object also contain the "non-captured" content!!!!


text:
Q: kubectl exec with curl Connection refused i cannot execute successfully a curl command inside a running pod
$ kubectl exec -t pulsar-pulsar-manager-79c6769595-xd596 -- bash -c "CSRF_TOKEN=$(curl -v  http://localhost:7750/pulsar-manager/csrf-token)"

connect to ::1 port 7750 failed: Connection refused
Trying 127.0.0.1:7750...
connect to 127.0.0.1 port 7750 failed: Connection refused
Failed to connect to localhost port 7750: Connection refused
0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
Closing connection 0
curl: (7) Failed to connect to localhost port 7750: Connection refused
But when i login to the container and execute the command, there is no issue
$ kubectl exec -ti pulsar-pulsar-manager-79c6769595-xd596  -- bash
$ CSRF_TOKEN=$(curl  http://localhost:7750/pulsar-manager/csrf-token)

% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Dload  Upload   Total   Spent    Left  Speed
100    36  100    36    0     0   2400      0 --:--:-- --:--:-- --:--:--  2400

A: If you want to get the token and stores it the host shell:

CSRF_TOKEN=$(kubectl exec -t pulsar-pulsar-manager-79c6769595-xd596 -- bash -c "curl -s http://localhost:7750/pulsar-manager/csrf-token")

If you want to get the token in the container:

kubectl exec -t pulsar-pulsar-manager-79c6769595-xd596 -- bash -c "CSRF_TOKEN=\$(curl -v  http://localhost:7750/pulsar-manager/csrf-token)"


text:
Q: Sum all value in angular without controller So I have a problem with Angular for 2 days, is there a way to sum all angular data without controller?
I want to print totalPrice from all subTotal, I tried to use method getTotalPrice() to sum in controller but I dont know how to pass the subTotal array
@foreach($products as $product)

id}}=0">

     {{Form::label($product->id, $product->name.' - '.$product->price, array('class'=>'col-md-4 control-label'))}}
     <input type="hidden" ng-model="price_{{$product->id}}" ng-init="price_{{$product->id}}={{$product->price}}">

       <input id="{{$product->id}}" type="number" min="0" value="0" step="1" class="form-control" name="qty_{{$product->id}}" ng-model='qty_{{$product->id}}'>

       <% qty_{{$product->id}} * {{$product->price}} %>

@endforeach

      Total Price
      <label for="" class="col-md-4 control-label" ng-model="totalPrice" ng-init="totalPrice = 0" ng-value="<% getTotalPrice() %>"><% getTotalPrice() %>

Heres my current controller
myApp.controller('cashierController', ['$scope', function($scope){
  $scope.subTotal = [];
  $scope.getTotalPrice = function(subTotal) {
    var totalPrice = 0;
    for(sub in subTotal){
      totalPrice += sub;
    }
    return totalPrice;
  }
}]);

P.S : I use angular in laravel
Sorry if there any weird codes, Thanks in advance.

A: One way is to solve it with php/laravel:
just before @foreach add a new variable
<?php $grandTotal = 0 ?>

and within your foreach before totalPrice label
<?php grandTotal += $product->price  ?>

And inside label just echo it:
{{ $grandTotal }}

Second option
Which is way cleaner, add a very simply route to return products as JSON file and $http get it from angular then pass it to your view, it will at least make things clearer to you (( you will use angular to handle and arrange FE views not handle everything via blade)).
Route::get('products/json','ProductsController@getAllJson');

inside ProductsController
public function getAllJson() {
//inject your repository above and use it here or simply use eloquent

return Product::all();

}

now inside your controller in angular just make simple $http get:
myApp.controller('cashierController', ['$scope,$http', function($scope,$http){

  $scope.products = [];
  $scope.grandTotal = 0;

  $http.get('products/json')
      .then(function(response){
    $scope.products = response.data;
       });

// there is no need for this function anymore since you've 2-way-binding
  $scope.getTotalPrice = function() {
    return totalPrice;
  }
}]);

finally, in your HTML use angular ng-repeat and that variable we've declared grandTotal.

@{{grandTotal}}


text:
Q: Alter value in pandas dataframe based on corresponding value in another dataframe I have two pandas dataframes.

*

*The first (df1) has two columns: 'Country' (string) and 'Population' (int). Each row consists of a different country and its corresponding population (~200 rows).

*The second (df2) also has two columns: 'Country' (string) and 'Value' (int). Each country appears a variable number of times in random order with a corresponding value (thousands of rows).

I want to divide each value in df2['Value'] by the corresponding population of that row's country.
My attempt: (Assume there's a list called 'countries' containing all countries in these dataframes
for country in countries:
  val = df2.loc[df2['Country'] == country]['Values'] # All values corresponding to country
  pop = df1.loc[df1['Country'] == country]['Population'] # Population corresponding to country
  df2.loc[df2['Country'] == country]['Values'] = val / pop

Is there a better way to do this? Perhaps a solution that doesn't involve a for-loop?
Thanks

A: Try the following:
# Assuming that there are the same countries in both df
df3 = pd.merge(df2, df1, how = 'inner' on='Country')
df3["Values2"] = df3["Values"] / df3["Population"]

A: An alternative implementation would be to join the two tables before applying the division operator. Something on the line of:
df2 = df2.join(df1,on='Country',how='left')
df2['Values'] = df2['Values'] / df2['Population']

A: You can use merge for that:
df3 = df2.merge(df1, on='Country') # maybe you want to use how='left'
df3['Div'] = df3['Values'] / df3['Population']

You can read more about merge in the docs


text:
Q: Notation for formal logical reasoning, premises & conclusions Is this notation correct? (Learning basics of logical notation)
∃x∈X: P(x)
∀yP(y) -> O(y)
∴∃x∈X: O(x)
"There exists an element x in a set X with property P."
"For all elements with property P has also property O."
"Therefore there exists an element in the set X with property O."

A: Looks pretty good, but for this site you can use MathJax rather than Unicode special characters.  For this specific notation, use:
$$\exists x \in X : P(x)$$
$$\forall y (P(y) \Rightarrow O(y))$$
$$\therefore \exists x \in X : O(x)$$

which produces:
$$\exists x \in X : P(x)$$
   $$\forall y (P(y) \Rightarrow O(y))$$
   $$\therefore \exists x \in X : O(x)$$
As for reading this out loud, I would verbalize it as follows:

$$\exists x \in X : P(x)$$
  There exists an element $x$ in $X$ for which predicate $P$ of $x$ is true.
  $$\forall y (P(y) \Rightarrow O(y))$$
  For all $y$, $P$ of $y$ implies $O$ of $y$.  (Or if I want to be explicit, "For all $y$, predicate $P$ of $y$ implies predicate $O$ of $y$.")
  $$\therefore \exists x \in X : O(x)$$
  Therefore, there exists an element $x$ in $X$ for which predicate $O$ of $x$ holds true.


text:
Q: Continuation monad "interface" The state monad "interface"
class MonadState s m where
    get :: m s
    put :: s -> m ()

(+ return and bind) allows to construct any possible computation with State monad without using State constructor. For example, State $ \s -> (s+1, s-1) can be written as
 do s <- get
    put (s-1)
    return (s+1)

Similarily, I never have to use Reader constructor, because I can create that computation using ask, return and (>>=). Precisely: Reader f == ask >>= return . f.
Is it the same true for continuations - is it possible to write all instances of Cont r a using callCC (the only function in MonadCont), return and bind, and never type something like Cont (\c -> ...)?

A: I don't think so.  Looking at the types:
Cont :: ((a -> r) -> r) -> Cont r a
callCC :: ((a -> Cont r b) -> Cont r a) -> Cont r a

If you only have callCC, there is no use of r as a type anywhere - it could be of any kind.  So I don't know how you could translate something that uses it as a type, eg:
Cont (const 42) :: Cont Int a

I have no way of constraining r if I only have callCC.
Anyway, that's my hunch. Not terribly rigorous, but it seems convincing.


text: Q: How do I make items in a navigation wrap down to the next line when I change the viewport size? How do you make the list items wrap down to the next line in a navigation like when you resize the page down from desktop size down to tablet sized viewport? I need my list items to go down to the next line as I change the screen size.


text:
Q: Understanding the rolling constraint for one cylinder rolling inside another cylinder This is the problem to find the equation of motion of 2 cylinders in which 1 cylinder is placed inside another cylinder with larger radius as shown in figure. The condition is that both are rolling. Now, in the figure they say:

The rolling constraint on 2nd cylinder can be written as :
  $ r_{2} \phi_{2} = r_{1} (\phi_{1}+\theta} $

(Eqn 2 at last in picture)
With symbols as shown in figure below. I want to understand how they come up with this rolling condition(i.e formula).
Thanks in advance

A: The $r_2 \phi_2$ is simply the length of the red line on the inner cylinder in your picture. That must be equal to the length of the red line on the outer cylinder, since this is the line that the inner cylinder tracked on the inner surface of the outer cylinder. That length is  given according to the picture by $r_1(\phi_1+\theta)$ since the arc defining the red line is given by $\phi_1+\theta$ as can be seen from the picture and $r_1$ is the radius of the inner circle of the outer cylinder.