text:
Q: Rails. Debugging a Uniqueness validation with scope that fails when object is updated I have a model Prediction for which its instances have references to other models Participant and Match through the  attributes :participant_id :match_id.
The idea is that a @participant can have only one @prediction per @match (every @participant is allowed to give maximum one prediction per  @match).
So I've included the following validation in my Prediction model
validates :match_id, uniqueness: { scope: [:participant_id] }

The validation works OK to disallow @prediction objects to be created when there's already a @prediciton for the same @match and @participant. The problem is that it does, as well, prevent updating an object even though I'm not changing those assigned ids of the original object. Plus, it's letting me update only one instance of Prediction, all other's through an error.
What's puzzling is that it was working fine but for some reason, I've been unable to track, it stopped working and I have run out of ideas on how to debug. Could you provide any ideas? Below what I've checked/tried:
The relevant params of a failed request:
"prediction"=><ActionController::Parameters {"participant_id"=>"1", "match_id"=>"2", "local_score"=>"2", "visitant_score"=>"0"}

The error I'm getting:
 @details={:match_id=>[{:error=>:taken, :value=>2}]},
 @messages={:match_id=>["has already been taken"]}>

There are plenty predictions in the database with match_id: 2. However, this is happening despite having no other @prediction in the database with both match_id: 2 and participant_id: 1 except, of course, for the instance that throws this error while updating.
Funnily enough, if I try the same operation in the console (as below) it successfully updates.
@prediction = Prediction.find_by(participant_id: 1, match_id: 2)
@prediction.update_attributes(local_score: 8, visitant_score: 8)

Suggesting the problem is in the controller action:
app/controllers/predicitons_controller.rb
  def update
    respond_to do |format|
      if @prediction.update(prediction_params)
        format.json { render :show, status: :ok, location: @prediction }
        format.js
      else
        @errorMessages = []
        @prediction.errors.full_messages.each do |message|
            @errorMessages << message
        end
        format.js {render template: 'predictions/update_error'}
      end
    end
  end

I see no problem there. Additionally, it seems that the only request sent to the controller that updates successfully is:
 "prediction"=><ActionController::Parameters {"participant_id"=>"1", "match_id"=>"1", "local_score"=>"1", "visitant_score"=>"1"}

And if I do these others, for example, it doesn't:
"prediction"=><ActionController::Parameters {"participant_id"=>"2", "match_id"=>"1", "local_score"=>"0", "visitant_score"=>"0"}

"prediction"=><ActionController::Parameters {"participant_id"=>"2", "match_id"=>"2", "local_score"=>"9", "visitant_score"=>"9"}

"prediction"=><ActionController::Parameters {"participant_id"=>"4", "match_id"=>"1", "local_score"=>"1", "visitant_score"=>"1"

All of these failed requests throw the "match_id already taken" error and  update just fine in the console.
The controller request is touching the correct action with the method: :put. I've tried to change the syntax of the validation switching   match_id for pool_id (which of course shouldn't make a difference) with no success.
Any, help would be appreciated.

app/models/prediction.rb
class MatchPrediction < ApplicationRecord
  belongs_to :participant
  belongs_to :match
  validates :match_id, uniqueness: { scope: [:pool_participant_id] }
  def correct_score?
    if match.official_outcome
      local_score == match.local_score && visitant_score == match.visitant_score ? true : false
    end
  end
  def correct_outcome?
    if match.official_outcome
      predicted_outcome == match.official_outcome ? true : false
    end
  end
end

and server output pre rollback:
Started PUT "/pools/1/predictions/19" for 127.0.0.1 at 2018-03-29 18:17:11 +1100
Processing by PredictionsController#update as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"SagJX+a7m0eCAdH7AdA0eYz6BVL1cesXYXOUkoe2FRynta6wyiWdskrC1007V1vyrIApPtdEQnVHWlzhSeJs5Q==", "prediction"=>{"participant_id"=>"4", "match_id"=>"2", "local_score"=>"7", "visitant_score"=>"0"}, "pool_id"=>"1", "id"=>"19"}
  User Load (1.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 4], ["LIMIT", 1]]
  ↳ /Users/andres/.rvm/gems/ruby-2.5.0@global/gems/rack-2.0.4/lib/rack/tempfile_reaper.rb:15
  Prediction Load (0.4ms)  SELECT  "predictions".* FROM "predictions" WHERE "predictions"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/predictions_controller.rb:86
   (0.2ms)  BEGIN
  ↳ app/controllers/predictions_controller.rb:55
  Participant Load (0.2ms)  SELECT  "participants".* FROM "participants" WHERE "participants"."id" = $1 LIMIT $2  [["id", 4], ["LIMIT", 1]]
  ↳ app/controllers/predictions_controller.rb:55
  Match Load (0.3ms)  SELECT  "matches".* FROM "matches" WHERE "matches"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
  ↳ app/controllers/predictions_controller.rb:55
  Prediction Exists (1.8ms)  SELECT  1 AS one FROM "predictions" WHERE "predictions"."match_id" = $1 AND "predictions"."id" != $2 AND "predictions"."participant_id" = $3 LIMIT $4  [["match_id", 2], ["id", 1], ["participant_id", 4], ["LIMIT", 1]]
  ↳ app/controllers/predictions_controller.rb:55
  Pool Load (0.5ms)  SELECT  "pools".* FROM "pools" WHERE "pools"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/models/prediction.rb:35
  Round Load (0.6ms)  SELECT  "rounds".* FROM "rounds" INNER JOIN "groups" ON "rounds"."id" = "groups"."round_id" WHERE "groups"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/models/prediction.rb:21
   (0.2ms)  ROLLBACK
  ↳ app/controllers/predictions_controller.rb:55

A: Embarrassing mistake really. I missed checking how the Predictions Controller was setting @prediction. I had entred the params to find the object incorrectly as @GorillaApe suggested:
def set_match_prediction
  @prediction = Prediction.find(params[:pool_id])
end

instead of:
def set_match_prediction
  @prediction = Prediction.find(params[:id])
end

this in turn was always setting the same object thus raising the validation error in all but one of the instances which, by chance, its :id coincided with :pool_id.


text:
Q: BIND server doesn't recognize my zone properly I'm pretty new to BIND so I was hoping maybe someone can help me understand why I can't resolve. What is wrong?
named.conf
options {
        listen-on port 53 { localhost; 10.30.0.10; };
        listen-on-v6 port 53 { ::1; };
        directory       "/var/named";
        dump-file       "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
        allow-query     { any; };
        recursion no;
        version "0";

        channel query.log {
                file "/var/log/query.log";
                severity debug 3;
                print-severity yes;
                print-time yes;
        };
        category queries { query.log; };
};
acl "Tele-Subnet" { 10.100.0.0/16; };
view "Tele" {
        match-clients { "Tele-Subnet"; };

        zone "example.net" IN {
                type master;
                file "/var/named/example.net.db";
                allow-update { none; };
                allow-query { any; };
                notify yes;
        };

};

example.net.db
ORIGIN example.net.
$TTL 86400

example.net.       IN      SOA     10.30.0.10.      admin.example.net. (
                        2012081901      ; serial number YYMMDDNN
                        28800           ; Refresh
                        7200            ; Retry
                        864000          ; Expire
                        86400           ; Min TTL
                        )
        IN      A       10.30.0.10
                NS      10.30.0.10.
                NS      10.30.0.10.

backup    IN       A      10.10.11.230  ; Engine

So when I query the server, I can only see this in the logs:

19-Aug-2012 14:45:09.566 info: client 10.100.0.13#5682: view Telenor:
  query: backup.example.net IN A + (10.30.0.10)

A: There are numerous issues with your named configs. The ones I can pick out:

*

*NS record is missing 'IN' keyword at the start

*IP addresses should not end with a dot (as already pointed out)

*your should have a proper FQDN (fully qualified domain name) for your
nameserver. In your configs, you currently have set 10.30.0.10 as your nameeserver's domain name. So bind will translate 10.30.0.10. to 10.30.0.10.example.net. Your nameserver's FQDN should be something like ns1.example.net..

