text:
Q: Can you have two instances of a model in one test function in phpunit? I'm trying to test that a duplicate user cannot be inserted.  To do this, I am creating 2 user objects with the same details, just changing account name - since this is something that is also unique.
However, my setter doesn't seem to be setting the company name second time around.  When I echo from the model, the property I am trying to set is still the same from the previous object I created.  My test fails as it throws the account already exists exception I set up
Failed asserting that exception of type "Models\AccountAlreadyExistsException" matches expected exception "Models\UserAlreadyExistsException".
public function testCantInsertDuplicateUser ()
{

    $user = new \Models\User();
    $user->first_name = 'John';
    $user->surname = 'Smith';
    $user->email = 'myemail@gmail.com';
    $user->password = 'password';
    $user->password_confirmation = 'password';
    $user->setCompanyName('Star');
    $user->setPackageId(2);
    $this->assertTrue($user->signUp());

    $user2 = new \Models\User();
    $user2->first_name = 'John';
    $user2->surname = 'Smith';
    $user2->email = 'myemail@gmail.com';
    $user2->password = 'password';
    $user2->password_confirmation = 'password';
    $user2->setCompanyName('cross');
    $user2->setPackageId(2);

    $this->setExpectedException('Models\UserAlreadyExistsException');
    $user2->signUp();
}

//user model
    public function setCompanyName ($company_name)
{
    $this->company_name = $company_name;
}

private function insertAccount ()
{
    $account = new \Models\Account;

    $account->setCompanyName($this->company_name);

    $account->setPackageId($this->package_id);

    $this->account_message_bag = new \Illuminate\Support\MessageBag();

    if (!$account->insert()) {

        $this->account_message_bag = $account->getValidationErrors();

    }

    return $account;
}

private function insertUser ()
{
    $save_user = $this->save(self::$rules, array(), array(), function ($model)
    {
        //this is all performed before save
        $existing_email = User::where('email', "=", $this->email)->count();

        if ($existing_email) {

            //delete account that was created in previous step
            //as the signup hasn't been successful

            $this->account->delete();

            throw new UserAlreadyExistsException();

        }

        //are there any account validation errors?

        if (count($this->account_message_bag->getMessages()>0)) {

            return false;
        }

    });

    return $save_user;
}

public function signUp ()
{
    $this->account = $this->insertAccount();

    $this->account_id = $this->account->getId();

    if (!$this->insertUser()) {

        //delete the company created in previous step

        $this->account->delete();

        $user_message_bag = Ardent::errors();

        //combine user and account validation eerrors

        $message_array = array_merge($user_message_bag->getMessages(), $this->account_message_bag->getMessages());

        $this->validation_errors = new \Illuminate\Support\MessageBag($message_array);

        throw new GenericValidationException();
    }

    //TODO - does this return false on failure?

    $sent = $this->sendConfirmEmail();

    if (!$sent) {

        throw new WelcomeEmailNotSent();
    }
    //sende confirm email
    return true;
}

//Account model

public function insert ()
{
    $result = $this->save(self::$rules, array(), array(), function()
    {
        $existing_company_name = \Models\Account::where('company_name', '=', $this->company_name)->count();

        if ($existing_company_name) {
            throw new AccountAlreadyExistsException();
        }
    });

    if (!$result) {

        $this->validation_errors = Ardent::errors();

        return false;
    }
    return true;
}

A: check the way you validate the AccountAlreadyExistsException
may be you should change the email

A: Your namespaces are likely the problem.
You create the class in \Models, but use Models (without the backslash) for the exception.  Maybe your code is throwing \Models\UserAlreadyExsitsException, not Models\UserAlreadyExistsException.
$user2 = new \Models\User();
...
$this->setExpectedException('Models\UserAlreadyExistsException');

Maybe this should be '\Models\UserAlreadyExistsException'
$user2 = new \Models\User();
...
$this->setExpectedException('\Models\UserAlreadyExistsException');


text:
Q: I am getting stuck here, I just need test apex /snippet /mock for this. Any input will be highly appreciated I am just new to apex testing, I am getting responce from Trigger upon that i am moving further in my class.
let me know id there is a way around to get better understanding to develop test cases. Trailhead is just about the core concept.
public with sharing class Opportunity_Post {

@future (callout=true)
public static void callout( string json_opp){

    string language,firstName, phoneNumberm, trialDays,companyName ;

        List<Opportunity> opp_data= new List<Opportunity>();

        opp_data = [ SELECT Name, No_of_Days__c, Contact_person_Name__c, Mobile__c, Contact_Language__c FROM Opportunity WHERE id =:leadID];
        String str = JSON.serialize(opp_data);
        system.debug('Query result :::: '+str );

        JSONParser parse_id = JSON.createParser(str);
        while(parse_id.nextToken()!= null) {
        if(parse_id.getCurrentToken() == JSONToken.FIELD_NAME) {
            parse_id.nextValue();

            if(parse_id.getCurrentName() == 'Name'){
                companyName = parse_id.getText();
                system.debug(' companyName :::: ' + companyName);
            }else if (parse_id.getCurrentName() == 'Contact_person_Name__c') {
                firstName = parse_id.getText();
                system.debug(' dropOff ::::' +firstName);
            }else if (parse_id.getCurrentName() == 'Contact_Language__c') {
                        language = parse_id.getText();
                        system.debug(' dropOff ::::' +language);
                        if(language =='English (en)'){
                            language= 'en';
                        }else if(language =='Arabic (ar)'){
                                 language= 'ar';
                        }else if(language =='Trukish (tr)'){
                                 language= 'tr';
                        }

            }else if (parse_id.getCurrentName() == 'Mobile__c') {
                phoneNumber = parse_id.getText();
                system.debug(' dropOff ::::' +phoneNumber);
            }else if (parse_id.getCurrentName() == 'No_of_Days__c') {
                trialDays = parse_id.getText();
                system.debug(' trialDays ::::' +trialDays);
            }
        }
    }

    string jsonUpdate = '{"trialDays":"'+trialDays+'", "phoneNumber":"'+phoneNumber+'", "firstName":"'+firstName+'", "companyName":"'+companyName+'"}';

    // Callout
        string url = '__//MyUrl';
        HttpRequest request = new HttpRequest();
        request.setEndpoint(url);
        request.setTimeout(120000);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setBody(jsonUpdate);
        Http http = new Http();
        system.debug('POST JSON updated: '+ jsonUpdate);
        HttpResponse response = http.send(request);
        system.debug('Helper class--Lead Resposne: ' + response);
        if(response.getStatusCode() == 403){
            system.debug('403 Confirmed...');
        }
        else if (response.getStatusCode() != 201) {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
        }
        else {
            System.debug('response.getBody() :  '+response.getBody());
        }
    }

}

A: Add a class that implements HttpCalloutMock. Mock respond method that gets HttpRequest as parameter and returns HttpResponse.
Here is link to the example: https://developer.salesforce.com/blogs/developer-relations/2013/03/testing-apex-callouts-using-httpcalloutmock.html
That is what you can do for your case:
@IsTest
public class Mocker implements HttpCalloutMock {
    public HttpResponse respond(HttpRequest req) {
        HttpResponse res = new HttpResponse();

        if (req.getEndpoint().endsWith(YOUR_URL)) {
            Map<String, Object> requestBody = (Map<String, Object>) JSON.deserializeUntyped(req.getBody());
            //check here your request body
            if (...) {
                res.setStatusCode(201);
                res.setBody(...);
            } else {
                res.setStatusCode(403);
            }
        } else {
            res.setStatusCode(404);
        }

        return res;
    }
}

Then in your test class just add this line of code: Test.setMock(HttpCalloutMock.class, new Mocker());

redpajama_set_name: RedPajamaStackExchange


text:
Q: Custom Font in Android ListView for RSS Reader I want to show News(Bengali language) from Rss feeds in Android ListView. When run the app nothing shows in screen. I'm sharing my codes. I will glad, if you guys tell me,if i doing anything wrong here

MainActivity.java

package com.andodev.android.reader;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.andodev.android.reader.data.RssItem;
import com.andodev.android.reader.listeners.ListListener;
import com.andodev.android.reader.util.RssReader;

public class NewsActivity extends Activity {
    /**
     * This method creates main application view
     */
    List<RssItem> listItems = new ArrayList<RssItem>();
    CustomAdapter adapt;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Set view
        setContentView(R.layout.main);

        try {
            // Create RSS reader
            RssReader rssReader = new RssReader("http://www.amaderbarisal.com/feed/");
            // Get a ListView from main view
            ListView itcItems = (ListView) findViewById(R.id.list);
            adapt = new CustomAdapter(this, listItems);
                itcItems.setAdapter(adapt);
            // Set list view item click listener
            itcItems.setOnItemClickListener(new             ListListener(rssReader.getItems(), this));

        } catch (Exception e) {
            Log.e("ITCRssReader", e.getMessage());
        }

    }

}

CustomAdapter

/**
 *
 */
package com.andodev.android.reader;

import java.util.List;

import com.andodev.android.reader.data.RssItem;

import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class CustomAdapter extends ArrayAdapter<RssItem> {

    List<RssItem> listItems;
    Context context;
    public CustomAdapter(Context context,List<RssItem> listItems) {
        super(context,R.layout.custom);
        // TODO Auto-generated constructor stub
        this.context = context;
        this.listItems = listItems;

    }

    public RssItem getItem(int position){
        return listItems.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View v = convertView;
        RssHolder holder = new RssHolder();
        if(convertView == null){
             LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
             v = inflater.inflate(R.layout.custom, null);
             TextView tv = (TextView)v.findViewById(R.id.name);
             Typeface myTYpe = Typeface.createFromAsset(context.getAssets(), "solaiman-lipi.ttf");
             tv.setTypeface(myTYpe);
             holder.RssTitle = tv;
             v.setTag(holder);
        }
        else{
             holder = (RssHolder) v.getTag();
             RssItem p = listItems.get(position);
             holder.RssTitle.setText(p.getTitle());
        }
        return v;
    }

    private static class RssHolder{
        public TextView RssTitle;
    }

}

custom.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textStyle="bold"
        />

</LinearLayout>

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#b5b5b5"
        android:dividerHeight="1dp"/>

</LinearLayout>

A: You are not setting the text in TextView in case convertView is null.
Instead of:
    if(convertView == null){
         LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         v = inflater.inflate(R.layout.custom, null);
         TextView tv = (TextView)v.findViewById(R.id.name);
         Typeface myTYpe = Typeface.createFromAsset(context.getAssets(), "solaiman-lipi.ttf");
         tv.setTypeface(myTYpe);
         holder.RssTitle = tv;
         v.setTag(holder);
    }
    else{
         holder = (RssHolder) v.getTag();
         RssItem p = listItems.get(position);
         holder.RssTitle.setText(p.getTitle());
    }

