text:
Q: Objects Array Get Specific Object and display together PHP I am facing a problem problem here and need some help.
I have saved in my database a json_aray array with objects.
After decoding and print_r it I get this result.
Array (
[0] => stdClass Object (
    [Title] => Image
    [Info] => info
    [ImageURL] => url.jpg )
[1] => stdClass Object (
    [Title] => Image
    [Info] => info
    [ImageURL] => url.jpg )
[2] => stdClass Object (
    [Title] => Accommodation
    [Info] => info
    [ImageURL] => image.jpg )
[3] => stdClass Object (
    [Title] => Accommodation
    [Info] => info
    [ImageURL] => image.jpg )
[4] => stdClass Object (
    [Title] => Accommodation
    [Info] => info
    [ImageURL] => image.jpg )
[5] => stdClass Object (
    [Title] => Image
    [Info] => info
    [ImageURL] => image.jpg )
[6] => stdClass Object (
    [Title] => Location
    [Info] => info
    [ImageURL] => image.jpg )
)

So here is the CASE:
I am trying to create a div for every different Object->Title e.g
I tried to check that with foreach loop but the result was creating 5 different divs instead of one.
Is there any built-in function in php to get all the $obj->Info if the $obj->Title == 'foo' or somehow check before the foreach loop what data the array has and separate them?
What i did in my code is below
   while($row = sqlsrv_fetch_array($get_details)) {
        $a = $row['additionalInformation'];
        $b = json_decode($a);
        $c = $b->AdditonalInfo;
        foreach ($c as $d){
            echo '
';
            if(($d->Title !== 'Image')){
                echo '
'.$d->Title.'
';
                echo '
'.$d->Info.'
';
            }
            echo "
";
        }
    }

UPDATE

*

*Change my code with the actual one

*This is what I get

But I need to create Accommodation or every same Title just once and all Info that has Title == 'Accommodation' under that div.
IF my question is clear enough please let me know so I can update it.
So to sum up i need to display all [Info] that has same [Title] in one div and create different div for each unique '[Title]'
Thanks In Advance

A: Requirements: Show 'nested groups' in a sequential stream of records.
Here we have a nested group indicated by a field called 'Title'.
The input records must be sorted so that all the records in each group are together and in the required order.
Now, the first thought is to use a 'foreach' loop. This is not the clearest approach because you cannot detect the end of the group by looking at the current record. Also, the foreach loop reads the next record at the end of the loop. So,  you end up trying to work out where you are in the group to know what to do.
I use a technique called 'read ahead'. The idea is to read a record before the loop and the read the next record immediately after you have processed the current one. The 'trick' is that you process all the records in a group inside a loop.
So, the logic is an iteration of:

*

*Process start of group - already has the first record of the group - important.

*Process all the detail records belonging to the group - records are read inside this loop.

*Process the end of the group - the current record is the first of the next group

*repeat for each group.

It results in easier to understand code.
I have split all the separate actions into function so that you easily modify the individual actions.
Notice the code matches the structure of the data. There is always one place in the code to put the required action for that particular data item.
Full working Source Code at eval.in
Run the code
outputAllGroups($src);
exit();

Process All the Groups
function outputAllGroups(&$inputList)
{
    reset($inputList);
    $currentDetails = current($inputList); // read the first record

    while ($currentDetails !== false) { // not end of records

        // start the title group
        $currentTitle = $currentDetails->Title;
        outputGroupHeader($currentDetails);

        // process all records in the group
        while (    $currentDetails !== false
                && $currentDetails->Title === $currentTitle) {

            outputDetails($currentDetails);

            $currentDetails = readNextDetails($inputList); // may end group
        }

        // end the title group
        outputGroupFooter($currentTitle);
    }
}

Functions for the individual actions
function outputGroupHeader($details)
{
    echo '
'. "". PHP_EOL
       . '
'. $details->Title .'
' . PHP_EOL;
}

function outputGroupFooter($title)
{
    echo '
'. "". PHP_EOL;
}

function outputDetails($details)
{
    echo '
'. PHP_EOL,
            $details->Info . PHP_EOL,
            $details->ImageURL .PHP_EOL,
         '
' . PHP_EOL;
}

function readNextDetails(&$inputList)
{
    $allOk = next($inputList); // advance next
    return $allOk !== false ? current($inputList) : $allOk; // advance next
}

Output

Image

info1
url1.jpg

info2
url2.jpg

Accommodation

info3
image3.jpg

info4
image4.jpg

info5
image5.jpg

Image

info6
image6.jpg

Location

info7
image7.jpg

Data
$src = Array (
    '0' => (object) array(
        'Title' => 'Image',
        'Info' => 'info1',
        'ImageURL' => 'url1.jpg', ),
    '1' => (object) array(
        'Title' => 'Image',
        'Info' => 'info2',
        'ImageURL' => 'url2.jpg', ),
    '2' => (object) array(
        'Title' => 'Accommodation',
        'Info' => 'info3',
        'ImageURL' => 'image3.jpg', ),
    '3' => (object) array(
        'Title' => 'Accommodation',
        'Info' => 'info4',
        'ImageURL' => 'image4.jpg', ),
    '4' => (object) array(
        'Title' => 'Accommodation',
        'Info' => 'info5',
        'ImageURL' => 'image5.jpg', ),
    '5' => (object) array(
        'Title' => 'Image',
        'Info' => 'info6',
        'ImageURL' => 'image6.jpg', ),
    '6' => (object) array(
        'Title' => 'Location',
        'Info' => 'info7',
        'ImageURL' => 'image7.jpg', ),
    );

A: Hi please do so to get for each result unique div. For the 2 quetion (Is there any built-in function in php to get all the $obj->Info if the $obj->Title == 'foo' or somehow check before the foreach loop what data the array has and separate them?) I will find some solution late :)
$a = $row['additionalInformation'];
$b = json_decode($a);
$c = $b->AddInfo;
$createDivArray = array();
echo '
';
foreach ($c as $value){
   if (in_array($value->Title, $createDivArray)) {
      continue;
   }
   $createDivArray[] = $value->Title;

   echo "
$value->Title
";
   echo "
$value->Info
";
}
echo "
";


text:
Q: Prove that a monic sum is irreducible over a field.

*

*Prove that $\sum_{k = 0}^{10} X^k$ is irreducible over $\mathbb{F}_2$.

*Prove that $\sum_{k = 0}^{20} X^k$ is the product of all irreducible polynomials of degree $2$ or $3$ and two polynomials of degree $6$ over $\mathbb{F}_2$.

I have no idea how to prove either...

A: Hints.
(1) First note that $1+x+\cdots+x^{10}$ divides $x^{2^{10}}-x$. Thus $1+x+\cdots+x^{10}$ must have as its prime factors uniqud primes of degree $1,2,5,$ or $10$.
Then show that $x^{2^5}-x$ and $x^{2^2}-x$ are relatively prime to $1+x+\cdots+x^{10}$ to get that it must only have prime factors of degree $10$ - that is, it must be prime.
(2) Use that $$1+x+\cdots + x^{20} = \frac{x^{2^6}-x}{x(1-x)(1+x^{21}+x^{42})}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: AngularJS - FAQ inside a modal (bug?) Currently i'm developing a webapp with AngularJS for a giant company, and i'm trying to have a simple FAQ inside a modal.
In my localhost the FAQ it's working just fine (very similar to the original FAQ in angular documentation), but when i write exactly the same code inside a modal i'm getting a console error:
TypeError: Object [object Object] has no method 'addGroup'

Important to state that inside the modal my $scope.oneAtATime = true; it's being ignored, so basically even if i force it to be true
<accordion close-others="true">

It's always false.
This addGroup method is on the AngularJS library code.
Any ideas?
The HTML:

            <accordion close-others="true">
                <accordion-group heading="{{faq.title}}" ng-repeat="faq in faqs">
                    {{faq.content}}
                </accordion-group>
            </accordion>

The controller
lobby.controller("AccordionController", ["$scope", function ($scope) {

    $scope.oneAtATime = true;

    $scope.faqs = [
      {
        title: "Q1?",
        content: "A1"
      },
      {
        title: "Q2?",
        content: "A2"
      },
        {
        title: "Q3?",
        content: "A3"
        },

        {
            title: "Q4?",
            content: "A4"
        }

    ];
}]);

Please notice that in the above code i'm forcing close-others to be true, directly in the html tab.
Help?

A: We had the same problem recently, change

to

That should fix it. You basically overwrote the plugin controller with your own. Don't forget to change the controller definition also, it's the part that's breaking it.


text:
Q: How to handle a long press event with yii2fullcalendar I use yii2fullcalendar for my website.
On mobile device, a "dayClick" event is fired although we just want to scroll down the screen.
How to change "dayClick" to a day double click event ?
UPDATE:
Actually, I want to avoid an inconvenient usage on mobile device. So, it's better if we can set a "long press" parameter instead of finding the way to change "dayClick" to a day double click event.
This is my view.php
<?= \yii2fullcalendar\yii2fullcalendar::widget(array(
        'options' => [
        ],
        'clientOptions' => [
            'allDaySlot' => false,
            'selectHelper' => true,
            'eventClick' => new JsExpression($JSEventClick),
            'dayClick' => new JsExpression($JSDayClick),
            'eventMouseover' =>new JsExpression($JSDayMouseover),
            'eventMouseout' =>new JsExpression($JSDayMouseout),
            'defaultView' => 'agendaWeek',
            'firstDay' => date('w'),  // Sunday=0, Monday=1, Tuesday=2, etc.
            'header' => [
                'center'=>'prev,next today',
                'left'=>'',
                'right'=>'agendaDay,agendaWeek,month',
            ],
        ],
        'ajaxEvents' => Url::to(......)
    ));
    ?>

Thank you.

A: You should be able to modify your dayClick function to handle a double click using the following algorithm:

*

*Set variable clicked_once to false.

*On click:

*

*If !clicked_once

*

*Set clicked_once to true.

*Start a timeout function to occur after xx seconds.

*

*On timeout, set clicked_once to false.

*If clicked_once

*

*Perform event

*set clicked_once to false.

Sorry to provide an algorithm rather than code, don't have any reference material in front of me at them moment.

A: I got a better solution for my issue.
That is set a parameter to:
longPressDelay

within the client options as below
<?= \yii2fullcalendar\yii2fullcalendar::widget(array(
        'options' => [
        ],
        'clientOptions' => [
            'allDaySlot' => false,
            'selectHelper' => true,
            'eventClick' => new JsExpression($JSEventClick),
            'dayClick' => new JsExpression($JSDayClick),
            'eventMouseover' =>new JsExpression($JSDayMouseover),
            'eventMouseout' =>new JsExpression($JSDayMouseout),
            'defaultView' => 'agendaWeek',

            'longPressDelay' => 1500, // -> Add here

            'firstDay' => date('w'),  // Sunday=0, Monday=1, Tuesday=2, etc.
            'header' => [
                'center'=>'prev,next today',
                'left'=>'',
                'right'=>'agendaDay,agendaWeek,month',
            ],
        ],
        'ajaxEvents' => Url::to(......)
    ));
    ?>

Refer to:
https://github.com/philippfrenzel/yii2fullcalendar/issues/72#issuecomment-268556312