Here are a number of dns troubleshooting tips you can try (if you haven't already done so):

*

*run named-checkconf and named-checkzone utilities (they should be part of the
bind package you've installed). Run the commands like so:
named-checkconf -jpz
named-checkzone example.net /var/named/example.net.db
What are the warning/error messages displayed after run those commands?

*

*run the dig command (you may have to install dnsutils for debian based OS, or bind-utils for redhat based OS). Run the command something like this for testing:
dig backup.example.net @localhost

*DNS service listens on udp port 53. So make sure your firewall traffic is configured to allow dns traffic.

*check out these following websites for good snippets of dns config examples:
http://www.server-world.info/en/note?os=CentOS_6&p=dns&f=1
https://help.ubuntu.com/community/BIND9ServerHowto

A: You missed several dots, are you sure it wasn't a typo ?
ORIGIN example.net.
$TTL 86400

example.net.       IN      SOA     10.30.0.10.      admin.example.net. (
                        2012081901      ; serial number YYMMDDNN
                        28800           ; Refresh
                        7200            ; Retry
                        864000          ; Expire
                        86400           ; Min TTL
                        )
        IN      A       10.30.0.10.
                NS      10.30.0.10.

backup    IN       A      10.10.11.230.  ; Engine

redpajama_set_name: RedPajamaStackExchange


text:
Q: python slice array produces different errors in several environments I have got 2 dev environment.
First I load the data into an array:
def loadData(filename):
    ins = open(filename, "r")
    array = []
    for line in ins:
        array.append(int(line))
   ins.close()
   return array

In the first one this works without problem
tempLeftArray = array[:(length / 2)]
tempRightArray = array[(length / 2):]

But in the second environment I have to change the code to the following because I was getting the 'slice indices must be integers or none or have __index__ method':
tempLeftArray = array[:int(length / 2)]
tempRightArray = array[int(length / 2):]

Dev env I : windows 8.1, visual studio 2013, python 3.4.0
Dev env II(error one): windows 7, visual studio 2013, python 3.4.0
Any idea of the problem with the first? Why do I need to change the code adding the cast?

A: By default, division in Python 3, gives you floating number. And you cannot use a floating point number as a list's index.
You might want to use integer division in this case, like this
tempLeftArray  = array[:length // 2]
tempRightArray = array[length // 2:]

In Python 2.x,
print(4 / 2)
# 2
print(4.0 / 2)
# 2.0
print(4.0 // 2)
# 2.0
print(4 // 2)
# 2

In Python 3.4,
print(4 / 2)
# 2.0
print(4.0 / 2)
# 2.0
print(4.0 // 2)
# 2.0
print(4 // 2)
# 2


text:
Q: check mybb password throw App login with CURL I use curl protocol on my application.
The users in my forum only allow to use this App after logging throw this appto his account in my forum but I have a problem on php side with password checking.
I think there is a problem on my php code because with correct user and password I have this error:
(incorrect username and/or password).
<?php
// Database info
$MySQL_Host = "localhost";
$MySQL_User = "lol";
$MySQL_Pass = "lol2";
$MySQL_DB = "lol3";
$tbl_name = "mybb_users";

function ParsePost( )
{
    $username = '';
    $password = '';

    $post = file_get_contents( "php://input" );

    $post = str_replace( "&", " ", $post );

    sscanf( $post, "%s  %s", $username, $password );

    return array( 'user' => $username,
                  'pass' => $password
                );
}

function mysql_fetch_full_result_array( $result )
{
    $table_result = array();
    $r = 0;

    if( $result === true )
    {
        return $result;
    }

    if( mysql_num_rows( $result ) == 0 )
    {
        return $result;
    }

    while( $row = mysql_fetch_assoc( $result ) )
    {
        $arr_row = array();
        $c = 0;

        while ( $c < mysql_num_fields( $result ) )
        {
            $col = mysql_fetch_field( $result, $c );
            $arr_row[ $col -> name ] = $row[ $col -> name ];
            $c++;
        }

        $table_result[ $r ] = $arr_row;
        $r++;
    }

    return $table_result;
}

class DWAuth
{
    var $keys;

    function AddDWValue( $val )
    {
        $this->keys[] = $val;
    }

    function GetAuthString( )
    {
        $result = "";

        foreach( $this->keys as $c )
        {
            $result .= $c."#";
        }

        return $result;
    }
}

class DB
{
    var $connection;
    var $started;

    function start()
    {
        global $MySQL_Host, $MySQL_User, $MySQL_Pass, $MySQL_DB;

        $this->connection = mysql_connect("$MySQL_Host", "$MySQL_User", "$MySQL_Pass");
        mysql_select_db("$MySQL_DB", $this->connection );
    }

    function query( $query )
    {
        $result = mysql_query( $query, $this->connection );

        if( $result )
        {
            return mysql_fetch_full_result_array( $result );
        }
        else
        {
            return $result;
        }
    }

    function end()
    {
        mysql_close( $this->connection );
    }

    function isStarted()
    {
        return $started;
    }
}

class Login
{

    function CheckLogin( $username, $password )
    {
        $db = new DB();
        $db->start();

        $query = "SELECT id, password, email FROM $tbl_name WHERE username='".$username."' AND password='".md5( $password )."';";

        $result = $db->query( $query );

        $db->end();

        if( $result == false )
            return false;
            fwrite($fh, $result);
            fclose($fh);

        if( md5(md5($row['salt']).md5($password)) == $result[ 0 ][ 'password' ] )
        {
            return array( 'id' => $result[ 0 ][ 'id' ],
                          'mail' => $result[ 0 ][ 'email' ],
                          'user' => $username
                        );
        }
    }
}

$packet = new DWAuth();
$result = ParsePost();

if( ( empty( $result[ 'user' ] ) ) || ( empty( $result[ 'pass' ] ) ) )
{
    $packet->AddDWValue( "fail" );
    $packet->AddDWValue( "Username and/or password is empty." );
    $packet->AddDWValue( 1 );
    $packet->AddDWValue( "Anonymous" );
    $packet->AddDWValue( "anonymous@example.com" );
    $packet->AddDWValue( 0 );

    echo $packet->GetAuthString();

    die();
}

$login = new Login();
$result = $login->CheckLogin( $result[ 'user' ], $result[ 'pass' ] );

if( $result == false )
{
    $packet->AddDWValue( "fail" );
    $packet->AddDWValue( "incorrect username and/or password." );
    $packet->AddDWValue( 1 );
    $packet->AddDWValue( "Anonymous" );
    $packet->AddDWValue( "anonymous@example.com" );
    $packet->AddDWValue( 0 );
}
else
{
    $sessionID = md5( rand() );
    // How to make the return
    $packet->AddDWValue( "ok" ); // fail or ok
    $packet->AddDWValue( "Success." ); // Success or error
    $packet->AddDWValue( $result[ 'id' ] ); // UserID
    $packet->AddDWValue( $result[ 'user' ] ); // Username
    $packet->AddDWValue( $result[ 'mail' ] ); // email
    $packet->AddDWValue( $sessionID ); // sessionID

    $db = new DB();
    $db->start();

    $query = "UPDATE users SET sid='".$sessionID."' WHERE id=".$result[ 'id' ];

    $result = $db->query( $query );
    $db->end();
}

echo $packet->GetAuthString();

?>

A: I know this might be a bit too late, but I believe the problem is within your query itself.
Change:
$query = "SELECT id, password, email FROM $tbl_name WHERE username='".$username."' AND password='".md5( $password )."';";

to
$query = "SELECT uid, password, email FROM $tbl_name WHERE username='".$username."' OR email='".$username."';";

Remember to sanitise your strings before using them with a database!


text:
Q: show that $\frac {a_{N+1}}{s_{N+1}} +...+\frac {a_{N+k}}{s_{N+k}}\geq 1 -\frac {a_{N}}{s_{N+k}} $ Suggestion of how to do it, please.

Suppose $\{a_n\}$ is a succession in $\mathbb R  ^+$ such that  $\sum a_n$ diverges, and if  $s_n = \sum\limits_{k=1}^n{a_k}$.
  show that $\frac {a_{N+1}}{s_{N+1}} +...+\frac {a_{N+k}}{s_{N+k}}\geq 1 -\frac {s_{N}}{s_{N+k}} $

and infer that $\sum\limits_{n=1}^\infty{\frac{a_n}{s_n}}$ diverge.
Please.thank

A: $$\frac {a_{N+1}}{s_{N+1}} +...+\frac {a_{N+k}}{s_{N+k}}\geq\frac {a_{N+1}}{s_{N+k}} +...+\frac {a_{N+k}}{s_{N+k}}=$$
$$=\frac{s_{N+k}-s_N}{s_{N+k}}= 1 -\frac {s_{N}}{s_{N+k}} $$


text:
Q: When debugging, can I make Xcode ignore certain signal? I am making some development on Xcode for a OS X application. I need to send SIGUSR1 to the application by:
  kill(getpid(), SIGUSR1)

This worked. However, each time the SIGUSR1 sent, Xcode was blocked to show me that a signal was caught. Can I make Xcode simply ignore this signal and keep continous running during debugging?
Thank you at advance!

A: Borrowing shamelessly from this question you can use something like
process handle SIGUSR1 -n true -p true -s false

from the LLDB console.  The accepted answer to that question has a method for enabling this automatically on every run.


text:
Q: Can I highlight code within an answer? (Not syntax highlighting.)
Possible Duplicate:
Allow highlighting certain bits of a code fragment or quote

Sometimes when I respond to a question that contains a block of code, and my answer includes the same block with minor (and sometimes not obvious) changes, I would like to highlight the lines of code that are different to make them stand out.  For example, in a different shade background, or maybe a bold font -- some way for it to visibly stand out from the rest of the code.
Is this possible, or has this been considered before?


text:
Q: Powershell - replace some lines I check a file for lines where a char in a special position is missing. If the char is missing, I insert it in that exact location. Now I want to write that new line with that extra char over the old line into the file. For example I have the following in the file:
"C:\\path\test\test"
"C:\\path\test\test2\"
"C:\\path\test\test3\"

After I run my short script, I want it to look like:
"C:\path\test\test\"
"C:\path\test\test2\"
"C:\path\test\test3\"

I try to accomplish that using this little loop:
$content = Get-Content C:\path\to\file.txt
foreach ($line in $content)
{
    if($line[-25] -ne '\') {
        $test = $line -replace '(?<!\\)(?=.{24}$)', '\' | Set-Content C:\path\to\file.txt
    }
    else {
        continue
    }
}

That code does insert me the char at the correct position. But in the end only line one is in the file, instead of all three lines.
I think I am close, but just started with powershell.

A: Set-Content replaces all the content in a file with the input values. You're calling it independently on each iteration of the loop, when what you really want is to call it with all the results of the loop.
There are many ways to change it, but I would consider replacing foreach with ForEach-Object, and piping the result into Set-Content:
Get-Content C:\path\to\file.txt |
ForEach-Object -Process {
    $line = $_
    if($line[-25] -ne '\') {
        $line -replace '(?<!\\)(?=.{24}$)', '\'
    } else {
        $line
    }
} | Set-Content C:\path\to\file.txt

A: As @briantist points out, you need to move the Set-Content outside the for loop to set the entire file at once.  Inside the for loop, there is no need for character counting, though.  And I find it is better to use the system APIs to work with paths rather than try to write a regex.
Get-Content $inputFileName | Foreach-Object {
  # Strip quotes
  $line = $_ -replace '"',''

  # Add trailing backslash if needed
  $line += '\'

  # Call .NET GetFullPath to normalize. This removes double backslashes
  # and resolves relative paths if needed.
  $line = [System.IO.Path]::GetFullPath($line)

  # Add quotes back, and output string
  '"' + $line + '"'
} | Set-Content $outputFileName

Or, in much condensed form
gc $inputFile | % { [io.path]::GetFullPath((($_+'\') -replace '"','')) } | sc $outputFile


text:
Q: AngularJS 1.4.1 ng-submit not firing after form reset I know there are a few older questions with related topics, but I have not found a satisfactory answer to this, plus those answers seem to be for older versions of Angularjs.
My issue is a form with angular validation and ng-submit does not fire after it has been submitted once, even after the model data has been reset, and the form has been untouched and set to pristine.
After the first submission, the form resets visually as expected and validates properly if used a second time, including activating the submit button when validation passes. Comparing the form code before any submissions and after reset produces identical HTML. Clicking submit brings up the preloader as designed. However the ng-submit action won't fire...
    $scope.resetMediaForm = function() {

        $scope.uploadMedia = {};
        $scope.uploadMedia.from = ''
        $scope.uploadMedia.message = ''
        $scope.uploadMedia.file = null;
        $scope.uploadMedia.fileType = '';
        $scope.uploadMedia.fileName = '';
        $scope.uploadMedia.done = false;
        $scope.uploadMedia.error = '';

        if ($scope.mediaForm) {
            $scope.mediaForm.$setUntouched();
            $scope.mediaForm.$setPristine();
            //$('form[name="'+$scope.mediaForm.$name+'"]')[0].reset();
        }

    };

    $scope.resetMediaForm();

    $scope.uploadMedia.submit = function() {

        var data = {
                from: $scope.uploadMedia.from,
                message: $scope.uploadMedia.message,
                file: $scope.uploadMedia.file,
                fileType: $scope.uploadMedia.fileType,
                fileName: $scope.uploadMedia.fileName
            };

        plotRemoteAPI.postMedia(data, function (data, status) {
            if (status >= 200 && status < 300) {
                if (data.success === true) {
                    $scope.resetMediaForm();
                } else {
                    $scope.uploadMedia.error = data.error;
                }
            } else {
                $scope.uploadMedia.error = status;
            }
        }, function (data, status) {
            $scope.uploadMedia.error = data.error;
        });
    };

Plunkr: http://embed.plnkr.co/zO3lEqa7sfqYDvjHRnqa/preview

A: You are calling $scope.resetMediaData(); in your submit handler which destroys the $scope.uploadMedia object including your submit function (and it doesn't get redeclared). I just moved $scope.uploadMedia = {}; outside the resetMediaData() function.
http://plnkr.co/edit/OhRwsfnx3rX3gXZ2bilc?p=preview


text:
Q: Why Am I getting this erroor : "ERROR Error: Cannot find control with unspecified name attribute" I'm trying to make a reusable input component but I'm getting this error on the console.  "ERROR Error: Cannot find control with unspecified name attribute".
this is my signup class file:
......
 authForm = new FormGroup(
    {
      username: new FormControl(
        '',
        [
          Validators.required,
          Validators.minLength(3),
          Validators.maxLength(20),
          Validators.pattern(/[⌃a-z0-9]+$/),
        ],
   ......

this is my signup template:
<form [formGroup]="authForm" class="ui form">
    <app-input
      label="Username"
      [control]="authForm.get('username')"
    ></app-input>

  .......

this is my input class file:
import { Component, OnInit, Input } from '@angular/core';

import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-input',
  templateUrl: './input.component.html',
  styleUrls: ['./input.component.css'],
})

export class InputComponent implements OnInit {
  @Input() label: string;
  @Input() control: FormControl;
  constructor() {}

.......
And this is my input template file:
<label>{{ label }}</label>
  <input type="text" [formControl]="control" />

A: if you are looking to make a reusable form component, look up Angular ControlValueAccessor. you will need to use this interface to create a reusable form component


text:
Q: Change Google Forms "Rich Text Formatting" by apps script Google added Rich text formatting to Google Forms titles and descriptions last month, but when I use Apps Script to create forms titles, I can't get any changes except "\n".
Would anyone be able to help me?
let questionHeader = form.addSectionHeaderItem();
questionHeader.setTitle("<b>"+question+"</b>\n"+"\b"+question+"\b0"); //test html format and test rtf format

A: UPDATE
As what Ruben has commented, the Google Apps Script is indeed usually behind the web apps as of the moment.
Upon diving into Google's Public Tracker, a Google engineer has stated recently that "At the moment this feature is only supported by the UI version." on a submitted Issue Tracker. This means that you can only add rich text formatting in Google Forms titles and descriptions on the https://docs.google.com/forms web interface.
With that being said, Google Feature Requests for Form API & Google Apps Script have already been internally submitted to address this limitation with rich text formatting.
You may visit these submitted Feature Request public links below:

*

*Google Forms rich text formatting using apps script

*Google Forms rich text formatting using forms API
To automatically get e-mail updates on these feature requests, you may "star" these public trackers:


text:
Q: playframework-2.3 Akka-Async interaction porting? I have some old playframework 2.2 java webservice that interacts with akka, and now I should port them to playframework 2.3.
However, async has been deprecated and even after reading the doc about the async porting (http://www.playframework.com/documentation/2.3.x/JavaAsync) I wasn't able to understand how to apply it to my case (code below):

*

*I must make the await for a timeout/akka server reply before starting the construction of my reply (ok()), otherwise I will block the thread.

*I should make the actorselection async too.

*I should make the akka server reply parsing/reply construction async too
I looked around and I wasn't able to find an example of such interactions, even in typesafe templates.
How could I do that?
/* playframework 2.2 code */

public class Resolve extends Controller {

    private final static String RESOLVER_ACTOR = play.Play.application().configuration().getString("actor.resolve");

    @CorsRest
    @VerboseRest
    @RequireAuthentication
    @BodyParser.Of(BodyParser.Json.class)
    public static Result getJsonTree() {
        JsonNode json = request().body().asJson();

        ProtoBufMessages.ResolveRequest msg;
        ResolveRequestInput input;

        try {
            input = new ResolveRequestInput(json);
        } catch (rest.exceptions.MalformedInputException mie) {
            return badRequest(mie.getMessage());
        }

        msg = ((ProtoBufMessages.ResolveRequest)input.getMessage());

        ActorSelection resolver = Akka.system().actorSelection(RESOLVER_ACTOR);

        Timeout tim = new Timeout(Duration.create(4, "seconds"));

        Future<Object> fut = Patterns.ask(resolver, input.getMessage(), tim);

        return async (
                F.Promise.wrap(fut).map(
                        new F.Function<Object, Result>() {
                            public Result apply(Object response) {
                                ProtoBufMessages.ResolveReply rsp = ((ProtoBufMessages.ResolveReply)response);
                                ResolveOutput output = new ResolveOutput(rsp);
                                return ok(output.getJsonReply());
                            }
                        }
                )
        );
    }
}

A: I came out with the code below
public class Resolve extends Controller {

    private final static String RESOLVER_ACTOR = play.Play.application().configuration().getString("actor.resolve");
    private final static BrainProtoMessages.ResolveReply request_error = BrainProtoMessages.ResolveReply.newBuilder()
        .setReturnCode(BResults.REQUEST_FAILED)
        .build();

    @CorsRest
    @VerboseRest
    @RequireAuthentication
    @BodyParser.Of(BodyParser.Json.class)

public static Result resolve_map() {

    final ResolveRequestInput input;
    final F.Promise<ActorSelection> selected_target;
    final F.Promise<Future<Object>> backend_request;
    final F.Promise<BrainProtoMessages.ResolveReply> backend_reply;
    final F.Promise<ObjectNode> decode_json;
    final F.Promise<Result> ok_result;
    final JsonNode json = request().body().asJson();

    try {
        input = new ResolveRequestInput(json);
    } catch (rest.exceptions.MalformedInputException mie) {
        return badRequest(mie.getMessage());
    }

    selected_target = F.Promise.promise(
      new F.Function0<ActorSelection>() {
          @Override
          public ActorSelection apply() throws Throwable {
              return Akka.system().actorSelection(RESOLVER_ACTOR);
          }
      }
    );

    backend_request =
            selected_target.map(
                    new F.Function<ActorSelection, Future<Object>>() {
                        @Override
                        public Future<Object> apply(ActorSelection actorSelection) throws Throwable {
                            return Patterns.ask(actorSelection, input.getMessage(),new Timeout(Duration.create(4, "seconds")));
                        }
                    }
            );

    backend_reply = backend_request.map(

            new F.Function<Future<Object>, BrainProtoMessages.ResolveReply>() {
                @Override
                public BrainProtoMessages.ResolveReply apply(Future<Object> akka_reply) throws Throwable {
                    try {
                        return (BrainProtoMessages.ResolveReply) Await.result(akka_reply, Duration.create(4, "seconds"));
                    }catch(Exception error)
                    {
                        return request_error;
                    }
                }
            }
    );

    decode_json = backend_reply.map(

            new F.Function<BrainProtoMessages.ResolveReply, ObjectNode>() {
                @Override
                public ObjectNode apply(BrainProtoMessages.ResolveReply response) throws Throwable {
                    return new ResolveOutput(response).getJsonReply();
                }
            }
        );

    ok_result = decode_json.map(
            new F.Function<ObjectNode, Result>() {
                @Override
                public Result apply(ObjectNode reply) {
                    return ok(reply);
                }
            }
    );

    try {
        return ok_result.get(8000);
    }catch(Exception error)
    {
        return internalServerError();
    }

}

}


text:
Q: jQuery $.each() returns only the first element from a Json object I want to populate the contents of #city div dynamically from $.each() function that loops through an Json object (result). How can I get all the elements from the object an put them in the #city div?
What is the best way to create and replace html elements in this situation? (from am each function)
My code:

$.ajax({
        url: "/Home/GetCity",
        type: "GET",
        data: { county: County}
    })
    .done(function (result) {
        $.each(result, function (index, value) {
            console.log(this.CityName); //here it returns all the elements
           $('#city').html("
" + this.CityName+ "
"); //here it return only the first one

       });
    });

A: You are overwritting all the values because you are using "html" jquery function.
I recommend to use append:
$('#city').empty().append("
" + this.CityName+ "
");


text:
Q: getintent().getStringExtra() shows null when pass data First activity Code is below:
 String col1 = c.getString(c.getColumnIndex("name"));
 Intent i = new Intent(Login.this, chat.class);
 i.putExtra("nam",col1.toString());
 startActivity(i);

Second activity Code is below:
 String fName = getIntent().getStringExtra("nam");
 Toast.makeText(this, fName+" Yes", Toast.LENGTH_LONG).show();

it shows null..why?


text:
Q: Using Click event and Dragend event I am wanting to have to event on my pins. one that when the user clicks on a pin a click method is called. A second method would be dragend for when the user drags the pin.
I currently have the following event handlers:
Microsoft.Maps.Events.addHandler(pin, 'click', displayInfobox);
Microsoft.Maps.Events.addHandler(pin, "dragend", endDragHandler);

the problem is that when the user only clicks on the pin, the endDragHandler gets called first and then calls the click method.
Any Suggestions on how to fix this?
Thanks

A: It certainly seems strange that dragend fires before click, but you are right this is indeed the case. The easiest workaround I can think of is this: rather than subscribing to the click event, suscribe to the mousedown event instead:
Microsoft.Maps.Events.addHandler(pin, 'mousedown', displayInfobox);
Microsoft.Maps.Events.addHandler(pin, "dragend", endDragHandler);

mousedown will fire before dragend. So if you can get away with using 'mousedown', I would suggest that you do this.  If you must use click, things might get complicated.

A: The solution I ended up comming up with was to check the current location and see if it was still in the same spot.

A: Although the question has already been answered, I found a solution at this CodeProject link, similar to what @johnston suggested above:
Basically on click event of pushpin, the new and old latitude/longitude is being compared in 3 decimal values. If it matches its assumed its a click event, otherwise its a drag event.
I am though amazed as to why Bing team hasn't looked itself into this weird issue, that took me hours to sort out. Bing API should itself address this issue.


text:
Q: Referral Traffic I run a website that contains links to other partner sites. According to my partners, no traffic comes through the links on my site. As a result, I created an artificial affiliate website myself and actually it was not possible to capture the links that go to the artificial website on my website. I already searched the source code and could not find any meta information like "no-referrer". Does anyone have any idea what else it could be?
Thanks in advance for your ideas!


text:
Q: merge two array if both token value is same I have two arrays
1.
Array
(
    [0] => Array
        (
            [token] => 5217158
            [time] => 234034
            [ltp] => 153.80
            [ltq] => 2
            [total_value] => 129688
        )

    [1] => Array
        (
            [token] => 5217158
            [time] => 234035
            [ltp] => 153.80
            [ltq] => 11
            [total_value] => 129699
        )

    [2] => Array
        (
            [token] => 5216450
            [time] => 234035
            [ltp] => 451.25
            [ltq] => 1
            [total_value] => 9947
        )
)

and 2.
Array
(
    [0] => Array
        (
            [token] => 5216450
            [asd] => 4409
        )

    [1] => Array
        (
            [token] => 5217158
            [asd] => 29950
        )

)

I want to make array final
Array
(
    [0] => Array
        (
            [token] => 5217158
            [time] => 234034
            [ltp] => 153.80
            [ltq] => 2
            [total_value] => 129688
            ['asdf']=> 29950
        )

    [1] => Array
        (
            [token] => 5217158
            [time] => 234035
            [ltp] => 153.80
            [ltq] => 11
            [total_value] => 129699
            ['asdf']=> 29950
        )

    [2] => Array
        (
            [token] => 5216450
            [time] => 234035
            [ltp] => 451.25
            [ltq] => 1
            [total_value] => 9947
            ['asdf']=> 4409

        )
)

if token is same.

A: foreach ($arrayOne as &$array1) {
    foreach ($arrayTwo as $array2) {
        if ($array1['token'] == $array2['token']) {
            $array1 = array_merge($array1, $array2);
        }
    }
}

It can be improved if you elaborate more.


text:
Q: background-position и зафиксированные 50%, 50% Меняю в зависимости от положения мыши свойство background-position блока:
...
var cbgpos = x + 'px,' + y + 'px';
$('#cover').css({'background-position': cbgpos});
...

(x, y вычисляются отдельно)
В итоге получается такая картина:

Не могу понять, откуда взялись 50% и как от них избавиться.
A: var cbgpos = x + 'px ' + y + 'px'; должно без запятой быть


text:
Q: creating and access properties file in spring mvc read this article on SO, and had some clarifying questions.
I put my config.properties under src/main/resources
In spring-servlet.xml config file
I added the following:
<context:property-placeholder location="classpath:config.properties"/>

In my business layer, I am trying to access it via
@Value("${upload.file.path}")
private String uploadFilePath;

Eclipse shows error:
The attribute value is undefined for the annotation type Value

Can i not access the property in the business layer or are property files only read in the controller?
UPDATE::
src/main/java/com.companyname.controllers/homecontroller.java
public String home(Locale locale, Model model) {
    MyServiceObject myObj = new MyServiceObject();
    System.out.println("Property from my service object: = " + myObj.PropertyValue());

    if(myObj.PerformService())
    {
      ///
    }
}

src/main/java/com.companyname.services/MyService.java
public class MyServiceObject {

    @Value("${db.server.ip}")
    private String _dbServerIP;

    public String PropertyValue() {

        return _dbServerIPaseURL;
    }

}

Another site where I found the explanation

A: Please check that you import Value from org.springframework.beans.factory.annotation package:
import org.springframework.beans.factory.annotation.Value;

also the property placeholder must be declared in the respective context configuration file, in case of controller it's likely Spring dispatcher servlet configuration file.
update You are confusing property-placeholder that post processes bean values, that contain dollar symbol ${<property name>} with Spring expression language container extension that process values containing a hash symbol #{<Spring expression language expression>}, in the link you have shown the latter approach is used.
regarding the  instantiation of MyServiceObject myObj
If you want the object to be managed by Spring you should delegate its creation to the container:

*

*if MyServiceObject is a stateless service then it's a singleton with the singleton bean scope, you should register it in your application context, for example with the following xml configuration:
<bean class="my.package.MyServiceObject"/>

and inject it to your controller:
private MyServiceObject myServiceObject;
@Autowired
public void setMyServiceObject(MyServiceObject myServiceObject){
   this.myServiceObject = myServiceObject;
}

*if many instances of MyServiceObject are required, you can declare it as a bean with some other (non-singleton) bean scope (prototype, or request, for example).
However, as there's only one instance of the controller, you can't merely let the Spring container to autowire MyServiceObject instance to the controller field, because there will be only one field and many instances of MyServiceObject class. You can read about the different approaches(for the different bean scopes) for resolving this issue in the respective section of the documentation.

A: Here is a method that allows us to fetch whatever values are needed from a property file.  This can be in Java code (Controller class) or in a JSP.

*

*Create a property file WEB-INF/classes/messageSource.properties It will be in the classpath and accessible in both controllers and JSTL.
Like any property file, this one consists of a key and a value
For example:
hello=Hello JSTL, Hello Contoller
For the Controllers

*

*Locate the xml file that you use to define your Spring beans.  In my case it is named servlet-context.xml.  You may need to determine that by looking in your web.xml in cases where you are using the servlet contextConfigLocation property.

*Add a new Spring bean definition with the id="messageSource". This bean will be loaded at runtime by Spring with the property file key value pairs. Create the bean with the following properties:

*

*bean id="messageSource"

*class = org.springframework.context.support.ReloadableResourceBundleMessageSource

*property name="basename" value="WEB-INF/classes/messageSource

*In the bean definition file for the controller class (testController) add the messageSource as a property.  This will inject the messageSource bean into the controller.

*

*bean id="testController" class="com.app.springhr.TestController"

*beans:property name="messageSource" ref="messageSource"

*In the controller JAVA class, add the messageSource Spring Bean field and its getters and setters. Note the field type is ReloadableResourceBundleMessageSource.
private org.springframework.context.support.ReloadableResourceBundleMessageSource messageSource;
public org.springframework.context.support.ReloadableResourceBundleMessageSource getMessageSource() {
        return messageSource;
    }
public void setMessageSource(
            org.springframework.context.support.ReloadableResourceBundleMessageSource messageSource) {
        this.messageSource = messageSource;
    }

*In your controller code, you can now fetch any known property value from the bundle.
String propValue = getMessageSource().getMessage("hello", objArray, null);
Using JSTL
Since the property file messageSource.properties is in the classpath, JSTL will be able to find it and fetch the value for the given key.

*

*Add the import of the fmt taglib

*

*taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"

*Use the fmt:tag in the JSP to fetch a value from the property file.
Sorry about the pseudo syntax, this editor doesn't seem to render any XML.
fmt:bundle basename="messageSource"
fmt:message key="hello"

*Hope this helps others


text:
Q: How do I get rich quick? I haven't played Terraria in a while and it has changed a lot, so I want to start over again. What should I do to get some good equipment as quick as possible?
I don't need to have the epicest equipment available, but I'd like to be able to roam the world freely, mine where I want, and have some cash.
(I only have a little previous experience with the game. I mostly dug down, found a cave and explored it. Dug even deeper, which took quite a lot of time, found a big cave, died a lot, was too weak, died some more and then moved on to other games.)

A: The fastest way to get what you want is to rush to Eater of Worlds & a set of Demonite equipment.
I've found the fastest way to do that, starting from scratch, is to obtain the following

*

*At least two pieces of silver armor, or better

*A bow & arrows. Copper is good enough but better will make things faster.

*Ironskin potion. This is the key element - it's frankly overpowered.

*Regeneration potion. Not as strong as Ironskin but very easy to craft.

*A stack of Shuriken

Then you kill the Eye of Cthulu, which drops demonite ore. With demonite alone you can only make the axe, bow & sword.
What you really want is the Dryad, who sells purification powder. This lets you dig through ebonstone and smash shadow orbs. Smashing shadow orbs lets you fight the Eater of Worlds and obtain Shadow Scales, along with even more demonite. (Smashing three orbs is faster than farming for worm food.) Before you venture into the corruption chasms, be sure to obtain a hookshot. When you fight Eater of Worlds for the first few times, use an Ironskin potion. I find that grenades slay Eater very quickly, and they're reasonably accessible.
Summoning Eater a few times through orb busting will net you the highest defense armor short of Hellstone; a pickaxe that can mine every pre-hardmode block; a fair quality sword, axe, bow, and hammer; the musket & arms dealer; and some nifty trinkets.
A full set of Demonite gives enough base defense to farm Eye and Eater without buff potions, and pre-hardmode I am aware of no faster way to obtain coin than farming these bosses & selling their drops. You will also activate the goblin invasion, which you must defeat once for the tinker and mechanic.
In some worlds, the crimson replaces the corruption, which also replaces ebonstone with crimstone, demonite with crimtane, and the Eater of Worlds with Cthulu's Brain. None of these substitutions breaks the overall strategy.

A: Normally I sell my items for money. You should gather tons of life crystals. 1 life crystal is worth 1 gold and 40 silver coins. I got at least 76 gold coins.
BTW, this works for iOS/android, console, and PC. I tried it on all versions just to make sure.

A: When you first start, it should be day. Run along the top of the world to gather wood and kill some slimes. You'll want torches for mining at night. Don't venture down into caves, because you'll want to know when night starts, and it's nice to start your mining near the guide/spawn in case you die (it will happen). As soon as night is near, get back and start mining. Remember that you can build dirt walls behind you while mining to prevent monsters from getting to you.
Caves are dangerous. You can be attacked from all sides, and monsters can spawn just about anywhere off screen. Mining by itself isn't very dangerous, but without caves, isn't a great way to get money. However, you don't need money to get good stuff. Mining iron and silver is a great way to get some decent armor and weapons in the beginning.
If you see treasure chests, jars, or heart containers, mine out to them. Don't be afraid to build dirt walls around you to make gathering loot safe. Make sure you carry a hammer. Remember the 'H' key (you'll find lesser healing potions in those jars, but make sure they come in front of any mushrooms you picked at the surface). Hammering empty chests will allow you to store extra loot and materials near spawn. After a couple day/night cycles, you should have enough materials to build a house for your guide and have decent enough equipment to be a little more reckless. You don't need to house the guide before then (if you find it a matter of honor to house the guide by the first night, you may do so).
For my current character (I restart from scratch every release), I upgraded to a gold pick before I upgraded my initial sword. I skipped gathering copper unless it was near silver/gold/iron. Digging fast made everything easier. Then the money and other loot was relatively easy to acquire.
Frustration tip: avoid playing on a server with lag. I started a game with a friend and had many initial deaths to teleporting demon eyes. I could see someone rage-quitting the game if that was their first time playing.

A: What we always end up doing is just exploring starting caves and trying to gather Iron and Wood. Once we had plenty of that, we'd go to the Jungle area and dig into the underground area, build a house with a bed, and just use that as a base of operations; all of the Jungle stuff is decent and a Blade of Grass is one of the easiest mid-tier weapons to get, and the enemies there are (while powerful) a good source of money. You'll need to go down there to get an Ivy Whip at some point anyway, so why not make it early? Bonus points for putting your house on the edge of the underground jungle so you can go through non-Jungle caves at the same time.
The biggest problem with a explore-the-main-caves approach is that the common mobs are pretty cheap and the best you'll be finding is just ore and gems, which you can find in the Jungle anyway.

A: I think the best solution in the early game is to explore your starting biome and search for shallow caves that contain treasure.  You'll likely find a boomerang early, which can be useful as a ranged and indirect fire weapon early in the game.
Once you've come across a few chests and have a bit of gear/weapons, start digging a shaft.  Explore caves and fight enemies, which will probably yield some amount of cash plus opportunities to mine ores you can use to forge better equipment.  Better equipment will allow you to dig deeper and/or explore some of the neighboring biomes, which will yield opportunities for even better gear.
Money's not super important as most of the gear in the game can be crafted or found as treasure.  You will need to purchase items from time to time, so make sure that you occasionally make time to satisfy the conditions for NPCs to arrive.
Lather, rinse, and repeat until you're epic and difficult to kill, and then you can tackle some of the more exciting boss fights and deepest regions of the world.  If you're at a loss as to what to do next, or how to craft some of the higher level gear, go dig around a bit at one of the Terraria Wiki sites, which contain info about all sorts of interesting artifacts.
Death is relatively cheap, as long as you leave as much of your money as possible at home.  Don't be afraid to go and explore something new, you might luck out and find a valuable artifact.  The worst case scenario is that you end up a tasty snack for something big and nasty, and maybe lose a few coins.
The goal of this game varies depending on what your goal is, so don't be afraid to do something risky or try something new if you're having fun!  If the game is getting frustrating, try exploring more closer to the surface, or looking up a strategy for dealing with the particular situation you're stuck on.

A: A good way to become rich in Terraria is to sell golden chests - which are quite rare. BUT, you can duplicate them.
How To Do It:

*

*Find a golden chest.

*Defeat Skeletron which will allow access to the dungeon. If you go far enough into the dungeon you will find the Mechanic. Build a house for her. I make mine 6 blocks tall and 10 blocks wide. Make sure it has wooden or stone background wall with a torch, chair, and table.

*Buy wire from the Mechanic. Don't forget to buy the wrench for placing wire and the wire cutter for removing it. You also need a lever.

*Collect two stone blocks.

*Craft two active stone block. To craft them you will need one stone and one wire.

*Place the active stone blocks,then mine the blocks under the active stone.

*Place a golden chest on top of the active stone.

*Place a lever right beside the active stone blocks.

*Use the wrench to place the wire. Connect the lever and active stone blocks using wire.

*Put something in the chest.

FINAL: Constantly flick the lever.

A: In my experience, the longest part of the game is the first part, before you go corruption/crimson diving. Going underground and looking for silver and gold can take a long time!
So to get past this part quickly and get into the faster progression of the game, I suggest something a little opposite of what you asked: Instead of trying to get the best equipment you can before going into the corruption or crimson, settle somewhat early for moderately good equipment. Once you have mostly silver equipment with a little bit of gold, you should be strong enough to defeat the Eye of Cuthulu and proceed to the next portion of the game. Once you have crimson or corruption-class items, you'll be back on the high end of equipment for how far you are in the game and stay that way until you enter hardmode.

A: Glitch to create any item you want (Console)
Item Generating Glitch Steps:

*

*Backup your save.

*Disconnect your console from the internet and set the date to Oct 25.

*Turn off autosave.

*Purchase X (however many items you want) copies of Dryad Loincloth from the Dryad.

*Empty out your safe or piggy bank (either, I will say safe to save words).

*Put the loincloths in the safe.

*Save from the menu and then return to the main menu without saving.

*Inside your safe will now be stacks of 1854 iron pickaxes.

*Remove the number of pickaxes necessary to reach the item you want from this list
http://terraria.wikia.com/wiki/Data_IDs
e.g. If I wanted a stake launcher (data id 1835) I would remove 19 picks and throw them into the trash.

*Repeat step 7.

*You will now find the items you wanted to create inside of your safe.

If you want something with an item id higher than 1854 then you will need to look through the list to find something easily obtainable that has such an id and then use that item instead of the loincloth. The number of iron pickaxes corresponds with the data id of the item you placed in the safe.

A: I would suggest beating the Eye of Cthulhu boss; it not only gives you Demonite Ore, but it also gives gold coins. I got 4 coins from it once.


text:
Q: check if current url/page equals checkout page I try to hide the "cash on pickup"-payment-gateway [cop] when I am on the checkout page of my woocommerce installation. When I echo the code it gets two times executed.
One time correctly,
the other time it truncates the end of the url:
functions.php
// Disable gateway on checkout page
function payment_gateway_disable_cash_on_delivery_on_checkout( $available_gateways ) {

    global $woocommerce;
    global $wp;

    // Helper
    echo(" || get_page_link: ");
    echo(get_page_link());
    echo(" || wp->request: ");
    echo(home_url( $wp->request));
    echo(" || get_checkout_url: ");
    echo($woocommerce->cart->get_checkout_url());
    echo(" || end. ");

    if ( isset( $available_gateways['cop'] ) && (get_page_link() == $woocommerce->cart->get_checkout_url())) {
        unset(  $available_gateways['cop'] );
    }
    return $available_gateways;
}

add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_cash_on_delivery_on_checkout' );

Output on the checkout page
  || get_page_link: https://mypage.com/en/checkout/
  || wp->request: https://mypage.com/en/checkout/
  || get_checkout_url: https://mypage.com/en/checkout/ || end.
  || get_page_link: https://mypage.com/en/
  || wp->request: https://mypage.com/en/
  || get_checkout_url: https://mypage.com/en/checkout/ || end.

The
Why this happens, or how to solve that?
Here a screenshot:

A: To answer the question in this posts's title, you don't need to check for the page's URL to see if you're on the checkout page as Woocommerce has a conditional for that - is_checkout()

A: This is my solution:
I had to disable the woocommerce checkout ajax script. It's causing a reload and adds some parameters which changes the url. This causes the fail of my equal.
/* hide payment method "cash on delivery on cart view (it should only available in POS) */

// Disable gateway on checkout page
function payment_gateway_disable_cash_on_delivery_on_checkout( $available_gateways ) {

    global $woocommerce;

    // we need to dequeue the checkout script, otherwise the ajax call will change our url and the cop option is shown
    wp_dequeue_script( 'wc-checkout' );

    if ( isset( $available_gateways['cop'] ) && (get_page_link() == $woocommerce->cart->get_checkout_url())) {
        unset(  $available_gateways['cop'] );
    }

    return $available_gateways;
}

add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_cash_on_delivery_on_checkout' );


text:
Q: Linq statement crashing (no exception) on 2nd method call instantiate object I have a method which instantiates an object, some of the properties of this object are arrays where i use linq to fetch the data.
private static GrowthYieldStructure CreateGrowthYieldStructure(int timberType, IEnumerable<Tree> trees)
    {
        var trees1 = trees;

        return new GrowthYieldStructure
                   {
                       TimberType = timberType,

                       CurrentDbhList = trees1.Select(x => x.DBH).ToArray(),
                       CurrentSpeciesList = trees1.Select(x => x.SpeciesNumber).ToArray(),
                       CurrentTpaList = trees1.Select(x => x.TPA).ToArray(),
                       CurrentTreeListLength = trees1.Count()

                   };
    }

The first time I call this method it works fine.
The second time it will fail with no exception on the second select statement.
-no matter which value its attempting to select
For instance, trees1.Select(x => x.DBH).ToArray() works, trees1.Select(x => x.SpeciesNumber).ToArray() crashes.
(I've tried switching the fetching order / making local variable copies / I've checked that values exist and they do, nothing out of the ordinary / using try/catch (no exp caught))
Edit:
I made more local variables to store the IEnumerable; still fails
If I only have one select statement it will run fine...
--
Edit2: (calling code - could be off going from memory)
stands,plots,trees are all IEnumerable (T being Stand,Plot,Tree)
foreach (var plot in plots.Where(x => x.StandID.Equals(stands.ID))) {
  var plot1 = plot;
  var treeList = trees.Where(x => x.PlotID.Equals(plot1.ID));
  var growthYieldStructure = CreateGrowthYieldStructure(stands.TimberType, treeList); }

Edit3:
Finally saw this error:
A first chance exception of type 'System.AccessViolationException' occurred in Unknown Module.
Then finally realized my error-
It was actually the code using after the object creation.
I was using arrays to send to a external library since arrays are reference types this worked out they way I suspected.
But since I was not copying the arrays and instead creating a new local variable which would have the same memory reference.
This caused the next object init to fail since it wanted to write in the same memory loc..
I just changed the object to use IEnumerable this way i can have the array reference once.
Sorry for the confusion.
Any thoughts to why it is crashing?

A: It might be do to the IEnumerable being an IQueryable and it is trying to enumerate more than once.
Try changing the line:
var trees1 = trees;

to
var trees1 = trees.ToList();

that will force the enumeration and trees1 will be a List instead of the possible IQueryable


text:
Q: toc in a github_document I am trying to add a table of contents to my rmd github_document, however I cannot get this to work. I am on R version 3.5.2 and following the documentation I have:
---
title: "test"
output:
  github_document:
    toc: true
---

# header 1
# header 2
# header 3

but the toc does not appear in the md:


text:
Q: Optimizing AWS spending without having access to account billing info I would like to know if it is possible to evaluate and optimize AWS spending (specifically, EC2 spending) without having access to account billing info?
Long story short, we do not have the ability to view account billing dashboards / metrics due to a company policy. (Such a permission would allow us to see other billing metrics that are sensitive).
However, I can get a monthly snapshot of our AWS bill, with a breakdown for each service.
I know that our EC2 spending is very high. But without having the ability to drill into this data to get more insights, how do I optimize? I have some theories on where most of our spending is coming from (EMR/spark compute nodes), but I can't know for sure unless I can measure it.
Is there a way for me to get compute hours usage for EC2, without going through billing dashboards / APIs? I imagine if I can get the total hours for a machine, and multiply it by the hourly rate, I should be able to generate a cost estimate myself?
RE: close vote:
I think this is not off topic. I am asking for a way to programmatically measure the compute hours for AWS virtual machines (EC2). This seems to be in scope for stackoverflow.

A: One suggestion, that I do not know if fits your company policy, is:

*

*Enable to generate a billing Detailes Billing CSV in an S3 Bucket with restricted access (https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-getting-started.html)

*Create a Lambda Function that runs when the CSV is updated and process the CSV to filter only the data you should have access (https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html)

*Save a new CSV with only the allowed information in a new S3 Bucket with more access allowed.

Hope this approach makes sense in your company policies. If it does, I can give more details on how to setup.

A: As a starting point, you could use AWS CloudWatch and check the metrics usage for each of your EC2 instances (such as CPU usage, memory, and so on...). This gives you a first overview of how your EC2 are using their resources. You can start adjusting from there.
Also there are basic steps to already save money with EC2 (i.e. using Reserved instances).
Then if your company don't give you direct access to aws billing through the console (I know the pain :/ I've experienced the same), then I really would suggest to build a website or whatever lambda function, give it's role access to aws cost explorer and use the API to retrieve billing data.
Here is a good benefit for that: using the API you can order by different values compared to the AWS console where you can just order by one single property. This way you can generate for instance a report per service but per environment too. I did that for my company splitting per stack but also per environment (DEV/TEST/PROD). This way I can generate a precise billing per month or "on the fly" for the current month up to current date (I can attach a screenshot later -> I have no access to it atm).
A review of your code will ensure the security officer or whoever is in charge that you only access your billing data.


text:
Q: Get sum of all the records before certain record in mongodb So I have something like this in my database:
{ "_id" : ObjectId("561c2ca2153678d113d03077"), "title" : "Level 8", "rewardCoins" : NumberLong(25)}
{ "_id" : ObjectId("5615980b153678d113d02d61"), "title" : "Level 9", "rewardCoins" : NumberLong(40)}
{ "_id" : ObjectId("56159796153678d113d02d60"), "title" : "Level 10", "rewardCoins" : NumberLong(55)}
{ "_id" : ObjectId("5613f5ad153678d113d01f4a"), "title" : "Level 11", "rewardCoins" : NumberLong(70)}

So I would like to get sum of all rewardCoins under "Level 11"
That total should be 55+40+25 = 120
I'm wondering how can I get this with mongo shell ?
I was trying something like:
db.userlevels.aggregate([
    {
        $match: {
        "title": {$lt: "Level 11"}
        },
    },
    {
        $group: {
            "_id": {"name": "Level 11"},
            "totalAmount": { $sum: "$rewardCoins"}
        }
    }
])

But I'm not getting what I'am expecting...
Hint or solution would be really appreciated. Thanks.

A: Consider introducing additional numeric field just to store level:
{ "_id" : ObjectId("561c2ca2153678d113d03077"), "title" : "Level 8", "rewardCoins" : NumberLong(25), level: 8}
{ "_id" : ObjectId("5615980b153678d113d02d61"), "title" : "Level 9", "rewardCoins" : NumberLong(40), level: 9}
{ "_id" : ObjectId("56159796153678d113d02d60"), "title" : "Level 10", "rewardCoins" : NumberLong(55), level: 10}
{ "_id" : ObjectId("5613f5ad153678d113d01f4a"), "title" : "Level 11", "rewardCoins" : NumberLong(70), level: 11}

Having it as a part of title and then comparing strings is a bit strange. Then this aggregation query should do the job:
db.userlevels.aggregate([{$match: {"level": {$lt: 11}}}, {$group: {"_id": null, "totalAmount": { $sum: "$rewardCoins"}}}])


text:
Q: Default location where docker images are saved on Windows 10 I installed docker on Windows 10 Pro and created/pulled several images some as big as 953 MB.
I'm however interested to know in what directory are all the images stored.
I checked Hyper-V manager for Virtual Hard Disks and Virtual Machines directories but they are not more than 500 KBs
Below is the snapshot of the same.

My docker was installed with default settings.
After reading some forums I also checked the following directories like C:\ProgramData\Docker and C:\Users\Public\Documents\Hyper-V but they are 0 bytes in size.
I'm using Windows 10 Pro
I did inspect an image but it does not contain any data indicating the image file on Windows. See below:
C:\Users\HOME>docker image inspect myfirstcont

"GraphDriver": {
    "Data": {
        "LowerDir": "/var/lib/docker/overlay2/rtdgjoc6gg00v0l0h381fy4gw/diff:/var/lib/docker/overlay2/squ8lhqlwajh2yv1ecc9yltaj/diff:/var/lib/docker/overlay2/819dca1c2bb7ce54c13c0c7421e5804538a9605b4daf0f8ab52a47024cb96d29/diff:/var/lib/docker/overlay2/12c27601a0dc2397cf87405d2ece5757d5f6d45e1c38e1c58cef4de1964ea04f/diff:/var/lib/docker/overlay2/d0862b28727db9ac5a3fed6eb3caad3968b8824919c4b5de742a25ca89b7b1dd/diff:/var/lib/docker/overlay2/c82c5574cb3aac2600976a38093c98e575c6d3e32aee7b9e548dc4f8ed3678b9/diff:/var/lib/docker/overlay2/5461792a7a73055859f45c624450a4d06f212e4437d9d1f81a012a2fa932a620/diff:/var/lib/docker/overlay2/f130395cf64a6182fdb6bd8f18e4a64f5763856464cded60f01214b8d695e56c/diff:/var/lib/docker/overlay2/a122314ee57fd42eb80b9d367cc579402afd36d0484579b97b0074d692cb0ec2/diff:/var/lib/docker/overlay2/e2c0039edd02283fce0f7e7a3f3bd798d2597b7c26ad85280db804d83697d238/diff:/var/lib/docker/overlay2/0bf984e8907a11ac4f000f1d7909f61dd6aac497517c6fb2a6947cf683ad3993/diff",
        "MergedDir": "/var/lib/docker/overlay2/lv5akhtcyzkioljls2bfolgdu/merged",
        "UpperDir": "/var/lib/docker/overlay2/lv5akhtcyzkioljls2bfolgdu/diff",
        "WorkDir": "/var/lib/docker/overlay2/lv5akhtcyzkioljls2bfolgdu/work"
    },
    "Name": "overlay2"
},

Can you please suggest where can I find the image files for all the docker images I pulled?

A: When using WSL2 with Docker Desktop, a new distro is created called docker-desktop-data, which is also where all your image layers are stored. You can find all your layers under \\wsl$\docker-desktop-data\version-pack-data\community\docker\overlay2.
You will have to docker image inspect <image_id> and look for GraphDriver.Data to find which directories are related to your docker images.


text:
Q: Android intent image How can I open a image with another app like the gallery ?
so which intent do I have to call ?
Intent in=new Intent("intent?");
         startActivity(in);

A: This will create an Intent for Android to show a image/png.
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(path)), "image/png");
startActivity(intent);

Just make sure the file is in a place visible to all, not in your private sandbox.  Saving it to sdcard in the data folder is common eg. /sdcard/data/appname/filename.png

A: use this
       intent.setData(android.Provider.MediaStore.Images.Media.Data);


text:
Q: SqlAlchemy - make a query where Relationship Attribute is a list I have two models:
class Profile(Base):
    __tablename__ = 'profiles'

    id = Column(Integer, primary_key=True)
    ...

    stagesP_list = relationship(
        'StageP',
        back_populates='profiles_list',
        secondary=stageP_profile
        )

class Project(Base):
    __tablename__ = 'projects'

    id = Column(Integer, primary_key=True)
    ...

    stagesP_list = relationship(
        'StageP',
        back_populates='projects_list',
        secondary=stageP_project
        )

I need to select Profiles for which at least one value of the Profile.stagesP_list is contained in the project.stagesP_list.
Please help to compose the query or indicate the direction in which to search.

A: If you have project instance loaded, you can compose the following query:
project = ...
stageP_ids = [obj.id for obj in project.stagesP_list]

query = session.query(Profile).filter(
    Profile.stagesP_list.any(StageP.id.in_(stageP_ids))
)

You can also perform joins on the database directly from having only project_id:
query = (
    session.query(Profile)
    .join(StageP, Profile.stagesP_list)
    .join(Project, StageP.projects_list)
    .where(Project.id == project_id)
    .distinct()
)


text:
Q: tranwrd doesn't replace correctly and truncate target string I'm replacing the target string which is '01 -DIC-17 ' with  '01 \ 12 \ 17', then convert it to sas date with the input function, but output is '01 \ 12 \ '. truncate  the '\ 17'.
The DATA SAS is:
data test;
input issueDate $10. lastDate $10.;
datalines;
05-DIC-16 04-ENE-17
05-DIC-16 04-ENE-17
05-DIC-16 04-ENE-17
05-DIC-16 20-ENE-17
05-DIC-16 20-ENE-17
05-DIC-16 04-ENE-17
05-DIC-16 20-ENE-17
05-DIC-16 04-ENE-17
05-DIC-16 20-ENE-17
;
run;

I have an adjust month table:
DATA ADJUST_MONTH;
INPUT TARGET $ REPLACEMENT $;
DATALINES;
-ENE- /01/
-FEB- /02/
-MAR- /03/
-ABR- /04/
-MAY- /05/
-JUN- /06/
-JUL- /07/
-AGO- /08/
-SEP- /09/
-OCT- /10/
-NOV- /11/
-DIC- /12/
;
RUN;

Run the code:
 proc sql;
 update test
 set issueDate = TRANWRD(issueDate,substr(issueDate,3,5),(select replacement from adjust_month where target eq substr(issueDate,3,5)));quit;

The output: IssueDate: '05-DIC-16' convert en IssueDate: '05/12/'
Thanks for help me.

A: Your replacement column contains trailing blanks. Trim or similar functions will help you. For example, replace the nested select by trim((select replacement from adjust_month where target eq substr(issueDate,3,5))),

A: There's no need to do all the transformations in your code.  You can use the relevant language date informat to read the data directly.  In your case it is in Spanish, so the espdfde9. informat will read the source data as a date (using the input function), then you can do with it as you please.
I would create extra columns to store these dates, rather than update the exisitng columns, for the reason that dates are generally better stored as numbers instead of character.  But it's your choice.
To use this informat, your SAS installation has to have European character sets and encoding loaded.
data test;
input issueDate $10. lastDate $10.;
datalines;
05-DIC-16 04-ENE-17
05-DIC-16 04-ENE-17
05-DIC-16 04-ENE-17
05-DIC-16 20-ENE-17
05-DIC-16 20-ENE-17
05-DIC-16 04-ENE-17
05-DIC-16 20-ENE-17
05-DIC-16 04-ENE-17
05-DIC-16 20-ENE-17
;
run;

data want;
set test;
issuedate_new = input(issuedate, espdfde9.);
lastdate_new = input(lastdate, espdfde9.);
format issuedate_new lastdate_new date9.;
run;


text:
Q: User input to break while loop to return to the main So, I need to break the loop with the user input if it was C, but it does not break the loop and return to the main.
It sticks to the same loop.
void createFile(void)
{
    FILE *NewFile;
    char *file_name = malloc(sizeof(*file_name));
    printf("\nEnter a name of the file you want to create:\n");
    scanf("%s",file_name);

    while(access(file_name, 0) != -1)//in case the file exists
        {
        printf("\n%s file already exists\nplease re_enter your file name or C to go back to the main menu.\n\n", file_name);
        scanf("%s", file_name);
        if ( file_name == 'C')
        {
            return;// returning to the main menu
        }
        }
    if(access(file_name, 0) == -1)//if it does not exist
    {
        NewFile = fopen(file_name,"w+");
        fclose(NewFile);
        printf("\nFile has been created successfully! :D\n\nPlease enter R to return to the main menu ");
        scanf("%s",file_name);
        if (file_name == 'R')
        {
            return;
        }
    }
    remove("C"); // just in case unwanted C file is created.
    remove("R");
}

A: file_name is a pointer to a character. (It's actually a pointer to the first character of a NUL-terminated sequence of characters, but it is still a pointer to a character.) That's evident from the declaration:
char *file_name;

On the other hand, 'C' is an integer. Most likely, it is the integer 67, which is the ascii code for the letter C.
So you are comparing a pointer -- that is, an address -- with an integer.
In C that's actually legal, but it is only meaningful if the integer you are comparing the pointer with is 0. So your compiler should warn you about this.
The end result is that the comparison file_name == 'C' is evaluating to 0 (false).
What you intended to do was to compare the string pointed to by file_name with the string literal "C", which you would do as follows:
if (strcmp(file_name, "C") == 0))

strcmp is a standard library function which compares two character strings (given pointers to their respective initial characters) and returns a negative integer if the first one comes first (alphabetically), a positive integer if the second one comes first, and 0 if the two strings are equal.


text:
Q: Save file (can be jpg,css,js...) with cURL to my server and keep directory structure To make it simple:

*

*I have an image file ex: https://www.example.com/a/b/c/image.jpg

*I want to use curl to download and save the image on my server but I want to keep the directory structure, so I want to save the file on my server to a/b/c/image.jpg , so the directories must also be created if they do not exist already

*If the file already exist to not download

Hope someone with more experience can help because I have tried 2 days on this an nothing.
For now I only have the CURL function that is working good:
    $curl = curl_init();
    curl_setopt( $curl, CURLOPT_URL, $urltoget );
    curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 0 );
    curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, 0 );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
    $tempsavefile = curl_exec( $curl );
    curl_close( $curl );


text:
Q: How to set color to some portion of text in radio.setLabel("Phone Number"+cont.getPhone); I am using Zk framework for UI and from Controller side i need to set the value for the radio.Have a look on below code
radio.setLabel("Phone Number#"+""+cont.getPhone().toString() +""+"Email Id"+cont.getEmail());

but it is not replacing the color,only color of phone number should be replaced

A: Try below line of code
If you want to do in ZUl page try this
 <radio id="radiog" label="Item D" value="itemD" style="color:blue;"/>

otherwise try
radio.setStyle("color:blue;");//Their can be syntax error please modify it according to your requirement.

A: Take a look at my fiddle. I separate your radio in 3 components: 1 radio and 2 labels, all inside 1 div. This is the only simple way I can think of
Fiddle
Code
<zk>
  <window border="normal" title="hello">

          <radio id="radio" value="itemD" />

  </window>
</zk>

A: I doubt ZK allows use of HTML code inside the radiobutton label.
I suggest breaking it into smaller pieces like @AlexGreg answer shows, you can even consider using spans or try a CSS approach like the one suggested in https://stackoverflow.com/a/4622818/1385048.

A: You can override the client widget's implementation domLabel_() function  as follows:
<radio xmlns:w="client">
    <attribute name="onCreate"><![CDATA[
    self.setLabel("test");
    ]]></attribute>
    <attribute w:name="domLabel_">
    function () { return this.getLabel(); }
    </attribute>
</radio>

A: i acheived this through a piece of code.
first create Outer Hlayout then radio button then inner hlayout
created two label's & then set css seperatly
set that lable to inner hlayout,
inner hlayout to radio
and radio to outerlayout.


text:
Q: groupPadding for stacking series in Highcharts In short, I need to somehow enable groupPadding for stacked series. It looks a little bit odd, but this is what you can do in PowerPoint if you set series overlap to 0:
With series overlap set to 100, they would be on top of each other like in Highcharts with stacking set to e.g. normal.
To me, it seems you are not allowed to move stacking columns horizontally relative to each other in Highcharts. But maybe I am missing something or there is a workaround?
Thanks!

A: You can create an additional hidden series with the same stack as the upper series. Example:
Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    plotOptions: {
        column: {
            stacking: 'normal',
            pointPadding: 0,
            dataLabels: {
                enabled: true,
                format: '{point.y}%'
            }
        }
    },
    series: [{
        data: data2,
        color: 'gray'
    }, {
        data: data1,
        color: 'rgba(0,0,0,0)',
        linkedTo: 'data1',
        dataLabels: {
            enabled: false
        }
    }, {
        id: 'data1',
        data: data1,
        stack: 'A',
        color: 'green'
    }]
});

Live demo: http://jsfiddle.net/BlackLabel/rkvs8cy7/
API Reference: https://api.highcharts.com/highcharts/series.column.stack


text:
Q: Jenkins release issue with jgit We are using jgit for the git project to checkout and complete the jenkins flow. It passes the snapshot build but fails for release build with the below error :
Building on master in workspace /home/jenkins2/jenkins/jobs/Git-end_to_end_4.0/workspace
Fetching changes from the remote Git repository
Checking out Revision 302b3bc2190db18b4661407ec67918e4f8ca65fc (refs/remotes/lighthouse/master)
Property '-Dm3plugin.lib' is already part of MAVEN_OPTS. This is usually a leftover of previous build which was forcibly stopped. Replacing the value with an updated one. Please remove it from the job configuration.
[RELEASE] Release build triggered
 > jgit rev-parse --verify HEAD # timeout=10
ERROR: Failed to parse POMs
java.io.IOException: Failed retrieving current commit hash: Error performing command: jgit rev-parse --verify HEAD
    at org.jfrog.hudson.release.scm.git.GitManager$CurrentCommitCallable.invoke(GitManager.java:194)
    at org.jfrog.hudson.release.scm.git.GitManager$CurrentCommitCallable.invoke(GitManager.java:168)
    at hudson.FilePath.act(FilePath.java:914)
    at hudson.FilePath.act(FilePath.java:887)
    at org.jfrog.hudson.release.scm.git.GitManager.getCurrentCommitHash(GitManager.java:52)
    at org.jfrog.hudson.release.scm.git.GitCoordinator.prepare(GitCoordinator.java:74)
    at org.jfrog.hudson.release.maven.MavenReleaseWrapper.setUp(MavenReleaseWrapper.java:131)
    at hudson.maven.MavenModuleSetBuild$MavenModuleSetBuildExecution.doRun(MavenModuleSetBuild.java:643)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:585)
    at hudson.model.Run.execute(Run.java:1676)
    at hudson.maven.MavenModuleSetBuild.run(MavenModuleSetBuild.java:519)
    at hudson.model.ResourceController.execute(ResourceController.java:88)
    at hudson.model.Executor.run(Executor.java:231)

For reference , below are my version details :
Jenkins version : Jenkins ver. 1.554
Git client plugin : 1.17.1
Git plugin : 2.4.0
I have visited couple of pages in and out of stackoverflow , but did not get the proper response. Will appreciate any further suggestion.

*

*https://git-scm.com/book/en/v2/Embedding-Git-in-your-Applications-JGit

*Determine Tracking Branch in JGit

*Is there a JGit method equivalent to git rev-parse --short?

*What does git rev-parse do?

A: From your console output it is clear that your Jgit is unable to fetch the SHA of the latest commit from the cloned repository present in you workspace.
The latest commit Hash is required to Parse the pom file for release build.
One reason (not likely but still if u r using pretty old Jgit) might be that the Jgit version you have configured in your Jenkins doesn't support the command to retrieve SHA of current commit ((as Jgit is still in  development phase and not yet a complete replacement for git-cli and that's why jenkins git-client plugin uses git-cli by default and not Jgit even though the latter comes with it's own set of advantages... For more info pls refer Jgit official docs))
Second cause (most probable) can be that you are not using the right combination of git plugin version, git-client plugin version and Jenkins version. All major DevOps tools are equally famous for plugin related issues as they are for the purpose they serve. And trust me... at times it becomes a nightmare for a DevOps engineer to resolve plugin issue.
Anyways it would be great if you could provide the version of plugins and tools you are using  (as they form to be part of critical piece of information which might come handy in resolving d issue.. Moreover your question might get downvoted by SO community members if your question lacks in availability of such important details)
For your reference:- I have been using Jgit in my Jenkins 1.596.2,  with git-client plugin 1.18.0,  git plugin 2.4.0. and it works as smooth as silk for both snapshot as well as release build..
Hope this helps.. :)

A: After so many days of head scratch, and even after putting the bounty, i did not get the proper help for Jgit .
I changed from Jgit to GIT plugin and it resolved my problem.


text:
Q: Error loading class: Bad major version number I'm trying to compile this java file manually (for learning purposes):
public class Test {
    public static void main(String[] args) {
        System.out.println("Hello world");
    }
}

So I saved file and run:
C:\Users\maikon.neitzel\Documents\Java>javac Test.java

No errors.
Next step:
C:\Users\maikon.neitzel\Documents\Java>java Test
Error loading class Test: Bad major version number

So I did my research and found things about the PATH.
So I did it:
This are the variable for my user:
JAVA_HOME: C:\Program Files\Java\jdk1.8.0_102

PATH: %JAVA_HOME%\bin

JRE_HOME: C:\Program Files\Java\jre1.8.0_102

And there is another PATH for the system where I put the same:
%JAVA_HOME%\bin

This is on Windows 10, and with the last java 8 version.
Versions:
C:\Users\maikon.neitzel\Documents\Java>javac -version
javac 1.8.0_102

C:\Users\maikon.neitzel\Documents\Java>java -version
java version "1.1.8.16"

From where this java 1.1.8.16 is coming?
Thanks a lot!

A: Solved. I found a c:\orant\jdk\bin AFTER %JAVA_HOME% at system variables. So I figured I needed %JAVA_HOME% defined not only for my user, but at system variables too.


text:
Q: How to login using Facebook account? I have been through this link and tried the code.
I am doing the same thing but there is no response coming from Facebook. No popup (not blocked). My code is given below:

Please tell me what I am doing wrong. I yea, I have not any checkbox in

Select how your app integrates with Facebook.

during creating Facebook app. If I have to define url so what I have given?

A:

In Body , use :-

    <fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
  </fb:login-button>

A: <!DOCTYPE html>

     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <title></title>
     <link rel="stylesheet" type="text/css" href="">

<button onclick="login()">login</button>
<button onclick="logout()">logout</button>

A: Use this code or follow https://github.com/radhey113/facebook_login/blob/master/index1.html
window.fbAsyncInit = function() {
        FB.init({
          appId      : '1557876490891744',
          appSecret  :  '302f28b9110351071840458316ce232f',
          xfbml      : true,
          version    : 'v2.5'
        });
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                document.getElementById('status').innerHTML = 'We are connected.';
                document.getElementById('login').style.visibility = 'hidden';
            } else if (response.status === 'not_authorized') {
                document.getElementById('status').innerHTML = 'We are not logged in.'
            } else {
                document.getElementById('status').innerHTML = 'You are not logged into Facebook.';
            }
        });
    };
    (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {return;}
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
    // login with facebook with extened publish_actions permission
    function login() {
        FB.login(function(response) {
            console.log(response);
            if (response.status === 'connected') {
                document.getElementById('status').innerHTML = 'We are connected.';
                document.getElementById('login').style.visibility = 'hidden';
            } else if (response.status === 'not_authorized') {
                document.getElementById('status').innerHTML = 'We are not logged in.'
            } else {
                document.getElementById('status').innerHTML = 'You are not logged into Facebook.';
            }
        }, {scope: 'publish_actions'});
    }
    // getting basic user info
    function getInfo() {
        FB.api('/me', 'GET', {fields: 'first_name,last_name,name,id'}, function(response) {
            document.getElementById('status').innerHTML = response.id;
        });
    }
    // uploading photo on user timeline
    function uploadPhoto() {
        FB.api('/me/feed', 'post', {source: 'http://lh3.googleusercontent.com/nYhPnY2I-e9rpqnid9u9aAODz4C04OycEGxqHG5vxFnA35OGmLMrrUmhM9eaHKJ7liB-=w300', message : "SHOWDOWN POST",link:'http://54.175.71.74:3000'}, function(response) {
            if (!response || response.error) {
                console.log(JSON.stringify(response));
                document.getElementById('status').innerHTML = "Error!";
            } else {
                console.log(JSON.stringify(response));
                document.getElementById('status').innerHTML = response.id;
            }
        });
    }

    function uploadFeed(imgUrl, des) {
        console.log("img Url-------- " + imgUrl);
        $scope.loaderOverlay = false;
        var linkPage = 'http://playshowdown.com/feed?categoryName='+vm.stateType.categoryName+'&id='+ vm.stateType._id +
            '&type='+vm.stateType.type + '&feedType='+vm.stateType.feedType;
        FB.ui({
                method: 'share_open_graph',
                action_type: 'og.shares',
                action_properties: JSON.stringify({
                    object: {
                        'og:url': linkPage,
                        'og:title': "Play Showdown",
                        'og:description': des,
                        'og:image': imgUrl
                    }
                })
            },
            function (response) {
            console.log(response);
                // if(response.post_id){
                if(response.error_code != 4201){
                    vm.areYouSure = false;
                    $timeout(function(){
                        $('.overlay').show();
                        $('#congract4').show();
                    },1000);
                    console.log("post response1: " + JSON.stringify(response));
                }
                // }
                // Action after response
            })

    }
    function readPermission() {
            FB.api(
                "/debug_token?input_token=EAAWI4WLX8eABAJHx3al6NIi2pLM7ZCZBXEgFUOp2gJQ3VOh7gRbLSdZBZAJgmjcuYcYT7jaqO4mrkOyUeCI2q8kuZBqZCzJajjEqPjsZAFzFnHJPhWWozOGqKRZCCvTARTOS67G04cUyeYi9RAZBSZCrZA1Jq6FOmiyksFnhSKkEaFHOQQbZB5siATE9AQCU7prTGv0ZD",
                function (response) {
                    console.log(response)
                    if (response && !response.error) {
                        /* handle the result */
                    }
                }
            );
    }


text:
Q: Unclear math contest solution I'm having difficulty understanding this solution to a problem in an old math contest. I understand everything up to the word "Hence". Can anybody explain this to me?
Question

Answer

A: The three roots satisfy the polynomial.  So, from
$$ x^5 = \cdots = -3 + 9x - x^2  $$
we get \begin{align*}
a^5 &= -3 + 9a - a^2  \\
b^5 &= -3 + 9b - b^2  \\
c^5 &= -3 + 9c - c^2  \text{.}
\end{align*}
Summing these, we get
$$ a^5 + b^5 + c^5 = 3(-3) + 9(a+b+c) - (a^2 + b^2 + c^2) = \dots  \text{.}  $$

A: Alternatively: From Vieta's theorem:
$$a+b+c=0, ab+bc+ac=-3, abc=-1.$$
We can find:
$$a^2+b^2+c^2=(a+b+c)^2-2(ab+bc+ac)=0^2-2(-3)=6.$$
From the equation:
$$\begin{cases} a^3=3a-1 \\ b^3=3b-1 \\ c^3=3c-1 \end{cases} \Rightarrow a^3+b^3+c^3=3(a+b+c)-3=-3.$$
Multiply the two:
$$(a^2+b^2+c^2)(a^3+b^3+c^3)=-18 \Rightarrow$$
$$a^5+b^5+c^5+(abc)^2(ab+bc+ac)=-18 \Rightarrow$$
$$a^5+b^5+c^5=-18-(-1)^2(-3)=-15.$$


text:
Q: $\mathbb{Q}$ is a torsion-free $\mathbb{Z}$-module which is not free?
Is $\mathbb{Q}$ a torsion-free $\mathbb{Z}$-module which is not free?

This is an exercise (page 94) in the book by Hartley and Hawkes.
It is apparent that it is torsion-free. But how to prove that it is not free?

A: Given any two elements $r,s\in\mathbb Q$, there are integers $n$ and $m$ such that $nr=ms$.  I don't think that's true in a free abelian group.
If you have two generators of a free abelian group, $a$ and $b$, then they generate a subgroup like $\mathbb Z\times\mathbb Z$ and in there $na$ never equals $mb$, when $a=(1,0)$ and $b=(0,1)$.

A: No two rational numbers are linearly independent: if $x=\dfrac ab,\;y=\dfrac cd$, you have:
$$bc x-ad y=0.$$
Actually this is true in a more general context: if $S$ is a multiplicative set in a commutative ring $A$, the ring of fractions $S^{-1}A$, albeit a flat $A$-module,  is never a free $A$-module, unless $A=S^{-1}A$, i.e. $S$ is made up of units in $A$.


text:
Q: Summing a column in a .csv file using python I'm trying to sum a column in a csv file using python. Here's a sample of the csv data;
Date,Profit/Losses
Jan-2010,867884
Feb-2010,984655
Mar-2010,322013
Apr-2010,-69417
May-2010,310503
Jun-2010,522857
Jul-2010,1033096
Aug-2010,604885
Sep-2010,-216386

I want to sum the Profit/Losses column.
I am using the following code but it's returning a 0. Where could I be going wrong?
import os
import csv

# Path to collect data from the csv file in the Resources folder
pybank_csv = os.path.join("resources", "budget_data.csv")

with open(pybank_csv, 'r') as csvfile:
   csvreader = csv.reader(csvfile, delimiter=',')
   next(csvfile, None)
   t = sum(float(row[1]) for row in csvreader)

   #print the results
   print(f"Total: {t}")

A: Easiest way is to use pandas library.
Use pip install pandas to install pandas on your machine
and then
import pandas as pd
df = pd.read_csv('your_filename.csv')
sumcol = df['Profit/Losses'].sum()
print(sumcol)

The sum is in sumcol object now. For future reference, If your task is to work with the data provided in csv file, pandas is a blessing. This library provides you with thousands of different types of operations you could perform on your data. Refer Pandas Website for more info.
If you want to make use of csv package only then you can read the csv as a dict and then sum the Profit/Loss entry of dict for each row
total = 0
with open('your_filename.csv', newline='') as csvfile:
    data = csv.DictReader(csvfile)
    for row in data:
        total = total + int(row['Profit/Losses'])
print(total)

Or If you want to use reader instead of dict reader, you need to ignore first row. Something like this
total = 0
with open('your_filename.csv', newline='') as csvfile:
    data = csv.reader(csvfile)
    for row in data:
        if not str(row[1]).startswith('P'):
            total = total + int(row[1])
 print(total)


text:
Q: C program - Segmentation Fault - popen: Too many open files - sh: 0: Pipe call failed My C program crashs after running for 1h30. I get a "segmentation fault".
I debug though gdb and there is my error:
sh: 0: Pipe call failed
popen: Too many open files

I checked my code and for all popen command, I put pclose, idem for open/close.
But, I still get the same behaviour.
What can I do?
Thanks for your help.
Regards,

A:
I checked my code and for all popen command, I put pclose, idem for open/close.

These are far from the only calls which open file descriptors. Some of the others are dup, pipe, socket, etc.

What can I do?

Run your program under strace -e file ... -- if opens keep returning higher and higher file descriptors, you definitely have a file descriptor leak, and looking at strace output should allow you to guess where it's happening.


text:
Q: url with multiple optional arguments right now I have a view to show info about some tickets and I'm trying to add a functionality to filter those tickets.
Say I will have 4 filters:

*

*Date

*Owner

*Category

*Status

Category  Status
I want to give the option to use some of those filters, all or none, the thing is I'm kinda lost in how can I make it work in the urls. So far I found that you can add some optional arguments but they appear in some sort of succession like:
/May/Jack/Gas/Accepted
But if I only select 2 filters like /Jack/Accepted/ it grabs the filters incorrectly.
Is there a way I can achieve this? Or some other method I can use instead of this. Ty

A: Don't try and do this with URL arguments. Instead, use querystring arguments. The URL should be in the form:
my_path/?date=May&owner=Jack&category=Gas&status=accepted

and the URL pattern is just:
url(r'^my_path/$', views.my_view, 'my_url'),

and in the view you can access request.GET['date'] etc.


text:
Q: Issue on renaming functions I'm writing some code to calculate derivatives of functions. I managed to generate 1st and 2nd derivatives for 1 variable and store in the environment as functions, so I can plot them later. Now I'm trying to calculate the partial derivates for equations with 2 or more variables and I can't find the code that can generate as much functions in the environment as partial derivatives of the function.
To clarify, for 1 variable I used:
    f <- function(x) cos(20*x)*exp(-1*x)
    F.<- function (x) eval(D(as.expression(body(f)), "x"))
    F..<- function (x) eval(D(as.expression(D(as.expression(body(f)), "x")),"x"))

and it worked perfect, I get the 3 functions in the environment:

But for more than 1 variable I have to loop through this functions and generate as many funtions as partial derivatives of the equation.
My question is: how can I generate a loop that calculates the partial derivatives of a function and stores them as functions, each one with a custom name?
I tried the derivative function inside a for loop but couldn't manage to define different names for each calculation of the derivatives:
    for (i in 1:nro_variables) {
      var_D = vector_variables[i]
      F.<- function (x) eval(D(as.expression(body(f)), var_D))
    }

A: Similar to avoiding the use of assigning many separate similar objects to flood your global environment, consider using a single list that can index elements for better serial organization. See @GregorThomas's best practices answer advocating:

Don't ever create d1 d2 d3, ..., dn in the first place. Create a list d with n elements.

Specifically, if vector_variables is a character vector, sapply using simplify=FALSE will return a named list of functions. And yes, functions within lists can still be called.
partial_deriv_funcs <- sapply(vector_variables, function(var_D) {
    f <- function(x) cos(20*x)*exp(-1*x)
    return(function(x) eval(D(as.expression(body(f)), var_D)))
}, simplify = FALSE)

To call function elements singularly or iteratively:
# CALL SINGLE FUNCTION WITH SINGLE PARAM
result <- partial_deriv_funcs[['var1']](param)

# CALL SAME FUNCTION WITH VECTOR OF PARAMS
results <- lapply(param_vector, partial_deriv_funcs[['var1']])

# CALL ALL FUNCTIONS USING SAME PARAM
results <- lapply(partial_deriv_funcs, function(f) f(param))

# CALL ALL FUNCTIONS EACH WITH DIFFERENT PARAM
results <- mapply(function(f,p) f(p), partial_deriv_funcs, param_per_func_vector, SIMPLIFY= FALSE)
results <- Map(function(f,p) f(p), partial_deriv_funcs, param_per_func_vector) # EQUIVALENT

A: eval and parse can be used to define the function and assign can give it the correct name.
f <- function(x) 2 * x
g <- function(x, y) x * y
h <- function(x, y, z) x * y + z

fns <- c("f", "g", "h")

for (fn in fns) {
  for (variable in formalArgs(fn)) {
    function_name <- glue::glue("{toupper(fn)}.{variable}")
    fn_definition <- eval(parse(text = glue::glue("function({paste0(formalArgs(fn), collapse = ',')}) eval(D(as.expression(body({fn})), '{variable}'))")))

    assign(
      function_name,
      fn_definition
    )
  }
}

ls.str(mode = "function")
#> f : function (x)
#> F.x : function (x)
#> fn_definition : function (x, y, z)
#> g : function (x, y)
#> G.x : function (x, y)
#> G.y : function (x, y)
#> h : function (x, y, z)
#> H.x : function (x, y, z)
#> H.y : function (x, y, z)
#> H.z : function (x, y, z)