Use
    ViewHolder holder;
    if (convertView == null) {
        convertView = LayoutInflater.from(context).inflate(R.layout.custom, null);

        holder = new ViewHolder();

        Typeface typeface = Typeface.createFromAsset(context.getAssets(), "solaiman-lipi.ttf")

        holder.rssTitle = (TextView) convertView.findViewById(R.id.name);
        holder.rssTitle.setTypeface(typeface);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.rssTitle.setText(listItems.get(position).getTitle());

    return convertView;


text:
Q: making a dropdown menu using javascript I am trying to create a dropdown menu for "My Journeys" in the navigation bar using javascript, and I am using flex for the css. And I have no idea what to do, all of the tutorials I've watched didn't use flex for the code. Thank you for your help!
This is my html body code

  Home

 My Journeys

  Media

  About Me & This Blog

        <form>
            <input type="search" placeholder="search...">
            <input type="image" src="pict/search-white.png" alt="search">
        </form>

and this is my css code
.pagewrap{
display: flex;
flex-direction: column;
background-color: blue;
width: 75%;
margin: 0 auto;

background-color: black;
}

body{
background-image: url(pict/wallpaper.jpeg);
}

header img{
width: 100%;
margin-top: 4%;
}

nav{
display: flex;
flex-direction: row;
order: -1;

height: 8%;
width: 75%;
top: 0;

background-color: black;
opacity: 0.9;

align-items: center;
position: fixed;
}

nav ul{
display: flex;
flex-grow: 1;
}

nav ul li, #dropdown{
list-style: none;
flex-grow: 1;

margin: 0 2%;
}

nav ul li a {
color: white;
text-decoration: none;
text-transform: uppercase;

font-family: 'Candal', sans-serif;
font-size: 100%;
}

nav ul li a:hover{
color: #660066;
}

form{
display: flex;
flex-direction: row-reverse;
justify-content: flex-start;

width: 20%;
height: 50%;
}

form input[type="search"]{
border-width: 0;
color: white;
background-color: transparent;

}

form input[type="image"]{
margin: auto 2%;
width: 5%;
}

A: what i have made up from your question is you need my journey drop down with two submenus. Below is the code for same.
Hope it will help.

$('.dropdown').click(function(){ $('.myList').slideToggle(100);});
body {
    margin:0;
    padding:0;
}
.pagewrap {
    background-color: blue;
    width: 100%;
    background-color: black;
}
body {
    background-image: url(pict/wallpaper.jpeg);
}
header img {
    width: 100%;
    margin-top: 4%;
}
nav {
    width:100%;
    top: 0;
    background-color: black;
    position: fixed;
    padding:5px;
}
nav ul {
    flex-grow: 1;
    margin:0;
    padding:0;
}
nav ul li, #dropdown {
    list-style: none;
    display:inline;
    margin-right:10px;
}
nav ul li a {
    color: white;
    text-decoration: none;
    text-transform: uppercase;
    font-family:'Candal', sans-serif;
    font-size: 100%;
}
nav ul li a:hover {
    color: #F99D9D;
}
form {
    flex-direction: row-reverse;
    justify-content: flex-start;
    width: 20%;
    height: 50%;
}
form input[type="search"] {
    border-width: 0;
    color: white;
    background-color: transparent;
}
form input[type="image"] {
    margin: auto 2%;
    width: 5%;
}
.myList {
    position:absolute;
    top:24px;
    left:0;
    background:#A0A0A0;
    width:100px;
    z-index:1
}
.myList li {
    margin:0;
}
.dropdown {
    position:relative;
    z-index:3;
}

  Home

 My Journeys

 menu 1

 menu 2

  Media

  About Me & This Blog


text:
Q: PHP Form data write I manage the forums and site of this game server I play. There's an application forum and it writes the data to another file. It works perfectly fine,  I just have a question; I'm not all to good with PHP, as I'm more focused on learning JavaScript atm, but I would like to know if there would be a way that I could make it write into a grid/table format? Even better, an example with a short walk-through. Again, what I need is a way for it to write it in a "grid/table" format, IF possible. Here's the PHP document (with HTML), and the file that it would send it to.
PHP / HTML:
<?php
if($_POST['formSubmit'] == "Submit")
{
    $errorMessage = "";

    if(empty($_POST['formSteam']))
    {
        $errorMessage .= "
You need to put your Steam ID!
";
    }
    if(empty($_POST['formName']))
    {
        $errorMessage .= "
Please put your first and/or lastname!
";
    }
    if(empty($_POST['formAge']))
    {
        $errorMessage .= "
Please tell us your age! This is just for reference.
";
    }
    if(empty($_POST['formApplication']))
    {
        $errorMessage .= "
Do I have to explain this? Please explain why you want to be apart of our staff!
";
    }
    $varSteam = $_POST['formSteam'];
    $varName = $_POST['formName'];
    $varAge = $_POST['formAge'];
    $varApplication = $_POST['formApplication'];

    if(empty($errorMessage))
    {
        $fs = fopen("mydata.csv","a");
        fwrite($fs,$varSteam . ", " . $varName . ", " . $varAge . ", " . $varApplication . "\n");
        fclose($fs);

        header("Location: success.html");
        exit;
    }
}
?>

    <title>Apply - POG</title>
    <link rel="shortcut icon" href="favicon.ico">
    <link rel="stylesheet" type="text/css" href="style.css">

    <?php
        if(!empty($errorMessage))
        {
            echo("
There was an error with your form:
\n");
            echo("
" . $errorMessage . "
\n");
        }
    ?>
    <form action="application.php" method="post">

            Whats your Steam ID? Find out here!

            <input type="text" name="formSteam" maxlength="50" value="<?=$varSteam;?>">

            What is your name?

            <input type="text" name="formName" maxlength="50" value="<?=$varName;?>">

                How old are you?

                <input type="text" name="formAge" maxlength="2" value="<?=$varAge;?>">

            Why do you want to apply for PossessedGaming Staff?

            <textarea name="formApplication" maxlength="3000" style="width:325px;height:150px;" value="<?=$varApplication;?>"></textarea>

        <input type="submit" name="formSubmit" value="Submit">
    </form>

    Copyright © The Gaming Hideout

    We own no rights on any game on this site unless otherwise noted.

    All Rights Reserved.

FILE DATA / OUTCOME:
Steam ID, Name, Age, Reason     <!Pre-Made
----------------------------                 !>
(Le Applications Private)
STEAM_0:xxxx, Bob, 15, Because I'm just an example and I really want to be admin!

A: I know, this is not the most elegant way to do this, but now it will do the job.
I am assuming, all the lines are valid, and has the 4 properties for all players.
Anyway, even if it not the most elegant, I hope you will get the point of it, so you can rewrite as you want.

    <?php
    $string = "Steam ID, Name, Age, Reason
(Le Applications Private)
STEAM_0:xxxx, Bob, 15, Because I'm just an example and I really want to be admin!
STEAM_1:xxxx, John, 18, This is my reason!
";

    $content = str_replace("\r","", explode("\n", $string));

//We need this, because we are need to use the first two row in special ways.
    $i = 0;
    foreach ($content as $row) {
        ?>

            <?php
            if ($i == 1) {
                //This is the first row, so these are table headers.
                //Explode the row by commas into an array.
                $pieces = explode(',', $row);

                //Then show the value of arrays.
                ?>
                <?php echo $pieces[0]; ?>
                <?php echo $pieces[1]; ?>
                <?php echo $pieces[2]; ?>
                <?php echo $pieces[3]; ?>
                <?php
            } elseif ($i == 2) {
                //This is the second row, so we need to colspan it
                //Just echoing it, becuause in this row we do not need to
                //explode anythin.
                ?>
                <?php echo $row; ?>
                <?php
            } else {
                //All the players.

                //Do the same as the first row.
                $pieces = explode(',', $row);
                ?>
                <?php echo $pieces[0]; ?>
                <?php echo $pieces[1]; ?>
                <?php echo $pieces[2]; ?>
                <?php echo $pieces[3]; ?>
                <?php
            }
            $i++;
            ?>

        <?php
    }
    ?>


text:
Q: Script Language to draw logic gates and funcional blocks There are several graph and circuit tools to draw, but I was unable to use them to do what I will describe below:
Suppose I have a block with three inputs and two outputs.
I'd like to draw a rectangle with three dots on the left face and two dots on the right face.
Each dots is an input or an output, depends on the side.
I'd like to connect blocks using scripts. Suppose a pseudo code like that:
block FA { a input, b input, cin input, s output, cout output }
logic_and and1 { a input, b input, o output }
logic_not not1 { a input, o output }
arrow a1 {and1.o , FA.a }
arrow a2 {FA.s, not1.a }

And as output I get an image like this:
Example of blocks connection
yED is fantastic, as well as Graphviz, but I couldn't create my own "link points" to connect the edges exactly where I want to.
I need a way to generate the script using the language that you advise me, then draw it.
I have very large circuits to draw and this task is unfeasible to be done by hand.
I prefer to build a converter than draw more than eight thousand circuits. :-)
I hope someone can help me.

A: dpic is a variant of the pic language.  The dpic developer has created a set of M4 macros aimed at EEs.  I don't use dpic for that purpose, so I can't vouch that it will do what you want, but I think it is worth a look.
http://mirror.utexas.edu/ctan/graphics/circuit_macros/doc/Circuit_macros.pdf
https://ece.uwaterloo.ca/~aplevich/dpic/dpic-doc.pdf


text:
Q: examples of unit testing methods that are expected to return JSON How does one unit test an object or collection - specifically a JSON packet??
Do you just test for he structure, key/values pairs? regardless of values??
Do I create an empty collection? and compare?
same question applies to any complex object (query,structure,array, etc)
Any help by real examples would be greatly appreciated.

*

*Im just getting started with TDD, and using MXUnit... Im not really quite sure where to begin...
Here is a sample of one basic test,
// Arrange
    // obj set up - handled in "setup"

// Act
    var expect = 1;
    var result = obj.getPersonByID();
    debug( result ); // throws data back to the tester for display

// Assert
    assertEqual( expect, result, 'Expected #expect#, got #result#.' );

A: Use the following process:

*

*Create a mock JSON

*Deserialize JSON to a struct using DeserializeJSON

*Create an array of keys using StructKeyArray

*Loop through the array

*Assert the name of each key

References

*

*Unit Testing the MVC JSON Result

*Closure Library Source: closure.goog.net.jsonp_test


text:
Q: Pg:Error column does not exist I am trying to make it so a user has_many goals, and then only let a user see their own goals.
My welcome controller where the code is failing:
class WelcomeController < ApplicationController
  def index
    if user_signed_in?
      @goals = current_user.goals.all
    else
      @goals = Hash.new
    end
  end
end

User.rb is like so:
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :goals
end

And my Goal.rb:
class Goal < ActiveRecord::Base
  belongs_to :user
end

The error I am getting is:
PG::Error: ERROR: column goals.user_id does not exist LINE 1: SELECT "goals".* FROM "goals" WHERE "goals"."user_id" = $1 ^ : SELECT "goals".* FROM "goals" WHERE "goals"."user_id" = $1

(I get this error while logged in, after having created a new goal)
I tried adding "foreign_key :user_id" to my User model but then I get the following error:
/Users/Thomas/newyears/app/models/user.rb:7: syntax error, unexpected tSYMBEG, expecting keyword_do or '{' or '(' has_many :goals, foreign_key :user_id ^

In my routes file on line 3, which looks like this:
Goalsy::Application.routes.draw do
  get "mycalendar/index"
  devise_for :users
  devise_for :goals
  resources :goals

  get "welcome/index"
  resources :posts

  root 'welcome#index'
end

A: I guess, the user_id column is missing in the goals table.
Just run the command in your console to create the migration
rails generate migration AddUserRefToGoals user:references

It will generate the migration file.
class AddUserRefToGoals < ActiveRecord::Migration
  def change
    add_reference :goals, :user, index: true
  end
end

Then do the rake db:migrate
Hope, it will fix your problem.


text:
Q: How to find which build paths a project is on Suppose I have a Java project in Eclipse called ProjectA. I have 50 other projects and I want a list of projects that have ProjectA as part of their build path.
How do I get such a list?

A: One way is - from Eclipse menu > Search > File, do a search as per this screen

Or if you use Maven, do a search for 'ProjectA' in all pom.xml


text:
Q: Facebook or LinkedIn like connection suggestion profile alert I have a "users" table like this:
+-----+------------+---------+---------------+
| uid | first_name | surname |         email |
+-----+------------+---------+---------------+
      1        joe    bloggs    joe@test.com
      2       bill    bloggs   bill@test.com
      3       john    bloggs   john@test.com
      4       karl    bloggs   karl@test.com

and a "connections" table like this:
+----+---------+----------+--------+
| id | user_id | user_id2 | status |
+----+---------+----------+--------+
   1         1          3        1
   2         3          1        1
   3         4          3        1
   4         3          4        1
   5         2          3        1
   6         3          2        1

Here id is auto auto_increment user id is saved in either user_id or user_id2. Status 1 means connection is approved and active.
Now I want to send an email alert to users with profile suggestion like Facebook or LinkedIn do. I assume it is possible to get mutual connections between users but not sure how to do. I have tried but it is not perfect. I want to get these all with one mysql query with user and their suggested connection profile. Any idea how to do this?
Many thanks in advance!

A: Such algorithms are never perfect: you can never know exactly if two people know each other. People might live in the same building, go to the same work, have 100 friends in common and even share the same hobbies without knowing each other (of course the odds are not that great).
What Social networks do exactly is of course unknown (that's part of the way they make money). But some aspects are known. For instance the number of mutual friends are important (together with for instance location, interests, hobbies, education, work, surname,...).
Based on what you provide, one can more or less only use the number of mutual friends. This can be done using the following query:
SELECT a.user_id, b.user_id2, count(*) --Select the two ids and count the number of transitive relations
FROM connections as a, connections as b --Use the table twice (transitivity)
WHERE a.user_id2 = b.user_id  -- Transitivity constraint
      AND a.user_id < b.user_id2 -- Maintain strict ordening (can be dropped when checked)
      AND a.status = 1 -- First relation must be confirmed.
      AND b.status = 1 -- Second connection must be confirmed.
      AND NOT EXISTS ( -- Not yet friends
          SELECT *
          FROM connections as c
          WHERE c.user_id = a.user_id
                AND c.user_id2 = b.user_id2
      )
GROUP BY a.user_id, b.user_id2 -- Make sure we count them correctly.

As you can see here, the fiddle calculates that (1,2), (1,4) and (2,4) are not yet friends, and all have one mutual friend.
Once the number of mutual friends surpasses a certain threshold, one can propose friendship.
I would however advice you to make your table more compact: add a CHECK to the table such that user_id is always strictly less than user_id2 (CHECK(user_id < user_id2)). This makes the database more compact, for most implementations of a database tool faster as well and queries will become simpler. What is after all the difference between (1,3,1) and (3,1,1).


text:
Q: Odoo SAAS: Add field from associated model into a tree view of another model I have 2 fields in res.partner that I would like to display in a tree view for account.invoice based on the partner_id field. I'm wondering how I can do that (reference another model and field) through the tree view web interface, due to the SaaS version not allowing programmatic access.
Thanks in advance!

A: create related field in you account.invoice model to the fields of  res.partner
x_invoice_preference=fields.Selection(related="partner_id.x_invoice_preference")

it's a good practice to name the related field the same name in the other model
Little exemple :
class class1(models.Model):
   _name = 'table1'
   name = fields.Char()

class class2(models.Model):
  _name = 'table2'
  table1_id = fields.Many2one('table1','table 1');
  #this how you create a related field in order to
  #show it in the form or the tree when you select the value of the many2one field it
  # will have the same value of the vield name of the tabl1
  name = fields.Char(related="table1_id.name",readonly=True)
#field_name                  m2onField.field_name


text:
Q: Handling long menu in TCL I have an old TCL app that has a menu that isn't displaying all the entries.
How can I create a multi-column menu or a scrolling menu so all menu entries can be seen?
This is TCL v8.0
This is for a gui.
The code fragment I'm looking at is:
#
# Setup the folder Menu
#
menubutton $w.folder -text Folder -menu $w.folder.menu
menu $w.folder.menu -tearoff 0
$w.folder.menu add command -label "New"      -command createNewFolder -state disabled
$w.folder.menu add command -label "Open"     -command openFolder
$w.folder.menu add command -label "Delete"   -command deleteFolder -state disabled
$w.folder.menu add command -label "Printer Setup" -command selectPrinter -state  disabled
$w.folder.menu add command -label "Quit"     -command xqmQuit
$w.folder.menu add separator
foreach queue $privateGlobals(folderList) {
   $w.folder.menu add command -label "$queue" -command [list openFolder "$queue"]
}

What is happening is that in the foreach loop there are a lot of entries that get created but I can only see about 46 out of 60 or 80.
I haven't done TCL in a long time but I didn't see any obvious options in the menu widget to do what I wanted.

A: You can use -columnbreak value option.
set i 0
foreach queue $privateGlobals(folderList) {
   $w.folder.menu add command -label "$queue" -command [list openFolder "$queue"] -columnbreak [expr $i % 10 == 0]
   incr i
}


text:
Q: JPA Mapping - Unique combination of parents per child I am using:
Spring 3.2
Hibernate 4.1.9
I need to map, with JPA, three classes.  Class A has a ManyToMany relationship with Class B.  A unique combination of Class A and Class B need to own a collection of Class C.
Table A
foo
id | name

Table B
bar
id | name

Table C
data
id | xrefId

Join Table -- Unique Key on (fooId,barId)
xref
id | fooId | barId

Altering the existing data structure is not an option.
Edit 1:
Goal: Load a Foo, get its collection of Bars.  From each Bar, get its (their!) collection of Data.
Class A
@Entity
public class Foo {
  @Id
  private UUID id;

  @ManyToMany(optional = false)
  @JoinTable(name               = "xref",
             joinColumns        = { @JoinColumn(name = "fooId") },
             inverseJoinColumns = { @JoinColumn(name = "barId") })
  private List<Bar> lstBar = new ArrayList<Bar>();
}

Class B
public class Bar {
  @Id
  private UUID id;

  @ManyToMany(mappedBy = "lstBar")
  private List<Foo> lstFoo = new ArrayList<Foo>();
}

Class C
public class Data {
  @Id
  private UUID id;
}

A: Just KISS. Make another class Xref, which contains id, foo, bar and Set<Data> fields. Make a DAO method to find an Xref using two parameters foo and bar (implement it with a simple HQL). The unique requirement could be achieved by an unique constraint in the database.
It doesn't look good trying to express it just by the class hierarchy, better to use DAOs.

A: Your join table, xref, has an extra id field, in order to be able to create such a table with JPA you need an extra entity class XRef and then you have to map the relation between A and XRef and betweem B and XRef (both are one-to-many). Then, you can create the entity class C and map the relation between C and XRef. Do you need more help? I don't have time right now to provide the code, but if you need ask and I will try to add it as soon as possible.

A: Look at this example (used Integer instead of UUID for simplicity, the rest should be OK).
Bar class:
public class Bar {
    @Id
    private Integer id;
    @Column(name = "name")
    private String name;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "barId")
    private Collection<Xref> xrefCollection;
}

Foo class:
public class Foo {
    @Id
    private Integer id;
    @Column(name = "name")
    private String name;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "fooId")
    private Collection<Xref> xrefCollection;
}