text:
Q: Issue with changing permission and owner recursively on files with puppet and vagrant I am trying to install tomcat on a virtual box guest machine using puppet and vagrant. For tomcat to run, I need to change permission of the /bin/*.sh files.
Here is the relevant section of my puppet config:
class tomcat{

 exec{
 'get-tomcat':
    command => "wget -P /home/vagrant/tmp http://apache.crihan.fr/dist/tomcat/tomcat-7/v7.0.42/bin/apache-tomcat-7.0.42.tar.gz",
    path => [ "/bin/", "/sbin/" , "/usr/bin/", "/usr/sbin/" ],
    require => File["/home/vagrant/tmp"];
 'expand-tomcat':
    command => "tar xzf apache-tomcat-7.0.42.tar.gz",
    cwd => "/home/vagrant/tmp",
    require => File["/home/vagrant/tmp"],
    path => [ "/bin/", "/sbin/" , "/usr/bin/", "/usr/sbin/" ],
    creates => "/home/vagrant/apache-tomcat-7.0.42",
 }

 file { "/home/vagrant/tmp":
    ensure => "directory",
    owner => "vagrant",
    group => "vagrant",
    mode => "u+rwx",
    recurse => true,
    require => File['/home/vagrant/tmp/apache-tomcat-7.0.42/bin/*.sh']
 }

 file { "/home/vagrant/tmp/apache-tomcat-7.0.42/bin/*.sh":
    owner => "vagrant",
    group => "vagrant",
    mode => "u+rwx",
    recurse => true
 }

}

What puzzles me is that I get the following output when I run vagrant provision:
debug: /File[/home/vagrant/tmp/apache-tomcat-7.0.42/webapps/docs/introduction.html]: The container /home/vagrant/tmp will propagate my refresh event
debug: /File[/home/vagrant/tmp/apache-tomcat-7.0.42/webapps/docs/introduction.html]: The container /home/vagrant/tmp will propagate my refresh event
debug: /File[/home/vagrant/tmp/apache-tomcat-7.0.42/webapps/docs/introduction.html]: The container /home/vagrant/tmp will propagate my refresh event
notice: /File[/home/vagrant/tmp/apache-tomcat-7.0.42/webapps/examples/jsp/plugin/plugin.jsp]/owner: owner changed 'root' to 'vagrant'
notice: /File[/home/vagrant/tmp/apache-tomcat-7.0.42/webapps/examples/jsp/plugin/plugin.jsp]/group: group changed 'root' to 'vagrant'
notice: /File[/home/vagrant/tmp/apache-tomcat-7.0.42/webapps/examples/jsp/plugin/plugin.jsp]/mode: mode changed '0644' to '0744' (u+rwx)

and so on...
and then after I do a vagrant ssh, and listing the files with ls -l, I notice that all files are owned by root!
vagrant@precise64:~/tmp/apache-tomcat-7.0.42/bin$  ls -l
total 696
-rw-r--r-- 1 root root  28616 Jul  2 07:59 bootstrap.jar
-rw-r--r-- 1 root root  13217 Jul  2 07:59 catalina.bat
-rwxr-xr-x 1 root root  19877 Jul  2 07:59 catalina.sh
-rw-r--r-- 1 root root   2121 Jul  2 07:59 catalina-tasks.xml
-rw-r--r-- 1 root root  24283 Jul  2 07:59 commons-daemon.jar
-rw-r--r-- 1 root root 204944 Jul  2 07:59 commons-daemon-native.tar.gz
-rw-r--r-- 1 root root   2131 Jul  2 07:59 configtest.bat
-rwxr-xr-x 1 root root   1982 Jul  2 07:59 configtest.sh
-rw-r--r-- 1 root root   1342 Jul  2 07:59 cpappend.bat
-rwxr-xr-x 1 root root   7492 Jul  2 07:59 daemon.sh
-rw-r--r-- 1 root root   2178 Jul  2 07:59 digest.bat
-rwxr-xr-x 1 root root   2021 Jul  2 07:59 digest.sh
-rw-r--r-- 1 root root   3264 Jul  2 07:59 setclasspath.bat
-rwxr-xr-x 1 root root   3524 Jul  2 07:59 setclasspath.sh
-rw-r--r-- 1 root root   2111 Jul  2 07:59 shutdown.bat
-rwxr-xr-x 1 root root   1960 Jul  2 07:59 shutdown.sh
-rw-r--r-- 1 root root   2112 Jul  2 07:59 startup.bat
-rwxr-xr-x 1 root root   1961 Jul  2 07:59 startup.sh
-rw-r--r-- 1 root root  38333 Jul  2 07:59 tomcat-juli.jar
-rw-r--r-- 1 root root 288166 Jul  2 07:59 tomcat-native.tar.gz
-rw-r--r-- 1 root root   4114 Jul  2 07:59 tool-wrapper.bat
-rwxr-xr-x 1 root root   5086 Jul  2 07:59 tool-wrapper.sh
-rw-r--r-- 1 root root   2116 Jul  2 07:59 version.bat
-rwxr-xr-x 1 root root   1965 Jul  2 07:59 version.sh

A: As Scott said, your wildcards aren't valid.
Just as importantly, your requires are wrong. The order in which puppet is going to try to manage your resources is

*

*File["/home/vagrant/tmp/apache-tomcat-7.0.42/bin/*.sh"]

*File["home/vagrant/tmp"]

*Either (because you didn't specify) Exec['get-tomcat'] or Exec['expand-tomcat']

*Either (because you didn't specify) Exec['get-tomcat'] or Exec['expand-tomcat']
The ownership problem you noticed happens because your declaration of the user and group for files in /home/vagrant/tmp takes effect before the tomcat files exist.
I think you're trying to write this:
class tomcat{

  $scripts = [
      '/home/vagrant/tmp/apache-tomcat-7.0.42/daemon.sh',
      '/home/vagrant/tmp/apache-tomcat-7.0.42/digest.sh',
      '/home/vagrant/tmp/apache-tomcat-7.0.42/setclasspath.sh',
      '/home/vagrant/tmp/apache-tomcat-7.0.42/shutdown.sh',
      '/home/vagrant/tmp/apache-tomcat-7.0.42/startup.sh',
      '/home/vagrant/tmp/apache-tomcat-7.0.42/tool-wrapper.sh',
      '/home/vagrant/tmp/apache-tomcat-7.0.42/version.sh'
  ]

  file { '/home/vagrant/tmp':
    ensure => 'directory',
    owner  => 'vagrant',
    group  => 'vagrant',
    mode   => 'u+rwx',
  }

  exec { 'get-tomcat':
    command => 'wget http://apache.crihan.fr/dist/tomcat/tomcat-7/v7.0.42/bin/apache-tomcat-7.0.42.tar.gz',
    cwd     => '/home/vagrant/tmp',
    path    => [ '/bin/', '/sbin/' , '/usr/bin/', '/usr/sbin/' ],
    creates => '/home/vagrant/apache-tomcat-7.0.42.tar.gz',
    require => File['/home/vagrant/tmp'],
  }

  exec { 'expand-tomcat':
    command => 'tar xzf apache-tomcat-7.0.42.tar.gz',
    cwd     => '/home/vagrant/tmp',
    path    => [ '/bin/', '/sbin/' , '/usr/bin/', '/usr/sbin/' ],
    creates => '/home/vagrant/apache-tomcat-7.0.42',
    require => Exec['get-tomcat'],
  }

  file { $scripts:
    owner   => 'vagrant',
    group   => 'vagrant',
    mode    => 'u+rwx',
    recurse => true,
    require => Exec['expand-tomcat'],
  }

}

Notice how I declared the dependencies logically, leading to this order

*

*File["/home/vagrant/tmp/"]

*Exec['get-tomcat']

*Exec['expand-tomcat']
Followed by all the files in $scripts

A: File resources in puppet do not expand wildcards, so the following puppet code is not doing what you are expecting:
file { "/home/vagrant/tmp/apache-tomcat-7.0.42/bin/*.sh":
   owner => "vagrant",
   group => "vagrant",
   mode => "u+rwx",
   recurse => true
}

That is looking for a single file that is literally named /home/vagrant/tmp/apache-tomcat-7.0.42/bin/*.sh.
To do what you are wanting to do, you need to remove the above code and add this code:
exec { 'set-tomcat-permissions':
  command => "chown -Rh vagrant:vagrant .; find . -name '*.sh' -exec chmod u+rwx {} ';'",
  cwd => "/home/vagrant/tmp",
  path => [ "/bin/", "/sbin/" , "/usr/bin/", "/usr/sbin/" ],
  subscribe => Exec["expand-tomcat"],
  refreshonly => true,
}


text:
Q: how to display selected values apex:selectList as selected I wanted to save some multiselected values stored in a custom setting and then retrieve the value and display as selected in the selectList.
The first option of saving the value in custom setting is working but i am not sure how we can get the values as selected.
Any pointers on how this can be done would be a great help.
<apex:pageBlockSectionItem id="pbsiStatus">
                <apex:outputlabel value="Don't Show Leads with Status"  id="lblStatus" />
                <apex:selectList id="selectStatus" value="{!cls.Dont_Show_Lead_With_Status__c}" multiselect="true" styleClass="convstatus" >
                    <apex:selectOptions value="{!statusList}"/>
                </apex:selectList>
 </apex:pageBlockSectionItem>

The saved value is stored as [Closed - Converted, Working - Contacted]
Update:
As suggested by @Keith, i am changing the way to store in the custom setting as Working - Contacted; Open - Not Contacted by removing the "[" and "]" and delimiter as semi-colon instead of comma.
I still cant see the values as default selected when i view the VF page.
Update 2:
If i select just 1 item from the selectList then i can see the value is selected. But there is no selection if more than one option is selected.

A: In your controller initialize Dont_Show_Lead_With_Status__c to all the option values (obtained from your custom setting) separated with a semi-colon using something like:
String[] optionValues = ...;

cls.Dont_Show_Lead_With_Status__c = String.join(optionValues, ';');

so they are all pre-selected.
PS Just saw you addition about the format they are stored in; I've only every seen the semi-colon used to separate the multiple selected values.

A: The Multiselect picklist is just the list of string. So cls.Dont_Show_Lead_With_Status__c can take list of string as parameter.
In your constructor,
List<String> dontshowstatus = new List<String>();
for(Custom_Settings__c c : Custom_Settings__c.getValues()) {
    dontshowstatus.add(c.Name);
cls.Dont_Show_Lead_With_Status__c = dontshowstatus;

The values from custom settings will be assigned to list of string and then assigned to cls.Dont_Show_Lead_With_Status__c.
Hope it helps.


text:
Q: spark 1.6 with akka within same application I'm working on one application which involved some ETL jobs which I'm trying to implement with spark 1.6. And also some web server which I've implemented with akka http. Both pieces work fine separately but when I move it in single app - spark start to fail with the following:
Exception in thread "main" java.lang.NoSuchMethodError: akka.actor.LocalActorRefProvider.log()Lakka/event/LoggingAdapter;
at akka.remote.RemoteActorRefProvider.<init>(RemoteActorRefProvider.scala:128)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at akka.actor.ReflectiveDynamicAccess$$anonfun$createInstanceFor$2.apply(ReflectiveDynamicAccess.scala:33)
at scala.util.Try$.apply(Try.scala:192)
at akka.actor.ReflectiveDynamicAccess.createInstanceFor(ReflectiveDynamicAccess.scala:28)
at akka.actor.ReflectiveDynamicAccess$$anonfun$createInstanceFor$3.apply(ReflectiveDynamicAccess.scala:39)
at akka.actor.ReflectiveDynamicAccess$$anonfun$createInstanceFor$3.apply(ReflectiveDynamicAccess.scala:39)
at scala.util.Success.flatMap(Try.scala:231)
at akka.actor.ReflectiveDynamicAccess.createInstanceFor(ReflectiveDynamicAccess.scala:39)
at akka.actor.ActorSystemImpl.liftedTree1$1(ActorSystem.scala:795)
at akka.actor.ActorSystemImpl.<init>(ActorSystem.scala:788)
at akka.actor.ActorSystem$.apply(ActorSystem.scala:246)
at akka.actor.ActorSystem$.apply(ActorSystem.scala:289)
at akka.actor.ActorSystem$.apply(ActorSystem.scala:264)
at org.apache.spark.util.AkkaUtils$.org$apache$spark$util$AkkaUtils$$doCreateActorSystem(AkkaUtils.scala:121)
at org.apache.spark.util.AkkaUtils$$anonfun$1.apply(AkkaUtils.scala:53)
at org.apache.spark.util.AkkaUtils$$anonfun$1.apply(AkkaUtils.scala:52)
at org.apache.spark.util.Utils$$anonfun$startServiceOnPort$1.apply$mcVI$sp(Utils.scala:2024)
at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:160)
at org.apache.spark.util.Utils$.startServiceOnPort(Utils.scala:2015)
at org.apache.spark.util.AkkaUtils$.createActorSystem(AkkaUtils.scala:55)
at org.apache.spark.SparkEnv$.create(SparkEnv.scala:266)
at org.apache.spark.SparkEnv$.createDriverEnv(SparkEnv.scala:193)
at org.apache.spark.SparkContext.createSparkEnv(SparkContext.scala:288)
at org.apache.spark.SparkContext.<init>(SparkContext.scala:457)

This is my dependencies:
"org.apache.spark" %% "spark-sql" % "1.6.2",
"org.apache.spark" %% "spark-hive" % "1.6.2",
"com.databricks" %% "spark-csv" % "1.5.0",
"com.typesafe.akka" %% "akka-actor" % "2.5.19",
"com.typesafe.akka" %% "akka-stream" % "2.5.19",
"com.typesafe.akka" %% "akka-http" % "10.1.3",
"com.typesafe.akka" %% "akka-http-spray-json" % "10.1.3"

Sample code:
object AppStarter {

  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setMaster("local[4]")
    val sc = new SparkContext(conf) // FAIL happens here
  }

}

I was trying to play around akka-native version settings but it doesn't help but I've got different error each time. Is there any way to force spark to ignore akka dependencies in the same scope?

A: it look like you want to use spark Sql, for this prefer the usage of SparkSession.builder
SparkSession.builder()
  .master("local[4]")
  .appName("Spark recommendation")
  .getOrCreate()

You can have a look at the documentation here : https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.SparkSession
With this you can pass more configuration parameters using :
.config("spark.executor.memory", "4g") for example.


text:
Q: AsymptoticDSolveValue returing input I would like to find a uniform approximation of the solution to the boundary layer problem
$$\epsilon y'' + (x+x^3)y'-2y=0, \hspace{20mm}y(1)=y(-1)=1$$
When using AsymptoticDSolveValue, I inputted the following:
    0, y[-1] == 1, y[1] == 1}, y[x], x, {\[Epsilon], 0, 1}]

However, it just returned my statement. It refuses to solve specifically this problem: if I get rid of the $x^3$ term, it works, and similarly if I get rid of the $x$ term. How can I get it to solve the problem for me?

A: The ode
ode = eps y''[x] + (x + x^3)*y'[x] - 2*y[x] == 0
ode /. y->(y[-#]&)
(* -2 y[-x] - (x + x^3) Derivative[1][y][-x] +eps (y^\[Prime]\[Prime])[-x] == 0*)

only has symmetric solutions! That's why the bc y[-1] == 1, y[1] == 1 aren't sufficient.
Change  bc to  y'[0] == 0, y[1] == 1 and try
sol = ParametricNDSolveValue[{ode, y'[0] == 0, y[1] == 1}, y, {x, -1, 1}, {eps}];
Plot[Table[sol[eps][x], {eps, {1, .1, .01, .001}}] , {x, -1, 1}]

A: Mathematica can not do it. May be because it is boundary value problem. Compare
ode = y''[x] + (x + x^3)*y'[x] - 2*y[x] == 0;
ic = {y[0] == 1, y'[0] == 0};
AsymptoticDSolveValue[{ode, ic}, y[x], {x, 0, 10}]

Now change the ic to
ode = y''[x] + (x + x^3)*y'[x] - 2*y[x] == 0;
ic = {y[-1] == 1, y[1] == 1};
AsymptoticDSolveValue[{ode, ic}, y[x], {x, 0, 10}]

So no point of trying the perturbation problem if it can't solve the asymptotic one.
Mathematica also can't solve this analytically (with or without $\epsilon$)
ode = y''[x] + (x + x^3)*y'[x] - 2*y[x] == 0;
ic = {y[-1] == 1, y[1] == 1};
DSolveValue[{ode, ic}, y[x], x]

So your best hope is to try numerical solution and manually adjust $\epsilon$ and look at the solution. Something like
ode = eps*y''[x] + (x + x^3)*y'[x] - 2*y[x] == 0;
ic = {y[-1] == 1, y[1] == 1};
sol = ParametricNDSolveValue[{ode, ic}, y, {x, -1, 1}, {eps}];
Manipulate[
 Plot[sol[eps][x], {x, -1, 1}, PlotRange -> {Automatic, {-1, 1}}],
 {{eps, .01, "eps"}, 0.01, .1, 0.01, Appearance -> "Labeled"},
 ContinuousAction -> False,
 TrackedSymbols :> {eps}
 ]

The analytical solution is given by Maple in terms of Heun special functions which I do not think Mathematica currently supports. Correction: Thanks to comment, these special function are now in Mathematica.
ode := epsilon* diff(y(x),x$2)+ (x + x^3)*diff(y(x),x) - 2*y(x) = 0;
sol:=dsolve([ode,y(1)=1,y(-1)=1])

y(x) = 1/HeunB(-1/2,1/epsilon^(1/2),-3/2,5/2/epsilon^(1/2),1/2/epsilon^(1/2))*
exp(-1/4*(x-1)*(x+1)*(x^2+3)/epsilon)*HeunB(-1/2,1/epsilon^(1/2),-3/2,5/2/
epsilon^(1/2),1/2/epsilon^(1/2)*x^2)

But Maple could not take the series of the above or figure the limit either. Maple does not have AsymptoticDSolveValue like command either. Here is plot of the analytical solution for small value of $\epsilon$
plot(eval(rhs(sol),epsilon=0.001),x=-2..2)

When trying for smaller $\epsilon$ in Maple I get
plot(eval(rhs(sol),epsilon=0.00001),x=-2..2)
Warning, breaking the computation of HeunB after 20000 terms, the series is not converging

And for #\epsilon=1$
   plot(eval(rhs(sol),epsilon=1),x=-2..2)

WHich agrees with what numerical solution by NDSolve shows as $\epsilon$ gets larger.
So it seems your problem is pushing the envelope of what Mathematica can do at this time.


text:
Q: Cannot resolve 'sport_details' given 1 input columns in Spark I'm trying to define a schema for my json in Spark. I have this error :

org.apache.spark.sql.AnalysisException: cannot resolve
'sport_details' given input columns: [user_agent, modified_at,
datamatrix_content, player_id, created_by, device_advertisers_id,
device_type, betslips, created_by_app, created_by_user, status,
device_id, uid, created_at, created_by_partner];;

Here is my code :
      val mySchema = StructType(Array(
    StructField("uid", StringType, true),
    StructField("modified_at", TimestampType, true),
    StructField("created_at", TimestampType, true),
    StructField("datamatrix_content", StringType, true),
    StructField("created_by", StringType, true),
    StructField("created_by_app", StringType, true),
    StructField("created_by_partner", StringType, true),
    StructField("created_by_user", StringType, true),
    StructField("status", StringType, true),
    StructField("player_id", StringType, true),
    StructField("device_type", StringType, true),
    StructField("device_id", StringType, true),
    StructField("user_agent", StringType, true),

    StructField("betslips", StructType(Array(
      StructField("game_name", StringType, true),
      StructField("type_id", IntegerType, true),
      StructField("expires_at", TimestampType, true),
      StructField("enabled", BooleanType, true),

      StructField("sport_details", StructType(Array(
        StructField("grid_id", IntegerType, true),
        StructField("double_count", IntegerType, true),
        StructField("triple_count", IntegerType, true)
      ))))))))

And here my json :
[
  {
    "uid": "*",
    "modified_at": "*",
    "created_at": "*",
    "datamatrix_content": "string",
    "created_by": "string",
    "created_by_app": "*",
    "created_by_partner": "string",
    "created_by_user": "string",
    "status": "pending",
    "player_id": "string",
    "device_type": "mobile/ios",
    "device_id": "string",
    "device_advertisers_id": "string",
    "user_agent": "string",

    "betslips": [
      {
        "game_name": "*",
        "type_id": 0,
        "expires_at": "*",
        "enabled": true,

        "sport_details": [
          {
            "grid_id": 122,
            "double_count": 2,
            "triple_count": 3
          }
        ]
      }
    ]
  }
]

A: I believe you might have a wrong schema specified.
betslips is of ArrayType and then the element type is a StructType.
Aslo the json seems to start with annonymous collection.
The correct schema should be:
val mySchema = StructType(
            Array(
                StructField("uid", StringType, true),
                StructField("modified_at", TimestampType, true),
                StructField("created_at", TimestampType, true),
                StructField("datamatrix_content", StringType, true),
                StructField("created_by", StringType, true),
                StructField("created_by_app", StringType, true),
                StructField("created_by_partner", StringType, true),
                StructField("created_by_user", StringType, true),
                StructField("status", StringType, true),
                StructField("player_id", StringType, true),
                StructField("device_type", StringType, true),
                StructField("device_id", StringType, true),
                StructField("user_agent", StringType, true),

                StructField("betslips", ArrayType(
                    StructType(
                        Array(
                            StructField("game_name", StringType, true),
                            StructField("type_id", IntegerType, true),
                            StructField("expires_at", TimestampType, true),
                            StructField("enabled", BooleanType, true),

                            ArrayType("sport_details",
                                StructType(Array(
                                    StructField("grid_id", IntegerType, true),
                                    StructField("double_count", IntegerType, true),
                                    StructField("triple_count", IntegerType, true)
                                ))
                            )
                        )
                    )
                ))
            )
        )

A: betslip and user details are ArrayType in your json, so you should add those in schema as below
val mySchema = StructType(Array(
  StructField("uid", StringType, true),
  StructField("modified_at", TimestampType, true),
  StructField("created_at", TimestampType, true),
  StructField("datamatrix_content", StringType, true),
  StructField("created_by", StringType, true),
  StructField("created_by_app", StringType, true),
  StructField("created_by_partner", StringType, true),
  StructField("created_by_user", StringType, true),
  StructField("status", StringType, true),
  StructField("player_id", StringType, true),
  StructField("device_type", StringType, true),
  StructField("device_id", StringType, true),
  StructField("user_agent", StringType, true),
  StructField("betslips", ArrayType(
    StructType(Array(
      StructField("game_name", StringType, true),
      StructField("type_id", IntegerType, true),
      StructField("expires_at", TimestampType, true),
      StructField("enabled", BooleanType, true),
      StructField("sport_details", ArrayType(
        StructType(Array(
          StructField("grid_id", IntegerType, true),
          StructField("double_count", IntegerType, true),
          StructField("triple_count", IntegerType, true)
        ))
      ))
    ))
  ))
))


text:
Q: Getting exception while running a project in mvc 2.0 I am having a problem in a project while running it it causes an exception :
The view at '~/Views/Employee/Index.aspx' must derive from ViewPage, ViewPage, ViewUserControl, or ViewUserControl.
I think it is caused as this project is in mvc 2.0 and i am having running it using mvc 3.0
but i am not getting it right. Does anyone know about this problem.
Any help will be highly appreciated..

A: It's to do with the content in your Inherits tag.
A standard view should have a tag similar to this at the top.
<%@ Page Language="C#"    Inherits="System.Web.Mvc.ViewPage <OBJECT PASSED IN> " %>

A: I got the solution. My project is created in MVC 2 with visual studio 2008 and on opening it in MVC 3 with visual studio 2010 desn't load the project correctly for this the installation of MVC 2 with visual studio 2008 is needed.


text:
Q: Separating by columns in read_bulk() I'm using the readbulk package to read 40 csv files and merge them. All of the input csv files have 21 columns, however when I inspect the outputs, there are only four columns. I notice that the columns are all together, separated by a period. I don't see an option to manage the columns in the output in the read_bulk() function. What can I do differently?
My code:
library(readbulk)
input_path<- "/Volumes/WININSTALL/Filename_Redux/Zone1_Output/"

file_list<- list.files(input_path, pattern = "[.]csv$")

file_paste<- paste(input_path, file_list, sep = "")

merged<- read_bulk(directory = input_path, subdirectories = FALSE, extension = ".csv")


text:
Q: Flutter DataTable remove extra padding I want to display some data in a DataTable, i have 9 columns, all of them are number except the first one.
The problem i'm having is, i only see the first 5 columns, not because data are too long, but because there are a lot of space between every column.

Is there a way to make the DataColumn wrap the data with a padding i choose?
This is my code:
Scaffold(
  appBar: AppBar(
    title: Text('DataTable Sample'),
  ),
  body: Container(
    child: DataTable(columns: <DataColumn>[
          DataColumn(
            label: Text('Name'),
          ),
          DataColumn(
            label: Text('A'),
          ),
          DataColumn(
            label: Text('B'),
          ),
          DataColumn(
            label: Text('C'),
          ),
          DataColumn(
            label: Text('D'),
          ),
          DataColumn(
            label: Text('E'),
          ),
          DataColumn(
            label: Text('F'),
          ),
          DataColumn(
            label: Text('G'),
          ),
          DataColumn(
            label: Text('H'),
          ),
        ], rows: <DataRow>[
          DataRow(cells: [
            DataCell(Text('1 Boston')),
            DataCell(Text('3')),
            DataCell(Text('3')),
            DataCell(Text('7')),
            DataCell(Text('1')),
            DataCell(Text('30')),
            DataCell(Text('8')),
            DataCell(Text('+2')),
            DataCell(Text('-22')),
          ]),
          DataRow(cells: [
            DataCell(Text('2 London')),
            DataCell(Text('3')),
            DataCell(Text('4')),
            DataCell(Text('12')),
            DataCell(Text('44')),
            DataCell(Text('7')),
            DataCell(Text('44')),
            DataCell(Text('-98')),
            DataCell(Text('0')),
          ]),
          DataRow(cells: [
            DataCell(Text('3 Rome')),
            DataCell(Text('10')),
            DataCell(Text('50')),
            DataCell(Text('90')),
            DataCell(Text('4')),
            DataCell(Text('7')),
            DataCell(Text('33')),
            DataCell(Text('+5')),
            DataCell(Text('-61')),
          ]),
        ]
        )
  ),
);

A: Try setting horizontalMargin to 0 as this value defaults to 24.0:

...
DataTable(
   horizontalMargin: 0,
   columnSpacing: 10,
   columns: [
...

Ref.Datatable horizontalMargin official documentation

A: Try passing columnSpacing parameter inside your 'DataTable()' function, it seems to accept it,
The default value is 56, reducing it will cramp the columns and increasing it will spread data out

A: you can use SingleChildScrollView and FittedBox as its child.
Scaffold(
  appBar: AppBar(
    title: Text('DataTable Sample'),
  ),
  body: SingleChildScrollView(
    scrollDirection: Axis.vertical,
    child: FittedBox(
      child: DataTable(
        columns: <DataColumn>[
          DataColumn(
            label: Text('Name'),
          ),
          DataColumn(
            label: Text('A'),
          ),
          DataColumn(
            label: Text('B'),
          ),
          DataColumn(
            label: Text('C'),
          ),
          DataColumn(
            label: Text('D'),
          ),
          DataColumn(
            label: Text('E'),
          ),
          DataColumn(
            label: Text('F'),
          ),
          DataColumn(
            label: Text('G'),
          ),
          DataColumn(
            label: Text('H'),
          ),
        ],
        rows: <DataRow>[
          DataRow(cells: [
            DataCell(Text('1 Boston')),
            DataCell(Text('3')),
            DataCell(Text('3')),
            DataCell(Text('7')),
            DataCell(Text('1')),
            DataCell(Text('30')),
            DataCell(Text('8')),
            DataCell(Text('+2')),
            DataCell(Text('-22')),
          ]),
          DataRow(cells: [
            DataCell(Text('2 London')),
            DataCell(Text('3')),
            DataCell(Text('4')),
            DataCell(Text('12')),
            DataCell(Text('44')),
            DataCell(Text('7')),
            DataCell(Text('44')),
            DataCell(Text('-98')),
            DataCell(Text('0')),
          ]),
          DataRow(cells: [
            DataCell(Text('3 Rome')),
            DataCell(Text('10')),
            DataCell(Text('50')),
            DataCell(Text('90')),
            DataCell(Text('4')),
            DataCell(Text('7')),
            DataCell(Text('33')),
            DataCell(Text('+5')),
            DataCell(Text('-61')),
          ]),
        ],
      ),
    ),
  ),
);

A: Yes. Lately flutter team merged an update to this Widget. It is now only in the "master" channel (You are probably on "stable"), to switch run flutter channel master and then flutter upgrade in the terminal. After doing so you can control the space between each column by setting the columnSpacing parameter of DataTable. For further information check out this closed issue

A: Currently, even I am stuck with the same issue, but I have found an alternative to this problem where you can see all your 9 columns. Have a look if it can help you.

use SingleChildScrollView to scroll the Datatable horizontally

Scaffold(
appBar: AppBar(title: Text('DataTable Sample')),
body: data()
)

create a function outside "Widget build(BuildContext context) {}" as given below

SingleChildScrollView data() {
return SingleChildScrollView(
  scrollDirection: Axis.horizontal,
  child: Container(
child: DataTable(columns: <DataColumn>[
      DataColumn(
        label: Text('Name'),
      ),
      DataColumn(
        label: Text('A'),
      ),
      DataColumn(
        label: Text('B'),
      ),
      DataColumn(
        label: Text('C'),
      ),
      DataColumn(
        label: Text('D'),
      ),
      DataColumn(
        label: Text('E'),
      ),
      DataColumn(
        label: Text('F'),
      ),
      DataColumn(
        label: Text('G'),
      ),
      DataColumn(
        label: Text('H'),
      ),
    ], rows: <DataRow>[
      DataRow(cells: [
        DataCell(Text('1 Boston')),
        DataCell(Text('3')),
        DataCell(Text('3')),
        DataCell(Text('7')),
        DataCell(Text('1')),
        DataCell(Text('30')),
        DataCell(Text('8')),
        DataCell(Text('+2')),
        DataCell(Text('-22')),
      ]),
      DataRow(cells: [
        DataCell(Text('2 London')),
        DataCell(Text('3')),
        DataCell(Text('4')),
        DataCell(Text('12')),
        DataCell(Text('44')),
        DataCell(Text('7')),
        DataCell(Text('44')),
        DataCell(Text('-98')),
        DataCell(Text('0')),
      ]),
      DataRow(cells: [
        DataCell(Text('3 Rome')),
        DataCell(Text('10')),
        DataCell(Text('50')),
        DataCell(Text('90')),
        DataCell(Text('4')),
        DataCell(Text('7')),
        DataCell(Text('33')),
        DataCell(Text('+5')),
        DataCell(Text('-61')),
      ]),
    ]
    )
  ),
  }

Let me know if it solves your problem

A: To remove the space between every column, you can change the value of columnSpacing which is 56 by default.

A: You can use Table instead of DataTable. For further reference - video.
This is how you can use it:
Scaffold(
    appBar: AppBar(title: Text('DataTable Sample')),
    body: Container(
      child: Table(
        columnWidths: {0:FractionColumnWidth(.2)},
        children: [
        TableRow(
          children: [
            Text("Name",),
            Text("A",textAlign: TextAlign.center,),
            Text("B",textAlign: TextAlign.center,),
            Text("A",textAlign: TextAlign.center,),
            Text("B",textAlign: TextAlign.center,),
            Text("A",textAlign: TextAlign.center,),
            Text("B",textAlign: TextAlign.center,),
            Text("A",textAlign: TextAlign.center,),
            Text("B",textAlign: TextAlign.center,),
          ]
         ),
         TableRow(
          children: [
            Text("1 Boston",),
            Text('3',textAlign: TextAlign.center,),
            Text('3',textAlign: TextAlign.center,),
            Text('7',textAlign: TextAlign.center,),
            Text('1',textAlign: TextAlign.center,),
            Text('30',textAlign: TextAlign.center,),
            Text('8',textAlign: TextAlign.center,),
            Text('+2',textAlign: TextAlign.center,),
            Text('-22',textAlign: TextAlign.center,),
          ]
         ),
         TableRow(
          children: [
            Text('2 London',),
            Text('3',textAlign: TextAlign.center,),
            Text('4',textAlign: TextAlign.center,),
            Text('12',textAlign: TextAlign.center,),
            Text('44',textAlign: TextAlign.center,),
            Text('7',textAlign: TextAlign.center,),
            Text('44',textAlign: TextAlign.center,),
            Text('-98',textAlign: TextAlign.center,),
            Text('0',textAlign: TextAlign.center,),
          ]
         ),
        TableRow(
          children: [
              Text('3 Rome'),
              Text('10',textAlign: TextAlign.center,),
              Text('50',textAlign: TextAlign.center,),
              Text('90',textAlign: TextAlign.center,),
              Text('4',textAlign: TextAlign.center,),
              Text('7',textAlign: TextAlign.center,),
              Text('33',textAlign: TextAlign.center,),
              Text('+5',textAlign: TextAlign.center,),
              Text('-61',textAlign: TextAlign.center,),
          ]
         ),
        ]
      ),
    )
  ),


text:
Q: PHP Redirection Error - not sure of the issue (new to PHP) I'm pretty new to PHP - I'm using a script that works great apart from one page. It is a Rare Values site for items. It can be viewed at ClassicHabbox.com/values
The main issue is on the admin side of things. You can add a value to the site no problem, you just can't edit the value. If I wanted to edit value 214 for example, it will try and take me to the following address http://classichabbox.com/values/admin/editvalue.214 - this comes up as a 404 error. Maybe it's an issue with the PHP, or even HTACCESS?
I have listed below the editvalue.php of /admin and my HTACCESS file.
I have also created an account for you to use, to see what I mean.
http://classichabbox.com/values/admin/login
Username: Stack
Password: Overflow
editvalue.php
<?php

    define('BoonValues', true);
    require_once('../global.php');

    if(!$core->loggedIn())
    {
        header('Location: '. $config['Site']['Link'] .'/admin/login');
        exit;
    }

    if(!$admin->hasPermission('editvalue', $_SESSION['admin']['username']))
    {
        header('Location: '. $config['Site']['Link'] .'/admin/permissions');
        exit;
    }

    if(isset($_POST['value']))
    {
        header('Location: '. $config['Site']['Link'] .'/admin/editvalue.'. $_POST['value']);
        exit;
    }

    if(isset($_GET['value']))
    {
        if(is_numeric($_GET['value']))
        {
            $pdo->query('SELECT `id`, `name`, `image`, `value_now`, `category`, `hidden` FROM `values_list` WHERE `id` = :rareId');
            $pdo->bind(':rareId', $_GET['value']);

            $aboutRare = $pdo->single();

            if(!$aboutRare)
            {
                $message = 'The selected rare does not exist.';
                $messageType = 'alert-danger';
            }
        }
        else
        {
            $message = 'Invalid rare selected.';
            $messageType = 'alert-danger';
        }
    }

    if(isset($_POST['rareName'], $_POST['rareImage'], $_POST['rareCategory'], $_POST['rareValue'], $_POST['valueChoice'], $_POST['hidden']))
    {
        $categories = array('HC', 'normal', 'super');

        if(is_numeric($_GET['value']))
        {
            $pdo->query('SELECT `id`, `name`, `image`, `value_now`, `category`, `hidden` FROM `values_list` WHERE `id` = :rareId');
            $pdo->bind(':rareId', $_GET['value']);

            $rareDetail = $pdo->single();

            if($rareDetail)
            {
                if(in_array($_POST['rareCategory'], $categories))
                {
                    $hidden = ($_POST['ltd'] == 'Not Hidden' ? '0' : '1');
                    $newName = ($admin->hasPermission('editvalue_name', $_SESSION['admin']['username']) ? $_POST['rareName'] : $rareDetail['name']);
                    $newImage = ($admin->hasPermission('editvalue_image', $_SESSION['admin']['username']) ? $_POST['rareImage'] : $rareDetail['image']);
                    $newCategory = ($admin->hasPermission('editvalue_category', $_SESSION['admin']['username']) ? $_POST['rareCategory'] : $rareDetail['category']);
                    $newHidden = ($admin->hasPermission('editvalue_hidden', $_SESSION['admin']['username']) ? $hidden : $rareDetail['ltd']);

                    if($admin->hasPermission('editvalue_value', $_SESSION['admin']['username']))
                    {
                        if($_POST['valueChoice'] == 'thrones')
                        {
                            $newValue = throneValue * $_POST['rareValue'];
                        }
                        else if($_POST['valueChoice'] == 'pbs')
                        {
                            $newValue = $_POST['rareValue'] * 5000;
                        }
                        else
                        {
                            $newValue = $_POST['rareValue'];
                        }
                    }
                    else
                    {
                        $newValue = $rareDetail['value_now'];
                    }

                    if($rareDetail['value_now'] > $newValue)
                    {
                        $change = $rareDetail['value_now'] - $newValue;
                        $way = 'down';
                        $silent = '0';
                    }
                    else if($rareDetail['value_now'] < $newValue)
                    {
                        $change = $newValue - $rareDetail['value_now'];
                        $way = 'up';
                        $silent = '0';
                    }
                    else
                    {
                        $change = '0';
                        $way = 'neutral';
                        $silent = '1';
                    }

                    $admin->recordEvent('Edit Value', 'Changed value of ID '. $rareDetail['id'] .' from '. $rareDetail['value_now'] .' to '. $newValue .'.');

                    $pdo->query('INSERT INTO `values_history` (`rareid`, `name`, `value`, `change`, `direction`, `silent`, `timestamp`, `changedby`) VALUES (:rareId, :name, :value, :change, :direction, :silent, :timestamp, :username)');
                    $pdo->bind(':rareId', $_GET['value']);
                    $pdo->bind(':name', $newName);
                    $pdo->bind(':value', $newValue);
                    $pdo->bind(':change', $change);
                    $pdo->bind(':direction', $way);
                    $pdo->bind(':silent', $silent);
                    $pdo->bind(':timestamp', time());
                    $pdo->bind(':username', $_SESSION['admin']['username']);
                    $pdo->execute();

                    $pdo->query('UPDATE `values_list` SET `name` = :name, `image` = :image, `value_now` = :value, `category` = :category, `hidden` = :hidden WHERE `id` = :rareId');
                    $pdo->bind(':rareId', $_GET['value']);
                    $pdo->bind(':name', $newName);
                    $pdo->bind(':image', $newImage);
                    $pdo->bind(':value', $newValue);
                    $pdo->bind(':category', $newCategory);
                    $pdo->bind(':hidden', $newHidden);
                    $pdo->execute();

                    $message = 'Rare updated and cache cleared.';
                    $messageType = 'alert-success';

                    $core->destroyCache();
                }
                else
                {
                    $message = 'Invalid category selected.';
                    $messageType = 'alert-danger';
                }
            }
            else
            {
                $message = 'The selected rare does not exist.';
                $messageType = 'alert-danger';
            }
        }
        else
        {
            $message = 'Invalid rare selected.';
            $messageType = 'alert-danger';
        }
    }

    $selectedPage = '2-1';

?>
<!doctype html>

        <meta charset="utf-8">
        <title>BoonValues - Edit Value</title>

        <link rel="stylesheet" href="<?php echo $config['Site']['Link']; ?>/resources/styles/bootstrap.min.css">
        <link rel="stylesheet" href="<?php echo $config['Site']['Link']; ?>/resources/styles/navbar.css">

        <?php include_once('navbar.php'); ?>

<?php if(isset($_GET['value'])){ ?><a href="<?php echo $config['Site']['Link']; ?>/admin/editvalue">« <?php } ?>Edit Value

            <?php

                if(isset($message, $messageType))
                {
                    echo '
'. $message .'
';
                }

                if(!isset($_GET['value']))
                {

                    if(!$admin->hasPermission('editvalue_hidden', $_SESSION['admin']['username']))
                    {
                        $pdo->query('SELECT `id`, `name`, `category`, `hidden` FROM `values_list` WHERE `hidden` = :hidden');
                        $pdo->bind(':hidden', '0');
                    }
                    else
                    {
                        $pdo->query('SELECT `id`, `name`, `category` FROM `values_list`');
                    }

                    $list = $pdo->resultSet();

            ?>
                <form method="post" class="form-inline" role="form">
                    <select class="form-control input-sm" id="rareValue" name="value" style="width: 50%;">
                        <option value="0">Select A Rare</option>
                        <option value="0"></option>
                        <optgroup label="HC Rares">
                        <?php

                            foreach($list as $rare)
                            {
                                if($rare['category'] == 'HC')
                                {

                        ?>
                            <option value="<?php echo $rare['id']; ?>"><?php echo $rare['name']; ?></option>
                        <?php

                                }
                            }

                        ?>
                        </optgroup>
                        <optgroup label="Normal Rares">
                        <?php

                            foreach($list as $rare)
                            {
                                if($rare['category'] == 'normal')
                                {

                        ?>
                            <option value="<?php echo $rare['id']; ?>"><?php echo $rare['name']; ?></option>
                        <?php

                                }
                            }

                        ?>
                        </optgroup>
                        <optgroup label="Super Rares">
                        <?php

                            foreach($list as $rare)
                            {
                                if($rare['category'] == 'super')
                                {

                        ?>
                            <option value="<?php echo $rare['id']; ?>"><?php echo $rare['name']; ?></option>
                        <?php

                                }
                            }

                        ?>
                        </optgroup>
                    </select>
                    <button class="btn btn-primary btn-sm" type="submit">Edit</button>
                </form>
            <?php } else { ?>
                <form method="post" role="form" style="width: 50%;">
                    <input type="hidden" name="rareid" value="<?php echo $_GET['value']; ?>">

                        Name:
                        <input type="text" class="form-control" id="rareName" name="rareName" placeholder="Name" value="<?php echo $aboutRare['name']; ?>" <?php if(!$admin->hasPermission('editvalue_name', $_SESSION['admin']['username'])){ echo 'readonly'; } ?>>

                    <div class="form-group" style="<?php if(!$admin->hasPermission('editvalue_image', $_SESSION['admin']['username'])){ echo 'display: none;'; } ?>">
                        Image:
                        <select class="form-control" id="rareImage" name="rareImage">
                        <?php
                        $arr=array();
                        if($open = opendir(ROOT .'/resources/images/small_furni')) {
                            while(false != ($file = readdir($open))) {
                                if($file == '.' || $file == '..') {
                                    continue;
                                }
                                $files[]=$file;
                            }
                        }
                        sort($files);
                        foreach($files as $file) echo '<option value="'. $file .'" '. ((isset($rareimage) && $rareimage == $file) ? 'selected' : '') .'>'. $file .'</option>';
                        ?>
                        </select>

                    <div class="form-group" style="<?php if(!$admin->hasPermission('editvalue_category', $_SESSION['admin']['username'])){ echo 'display: none;'; } ?>">
                        Category:
                        <select class="form-control" id="rareCategory" name="rareCategory">
                            <option value="HC" <?php if($aboutRare['category'] == 'HC'){ echo 'selected'; } ?>>HC Rare</option>
                            <option value="normal" <?php if($aboutRare['category'] == 'normal'){ echo 'selected'; } ?>>Normal Rare</option>
                            <option value="super" <?php if($aboutRare['category'] == 'super'){ echo 'selected'; } ?>>Super Rare</option>
                        </select>

                    <div class="form-group" style="<?php if(!$admin->hasPermission('editvalue_value', $_SESSION['admin']['username'])){ echo 'display: none;'; } ?>">
                        Value:

                            <input type="text" class="form-control" id="rareValue" name="rareValue" placeholder="Value" value="<?php echo $aboutRare['value_now']; ?>">

                                <input type="hidden" name="valueChoice" value="credits" id="valueChoice">
                                <button type="button" class="btn btn-default" tabindex="-1" id="valueSelector" value="1" style="margin-right: -1px;">Credits</button>
                                <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" tabindex="-1">

                                    Toggle Dropdown
                                </button>

Credits

Thrones

Platinum Bars

                        <label class="radio-inline" style="<?php if(!$admin->hasPermission('editvalue_hidden', $_SESSION['admin']['username'])){ echo 'display: none;'; } ?>">
                            <input type="radio" name="hidden" id="hidden1" value="Hidden" <?php if($aboutRare['hidden'] == '1'){ echo 'checked'; } ?>> Hidden

                        <label class="radio-inline" style="<?php if(!$admin->hasPermission('editvalue_hidden', $_SESSION['admin']['username'])){ echo 'display: none;'; } ?>">
                            <input type="radio" name="hidden" id="hidden2" value="Not Hidden" <?php if($aboutRare['hidden'] == '0'){ echo 'checked'; } ?>> Not Hidden

                        <button type="submit" class="btn btn-primary btn-sm" style="float: right;">Save</button>
                        <?php if($admin->hasPermission('deletevalue', $_SESSION['admin']['username'])){ ?>
                        <button type="submit" class="btn btn-danger btn-sm" name="deleteRare" style="float: right; margin-right: 5px;">Delete Rare</button>
                        <?php } ?>

                </form>
            <?php } ?>

.htaccess file - in /values directory
# Run Php without filename extension
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php

# Return 404 if original request is .php
RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$"
RewriteRule .* - [L,R=404]

PHP Version 5.4


text:
Q: why does bidirectional mapping give infinate loop? I am working on a project. I want to give one to one bidirectional relationship. I am getting infinate loop json. why i do not know. I refereed in internet. i could not get it clearly. please give me a solution.
@GetMapping(value = "/employees")
List<Employee> getEmployees() {
    return this.employeeRepository.findAll();
}

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {

}

package com.example.jpa.model;
import java.io.Serializable;
import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="EMPLOYEES")
public class Employee implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="EMP_ID", unique = true, nullable = false)
    private Long empId;

    private String name;

    private String department;

    private Long salary;

    @Column(name="JOINED_ON")
    private Date joinedOn;

    @OneToOne(fetch = FetchType.EAGER, mappedBy = "employee", cascade = CascadeType.ALL)
    private EmpDetails empDetails;

    public Long getEmpId() {
        return empId;
    }

    public void setEmpId(Long empId) {
        this.empId = empId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public Long getSalary() {
        return salary;
    }

    public void setSalary(Long salary) {
        this.salary = salary;
    }

    public Date getJoinedOn() {
        return joinedOn;
    }

    public void setJoinedOn(Date joinedOn) {
        this.joinedOn = joinedOn;
    }

    public EmpDetails getEmpDetails() {
        return empDetails;
    }

    public void setEmpDetails(EmpDetails empDetails) {
        this.empDetails = empDetails;
    }

    @Override
    public String toString() {

        String resp = this.empId+" | "+this.name+" | "+this.department+" | "+this.salary+" | "+this.joinedOn;
        if(this.empDetails != null) {
            resp += "|"+this.empDetails.toString();
        }

        return resp;
    }
}

package com.example.jpa.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="EMP_DETAILS")
public class EmpDetails {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="ED_ID", unique = true, nullable = false)
    private Long edId;

    private String address;

    private String gender;

    @Column(name="YEARS_OF_SERVICE")
    private Long yearsOfService;

    @Column(name="BANK_ACCOUNT")
    private String bankAccount;

    @OneToOne
    @JoinColumn(name="EMP_ID")
    private Employee employee;

    public Long getEdId() {
        return edId;
    }

    public void setEdId(Long edId) {
        this.edId = edId;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Long getYearsOfService() {
        return yearsOfService;
    }

    public void setYearsOfService(Long yearsOfService) {
        this.yearsOfService = yearsOfService;
    }

    public String getBankAccount() {
        return bankAccount;
    }

    public void setBankAccount(String bankAccount) {
        this.bankAccount = bankAccount;
    }

    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

    @Override
    public String toString() {

        return this.gender+" | "+this.address+" | "+this.yearsOfService+" | "+this.bankAccount;
    }
}

infinate JSON:
[
    {
        "empId": 1,
        "name": "Nataraja G",
        "department": "Documentation",
        "salary": 10000,
        "joinedOn": "2019-09-17T08:12:24.362+0000",
        "empDetails": {
            "edId": 1,
            "address": "Bangalore",
            "gender": "Male",
            "yearsOfService": 4,
            "bankAccount": "00343466",
            "employee": {
                "empId": 1,
                "name": "Nataraja G",
                "department": "Documentation",
                "salary": 10000,
                "joinedOn": "2019-09-17T08:12:24.362+0000",
                "empDetails": {
                    "edId": 1,
                    "address": "Bangalore",
                    "gender": "Male",
                    "yearsOfService": 4,
                    "bankAccount": "00343466",
                    "employee": {
                        "empId": 1,
                        "name": "Nataraja G",
                        "department": "Documentation",
                        "salary": 10000,
                        "joinedOn": "2019-09-17T08:12:24.362+0000",
                        "empDetails": {
                            "edId": 1,
                            "address": "Bangalore",
                            "gender": "Male",
                            "yearsOfService": 4,
                            "bankAccount": "00343466",
                            "employee": {
                                "empId": 1,
                                "name": "Nataraja G",
..............
}]

A: Because your Employee entity has a EmpDetails and EmpDetails has a Employee entity. Use @JsonIgnore annotation on the employee field of the EmpDetails entity to make it work
  @OneToOne
  @JsonIgnore
  @JoinColumn(name="EMP_ID")
  private Employee employee;

A: When Jackson is trying to serialize your entity to json. He should serialze the employee field. To do that he will try to serialize empDetails field. So again trying to serialize the employee field in this empDetails and like that he is going to be in a circular infinite loop.
The solution is prevent serialize the field employee. In the class employee you add @JsonIgnore in employee field.
@OneToOne
@JoinColumn(name="EMP_ID")
@JsonIgnore
 private Employee employee;


text:
Q: Question about the equality of variances of two populations When finding the confidence interval for the mean difference between two groups of sample, under which assumption about the equality of their population variances should we take if no information about their population variances is given?
Is it correct that if 1 is within the 98% confidence interval for the ratio of variance, then we can assume equal population variance when finding the confidence interval for the mean difference? At least that is what I understand from my lecture notes:]2

A: In R, the procedure var.test implements the standard F-test for equality of variances for data from two normal populations.
Here is an example, using samples of size $n = 20$ from two normal populations with respective variances $\sigma_1^2 = 49$ and $\sigma_2^2 = 25.$  The null hypothesis of equal variances is not rejected at the 5% level.
set.seed(2019)
x = rnorm(20, 50, 7);  y = rnorm(20, 50, 5)
var.test(x, y)

        F test to compare two variances

data:  x and y
F = 1.8786, num df = 19, denom df = 19, p-value = 0.1785
alternative hypothesis:
   true ratio of variances is not equal to 1
95 percent confidence interval:
 0.7435627 4.7461266
sample estimates:
ratio of variances
          1.878575

The figure below shows the density function of $\mathsf{F}(19, 19),$ with vertical dotted lines at the critical values for a two-sided
test at the 5% level. The observed variance ratio $F = 1.8786$
lies between them.

This is not really an unusual case. According to the simulation below, the power of such a test is only about 30%.
set.seed(1234)
pv = replicate(10^5,
       var.test(rnorm(20, 50, 7), rnorm(20,50,5))$p.value)
mean(pv < .05)
[1] 0.29359

Addendum: I'm not sure what is left to explain at this point,
but I will make a few comments and show some output from R.
(a) As I have hinted and @HeteroskedasticJim has documented: Whenever the goal is to test whether two normal population means are equal and there is doubt about equality of population variances, the recommended procedure is to do a Welch two-sample t
test of the null hypothesis that population means are equal.
[Thus I suppose both of us disagree with the boxed instruction with the "!" in you Question.]
For your data, that null hypothesis cannot be rejected. You can find formulas for the Welch test in you text, class notes, or online.
x = c(12,11,7,13,8,9,10,13);  y = c(13,11,10,6,7,4,10)
t.test(x,y)

        Welch Two Sample t-test

data:  x and y
t = 1.1583, df = 10.771, p-value = 0.2718
alternative hypothesis:
   true difference in means is not equal to 0
95 percent confidence interval:
 -1.503134  4.824562
sample estimates:
mean of x mean of y
10.375000  8.714286

(b) If you had done a pooled two-sample t test (which requires the assumption that population variances are equal), then you would have $T = 1.1851, df = 13,$ and P-value = 0.2572, so again no rejection. (However as mentioned above, it is not recommended to do a 'composite test', first testing for equal variances; and if failing to reject, going on to do the pooled two-sample tests for equal means. The overall significance level of this rwo-test process is unclear.)
(c) If you use R's var.test procedure, mentioned in this Answer above, you can request a 98% CI, which agrees with what you say in your Question. The fact that
this CI includes $1$ does lead one to believe that population variances are equal (but it would be more direct to test the hypothesis that the ratio of population variances is 1.)
var.test(x,y, conf.lev=.98)

        F test to compare two variances

data:  x and y
F = 0.51743, num df = 7, denom df = 6, p-value = 0.4087
alternative hypothesis:
    true ratio of variances is not equal to 1
98 percent confidence interval:
 0.06264264 3.72103337
sample estimates:
ratio of variances
         0.5174279

The overall conclusion is that the data do not show convincing
evidence of a difference between the two fertilizers--neither in terms of their
population means nor in terms of their population variances.
The lack of significance is unsurprising on account of the small
sample sizes.


text:
Q: Oracle sql issue with dynamically created IN clause This makes a correct string in parenthesis and quoted.
select '('||REPLACE('''Binnenstad Boerhaavedistrict''',' ',''',''')||')' from dual

Namely:

('Binnenstad','Boerhaavedistrict')

But when I use it in an IN statement it fails:
select dn.DISTRICTSNAAM
from DISTRICTNAAM dn
where   dn.DISTRICTSNAAM in '('||REPLACE('''Binnenstad Boerhaavedistrict''',' ',''',''')||')'

No error, just no result.
My intent is to create the IN list from a space separated input variable.
But it only seems to work when I feed it a variable with quoted comma separated string.
Why is this? Or is it too dynamic?

A: The problem is your IN compare to the full string instead of an array
where  dn.DISTRICTSNAAM in ( full string )

instead
where  dn.DISTRICTSNAAM in ( stringA, stringB)

A: in will not parse a string containing comma-separated values. It will only handle a comma-separated list of strings.
in ('a', 'b', 'c') is okay.
in ('''a''', ''b'', ''c''') will only test a single value.
in '(''a''', ''b'', ''c'')' will also only test a single value.
To do what you're attempting, you will need to use dynamic SQL.

A: You can use q-operator for creating dynamic sql containing quotes. With this you can get rid of unnecessary quote marks.
For reference you can see
http://www.oracle-developer.net/display.php?id=311
or https://community.oracle.com/thread/2146817


text:
Q: Link class function calls to modules loaded in a process What I am trying to do is inject into a process and then use the modules that are available within that process. That's pretty straight forward by using GetProcAddress() and requesting individual functions as needed.
However, I have third party API files that I am trying to utilize as well. These files contain classes that I can use to make various API calls. When importing them into my project and attempting to compile them I get the LNK2019 unresolved external symbol error. This error stems from the fact I am not importing the lib files. The problem is I cannot import them because I do not have access to the lib files. I'd like to use the existing loaded modules in the process I am injecting into.
I am struggling with finding a way to put these two pieces together. How can I link the various function calls within the class files to modules already loaded into a process? If this is not possible what approach should be taken?
EDIT: Modified sentence about lib files

A: You must import the LIB. Otherwise the references to the functions can't be resolved by the linker.
You can bypass this by using LoadLibary/GetProcAddress for this functions to. For classes this will be complicated.
But what is your problem including the LIB into your DLL.
When Your module is injected into the other program the required DLLs are loaded into the process too. If they are already loaded the loaded DLLs will be used and the "existing DLLs" (already loaded DLLs) in the process are used.
A problem might only be the DLL search sequence... Remember: If you use USER32.DLL functions you get the already loaded copy and use it too. No second User32.dll is loaded when you use the import library.
If the DLLs are not loaded they are implicitly loaded, when you module is injected into the process.


text:
Q: function that returns a 2d array of int and string - Go So I'm trying to create a function that returns a 2D array that stores and integer value and a string value. Obviously i can just use a normal array like i would in python as go uses data types.
I've looked into using a struct but i don't know if I'm missing something or not but I've deleted my small bit of code about 5 times and got nowhere, is anyone able to point me in the right direction please, i feel like I'm getting nowhere...
type user_info struct{
id int
name string
}

new_user := []user_info{{id: 1, name: "Max"}}

This will create one instance but how to i create a single array that i can append the new user to?

A: you have multiple ways to appned:
new_user := []user_info{
    {id: 1, name: "Max"},
    {id: 2, name: "John"},
    {id: 3, name: "George"},
}

or you can append item by item:
new_user = append(new_user, user_info{id: 4, name: "Sam"})


text:
Q: The value of a real series What is the value of
$$    \sum_{n=1}^\infty\frac{\sum_{k=1}^n \frac{1}{k^2}}{(n+1)(n+2)} $$

A: First, change the order of summation (which we can do, since all terms are non-negative), to get
$$
\sum_{n=1}^{\infty}\sum_{k=1}^{n}\frac{1}{k^2}\frac{1}{(n+1)(n+2)}=\sum_{k=1}^{\infty}\frac{1}{k^2}\sum_{n=k}^{\infty}\frac{1}{(n+1)(n+2)}.
$$
Using partial fractions on the inner sum, you'll find that this actually telescopes, yielding
$$
\sum_{n=k}^{\infty}\frac{1}{(n+1)(n+2)}=\frac{1}{k+1}.
$$
So, we are now trying to compute
$$
\sum_{k=1}^{\infty}\frac{1}{k^2(k+1)}.
$$
Another application of partial fractions yields
$$
\frac{1}{k^2(k+1)}=\frac{1}{k^2}-\frac{1}{k}+\frac{1}{k+1}.
$$
But
$$
\sum_{k=1}^{\infty}\frac{1}{k^2}=\frac{\pi^2}{6},
$$
and by again noticing telescoping we find that
$$
\sum_{k=1}^{\infty}\left(\frac{1}{k+1}-\frac{1}{k}\right)=-1.
$$
Combining these then yields
$$
\sum_{n=1}^{\infty}\sum_{k=1}^{n}\frac{1}{k^2}\frac{1}{(n+1)(n+2)}=\frac{\pi^2}{6}-1.
$$

A: Your sum can be rewritten as
$$\sum_{n = 1}^{\infty}\bigg(\sum_{k = 1}^n {1 \over k^2}{1 \over (n+1)(n+2)}\bigg)$$
Changing the order of summation this becomes
$$\sum_{k = 1}^{\infty}\bigg(\sum_{n = k}^{\infty} {1 \over k^2}{1 \over (n+1)(n+2)}\bigg)$$
$$= \sum_{k = 1}^{\infty}{1 \over k^2}\bigg(\sum_{n = k}^{\infty}{1 \over (n+1)(n+2)}\bigg)$$
This telescopes into
$$\sum_{k = 1}^{\infty}{1 \over k^2(k+1)}$$
To sum this, use partial fractions... Key fact to be used is ${\displaystyle {1 \over k(k+1)} = {1 \over k} - {1 \over k+1}}$. So the sum is
$$\sum_{k = 1}^{\infty}{1 \over k}\bigg({1 \over k} - {1 \over k+1}\bigg)$$
$$= \sum_{k = 1}^{\infty}{1 \over k^2} - \sum_{k = 1}^{\infty}{1 \over k(k+1)} $$
First sum adds to ${\pi^2 \over 6}$, second telescopes to $1$, so the overall sum is
$${\pi^2 \over 6} - 1$$


text:
Q: Drawing FFT discrete signal using continuous sine-waves ?! I do np.fft.fft() to decompose discrete-signal to frequencies.
Then I pick top N freqs and now I want to draw a signal of the sum of those frequencies using the following formula :
 amp * np.sin( 2 * np.pi * freq * time + phase )

I extract the freqs based on their position in the array (fftfreqs), amplitudes with np.abs(complex_num) and phases with np.angle(complex_num, deg=True), from the data I got from from fft() call.
It does not seem to work very well.
What I'm doing wrong ?
Do I understand correctly that the complex-num contains the amp&phase of sinusoid ? Do I have to use sin&cos for the drawing ?
The documentation is very sparse on exact interpretation of the result of fft().
PS> I know I can use np.fft.ifft() to draw close approximation, but this way of doing it is limited to the time-frame of the original signal.
I want to draw/fit the original signal with the top N freqs in the original timeframe, but also to draw the "continuation" of the signal after this timeframe using those freqs i.e. the extended signal.

A: I found my mistakes.. first the correct way to calculate the waves is (sum of those for topN freqs) :
cos_amp * np.cos( 2 * np.pi * freq * time) + sin_amp * np.sin( 2 * np.pi * freq * time)

not just sin()..second it is incorrect to use abs-amplitude and angle-phase extraction from the complex array.
The real part contains the cos-amp and the negative-imaginary part contains the sin-amplitude i.e. once I get the complex array out of fft(), I do something like this :
fft_res = np.fft.fft(signal)
.... topN_freqs_idx = find top freqs from PSD
all_freqs = np.fft.fftfreq(N)
freqs = all_freqs[topN_freq_idx]
norm = fft_res[topN_freq_idx] / (N/2)
cos_amp = np.real(norm)
sin_amp = -np.imag(norm)

I figured out this from here :
http://www.dspguide.com/ch8/5.htm


text:
Q: Retrieving filename from Jfilechooser into JList I'm having some problems with my class that I need some help with. The class is supposed to take retrieve a csv.file from the file chooser, and then put the name of the file into a Jlist, but I can't get the JList to print the arraylist that I put the chosen files into. This is the code I've got, so I'd be grateful if you could take a look at it and tell me what I need to change with it in order to get the JList to print the arraylist.
import dao.UserDAO;
import db.DemoDB;
import model.Activity;
import model.DataPoint;
import model.Statistics;

public class LoginGUI1 {
    DemoDB DemoDBSingleton = null;

    private JTabbedPane tabbedPane = new JTabbedPane();
    UserDAO userDao = new UserDAO();
    JFrame mainFrame = new JFrame("Välkommen till din app");
    JFrame f = new JFrame("User Login");
    JLabel l = new JLabel("Användarnamn:");
    JLabel l1 = new JLabel("Lösenord:");
    JTextField textfieldUsername = new JTextField(10);
    JPasswordField textfieldPassword = new JPasswordField(10);
    JButton loginButton = new JButton("Logga In");
    JFileChooser fc = new JFileChooser();
    JMenuBar mb = new JMenuBar();
    JList listAct = new JList();
    List<Activity> activityList = new ArrayList<Activity>();
    List activityList1 = new Vector();

    JFrame jf;
    JMenu menu;
    JMenuItem importMenu, exitMenu;

    Activity activity = new Activity();

    public LoginGUI1() throws IOException {

        DemoDBSingleton = DemoDB.getInstance();
        ProgramMainFrame();

    }

    private void ProgramMainFrame() throws IOException {

        mainFrame.setSize(800, 600);
        mainFrame.setVisible(true);
        mainFrame.setJMenuBar(mb);
        mainFrame.getContentPane().setLayout(new BorderLayout());;

        tabbedPane.add("Dina Aktiviteter", createViewActPanel());
        mainFrame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
        tabbedPane.add("Diagram för vald aktivitet", createViewDiagramPanel());
        tabbedPane.add("Statistik för vald aktivitet", createViewStatisticsPanel());
        tabbedPane.add("Kartbild över vald aktivitet", createViewMapPanel());

        JMenuBar mb = new JMenuBar();
        menu = new JMenu("Meny");
        importMenu = new JMenuItem("Importera aktivitet");
        importMenu.addActionListener(importActionListener);
        exitMenu = new JMenuItem("Avsluta program");
        exitMenu.addActionListener(exitActionListener);
        menu.add(importMenu);
        menu.add(exitMenu);
        mb.add(menu);
        mainFrame.setJMenuBar(mb);

    /*  JPanel listholder = new JPanel();
        listholder.setBorder(BorderFactory.createTitledBorder("ListPanel"));
        mainFrame.add(listholder);
        listholder.setVisible(true);
        listholder.setSize(500,400);*/

    }

    private JPanel createViewActPanel() {
        JPanel analogM = new JPanel();
        analogM.setBackground(new Color(224, 255, 255));
        return analogM;
    }

    ActionListener importActionListener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int returnValue = fc.showOpenDialog(mainFrame);
            if(returnValue == JFileChooser.APPROVE_OPTION)
            {
                File file = fc.getSelectedFile();
                if(file != null)
                {
                    String fileName = file.getAbsolutePath();
                Activity activity = null;
                try {
                    activity = new Activity();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                    try {
                        activity.csvFileReader(fileName);
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    activityList.add(activity);
                    listAct.setListData(activityList.toArray());

                }

            }
        }

    };

    public static void main(String[] args) throws IOException {
        new LoginGUI();

    }
}