Xref  class:
public class Xref {
    @Id
    private Integer id;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "xrefId")
    private Collection<Data> dataCollection;
    @JoinColumn(name = "bar_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Bar barId;
    @JoinColumn(name = "foo_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Foo fooId;
}

Data Class:
public class Data {
    @Id
    private Integer id;
    @JoinColumn(name = "xref_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Xref xrefId;
}

This code has been automatically generated by NetBeans, provided that all tables and indexes are correctly defined in the DB


text:
Q: dijkstra algorithm for big graphs I am implementing Dijkstra's algorithm using standard Python libraries.
my implementation below is ok for test cases with little graphs.
When I run it on a big one (more than 30k nodes), it is not great.
Wonder if anybody can help improving it.
I do not understand if the stop checks are not correct of if there is something else missing
import logging
from collections import deque, namedtuple

logger = logging.getLogger(__name__)
# use infinity as a default distance to nodes.
inf = float("inf")
Edge = namedtuple("Edge", "start, end, cost")

def make_edge(start, end, cost=1):
    return Edge(start, end, cost)

class Graph:
    def __init__(self, edges):
        # check that the data is right
        wrong_edges = [i for i in edges if len(i) not in [2, 3]]
        if wrong_edges:
            raise ValueError("Wrong edges data: {}".format(wrong_edges))

        self.edges = [make_edge(*edge) for edge in edges]

    @property
    def vertices(self):
        return set(sum(([edge.start, edge.end] for edge in self.edges), []))

    def get_node_pairs(self, n1, n2, both_ends=True):
        if both_ends:
            node_pairs = [[n1, n2], [n2, n1]]
        else:
            node_pairs = [[n1, n2]]
        return node_pairs

    def remove_edge(self, n1, n2, both_ends=True):
        node_pairs = self.get_node_pairs(n1, n2, both_ends)
        edges = self.edges[:]
        for edge in edges:
            if [edge.start, edge.end] in node_pairs:
                self.edges.remove(edge)

    def add_edge(self, n1, n2, cost=1, both_ends=True):
        node_pairs = self.get_node_pairs(n1, n2, both_ends)
        for edge in self.edges:
            if [edge.start, edge.end] in node_pairs:
                return ValueError("Edge {} {} already exists".format(n1, n2))

        self.edges.append(Edge(start=n1, end=n2, cost=cost))
        if both_ends:
            self.edges.append(Edge(start=n2, end=n1, cost=cost))

    # @property
    # def neighbours(self):
    #     neighbours = {vertex: set() for vertex in self.vertices}
    #     for edge in self.edges:
    #         neighbours[edge.start].add((edge.end, edge.cost))

    #     return neighbours

    # use the following if the graph is undirected / bidirectional
    @property
    def neighbours(self):
        neighbours = {vertex: set() for vertex in self.vertices}
        for edge in self.edges:
            neighbours[edge.start].add((edge.end, edge.cost))
            neighbours[edge.end].add((edge.start, edge.cost))

        return neighbours

    def dijkstra(self, source, dest):
        assert source in self.vertices, "Such source node doesn't exist"
        distances = {vertex: inf for vertex in self.vertices}
        previous_vertices = {vertex: None for vertex in self.vertices}
        distances[source] = 0
        vertices = self.vertices.copy()

        while vertices:
            current_vertex = min(vertices, key=lambda vertex: distances[vertex])
            vertices.remove(current_vertex)
            if distances[current_vertex] == inf:
                break
            for neighbour, cost in self.neighbours[current_vertex]:
                alternative_route = distances[current_vertex] + cost
                if alternative_route < distances[neighbour]:
                    distances[neighbour] = alternative_route
                    previous_vertices[neighbour] = current_vertex
                    logger.debug("updating Graph distances", format(distances))

        path, current_vertex = deque(), dest
        while previous_vertices[current_vertex] is not None:
            path.appendleft(current_vertex)
            current_vertex = previous_vertices[current_vertex]
        if path:
            path.appendleft(current_vertex)
        logger.debug("path to destination is \n")

        while path:
            value = path.popleft()
            logger.debug("{} \n".format(value))

        return distances[dest]

and this is the test case:
graph = Graph(
    [
        ("a", "b", 7),
        ("a", "c", 9),
        ("a", "f", 14),
        ("b", "c", 10),
        ("b", "d", 15),
        ("c", "d", 11),
        ("c", "f", 2),
        ("d", "e", 6),
        ("e", "f", 9),
    ]
)

result = graph.dijkstra("a", "e")
print(result)
assert result == 20


text:
Q: 2d array table form print out
so if a user input 9 random numbers
my code prints like this in its sorted form
1 2 3 4 5 6 7 8 9
but I want it to print like a table form
like this
1   2   3

4   5   6

7   8   9
The output after running the code appears as follows:
Please enter number of rows: 3
Please enter number of columns: 3
Please enter 9 numbers to sort: 9 8 7 6 5 4 3 2 1
Sorted numbers:
1 2 3 4 5 6 7 8 9
<emtpy line>

import java.util.Scanner;
public class table
{
    public static void main(String args[])
    {

        System.out.println("Sorted numbers: ");
        for(int x = 0; x < matrix.length; x++)
            for (int y = 0; y < matrix[x].length; y++)
            {
                System.out.print(matrix[x][y] + " ");
            }

        System.out.println(" ");

    }
}

A: Your issue is here:
for(int x = 0; x < matrix.length; x++)
    for (int y = 0; y < matrix[x].length; y++)
    {
        System.out.print(matrix[x][y] + " ");
    }

System.out.println(" ");

You didn't enclose your print statement in the outer for loop. If you add brackets, everything in your for loop will execute.
for(int x = 0; x < matrix.length; x++)
{
    for (int y = 0; y < matrix[x].length; y++)
    {
        System.out.print(matrix[x][y] + " ");
    }

    System.out.println(" ");
}

This way your inner for loop will execute printing all your numbers on a line followed by the println execution and then it repeats.
With this modification, I have arrived at this output:
Please enter number of rows: 3
Please enter number of columns: 3
Please enter 9 numbers to sort: 8 7 6 4 3 1 2 5 9
Sorted numbers:
1 2 3
4 5 6
7 8 9
<empty line>


text:
Q: Is the error "Duplicate variable definition" serious? Just a question that I was asking to myself.
Is it serious the error of duplicate variable definition ? What happen if we don't correct it ? (I had a project with , at least, 40 errors of duplicates variables. I correct it, but what happen if I don't ?)
It is just a curiosity question.
Thx,

A: You mean Errors or Warnings?
As far as I know it's not "Serious" because in bytecode variable is declared at the beginning of the function so it doesn't matter if you define it once or more times...


text:
Q: Ag-grid cell Render html or template with function() I am rendering cell template when on click it should perform some function.My Bellow code is not working.Thanks in Advance
             {
                field: "expiry_date",
                headerName: "End date"
              },{
                field:"Reserved Date",
               // template: `<p (click)='open()'>Reserve Date</p>`,
               cellRenderer: function (params) {
                var html = `<p (click)=${this.open(params.data)}'>Reserve Date</p>`;

                return html;
            }

A: We can bind the method and it's label with help of cellRendererParams of ag-grid library.
You can do this like below,
        {
            field: "expiry_date",
            headerName: "End date"
        },
        {
            field:"Reserved Date",
            cellRendererParams: {
                    onClick: this.open.bind(this),
                    label: 'Reserve Date'
            }
        }

You can read more about cellRenderParams here: component-cell-renderer

A: You need to create a new cellRendererComponent.
Something like this:
import { Component } from '@angular/core';
import { ICellRendererAngularComp } from 'ag-grid-angular';
import { ICellRendererParams, IAfterGuiAttachedParams } from 'ag-grid-community';

@Component({
  selector: 'cpl-button-renderer',
  template: `
    <button type="button" (click)="onClick($event)">{{label}}</button>
    `,
    styles: []
})

export class ButtonRendererComponent implements ICellRendererAngularComp {

  params;
  label: string;

  agInit(params): void {
    this.params = params;
    this.label = this.params.label || null;
  }

  refresh(params?: any): boolean {
    return true;
  }

  onClick($event) {
    if (this.params.onClick instanceof Function) {
      // put anything into params u want pass into parents component
      const params = {
        event: $event,
        rowData: this.params.node.data
        // ...something
      }
      this.params.onClick(params);

    }
  }
}

From the parent component, You need to add it to framework object of aggrid, and provide it in columnDefs:
ngOnInit() {
        this.frameworkComponents = {
            buttonRenderer: ButtonRendererComponent,
        }
    }

ColumnDefs:
       {
            headerName: 'Button Demo',
            cellRenderer: 'buttonRenderer',
            cellRendererParams: {
                onClick: this.open.bind(this),
                label: 'Reserve Date'
            }
        },

Add open function like this:
private open(params) {
    // do whatever you want.
    // Params will contain the oject that you passed in .onclick method of renderer component
}

HTML file:
<ag-grid-angular style="height: 450px;" class="ag-theme-alpine" [rowData]="rowData"
            [columnDefs]="columnDefs" [defaultColDef]="defaultColDef" (gridReady)="onGridReady($event)"
            [frameworkComponents]="frameworkComponents">
</ag-grid-angular>


text:
Q: Overlapping stack chart in Canvas JS i have a code which should give me an overlapping bar chart , one inside other in canvas js , something like below
Output Needed
So it should be combination of stacked horizontal graph , and one overlapping graph inside the first ( as in pic)
but am getting everything inside one main graph
below is the code .
var chart = new CanvasJS.Chart("chartContainer", {
    theme: "light2",
    title: {
    text: "Chart Title"
  },
  reversed:true,

  data: [
    {
      type: "error",
      whiskerThickness: 0,
      color: "#004ca0",
      dataPoints: [
        { label: "Alpha", y: [0 , 71] },
      ]
    },
    {
      type: "column",
      axisXType: "secondary",
      color: "#34dc00",
      dataPoints: [
        { label: "Alpha", y: 60 },
      ]
    },
    {
      type: "column",
      axisXType: "secondary",
      color: "#3cfa00",
      dataPoints: [
        { label: "Alpha", y: 50 },
      ]
    },

  ]
});

chart.render();
chart.data[0].set("stemThickness", chart.get("dataPointWidth") * 4 + 10);

Thanks

A:

var chart = new CanvasJS.Chart("chartContainer", {
    theme: "light2",
    title: {
        text: "Chart Title"
    },
    reversed:true,
    data: [
        {type: "error",  axisXType: "secondary", color: "#34dc00", dataPoints: [{ label: "Alpha", y: [ 0, 100 ] }, ]},
        {type: "column", axisXType: "secondary", color: "#004ca0", dataPoints: [{ label: "Alpha", y: 71 }, ] },
        {type: "column", axisXType: "secondary", color: "#ff0000", dataPoints: [{ label: "Alpha", y: 50 }, ] }
    ]
});

chart.render();
chart.data[0].set("stemThickness", chart.get("dataPointWidth") * 4 + 10);

A: In the code that you have shared, you are using column chart whereas in the screenshot shared it needs Stacked Bar Chart. Using Stacked Bar / Stacked Bar 100% & Error chart, you can achieve as shown in the screenshot shared. Below is the working code.

var chart = new CanvasJS.Chart("chartContainer", {
  dataPointWidth: 70,
  axisX: {
    lineThickness: 0,
    tickLength: 0,
    labelFormatter: function(e) {
      return "";
    }
  },
  axisY: {
    includeZero: true,
    lineThickness: 0,
    gridThickness: 0,
    tickLength: 0,
    labelFormatter: function(e) {
      return "";
    }
  },
  toolTip: {
    shared: true
  },
  data: [{
    type: "stackedBar100",
    name: "Unique Opens: 33.3%",
    showInLegend: true,
    color: "#23a9e8",
    dataPoints: [
      { x: 1, y: 33.3 }
    ]
  }, {
    type: "error",
    name: "Unique Clicks: 33.3%",
    showInLegend: true,
    legendMarkerType: "square",
    linkedDataSeriesIndex: 0,
    stemThickness: 25,
    whiskerThickness: 0,
    color: "#336a84",
    dataPoints: [
      { x: 1, y: [0, 33.3] }
    ]
  }, {
    type: "stackedBar100",
    name: "Unique Opens: 66.7%",
    showInLegend: true,
    color: "#dfe3e4",
    dataPoints: [
      { x: 1, y: 66.7 }
    ]
  }]
});

chart.render();


text:
Q: How could I run this python script on my webserver? TorBulkExitList.py I have a web server that can run python scripts, but I have no experience at all with python. I uploaded the file (TorBulkExitList.py) to my server inside the cgi-bin folder and I tried calling it in the browser but it's giving me a 500 Internal Server Error. Here's the python script:
https://svn.torproject.org/svn/check/trunk/cgi-bin/TorBulkExitList.py
Is there anything I need to do before I could run this script? I didn't change anything from the script at all. Any other alternative, I just need to get a list of the TOR exit IPs. I'm on a Linux/PHP/Apache server btw.

A: I see that file is a wsgi application (because it implements a application method.) You need to configure apache to send requests to it using mod_wsgi (or some other wsgi server.)
Try adding this to the site's .htaccess (with the correct file path):
WSGIScriptAlias /TorBulkExitList /usr/local/www/cgi-bin/TorBulkExitList.py

and then visit http://example.com/TorBulkExitList
Click here to read more about mod_wsgi configuration.


text:
Q: Send a list of items with hyperlink attached ASP.net VB I am trying to send an email with a list of items. This items has a link attached in a grid view.
Dim mm As New MailMessage()
       mm.To.Add(txtEmail.Text)
       mm.From = New MailAddress("librarieonlineASE@gmail.com")
       mm.Subject = "Comanda dvs. a fost plasata"

       mm.Body = "Comanda dvs se poate descărca de la aceste adrese:
"

       For Each row As DataRow In shoppingCart.Rows
           mm.Body += "
"
           mm.Body += row(1) + " " + ""
           mm.Body += "
"
       Next

I am getting the error end "End of statement expected" at this line
mm.Body += row(1) + " " + ""
Row 1 has the name of the item and Row 8 has the link which I want to attach. Thanks in advance

A: The issue is with the quotes (""). You need to escape the "" when using to define your hyperlink reference.
The correct way to escape "" in VB.net is to double them like
"

Also the way you use row(8) will mean that the link will not get the value from the array.
Use string.Format -
Dim link As String
link = String.Format("<a href=""{0}""", row(8))

A: try to change your logic to combine string values
For Each row As DataRow In shoppingCart.Rows
           mm.Body &= "
"
           mm.Body &= row(1) & " " & ""
           mm.Body &= "
"
       Next

In vb.net we should combine string values using & instead of +
Hope this help.


text:
Q: OrderBy Clause prevents navigation properties from being loaded I'm working on a portfolio website, where, on a product page, I want to display related articles from the same category.
I've created a method to allow me to pick a defined number of article, in a defined category, randomly. Unfortunately, when I add the OrderByclause to "enable" the randomness, I'm not able anymore to retrieve the navigation properties.
public async Task<IEnumerable<Article>> GetRandomArticlesByCategoryIdAsync(int categoryId, int numberOfArticles)
{
    return await _ptitsBricosContext
        .Articles
        .OrderBy(a => Guid.NewGuid())
        .Include(a => a.Pictures)
        .Where(a => a.Category.Id == categoryId)
        .Take(numberOfArticles)
        .ToListAsync();
}

When I remove the .OrderBy(a => Guid.NewGuid()), I rightly retrieve the Pictures related, but when I add it again, I always retrieve an empty list of pictures (even if I always have results).
I'm kind of stuck, I don't see why it changes the behavior of the request.

A: The issue is caused by the combination of the random order, Take operator and sub collection Include.
EF Core processes collection Includes by using a separate database query, joining the primary query with the related table.
Since the primary query in this scenario returns different records, the second query join simply does not return the related records of the first query result. The related collections might be empty or partially populated.
Unfortunately I see no good workaround for this scenario. Consider posting it to their GitHub issue tracker and see what they will say.
The only relatively efficient workaround I see is to modify the main query to return just the PKs, execute it and use the list as criteria for the actual query:
var ids = await _ptitsBricosContext
    .Articles
    .OrderBy(a => Guid.NewGuid())
    .Where(a => a.Category.Id == categoryId)
    .Take(numberOfArticles)
    .Select(a => a.Id)
    .ToListAsync();

return await _ptitsBricosContext
    .Articles
    .Include(a => a.Pictures)
    .Where(a => ids.Contains(a.Id))
    .ToListAsync();


text:
Q: How to show that $\int_0^\pi \arcsin{\left(\frac{\sin{x}}{\sqrt{5/4-\cos{x}}}\right)}dx=\frac{\pi^2}{4}$? I am trying to show that
$$\int_0^\pi \arcsin{\left(\frac{\sin{x}}{\sqrt{5/4-\cos{x}}}\right)}dx=\frac{\pi^2}{4}$$
Context: I was working on another question ("Attempt $2$") and miscopied an integral, so I was trying to evaluate the integral in my question here. Anyway, now I'm intrigued by this integral, because my computer strongly suggests that it has a closed form, $\frac{\pi^2}{4}$.
My attempt: I have tried substituting $u=\cos{x}$ or $u=\frac{\sin{x}}{\sqrt{5/4-\cos{x}}}$, and the half-angle tangent substitution, but they do not seem to work.
(Ideally, there is an elementary solution, but any solution would be appreciated.)

A: One can show that $\sin(x)/\sqrt{5/4-\cos(x)}$ increases from $0$ to $1$ for $x$ going from $0$ to $\pi/3$ and decreases from $1$ to $0$ for $x$ going from $\pi/3$ to $\pi$. Then the integral can be separated into
\begin{align}
 I&=\int_0^\pi \arcsin{\left(\frac{\sin{x}}{\sqrt{5/4-\cos{x}}}\right)}\,dx\\
 &=\int_0^{\pi/3} \arcsin{\left(\frac{\sin{x}}{\sqrt{5/4-\cos{x}}}\right)}\,dx+\int_{\pi/3}^\pi \arcsin{\left(\frac{\sin{x}}{\sqrt{5/4-\cos{x}}}\right)}\,dx
\end{align}
We define
\begin{equation}
 u=\frac{\sin{x}}{\sqrt{5/4-\cos{x}}}
\end{equation}
or $u^2(5/4-\cos{x})=1-\cos^2x$.
Solving this equation for $\cos x$,

*

*for $0\le x\le\pi/3$, we have $\cos x=(u^2+\sqrt{u^4-5u^2+4})/2$

*for $\pi/3\le x\le\pi$, we have $\cos x=(u^2-\sqrt{u^4-5u^2+4})/2$.

Substituting $u$ into the integral, it comes
\begin{align}
 I&=\int_0^1\arcsin(u)\frac{\sqrt{5-2 u^{2}-2 \sqrt{u^{4}-5 u^{2}+4}}}{\sqrt{u^{4}-5 u^{2}+4}}\,du+
 \int_0^1\arcsin(u)\frac{\sqrt{5-2 u^{2}+2 \sqrt{u^{4}-5 u^{2}+4}}}{\sqrt{u^{4}-5 u^{2}+4}}\,du\\
 &=\int_0^1\frac{\arcsin(u)}{\sqrt{u^{4}-5 u^{2}+4}}
 f(u)\,du
\end{align}
where $f(u)=\sqrt{5-2 u^{2}-2 \sqrt{u^{4}-5 u^{2}+4}}+\sqrt{5-2 u^{2}+2 \sqrt{u^{4}-5 u^{2}+4}}$.
Now, it is possible to simplify:
\begin{align}
 \left[f(u)\right]^2&=10-4u^2+2\sqrt{5-2 u^{2}-2 \sqrt{u^{4}-5 u^{2}+4}}\sqrt{5-2 u^{2}+2 \sqrt{u^{4}-5 u^{2}+4}}\\
 &=4(4-u^2)
\end{align}
and
\begin{equation}
 \sqrt{\frac{4(4-u^2)}{u^{4}-5 u^{2}+4}}=\frac{2}{\sqrt{1-u^2}}
\end{equation}
Then
\begin{align}
 I&=2\int_0^1\frac{\arcsin(u)}{\sqrt{1-u^2}}\,du\\
&=\left.\arcsin^2(x)\right|_0^1\\
 &=\frac{\pi^2}{4}
\end{align}
as expected.


text:
Q: How to add new systemcall in Linux 3.2.x? I'm new to Linux, and I want to compile my kernel for Debian-amd64 with a new system call. The only tutorial I could find online was for a i386 or x86 system. I followed their instructions but at the end my new system call returned -1.
#define _CS2456_TEST_ 349
printf ("\n%d\n",  syscall(_CS2456_TEST_ , 2456)) ;

My current kernel is 3.2.63.
How can I add a new system call into my kernel for AMD64? Either a description of the details or a good tutorial or guide would be helpful.

A: It is pretty easy, there is a quick and small tutorial at https://arvindsraj.wordpress.com/2012/10/05/adding-hello-world-system-call-to-linux/


text:
Q: What is the need to do sharding of TFRecords files? Why TFRecords file is sharded in the inception model example in TensorFlow ?
For randomness, can't the list of files be shuffled before creating one single TFRecord file ?

A: Why TFRecords file is sharded in the inception model example in TensorFlow ?
According to object detection API, there are two advantages in sharding your dataset:

*

*Files can be read in parallel, improving data loading speed

*Examples can be shuffled better by sharding

You probably already knew the second point as it is in your second question:
For randomness, can't the list of files be shuffled before creating one single TFRecord file ?
Shuffling the dataset before creating the record is indeed a good practice because shuffling a TFRecord can only be done partially. Indeed, you can only load a certain number of examples in memory. The shuffling is then done by selecting randomly your next example among the ones in memory. You can see more in this question
However, if you only shuffle the dataset when creating the record, your network will always see examples in the same order in the successive training epochs. This might result in unwanted convergence behaviours due to the random order that was given once and for all. It is thus more interesting to shuffle the dataset on the fly to have different orderings in different epochs.
Sharding your dataset can easen the shuffling. Instead to be forced to always read in the same order from the same one file, you can start to read a bit from each file, choosing at random.


text:
Q: Adding a column requires a default value for another column? I'm adding a column to a table, but it tells me I'm not setting a default value for another column of the table;
ALTER TABLE `myDatabase`.`myTable` ADD myNewColumn varchar(2);

Gives me the response
ERROR 1067 (42000): Invalid default value for 'modifiedDate'
I don't get why I need to set a default value for a column when I'm just altering a table?

A: The problem was with my table definition, not the command itself.
The table had modifiedDate set incorrectly I assume, I changed it to use CURRENT_TIMESTAMP instead with the following command
ALTER TABLE myTable MODIFY column modifiedDate timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP;
After this everything worked. Below is the description of this row before:
| Field       | Type      | Null| Key | Default
| modifiedDate | timestamp | NO  |     | 0000-00-00 00:00:00
And after :
| Field       | Type      | Null| Key | Default
| modifiedDate | timestamp | NO  |     | CURRENT_TIMESTAMP


text:
Q: How can I incorporate this JQuery to my D3 force layout? I am trying to open a URL on node click in a frame or dialog box but can't figure it out.
Here is the JSFiddle I've been playing around with around with and here is the JQuery dialog box I am trying to use on it. Below is the code I used to trigger a URL on click but I want to open the URL in dialog box, not the same window. Thanks!
    .append("a")
 .attr("xlink:href", function (d) { return "http://www.google.com/" + d.atom })
  .call(force.drag);

A: You can add another event listener to your nodes, you already have two, one for mouseover and mouseout, now you can add one for click (and pass a property to indicate what URL you want to load).
.on("click",function(d) { click(d.atom); });

Then all you have to do is set a dialog box div's content however you want:
function click(link) {
     $("#dialog").html('<iframe src="http://www.'+link+'.com"></iframe>').dialog({
         autoOpen: false,
         modal: true
      });

    $("#dialog").dialog('open');

 }

Here is a link to an updated fiddle: http://jsfiddle.net/pzuyhobc/1/


text:
Q: Access Electron API from a completely different system process I am looking for a way to capture a screenshot of a VS Code extension host window. This window is opened when my extension's tests are being run (this is coming from the default Yeoman template for VS Code extensions).
I cannot use my extension's context as the extension only has access to the VS Code API and VS Code runs extensions in a different Node process from the Electron one (main or renderer). IPC is used through the API instead of running extensions in-process.
I can run this code in an Electron renderer process (using DevTools or as a part of the Electron application's script) to capture the Electron window:
const electron = require('electron');
electron.remote.getCurrentWindow().capturePage(image => {
  //electron.clipboard.writeImage(image);
  electron.clipboard.writeText(image.toDataURL());
  console.log('Data URL is in clipboard.');
});

I have verified that placing this in VS Code window DevTools will produce the correct Data URI.
In order to be able to do this from a different Node process, knowing only the Code window PID, I figured I would attach a debugger to the VS Code extension host Electron window and using CDP I would issue a Runtime.evaluate call to run the above code as if it was entered into the DevTools.
However, I am struggling with attaching the debugger. There are generally two ways to do it:

*

*kill -s SIGUSR1 <node-pid> for Unix/macOS

*process._debugProcess(proc.pid); for Windows

I am interested in Windows right now, so I issue the Windows line from a new Node process. What should happen upon successful debugger attachment is the target process should print out something like this:
Debugger listening on ws://127.0.0.1:9229/cf49bcfe-d922-4f89-b438-57755d254198
For help see https://nodejs.org/en/docs/inspector

However in my case, this only works if I start the barebones Electron app with --inspect and then issue process._debugProcess(proc.pid);, without --inspect it doesn't throw an error, but doesn't attach the debugger either.

A: process._debugProcess now works for me with Electron 5.


text:
Q: Is there some sort of "no newline at eof" rules for bash scripts? I have two files, an env file and a run file. When I deploy them to my Ubuntu Server box I get the error:

./start-admin: line 10: syntax error: unexpected end of file

If I deploy and then add a newline to the end of the file, it will show the error. If I then remove it the error goes away. If I deploy again and don't add the newline, it still shows the error, but if I then add a newline the error goes away. What could possibly cause that?
Below are my scripts:
env:
if [ "x${WD}" == "x" ];  then echo "missing required conf \"\${WD}\"" >&2; exit -1; fi

export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64
export JAR_FILE="$WD/mfa-admin.jar"
export MYSQL_URL=url1
export MYSQL_USER=root
export MYSQL_PASSWORD=pwd
export DB_URL=url2
export DB_USER=user
export DB_PASSWORD=pwd2

export EMAIL_HOST=mail-inbox
export EMAIL_PORT=25
export EMAIL_PERMISSION=false
export FAKE_EMAIL=email
export ACTIVATION_URL=url

export BIND_HOST=0.0.0.0
export BIND_PORT=8282

start:
WD=`dirname $0`;

JAVA_OPTS=""

if [ -r "$WD/admin.env.conf" ]; then
  . $WD/admin.env.conf
fi

# required stuff
if [ "x${JAVA_HOME}" == "x" ];                              then echo "missing required conf \"\${JAVA_HOME}\""                                                  >&2; exit -1; fi
if [ "x${JAR_FILE}" == "x" ];                               then echo "missing required conf \"\${JAR_FILE}\""                                                   >&2; exit -1; fi
if [ "x${MYSQL_URL}" == "x" ];                   then echo "missing required conf \"\${MYSQL_URL}\""        >&2; exit -1; fi
if [ "x${MYSQL_USER}" == "x" ];                  then echo "missing required conf \"\${MYSQL_USER}\""       >&2; exit -1; fi
if [ "x${MYSQL_PASSWORD}" == "x" ];              then echo "missing required conf \"\${MYSQL_PASSWORD}\""   >&2; exit -1; fi
if [ "x${DB_URL}" == "x" ];                      then echo "missing required conf \"\${DB_URL}\""                            >&2; exit -1; fi
if [ "x${DB_USER}" == "x" ];                     then echo "missing required conf \"\${DB_USER}\""                           >&2; exit -1; fi
if [ "x${DB_PASSWORD}" == "x" ];                 then echo "missing required conf \"\${DB_PASSWORD}\""                       >&2; exit -1; fi

if [ "x${EMAIL_HOST}" == "x" ];                  then echo "missing required conf \"\${EMAIL_HOST}\""                       >&2; exit -1; fi
if [ "x${EMAIL_PORT}" == "x" ];                  then echo "missing required conf \"\${EMAIL_PORT}\""                       >&2; exit -1; fi
if [ "x${EMAIL_PERMISSION}" == "x" ];            then echo "missing required conf \"\${EMAIL_PERMISSION}\""                 >&2; exit -1; fi
if [ "x${FAKE_EMAIL}" == "x" ];                  then echo "missing required conf \"\${FAKE_EMAIL}\""                       >&2; exit -1; fi
if [ "x${ACTIVATION_URL}" == "x" ];              then echo "missing required conf \"\${ACTIVATION_URL}\""                   >&2; exit -1; fi

if [ "x${BIND_HOST}" == "x" ];                    then echo "missing required conf \"\${BIND_HOST}\""                         >&2; exit -1; fi
if [ "x${BIND_PORT}" == "x" ];                    then echo "missing required conf \"\${BIND_PORT}\""                         >&2; exit -1; fi

JAVA_OPTS="${JAVA_OPTS} -Dmysql.URL=\"${MYSQL_URL}\" "
JAVA_OPTS="${JAVA_OPTS} -Dmysql.USER=\"${MYSQL_USER}\" "
JAVA_OPTS="${JAVA_OPTS} -Dmysql.PASSWORD=\"${MYSQL_PASSWORD}\" "
JAVA_OPTS="${JAVA_OPTS} -Ddb.URL=\"${DB_URL}\" "
JAVA_OPTS="${JAVA_OPTS} -Ddb.USER=\"${DB_USER}\" "
JAVA_OPTS="${JAVA_OPTS} -Ddb.PASSWORD=\"${DB_PASSWORD}\" "

JAVA_OPTS="${JAVA_OPTS} -DEMAIL_HOST=\"${EMAIL_HOST}\" "
JAVA_OPTS="${JAVA_OPTS} -DEMAIL_PORT=\"${EMAIL_PORT}\" "
JAVA_OPTS="${JAVA_OPTS} -DEMAIL_PERMISSION=\"${EMAIL_PERMISSION}\" "
JAVA_OPTS="${JAVA_OPTS} -DFAKE_EMAIL=\"${FAKE_EMAIL}\" "
JAVA_OPTS="${JAVA_OPTS} -DACTIVATION_URL=\"${ACTIVATION_URL}\" "

JAVA_OPTS="${JAVA_OPTS} -DBIND_HOST=\"${BIND_HOST}\" "
JAVA_OPTS="${JAVA_OPTS} -DBIND_PORT=\"${BIND_PORT}\" "

JAVA="$JAVA_HOME/bin/java"

eval \"$JAVA\" $JAVA_OPTS -cp "${WD}:${JAR_FILE}" VertxNode

A: When I have obtained this message, it is the result of mismatched `, ', or " strings within the script.  Sometimes this also happens with mismatched if/then/fi, do/while, or case/esac statements.  I'd strongly check out your scripting closely.


text:
Q: characters being skipped being output file i/o I have a function meant to encrypt a file by replacing each character with the character three letters before, but I'm having some issues with the output.
void file_encrypt(char * filename)
{
    FILE *file1 = fopen(filename, "r");
    char c;

    if(file1 != NULL) {
        while(fscanf(file1, "%c", &c) == 1) {
            c = fgetc(file1);
            if(c == 'a' || c == 'b' || c == 'c' || c == ' ') {
                switch(c) {
                    case 'a': putchar('x');
                        break;
                    case 'b': putchar('y');
                        break;
                    case 'c': putchar('z');
                        break;
                    case ' ': putchar(' ');
                        break;
                }
            }
            else
                printf("%c", c - 3);
        }
    }
}

my input file is a text file containing aaaaa bbbbb ccccc def as a simple test, so my output should be xxxxx yyyyy zzzzz abc but instead it's xx yy zz b.
I've tried messing around with the while loop condition (making it != EOF instead of == 1, changing the fscanf to a fgetc check) the c = fgetc(file1) statement had previously been fscanf(file1, "%c", &c) to assign the char to the address of c, same result.
Looking at it now I can see that it is reading or writing every other character rather, including skipping the first one. Anyone have any idea why this is?

A: At the beginning of the loop, you read twice from the file, ignoring the first value read (into c, by fscanf()):
    while(fscanf(file1, "%c", &c) == 1) {
        c = fgetc(file1);

You probably want to simplify this to read only once:
    int c;   // EOF is not a 'char' value
    while ((c = fgetc(file1)) != EOF) {


text:
Q: VIM: How can i know which highlight rule is being used for a keyword? :colorscheme default

The filetype is php.

Can anyone help me to find out the highlight rule ?

A: :hi[light]

will list all defined rules with a preview. You can also query single items:
:hi Keyword

To manually look up any syntax group under the cursor, there are choices. Mine is a function bounded to a key like this:
" Show syntax highlighting groups for word under cursor
nmap <F2> :call <SID>SynStack()<CR>
function! <SID>SynStack()
    if !exists("*synstack")
        return
    endif
    echo map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")')
endfunc

It'll list every syntax group the word belongs to.

A: I've had the following snippet tucked away for a while now, not sure where I got it.  This will set your statusline to show the highlight group of the word currently under the cursor:
:set statusline=%{synIDattr(synIDtrans(synID(line('.'),col('.'),1)),'name')}

This will update your statusline as you move around the file.

A: I have something like this in my _gvimrc:
function! SyntaxBalloon()
    let synID   = synID(v:beval_lnum, v:beval_col, 0)
    let groupID = synIDtrans(synID)
    let name    = synIDattr(synID, "name")
    let group   = synIDattr(groupID, "name")
    return name . "\n" . group
endfunction

set balloonexpr=SyntaxBalloon()
set ballooneval


text:
Q: unknown host for domain on ec2 instance I have an EC2 instance with WHM installed and I'm trying to host a website on it. I can ping the EC2 just fine but attempting to ping the domain gets me "unknown host". As far as I can tell my DNS and vhost info is set up correctly.
Is there some common configuration step I'm missing to get a domain up and running on ec2?

A: You need to create 'A record' for DNS to bind domain to IP address. This can be done in route 53, there are various types of options please find here that suits you.


text:
Q: Fetch an array in zend framework I am new with zend and I don't know how to fetch an array into a view (phtml).
This is my array:
[["0","Henedy"],["0","Samer"],["0","Walid"]]

and this is my controller and my model table code :
public function getUsersCoNbre()
{
    $select = new Select();
    $select->from('user');
    $select->columns(array('*'));
    $select->join(
        'co_addi_info',
        'user.pin = co_addi_info.user_pin',
        array('co_nbre'),
        'inner'
    );
    $statement = $this->tableGateway->getSql()->prepareStatementForSqlObject($select);
    $resultSet = $statement->execute();

    return $resultSet;
}

public function indexAction()
{
    $users_co_nbre = iterator_to_array($this->getAddiinfoTable()->getUsersCoNbre());

    // $jsonres = Json::encode($users_co_nbre);
    // print_r($jsonres);die;
    $view = new ViewModel();
    $view->setTemplate('covoiturage/covoiturage/admin/statistics');
    $view->setVariables(array(
        'users_co_nbre' => $users_co_nbre,
    ));

    return $view;
}


text:
Q: fgetc reads wrong characters from file I use fgetc to read characters from a file and it reads something strange.
I have this in the txt file:

But when i look at the file info it shows this:

and fgetc actually reads the { as first character of the file instead of S.
I tried to change the file extension to rtf,txt, no extension but same result.
Any ideas how to fix this?

A: Looks like you wrote the file in some sort of editor that stores its metadata at the beginning of the file.  Try recreating the file with a more basic editor that does just text editing.  Or from the command line echo "my file contents" > myfilename.txt.


text:
Q: What is '^' operator used in C other than to check if two numbers are equal? What are the purposes of ^ operator used in C other than to check if two numbers are equal? Also, why is it used for equality in stead of == in the first place?

A: The ^ operator is the bitwise XOR operator. Although I have never seen it's use for checking equaltity.
x ^ y will evaluate to 0 exatly when x == y.

A: ^ is a bit-wise XOR operator in C. It can be used in bits toggling and to swap two numbers;
x^=y, y^=x, x^=y;

and can be used to find max of two numbers;
int max(int x, int y)
{
      return x ^ ((x ^ y) & -(x < y));
}

A: It can be used to selectively flip bits. (e.g. to toggle the value of bit #3 in an integer, you can say x = x ^ (1<<3)  or, more compactly, x = x^0x08 or even x^=8. (although now that I look at it, the last form looks like some sort of obscene emoticon and should probably be avoided. :)
It should never be used in a test for equality (in C), except in tricky code meant to test undergrads' understanding of the ^ operator. (In assembly, there may be speed advantages on some architectures.)

A: The XOR operator is used in cryptography (en- and decrypting text using a pseudo-random bit stream), random number generators (like the Mersenne Twister) and in inline-swap and other bit twiddling hacks:
 int a = ...;
 int b = ...;

 // swap a and b
 a ^= b;
 b ^= a;
 a ^= b;

(useful if you don't have space for another variable like on CPUs with few registers).

A: ^ is the Bitwise XOR.
A bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. It is a fast, primitive action directly supported by the processor, and is used to manipulate values for comparisons and calculations. (source: Bitwise Operation)
The XOR Operator has two operands and it returns 1 if only one of the operands is set to 1.
So a Bitwise XOR Operation of two numbers is the resulting of these bit by bit operations.
For exemple:
00000110 // A = 6

00001010 // B = 10

00001100 // A ^ B = 12

A: It it's the exclusive or operator. It will do bitwise exclusive or on the two arguments. If the numbers are equal, this will result in 0, while if they're not equal, the bits that differed between the two arguments will be set.
You generally wouldn't use it inserted of ==, you would use it only when you need to know which bits are different.

A: Two real usage examples from an embedded system I worked on:
In a status message generating function, where one of the words was supposed to be a passthrough of an external device's status word. There was an disconnect between the device behavior and the message spec - one thought bit0 meant 'error' while the other thought it meant 'OK'.
statuswords[3] = devicestatus ^ 1; //invert B0

The 16-bit target processor was terribly slow to branch, so in an inner loop if (sign(A)!=sign(B) B=0; was coded as:
B*=~(A^B)>>15;

which took 4 cycles rather than 8, and does the same thing: sets B to 0 iff the sign bits are different.

A: in many general cases we might use '^' as a replacement for'==' but that doesn't exactly give the result for being equal or not.Instead - it checks the given variables bit by bit and sets a result for each bit individually and finally displays a result summed up with the resulting bits as a bulk.


text:
Q: Data not return from mysql json data type I have search data from json field of mysql by where condition. but there are no data show.
MySql field name of "attributes_list" which is json type
My json data:
{
 "0":
    {
      "id": "01c93aae-8603-42f3-b097-89357467872a#####ed20eb29-611a-4e5c-a966-c09708c98179",
      "text": "Canada",
      "attr_name": "Country"
    },
 "1":
    {
      "id": "01c93aae-8603-42f3-b097-89357467872a#####6e6269a1-afbb-4d5d-b2ee-6d25fe38fec7",
      "text": "Ontario",
      "attr_name": "REGION"
    },
 "2":
    {
      "id": "5a0a085e-f3e4-4fbe-9f3e-61cec4836d36#####d81923c9-9532-4375-ba3d-19214ac61c4e",
      "text": "Lager",
      "attr_name": "TYPE"
    },
 "-1": {"id": "", "text": "", "attr_name": ""}
}

My json query of mysql:
when I run following query then show data
SELECT * FROM products where attributes_list->'$[0]."0".text' = 'Canada';

but when I run this there are not show data
SELECT * FROM products where attributes_list->'$[0]."*".text' = 'Canada';

I explain my condition:
In product table there are 6 rows. In product table, there are a field which name attribute list.
This field is json type. There are save multiple attribute of a product. my attribute_list json format is
{"0":{"id":"","text":""},"1":{"id":"","text":""}}.

Now I want to search where text='Canada' then read those product information

A: According to mySql manual selector $**.text will come in use.
[search for (the path $**.b) on the page to reach there.]
This will search for second level of every document and will return the value of text key at second level.
So your query will be like:
SELECT * FROM products where attributes_list->'$.*.text' = 'Canada';

Also I have tried to perform same task as you mentioned above in fiddle


text:
Q: Using multiple for loop with Python Using Beautiful Soup from bs4 import BeautifulSoup as bs
import requests
import pandas as pd

url = "https://www.property24.com/for-sale/woodland-hills-wildlife-estate/bloemfontein/free-state/10467/109825373"

data = requests.get(url)
soup = bs(data.content,"html.parser")

The code below are a test with to get 1 item.
property_overview = soup.find(class_="p24_regularListing").find(class_="p24_propertyOverview").find(class_='p24_propertyOverviewRow').find(class_='col-xs-6 p24_propertyOverviewKey').text

property_overview

Output : 'Listing Number'

The code below is what we have to get all the col-xs-6 p24_propertyOverviewKey
p24_regularListing_items = soup.find_all(class_="p24_regularListing")

for p24_propertyOverview_item in p24_regularListing_items:
    p24_propertyOverview_items = p24_propertyOverview_item.find_all(class_="p24_propertyOverview")

    for p24_propertyOverviewRow_item in p24_propertyOverview_items:
        p24_propertyOverviewRow_items = p24_propertyOverviewRow_item.find_all(class_="p24_propertyOverviewRow")

        for p24_propertyOverviewKey_item in p24_propertyOverviewRow_items:
            p24_propertyOverviewKey_items = p24_propertyOverviewKey_item.find_all(class_="col-xs-6 p24_propertyOverviewKey")

p24_propertyOverviewKey_items

The code above only outputs 1 item. and not all

A: To put things more simply, you can use soup.select() (and via the comments, you can then use .get_text() to extract the text from each tag).
from bs4 import BeautifulSoup
import requests

resp = requests.get(
    "https://www.property24.com/for-sale/woodland-hills-wildlife-estate/bloemfontein/free-state/10467/109825373"
)
resp.raise_for_status()
soup = BeautifulSoup(resp.content, "html.parser")
texts = []
for tag in soup.select(
    # NB: this selector uses Python's implicit string concatenation
    #     to split it onto several lines.
    ".p24_regularListing "
    ".p24_propertyOverview "
    ".p24_propertyOverviewRow "
    ".p24_propertyOverviewKey"
):
    texts.append(tag.get_text())
print(texts)


text:
Q: Strange thread behavior with onClickListener I am trying to change the background of a button to 'pressed' for 1 second, then change that background back to 'default'. I created one Thread called sleeper that simply sleeps for 1 second. Below is the method I am using. The strange thing is, the buttons background doesn't change until the sleeper thread is done sleeping. I know threads are never guarenteed to start at any given time but since I am setting the background of the button before starting the Thread I figured this should work.
private void handleButtonPress(View button, int buttonPressedID,
        int buttonNormalID) {

    button.setBackgroundResource(buttonPressedID);
    Sleeper sleeper = new Sleeper();
    sleeper.start();
    try {
        sleeper.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

Thanks for having a look!

A: Please simply use a Handler for that:
Handler h = new Handler();

h.postDelayed(new Runnable() {

    @Override
    public void run() {
        // do your delayed stuff here
    }
}, 1000); // execute the code inside run() after 1000ms


text:
Q: Scala: "recursive value ... needs type" but I use Java types only object Rec extends App {
  val outStream = new java.io.ByteArrayOutputStream
  {
    val out = new java.io.PrintStream(new java.io.BufferedOutputStream(outStream))
  }
}

This seemingly simple code causes a compile error:
$ scalac rec.scala
rec.scala:2: error: recursive value out needs type
  val outStream = new java.io.ByteArrayOutputStream
                  ^
one error found

But I don't see what is "recursive."
Scala compiler version 2.11.7 -- Copyright 2002-2013, LAMP/EPFL
Background: I was trying to write a unit test on println with Console.withOut

A: You are assigning a value to outStream by invoking stuff to which you pass on the outStream (I marked it in CAPS). Hence the recursion.
object Rec extends App {
  val OUTSTREAM = new java.io.ByteArrayOutputStream
  {
    val out = new java.io.PrintStream(new java.io.BufferedOutputStream(OUTSTREAM))
  }
}

A: After putting braces where they belong code looks like this:
object Rec extends App {
  val outStream = new java.io.ByteArrayOutputStream {
    val out = new java.io.PrintStream(new java.io.BufferedOutputStream(outStream))
  }
}

and this is how you create object of an anonymous class with a member out that uses the defined object recursively (outStream uses outStream in its definition).
I believe this is what you wanted to do
object Rec extends App {
  val outStream = new java.io.ByteArrayOutputStream
  val out = new java.io.PrintStream(new java.io.BufferedOutputStream(outStream))
}

If you for some reason need to create another scope, you can use locally
What does Predef.locally do, and how is it different from Predef.identity


text:
Q: Amazon SimpleDB cache problem I'm experimenting with Amazon SimpleDB (using Rick Helms' PHP API) and I've noticed that the updates are not in real time. I mean, if in the same page I contact the service to delete and item and the retrieve the items list, the deleted item is often still there.
Any idea on what's going on and how to solve the problem? Thanks

A: It is generally the case with large scale databases, they have eventual consistency, meaning that information does not immediately nor atomically propagate to all the nodes.
You can have a look to this: http://www.satine.org/archives/2007/12/13/amazon-simpledb/
The official page also notes that it is eventually consistent giving an explanation here:
http://aws.amazon.com/simpledb/#eventually-consistent
Apparently, you can force consistent reads as explained here:
http://aws.amazon.com/simpledb/#consistent


text:
Q: Simulate a laptop behind a proxy server I wrote a small java code that uploads a file to an ftp server.
It's not working for people behind a proxy server, to debug, I'd like to simulate their conditions.
What's the best way to do it? is there a proxy server I can download and setup so that my computer requires proxy setup to access the network?
Thanks a lot

A: You can use Squid for Windows, which is a very good proxy, but maybe the smaller CC Proxy is enough for your needs.


text:
Q: Angular material md-toolbar expansion transition I'm using the md-toolbar component from Angular material. By default, its height is "normal", and by adding the class md-tall, it can be taller.
I'm trying to apply a CSS transition to make it expand smoothly, but it doesn't behave as expected. The transition only occurs one way, but not in reverse.
Here is the code (and a codepen : http://codepen.io/anon/pen/MwbrjL) :
Markup

    <md-toolbar layout="row" class="toolbar" ng-class="{'md-tall': expanded}">

Title

    </md-toolbar>
    <md-content>
      <md-button class="md-raised" ng-click="expand()">Expand</md-button>
    </md-content>

Javacript
(function () {
  angular
    .module('TestApp', ['ngMaterial']);
})();

(function () {
  angular
    .module('TestApp')
    .controller('App', App);

  App.$inject = ['$scope'];

  function App($scope) {
    $scope.expanded = false;

    $scope.expand = function() {
      $scope.expanded = !$scope.expanded;
    }
  }
})();

CSS
.toolbar {
  transition: all 1s;
}

Thank you for your time.

A: Short answer:
Add the following to your css:
.md-toolbar.md-tall {
    max-height: 0px;
}

CodePen: http://codepen.io/anon/pen/WvodLL
Long answer:
Angular material's toolbar (md-toolbar) has a height of 64px. Angular actually sets the height, min-height and max-height to 64px. The tall toolbar (md-toolbar.md-tall) has double that height (and min-/max-height as well).
See https://github.com/angular/material/blob/master/src/components/toolbar/toolbar.scss for the actual implemetation.
Now, this is speculation: when you add the .md-tall class to your toolbar, its height (, min-height and max-height) will be set to 128px before the transition begins - and therefore has nothing to transition to. In fact, when you change the max-height of .md-tall to something bigger than 128px, it will be animated beyond it. My feeling here is that it has something to do with a) min-height overriding max-height/height when they are smaller and b) the order in which angular adds classes by ng-class and css transitions take place.

A: You need to override the .md-tall css class to give it transition property.
Something like this:
  <md-toolbar layout="row"  ng-class="{'toolbar': !expanded, 'xtoolbar' : expanded}">

and the CSS will be as following:
.toolbar {
  transition: all 1s;
}
.xtoolbar {
  transition: all 1s;
  min-height: 128px;
  max-height: 128px;
}


text:
Q: how to override settings per test file in django? I have two tests that when run at the same time fails:
pytest -s -v blog/tests/

but when run individually it passes:
pytest -s -v blog/tests/test_A.py
pytest -s -v blog/tests/test_B.py

I think the cause of this is both uses this pytest.fixture to override the settings:
test_A.py:
@pytest.fixture(autouse=True)
def override_url(settings):
    settings.A_URL = f'https://{ip_host}:{port}'

test_B.py
@pytest.fixture(autouse=True)
def override_url(settings):
    settings.B_URL = f'https://{ip_host}:{port}'

Is there a way to fix this fixture to avoid the tests failing when ran at the same time?

A: Try removing autouse=True
With the value set to 'True', all tests in this session just use the fixture automatically.


text:
Q: Choice of Outcomes in Experiments Suppose I design an experiment. I can choose between two types of outcomes:
(i) continious outcome $Y$, which is restricted to the interval $0\leq Y \leq 1$
(ii) quasi-continious outcome $Y$, which takes the values: $0.1, 0.2,...,1$
Which one should I choose given that I want to maximize statistical power of the following regression (OLS):
$Y=\beta_0+\beta_1T$.
$T$ is a binary treatment indicator.

A: I'd always choose the more granular option (i), all else being equal.
Then, maybe try transforming your $Y$ in to $Y^*$ before OLS estimation using the inverse CDF of an appropriate distribution. Once you get your $\hat{Y}^*,$ put it through the CDF to get $\hat{Y}$ and back into the 0 to 1 interval.
Caution should be used, however, since it is probably true in your case that $E[f(Y)]\neq f(E[Y])$


text:
Q: How to add MessageID in SOAP request using Axis2 and Rampart I am trying to build a client application that consume external server application using Axis2 and rampat 1.6.
Everything seems to be fine when checking SOAP request, since SOAP get encrypted and signed as expected. Following is the policy.xml file used for that purpose:
<wsp:Policy wsu:Id="MyPolicy"
    xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
    xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
    xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy"
    xmlns:wsam="http://schemas.xmlsoap.org/ws/2004/08/addressing"
    xmlns:wst="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID">
<wsp:ExactlyOne>
    <wsp:All>
        <sp:SignedSupportingTokens xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
            <wsp:Policy>
                <sp:UsernameToken sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/AlwaysToRecipient" />
            </wsp:Policy>
        </sp:SignedSupportingTokens>
        <sp:SymmetricBinding>
            <wsp:Policy>
                <sp:ProtectionToken>
                    <wsp:Policy>
                        <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                            <wsp:Policy>
                                <sp:RequireIssuerSerialReference/>
                                <sp:WssX509V3Token10/>
                            </wsp:Policy>
                        </sp:X509Token>
                    </wsp:Policy>
                </sp:ProtectionToken>

                <sp:AlgorithmSuite>
                    <wsp:Policy>
                        <sp:Basic128/>
                    </wsp:Policy>
                </sp:AlgorithmSuite>
                <sp:IncludeTimestamp/>
                <sp:Layout>
                    <wsp:Policy>
                        <sp:Strict/>
                    </wsp:Policy>
                </sp:Layout>
                <sp:OnlySignEntireHeadersAndBody/>
            </wsp:Policy>
        </sp:SymmetricBinding>
        <sp:EncryptedParts>
            <sp:Body />
        </sp:EncryptedParts>
        <sp:SignedParts>
            <sp:Body/>
            <sp:Header Namespace="http://www.w3.org/2005/08/addressing" Name="ReplyTo"/>
            <sp:Header Namespace="http://www.w3.org/2005/08/addressing" Name="To"/>
            <sp:Header Namespace="http://www.w3.org/2005/08/addressing" Name="From"/>
            <sp:Header Namespace="http://docs.oasis-open.org/ws-rx/wsrm/200702" Name="AckRequested"/>
            <sp:Header Namespace="http://docs.oasis-open.org/ws-rx/wsrm/200702" Name="CreateSequence"/>
            <sp:Header Namespace="http://docs.oasis-open.org/ws-rx/wsrm/200702" Name="Sequence"/>
            <sp:Header Namespace="http://www.w3.org/2005/08/addressing" Name="MessageID"/>
            <sp:Header Namespace="http://www.w3.org/2005/08/addressing" Name="FaultTo"/>
            <sp:Header Namespace="http://docs.oasis-open.org/ws-rx/wsrm/200702" Name="SequenceAcknowledgement"/>
            <sp:Header Namespace="http://www.w3.org/2005/08/addressing" Name="Action"/>
            <sp:Header Namespace="http://www.w3.org/2005/08/addressing" Name="RelatesTo"/>
        </sp:SignedParts>
        <sp:Wss11>
            <wsp:Policy>
                <sp:MustSupportRefEncryptedKey/>
                <sp:MustSupportRefIssuerSerial/>
                <sp:MustSupportRefThumbprint/>
            </wsp:Policy>
        </sp:Wss11>
        <ramp:RampartConfig xmlns:ramp="http://ws.apache.org/rampart/policy">
            <ramp:userCertAlias>mySignAlias</ramp:userCertAlias>
            <ramp:encryptionUser>myEncryptAlias</ramp:encryptionUser>
            <ramp:user>myUser</ramp:user>
            <ramp:passwordCallbackClass>myPackage.PasswordCallBackHandler</ramp:passwordCallbackClass>
            <ramp:encryptionCypto>
                <ramp:crypto provider="org.apache.ws.security.components.crypto.Merlin">
                    <ramp:property name="org.apache.ws.security.crypto.merlin.keystore.type">JKS</ramp:property>
                    <ramp:property name="org.apache.ws.security.crypto.merlin.file">[path goes here]/clientTrustStore.jks</ramp:property>
                    <ramp:property name="org.apache.ws.security.crypto.merlin.keystore.password">changeit</ramp:property>
                </ramp:crypto>
            </ramp:encryptionCypto>

            <ramp:signatureCrypto>
                <ramp:crypto provider="org.apache.ws.security.components.crypto.Merlin">
                    <ramp:property name="org.apache.ws.security.crypto.merlin.keystore.type">JKS</ramp:property>
                    <ramp:property name="org.apache.ws.security.crypto.merlin.file">[path goes here]/clientKeyStore.jks</ramp:property>
                    <ramp:property name="org.apache.ws.security.crypto.merlin.keystore.password">changeit</ramp:property>
                </ramp:crypto>
            </ramp:signatureCrypto>
        </ramp:RampartConfig>

    </wsp:All>
</wsp:ExactlyOne>

But I am getting the following axis fault while calling external server application:
SEVERE: org.apache.axis2.AxisFault: com.sun.xml.wss.XWSSecurityException: Policy verification error:Missing target MessageID for Signature
at org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(Utils.java:531)
at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:375)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:421)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)

The error is self descriptive, SOAP request is missing MessageID tag in SOAP header. I tired to find out how to add mentioned tag but no luck; I found out how to add custom SOAP header in this link adding authentication header to client stub axis2
But I want to avoid that since I am using PasswordCallBackHandler to add authentication proprieties.
Is there any way to add the MessageID automatically within SOAP header ? Further, there is similar tags like Action , ReplyTo ,To , and From how to add them to SOAP header ?
-- UPDATE:
From the auto generated java files using Axis2 tool  - see Apache Axis2 User's Guide - Creating Clients to know how stub files has been generated - I went to the API method in the auto generated Java class ServiceStub. There is a message contxet is created to send SOAP request like the follwoing:
 // create a message context
_messageContext = new org.apache.axis2.context.MessageContext();

I used the object _messageContext to set the message ID as follow:
_messageContext.setMessageID("TEST_123456");

Further, I ran application on debug mode and I can see that TEST_123456 has been added to the SOAP request as MessageID and the server is using the same MessageID in its response. But still I am getting this wired error Policy verification error:Missing target MessageID for Signature
It is confusing me how server said he is missingMessageID although it is appearing in SOAP request and response which coming from the server only !
Is this has any thing to do with the auto signature proccess ? But even so,  MessageID is already added in the SignedParts from policy file what else could be done to over come this issue ?

A: You can add all properties like Message,Action,To and Other Properties in Stub::ServiceClient::Options.
ServiceClient client = serviceStub._getServiceClient();
Options options = client.getOptions();
options.setAction(action);
options.setTo(new EndpointReference(referenceURL));
options.setMessageId(UUID.randomUUID().toString());

Sample Reference


text:
Q: Does Sitecore 9 scheduled publishing publish not only an item but also its child and related items? In Sitecore 7, if I put a scheduled publish on an item, which has children and related items, the item is published correctly, but its child items and related items are not published. Does Sitecore 9 scheduled publishing publish not only an item but also its child and related items correctly? If so, we will migrate to Sitecore 9, instead of spending a lot of time and energy on building custom code and items to make scheduled publishing work correctly. I googled but couldn't find answers to my question.

A: You are likely speaking about PublishAgent that is launched periodically (like every hour), and does Smart publish (publishes any difference between master & live).
The scheduled publish is usually achieved via publishing restrictions so that item becomes eligible to be published only after configured time (saying by midnight).
The PublishAgent would be running regularly and publish everything that is eligible. Should item kids had been unpublishible as parent was not publishable, they would be published along with parent.
The likely answer to your question - yes.


text:
Q: Securely provide a one-liner bash install script I like to provide one-line bash install scripts for things, that look something like this:
curl https://gist.githubusercontent.com/.../raw/install.sh | bash

or even
curl http://tinyurl.com/installmything | bash

But that's obviously a massive security risk for anyone that doesn't trust me.
Is there any convenient, simple way that would:

*

*let the user view the script before it runs,

*still only requires a single copy-paste operation

*isn't excessively cumbersome?

For example, I could provide the one-liner like this:
wget https://gist.githubusercontent.com/.../installthing.sh ; cat installthing.sh ; read -p "Type YES to continue: " X && [ $X = "YES" ] && bash installthing.sh

That fails the cumbersomeness requirement. Any better ways?

A: There are two types of people who don't trust you:

*

*Who know bash: These people will download your script anyway and view its content. They understand what curl ... | bash does and they won't execute that command.

*Who don't know bash: Even if you show the source code to these people, they won't be able to do anything with that. They won't be able to decide whether that code is a security risk or not.
So I think it's not needed to let the user view the content of the script before execution. But if you still want it, you could for example run the script, but ask the user before the real code gets executed. Something like:
#!/bin/bash

read -p "Do you wish to see the content of this script before execution?" -n 1 -r
echo

if [[ $REPLY =~ ^[Yy]$ ]]
then
  tail -n +20 "$0"

  echo
  read -p "Continue? " -n 1 -r
  echo

  if [[ $REPLY =~ ^[Nn]$ ]]
  then
    exit
  fi
fi

echo "INSTALL"

This way you can keep using:
curl https://gist.githubusercontent.com/.../raw/install.sh | bash