A: There's a lot of context missing, so the best I can do is provide a simple running example which works.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class Test {

    public static void main(String args[]) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JList<File> fileList;
        private DefaultListModel<File> fileListModel;

        public TestPane() {
            fileListModel = new DefaultListModel<>();
            fileList = new JList(fileListModel);

            JButton addButton = new JButton("Add");
            addButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    JFileChooser fileChooser = new JFileChooser();
                    if (fileChooser.showOpenDialog(TestPane.this) == JFileChooser.APPROVE_OPTION) {
                        File file = fileChooser.getSelectedFile();
                        fileListModel.addElement(file);
                    }
                }
            });

            setLayout(new BorderLayout());
            add(new JScrollPane(fileList));
            add(addButton, BorderLayout.SOUTH);
        }

    }
}

I'd highly recommend having a look at How to use lists to get a better understanding of how the API works


text:
Q: Check if div there after click, remove it if it was there I have a JavaScript which is create a type of accordion, I would like to open divs on click and then close them on a second click. I could done that but then I don't know where to insert the removing code el.classList.remove("openDiv"); to close all tabs that might was open and the only tab which should be open is the clicked one.
Here is the JavaScript code:
var el = document.getElementsByClassName('applications');
var i;
var action = 1;

function addHandler(el) {
   el.addEventListener("click", function() {

     if ( action == 1 ) {
       el.classList.add('openDiv');
       action = 2;
     } else {
       el.classList.remove("openDiv");
       action = 1;
     }
   });
}

for (i = 0; i < el.length; i++) {
   addHandler(el[i]);
}

I also created a DEMO

A: var el = document.getElementsByClassName('applications');
var i;

function addHandler(el) {
  el.addEventListener("click", function() {

     //updated condition for click
     if ( !this.classList.contains('openDiv')) {
        var a = document.getElementsByClassName('openDiv');
        for (var i in a) {
          if (a[i].classList) {
            a[i].classList.remove("openDiv");
          }
        }
        el.classList.add('openDiv');
        action = 2;
    } else {
        el.classList.remove("openDiv");
        action = 1;
    }

  });
}

for (i = 0; i < el.length; i++) {
  addHandler(el[i]);
}

Working demo

A: I've edited a little your code, find an example here: https://jsfiddle.net/48Lpvmbr/2/
code:
var els = document.getElementsByClassName('applications');

function addHandler(el) {
  el.addEventListener("click", function() {

     for(var x = 0; x < els.length; x++){
        if(els[x] === el){
            console.log("NOT ME!!!");
        }else{
            els[x].classList.remove("openDiv");
        }
     }

     if(el.classList.contains("openDiv")){
        el.classList.remove("openDiv");
     }else{
        el.classList.add("openDiv");
     }

  });
}

for (var i = 0; i < els.length; i++) {
  addHandler(els[i]);
}

A: var el = document.getElementsByClassName('applications');
var i;

function addHandler(el) {
  el.addEventListener("click", function() {
     el.classList.toggle('openDiv');
      removeOpen(el);
  });
}

function removeOpen(openElement){
  for (i = 0; i < el.length; i++) {
   if(el[i] !== openElement){
     el[i].classList.remove("openDiv");
   }
  }
}

for (i = 0; i < el.length; i++) {
  addHandler(el[i]);
}

A: I changed up your code a little to have a wrapper element around the content so there is only one event listener. But basically you need to select the open elements and than remove the class.

var wrapper = document.getElementById("application_wrapper");
wrapper.addEventListener("click", function(evt) {
  var elem = evt.target; //get what was clicked
  if (elem.nodeName === "H2") { //see if it was an h2
    elem.classList.toggle("open");

    //now to remove
    var opened = wrapper.querySelectorAll("h2.open");  //find opened
    for(var i=opened.length-1; i>=0;i--) { //loop
        if (opened[i]==elem) continue; //make sure we do not remove the one we just added
        opened[i].classList.remove("open");
    }
  }
});
h2 + h1,
h2 + h1 + p {
  display: none;
}
h2.open + h1,
h2.open + h1 + p {
  display: block;
}

.applications { border: 1px solid black; }
h1{ border-top: 1px solid #CCC; }
h2{cursor: pointer;}

Color Cosmetics

Color Cosmetics

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt ultrices arcu, ut pulvinar risus maximus sed. Quisque dolor nisl, iaculis id sem eget, molestie mollis est. Phasellus scelerisque sagittis ex, nec vestibulum turpis euismod
      eu. Aliquam aliquet orci et sapien euismod, vitae pellentesque velit porttitor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin rhoncus, felis non elementum ultrices, dui nisl tincidunt risus, sit
      amet sodales nunc dolor semper lacus. Vivamus egestas lectus id imperdiet pharetra. Nulla non sem elit. Fusce porta velit leo, nec gravida ligula auctor vitae. Sed justo sem, sodales ut imperdiet at, fringilla pharetra neque.

Hair Care

Hair Care

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt ultrices arcu, ut pulvinar risus maximus sed. Quisque dolor nisl, iaculis id sem eget, molestie mollis est. Phasellus scelerisque sagittis ex, nec vestibulum turpis euismod
      eu. Aliquam aliquet orci et sapien euismod, vitae pellentesque velit porttitor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin rhoncus, felis non elementum ultrices, dui nisl tincidunt risus, sit
      amet sodales nunc dolor semper lacus. Vivamus egestas lectus id imperdiet pharetra. Nulla non sem elit. Fusce porta velit leo, nec gravida ligula auctor vitae. Sed justo sem, sodales ut imperdiet at, fringilla pharetra neque.

Baby Care

Baby Care

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt ultrices arcu, ut pulvinar risus maximus sed. Quisque dolor nisl, iaculis id sem eget, molestie mollis est. Phasellus scelerisque sagittis ex, nec vestibulum turpis euismod
      eu. Aliquam aliquet orci et sapien euismod, vitae pellentesque velit porttitor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin rhoncus, felis non elementum ultrices, dui nisl tincidunt risus, sit
      amet sodales nunc dolor semper lacus. Vivamus egestas lectus id imperdiet pharetra. Nulla non sem elit. Fusce porta velit leo, nec gravida ligula auctor vitae. Sed justo sem, sodales ut imperdiet at, fringilla pharetra neque.

Skin Care

Skin Care

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt ultrices arcu, ut pulvinar risus maximus sed. Quisque dolor nisl, iaculis id sem eget, molestie mollis est. Phasellus scelerisque sagittis ex, nec vestibulum turpis euismod
      eu. Aliquam aliquet orci et sapien euismod, vitae pellentesque velit porttitor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin rhoncus, felis non elementum ultrices, dui nisl tincidunt risus, sit
      amet sodales nunc dolor semper lacus. Vivamus egestas lectus id imperdiet pharetra. Nulla non sem elit. Fusce porta velit leo, nec gravida ligula auctor vitae. Sed justo sem, sodales ut imperdiet at, fringilla pharetra neque.

Soap & Bath

Soap & Bath

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt ultrices arcu, ut pulvinar risus maximus sed. Quisque dolor nisl, iaculis id sem eget, molestie mollis est. Phasellus scelerisque sagittis ex, nec vestibulum turpis euismod
      eu. Aliquam aliquet orci et sapien euismod, vitae pellentesque velit porttitor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin rhoncus, felis non elementum ultrices, dui nisl tincidunt risus, sit
      amet sodales nunc dolor semper lacus. Vivamus egestas lectus id imperdiet pharetra. Nulla non sem elit. Fusce porta velit leo, nec gravida ligula auctor vitae. Sed justo sem, sodales ut imperdiet at, fringilla pharetra neque.


text:
Q: jQuery css selector for table I'm having the following table markup:

foo	foo	foo

foo	foo	foo

foo	foo	foo

foo	foo	foo

Several cells are marked with class marked - how can I select all rows which have cells with class marked? I know how to select all marked cells but I need the rows for the selector in order to loop through them.
What I want to achieve is an array/JSON string which contains all data of all rows with cell indexes of the marked cells, which would look something like that:
rowdata[0] = [1];
rowdata[1] = [0,1,2];
rowdata[3] = [2];

Any ideas what's the easiest way to to it?
EDIT: Sorry, there was a typo, I meant class "marked"

A: Try like
var rowdata=[];

$('tr').each(function(){
   $td=$(this).find('td');
   arr=[];
   $td.each(function(index,value){
       if($(this).hasClass('marked'))
          arr.push(index);
   });
   rowdata.push(arr);
});

Fiddle

A: var rowdata = [];
$('table tr').each(function () {
    rowdata.push($(this).find('.marked').map(function () {
        return $(this).index();
    }).get());
});

DEMO


text:
Q: Text based browser game I wanted to create a text based browser game, so how should I go about? I can do programming in asp or jsp or php that is not a barrier, but I am unaware of what steps that one needs to follow while attempting to make such games. So please guide me.
please also recommend me a programming language for making the same.

A: One of the simplest browser games is just a series of static pages with links on each page leading to other pages. Often there will be some "story" on the page followed by a few choices you can make. Different choices lead to different pages.
The next step up is to use dynamic pages instead. When loading a new page, the browser can send some variables to the server and the server can generate a page on the fly. This saves you the effort of creating lots of similar pages by hand, and also allows you to do things like random outcomes.
However, if you want to keep a lot of user state (such as inventory, skills, or whatever), it becomes cumbersome (and insecure) to continually pass this from server to browser to server. This is what session handling is for: it remembers a user for a while, and lets you remember some variables at the server side.
If you want a more interactive game, you would need to look into Javascript and perhaps AJAX, which allow things to change in the browser without needing to load a new page.
In terms of language, I would suggest Python CGI, 'cause I like Python. Start with something simple so you can get a better idea of what you're working with, before you design something large.
Have fun!

A: Sounds like you could map it out using a state machine (in any of your chosen languages)...could be a fun little project (:

A: create a map - basically a two-dimensional array of "rooms" - alternatively you can make it three dimensional if you need to have your character go up and down as well...
then in the game when the player moves character to the south, just find that room in the array.
array could contain all required things related to the room (description, objects, NPCs etc.)

A: Personally I would make a text based game in python and then get that to talk to a webserver. that way you can test the game without so much hassle.
What kind of game are you looking to write?
you have to think about what the user might do as well. They can duplicate their window and send the same information twice. They can click back which might mess up the game. You could get the user to submit the time and a session ID each time they click submit.
p.s. continuation passing style is one way to emulate the ability to call an return. It's not an easy way to write things though.

A: Design. Implement. Test. Play.
If it is a text-based browser game, you should go with HTML. :)


text:
Q: *ngFor - two different arrays for single row on table I need to populate table with two different arrays "A" and "B" into a same row.
let A = ["a","b","c","d"]
let B = ["success","success","success","success"];

HTML

  <ng-container *ngFor="let alphabet of A; let i = index">

  {{ alphabet }}
  {{ status }}

  </ng-container>

But here with this i get repeated set of rows
Expected:
a    success
b    success
c    success
d    success

A: You can access the the data of the second array by its index:

  {{ alphabet }}
  {{ B[i] }}


text:
Q: Nginx 301 redirect if string is given I would like to create a permanent redirect for specific querys inside my nginx server block. As example on my current url links to the php script have been:
website.com/?hash=12345

So i need to change this to website.com/folder/?hash=12345
Is there a way to redirect permanent only if the parameter ?hash= is given inside the query and leave all other querys how they are?
Edit: I did some testings with this here
        location ~* /.*hash\=.*/ {
     rewrite ^ https://mysite.eu/bluetracker/$request_uri? permanent;
    }

but Sadly this is also not working

A: This is pretty simple. Just check for the existence of the argument.
location / {
    if ($arg_hash) {
        return 301 /folder/$is_args$args;
    }

    # everything else...
}

Note here, that $is_args returns a ? if there is a query string, and an empty string otherwise. And $args returns the entire query string.


text:
Q: shell script that takes a file name as an argument and deletes this file from every directory above the pwd in Unix / Linux / Ubuntu my shell script is as follows.
if [ $# -eq 0 ]
then
    echo "pass the file name"
    exit
 fi
fl=$1
ch=1
h=/home

while [ $ch -eq 1 ]
do
    cd ..
    p=`pwd`
    echo "$p/$fl"
    rm `echo "$p/$fl"` 2> /dev/nullif [ $p = $h ]
    then
            ch=0
    fi
done

but when executing shows a syntax error.
 line16: syntax error near unexpected token then'
 line 16:        then'
What is the mistake in this script?

A: You misplaced if the script.
if [ $# -eq 0 ]
then
    echo "pass the file name"
    exit
fi

fl=$1
ch=1
h=/home

while [ $ch -eq 1 ]
do
    cd ..
    p=`pwd`
    echo "$p/$fl"
    rm `echo "$p/$fl"` 2> /dev/null
    if [ $p = $h ]
    then
            ch=0
    fi
done


text:
Q: Android Global Search app replacement I am working on an app that will be an alternative to the default Android search app. I want my app to be the default app that runs when the user presses (not long press) the hardware search button. Is this possible?

A: There is an intent for that: http://developer.android.com/reference/android/content/Intent.html#ACTION_SEARCH
So basically you just need an app that listens to the intent and the rest is the choice of the user...


text:
Q: running uwsgi on docker causing no such file or directory I'm trying to run an application using uwsgi inside a docker container, but i'm getting

docker: Error response from daemon: OCI runtime create failed:
  container_linux.go:348: starting container process caused "exec:
  \"uwsgi --http :80 -s /tmp/uwsgi.sock  --pidfile /var/run/uwsgi.pid
  --wsgi-file /app/api.py -M -p 4 --die-on-term --callable app -d /tmp/uwsgi.log\": stat uwsgi --http :80 -s /tmp/uwsgi.sock  --pidfile
  /var/run/uwsgi.pid --wsgi-file /app/api.py -M -p 4 --die-on-term
  --callable app -d /tmp/uwsgi.log: no such file or directory": unknown.

my docker file:
FROM ubuntu

RUN apt-get update && apt-get install -y build-essential python-dev python-pip

RUN pip install uwsgi

RUN pip install Flask

EXPOSE 9090

COPY ./flask /app
WORKDIR /app

CMD ["uwsgi --http :80 -s /tmp/uwsgi.sock  --pidfile /var/run/uwsgi.pid --wsgi-file /app/api.py -M -p 4 --die-on-term --callable app -d /tmp/uwsgi.log"]

What could i do to run that successfully?

A: You can try the CMD exec form
CMD ["uwsgi", "--http", ":80", "-s", "/tmp/uwsgi.sock",  "--pidfile", "/var/run/uwsgi.pid", "--wsgi-file", "/app/api.py", "-M", "-p", "4", "--die-on-term", "--callable", "app", "-d", "/tmp/uwsgi.log"]

instead of
CMD ["uwsgi --http :80 -s /tmp/uwsgi.sock  --pidfile /var/run/uwsgi.pid --wsgi-file /app/api.py -M -p 4 --die-on-term --callable app -d /tmp/uwsgi.log"]

Wish this answer is helpful to you and Dockerfile CMD shell versus exec form is the reference.