text:
Q: MySQL return N rows based on date interval I need create a query to return N rows based in an date interval. It's simple but i don't can be :/
The base query:
SELECT
  f.many_fields
FROM
  tb_foo f
WHERE
  f.id_foo = 14

This query returns 1 row based on my ID.
But, I've date interval like '2012-10-10' at '2012-10-30' to apply on this query and at end the base query will be return 20 rows based on diff of date interval.
Can be possible make this ?
SELECT
  f.many_fields,
  bar.*
FROM
  tb_foo f,
  (SELECT x FROM dual limit DATEDIFF('2012-10-10','2012-10-30')) bar
WHERE
  f.id_foo = 14

Real query:
SELECT
  m.id_matricula,
  a.nome
FROM
  tb_matricula m
    inner join tb_aluno a on (a.id_aluno = m.id_matricula)
WHERE
  m.id_matricula = 14

Start date = 2012-10-10
End date = 2012-10-30
I'll use this result on iReport to build an grid with num of rows based on difference between of this dates.
Example founded on Google searches:
SELECT
    CONCAT( dt.d ,'-' ,days.d ) AS dates
FROM
    (
        SELECT
            CONCAT( a1 ,b1 ) AS d
        FROM
            (
                SELECT
                    '0' AS a1
            UNION ALL SELECT
                    '1'
            UNION ALL SELECT
                    '2'
            UNION ALL SELECT
                    '3'
            ) a JOIN(
                SELECT
                    '0' AS b1
            UNION ALL SELECT
                    '1'
            UNION ALL SELECT
                    '2'
            UNION ALL SELECT
                    '3'
            UNION ALL SELECT
                    '4'
            UNION ALL SELECT
                    '5'
            UNION ALL SELECT
                    '6'
            UNION ALL SELECT
                    '7'
            UNION ALL SELECT
                    '8'
            UNION ALL SELECT
                    '9'
            ) b
        WHERE
            CONVERT(
                CONCAT( a1 ,b1 ) ,
                UNSIGNED
            ) <=(
                SELECT
                    DAY(
                        CONCAT( '2012-10' ,'-01' ) + INTERVAL 1 MONTH - INTERVAL 1 DAY
                    )
            )
            AND CONCAT( a1 ,b1 ) <> '00'
    ) days JOIN(
        SELECT
            '2012-10' AS d
    ) dt
 HAVING
    dates BETWEEN '2012-10-02' AND '2012-10-05'
ORDER BY
    dates
;

A: I've found an solution to this. Using a sub-query i can return many rows based on date interval, that, don't have any relation with main query. So i have this:
SELECT
    datas. * ,
    m.id_matricula ,
    p.nome
FROM
    tb_matricula m INNER JOIN tb_aluno a
        ON(
        a.id_aluno = m.id_aluno
    ) INNER JOIN tb_perfil p
        ON(
        p.id_perfil = a.id_perfil
    ) ,
    (
        SELECT
            CONCAT( dt.d ,'-' ,days.d ) AS dates
        FROM
            (
                SELECT
                    CONCAT( a1 ,b1 ) AS d
                FROM
                    (
                        SELECT
                            '0' AS a1
                    UNION ALL SELECT
                            '1'
                    UNION ALL SELECT
                            '2'
                    UNION ALL SELECT
                            '3'
                    ) a JOIN(
                        SELECT
                            '0' AS b1
                    UNION ALL SELECT
                            '1'
                    UNION ALL SELECT
                            '2'
                    UNION ALL SELECT
                            '3'
                    UNION ALL SELECT
                            '4'
                    UNION ALL SELECT
                            '5'
                    UNION ALL SELECT
                            '6'
                    UNION ALL SELECT
                            '7'
                    UNION ALL SELECT
                            '8'
                    UNION ALL SELECT
                            '9'
                    ) b
                WHERE
                    CONVERT(
                        CONCAT( a1 ,b1 ) ,
                        UNSIGNED
                    ) <=(
                        SELECT
                            DAY(
                                CONCAT( '2012-02' ,'-01' ) + INTERVAL 1 MONTH - INTERVAL 1 DAY
                            )
                    )
                    AND CONCAT( a1 ,b1 ) <> '00'
            ) days JOIN(
                SELECT
                    '2012-02' AS d
            ) dt
    UNION ALL SELECT
            CONCAT( dt.d ,'-' ,days.d ) AS dates
        FROM
            (
                SELECT
                    CONCAT( a1 ,b1 ) AS d
                FROM
                    (
                        SELECT
                            '0' AS a1
                    UNION ALL SELECT
                            '1'
                    UNION ALL SELECT
                            '2'
                    UNION ALL SELECT
                            '3'
                    ) a JOIN(
                        SELECT
                            '0' AS b1
                    UNION ALL SELECT
                            '1'
                    UNION ALL SELECT
                            '2'
                    UNION ALL SELECT
                            '3'
                    UNION ALL SELECT
                            '4'
                    UNION ALL SELECT
                            '5'
                    UNION ALL SELECT
                            '6'
                    UNION ALL SELECT
                            '7'
                    UNION ALL SELECT
                            '8'
                    UNION ALL SELECT
                            '9'
                    ) b
                WHERE
                    CONVERT(
                        CONCAT( a1 ,b1 ) ,
                        UNSIGNED
                    ) <=(
                        SELECT
                            DAY(
                                CONCAT( '2012-03' ,'-01' ) + INTERVAL 1 MONTH - INTERVAL 1 DAY
                            )
                    )
                    AND CONCAT( a1 ,b1 ) <> '00'
            ) days JOIN(
                SELECT
                    '2012-03' AS d
            ) dt
        ORDER BY
            dates
    ) datas
WHERE
    m.id_matricula = 42
    and
    datas.dates BETWEEN '2012-02-25' AND '2012-03-05';

Running this statement for ID = 42 and 3 days of date difference i have:
DATES,          ID_MATRICULA, NOME
2012-02-25  42        R ANDRE F DOMINGOS
2012-02-26  42        R ANDRE F DOMINGOS
2012-02-27  42        R ANDRE F DOMINGOS


text:
Q: The right way to pass a database object? I have 2 classes:
1. Database Class
class Database extends Config{

private $connection;

function __construct()
{
    $this->openConn();
}

public function openConn(){
    $this->connection = new mysqli($this->dbHost . ":" . $this->dbPort,
                                       $this->dbUser,
                                       $this->dbPass,
                                       $this->dbName);
    if (mysqli_connect_errno()) {
        echo 'Database connection failed ' . mysqli_errno() . mysqli_connect_error();
    }
}

2. Login Class
class Login{

private $connection;

function __construct(){

    global $database;
    $this->connection = $database;

    $query = $this->connection->prep("
        SELECT * FROM `Users`
        WHERE `Email` = ?
        AND `Password` = ?
        LIMIT 1
        ");
}

After binding params, and trying to run Login.php, I get the following error:
Fatal error: Call to undefined method Database::prepare()

After searching online I found many ideas but no practical examples, as I understood, the mysqli object is not being passed correctly, and I should use another approach to pass it as it should (if extending the Database class can be prevented - it would be preferred, as I plan to use the "extends" option for another use).
Thank you.

A: Your Openconn() is not returning anything.
Make sure your it returns the database cursor
You can do this by updating your code into:
public function openConn(){
    $this->connection = new mysqli($this->dbHost . ":" .
         $this->dbPort,
         $this->dbUser,
         $this->dbPass,
         $this->dbName);

    //Check for connection errors

    return $this-connection;
}

A: So many things where do I start, I guess I will post the corrected code first ( untested )
class Database extends Config{

    private $connection;

    function __construct(){
        $this->openConn();
    }

    protected function openConn(){
            $this->connection = new mysqli($this->dbHost . ":" . $this->dbPort,
                    $this->dbUser,
                    $this->dbPass,
                    $this->dbName);
            if (mysqli_connect_errno()) {
                echo 'Database connection failed ' . mysqli_errno() . mysqli_connect_error();
            }
    }

    public function getConnection(){
        return $this->connection;
    }
}

class Login{
    private $Database;

    function __construct(\Database $Database){
        $this->Database = $Database;
        $connection = $this->Database->getConnection();

        $query = $connection->prep("
    SELECT * FROM `Users`
    WHERE `Email` = ?
    AND `Password` = ?
    LIMIT 1
    ");
    }
}

You should avoid globals and instead use dependency injection.  So this
 global $database

Is replaced with
$Database = new Database();
$Login = new Login( $Database  );

I'm not sure what that global was, if it was a Database instance or the actual connection, but the $connetion in the Database class is private so in order to get it outside it should have a get method.  I also changed the openConn() method to be protected because it's pointless calling from outside the class.
There are a lot of other things that I would change, or do differently but it largely outside the scope of the question.
Most likely your issue is:

*

*you are not setting the global

*you are setting the global to be a $Database and not the connection.

Based on the error you report it's most likely the second one, because you are calling prepare on the Database class and not it's stored connection.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ViewChild doesn't work to me - upgrade to beta7 import {Page,NavController,NavParams,Platform,IonicApp} from 'ionic-angular';
import {ViewChild} from '@angular/core';

@Page({
    templateUrl: 'build/pages/tabspage/tabspage.html'
})

@ViewChild('myTabs') tabRef: Tabs

export class TabsPage {
     tab1;
     tab2;
     tab3;

     constructor(app:IonicApp, params:NavParams) {
        this.tab1 = Page1;
        this.tab2 = Page2;
        this.tab3 = Page3;

     }

     onPageDidEnter() {
         this.tabRef.select(1);
      }

}

I have this code. This code is inside of a typescript file. I get the error: Error TS1146: Declaration expected.

A: The @ViewChild() should be inside your class declaration.
export class TabsPage {
    @ViewChild('myTabs') tabRef: Tabs
    ...
}

A: For it says expecting declaration, I think you may need import 'Tabs' class in advance.
import {Tabs} from '..~~tabs';


text:
Q: 'this' pointer changes after calling a member function I use Visual Studio 2012 Express to debug a 64-bit app. Let's say both 'foo' and 'bar' are some member functions of a class C.
'foo' looks like:
void foo() {
    bar();    // change to this->bar() works!
}

My program crashed because 'this' pointer is changed when it went inside 'bar'. The problem can be fixed by changing to 'this->bar()'.
Any idea how I should debug this problem? Thanks

A: You mean that the following code works?
void foo() {
    this->bar();    // instead of bar()
}

So, presuming foo() is a member function that calls another member function bar() for the same object, check two things: (1) whether there is another non-member function bar() having same signature of member function bar(), if so exist, change the non-member function name op always qualify with this-> for member function call as a good programming practice (2) When you call foo() for some object instance or pointer to object instance, check whether the object has been allocated and initialized properly.


text:
Q: Problems using the toString method in Java I'm working on a banking program that is supposed to use 3 classes (Account-base class, CheckingAccount, and SavingsAccount) and several methods to display the banking information (ID, balance after a withdrawal and deposit, and the annual interest rate). This should be a pretty simple program, but I'm getting hung up on one portion of it. In the 2 subclasses (CheckingAccount and SavingsAccount) we are told to "invoke their toString() methods" We briefly hit on the topic of overrides and toString() methods in class, but there's not a whole lot in our textbook on the topic and I'm having some trouble figuring out how to do this as it applies to my particular program?
Here is the code I have so far (haven't tested it to see if it works yet since I'm still trying to get the toString() methods in there, but other than that I THINK it's almost done).
import java.util.Date;

public class Account {
    private int id = 0;
    private double balance = 0;
    private double annualInterestRate = 0;
    private Date dateCreated = new Date();

    public Account() {
      id = 0;
      balance = 0.0;
      annualInterestRate = 0.0;
    }

    public Account(int newId, double newBalance) {
      id = newId;
      balance = newBalance;
    }

    public int getId() {
      return id;
    }

    public double getBalance() {
      return balance;
    }

    public double getAnnualInterestRate() {
      return annualInterestRate;
    }

    public int setId(int newId) {
      id = newId;
    }

    public double setBalance(double newBalance) {
      balance = newBalance;
    }

    public double setAnnualInterestRate(double newAnnualInterestRate) {
      annualInterestRate = newAnnualInterestRate;
    }

    public java.util.Date getDateCreated() {
      return dateCreated;
    }

    public double getMonthlyInterestRate() {
      return annualInterestRate/12;
    }

    public void withdrawal (double withdrawalAmount) {
      return balance -= withdrawalAmount;
    }

    public void deposit (double depositAmount) {
      return balance += depositAmount;
    }

  public static void main(String[] args) {
    //System.out.println("Account Created!");
    //System.out.println("Savings Account: " + savingsAccount.getId() + "Balance: $%1.2f." + savingsAccoung.getBalance() + "Rate: " + savingsAccoung.getAnnualInterestRate() + "%");
    //System.out.println("Checking Account: " + checkingAccount.getId() + "Balance: $%1.2f." + checkingAccount.getBalance() + "Rate: " + checkingAccount.getAnnualInterestRate() + "%");

  }
}

Here's my CheckingAccount class:
public class CheckingAccount extends Account {
  Account checkingAccount = new Account(1271, 150);
  checkingAccount.setAnnualInterestRate(1.25);
  checkingAccount.withdrawal(300);
  checkingAccount.deposit(500);
  double overdraft = 200;

  public String toString() {
    return
  }

And here's my SavingsAccount class:
public class SavingsAccount extends Account {
    Account savingsAccount = new Account(1122, 20000);
    savingsAccount.setAnnualInterestRate(4.5);
    savingsAccount.withdrawal(5000);
    savingsAccount.deposit(10000);

}

If it helps, the final output is supposed to look something like this:
Account Created!
Savings Account ID: 1122 Balance: $20000.00 Rate: 4.5%
Checking Account ID: 1271 Balance: $150.00 Rate: 1.25%
Updating Interest
Savings Account ID: 1122 Balance: $20900.00 Rate: 4.5%
Checking Account ID: 1271 Balance: 151.88 Rate: 1.25%
Processing Withdrawals
Savings Account ID: 1122 Balance: $15900.00 Rate: 4.5%
Checking Account ID: 1271 Balance: $... Rate: 1.25$ Overdraft
Processing Deposits
Savings Account ID: 1122 Balance:... Rate: 4.5%
Checking Account ID: 1271 Balance:... Rate: 1.25%
Thank you for your business!

Any suggestions would be very much appreciated.
Update
Would the toString() method look something like the following?
public String toString() {
    return ID: + id + Balance: + balance + Rate: + annualInterestRate;
  }

I guess the thing that's really confusing me is how to use the two toString() methods (one for each subclass) to print the output like it's laid out in the example?
Update
Here is my most up-to-date code, I'm still getting some compiler errors, all of which deal with non-static variables being called from a static context (I'll also post these errors following the code). Up until the middle of last week, we just declared everything as static, but that's changed and I'm having trouble figuring out when to and when not to use static when declaring my methods, hence the compiler errors.
I was told once that replacing the original code with the updated code can make the answers look bad, so I'm just adding my current code, I hope that's ok.
import java.util.Date;

public class Account {
    private int id = 0;
    private double balance = 0;
    private double annualInterestRate = 0;
    private Date dateCreated = new Date();

    public Account() {
      id = 0;
      balance = 0.0;
      annualInterestRate = 0.0;
    }

    public Account(int newId, double newBalance) {
      id = newId;
      balance = newBalance;
    }

    public int getId() {
      return id;
    }

    public double getBalance() {
      return balance;
    }

    public double getAnnualInterestRate() {
      return annualInterestRate;
    }

    public void setId(int newId) {
      id = newId;
    }

    public void setBalance(double newBalance) {
      balance = newBalance;
    }

    public void setAnnualInterestRate(double newAnnualInterestRate) {
      annualInterestRate = newAnnualInterestRate;
      balance = balance * annualInterestRate;
    }

    public java.util.Date getDateCreated() {
      return dateCreated;
    }

    public double getMonthlyInterestRate() {
      return annualInterestRate/12;
    }

    public double withdrawal (double withdrawalAmount) {
      return balance -= withdrawalAmount;
    }

    public double deposit (double depositAmount) {
      return balance += depositAmount;
    }

  public static void main(String[] args) {
    Account savingsAccount = new Account(1122, 20000);
    Account checkingAccount = new Account(1271, 150);
    System.out.println("Accounts Created!");
    System.out.println(savingsAccount);
    System.out.println(checkingAccount);
    savingsAccount.setAnnualInterestRate(4.5);
    checkingAccount.setAnnualInterestRate(1.25);
    System.out.println("Updating Interest");
    System.out.println(savingsAccount);
    System.out.println(checkingAccount);
    savingsAccount.withdrawal(5000);
    checkingAccount.withdrawal(300);
    System.out.println("Processing Withdrawal");
    System.out.println(savingsAccount);
    System.out.println(checkingAccount);
    savingsAccount.deposit(10000);
    checkingAccount.deposit(500);
    System.out.println("Processing Deposit");
    System.out.println(savingsAccount);
    System.out.println(checkingAccount);
    System.out.println("Thank you for your business!");
    }
  }

public class CheckingAccount extends Account {
  public static void main(String[] args) {
    //double overdraft = 200;
  }
    @Override
    public String toString() {
      return "Checking Account: ID: " + Account.getId() + "Balance: " + Account.getBalance() + "Rate: " + Account.getAnnualInterestRate();
    }
}

public class SavingsAccount extends Account {
  public static void main(String[] args) {
  }
    @Override
    public String toString() {
      return "Savings Account: ID: " + Account.getId()+ "Balance: " + Account.getBalance() + "Rate: " + Account.getAnnualInterestRate();
    }
}

Here are the compiler errors I am receiving:
Compilation completed.  The following files were not compiled:
6 errors found:
File: C:\Users\HiTechRedneck\Desktop\Summer II 2014\Computer Programming Principle\Program 5\CheckingAccount.java  [line: 7]
Error: non-static method getBalance() cannot be referenced from a static context
File: C:\Users\HiTechRedneck\Desktop\Summer II 2014\Computer Programming Principle\Program 5\CheckingAccount.java  [line: 7]
Error: non-static method getAnnualInterestRate() cannot be referenced from a static context
File: C:\Users\HiTechRedneck\Desktop\Summer II 2014\Computer Programming Principle\Program 5\SavingsAccount.java  [line: 6]
Error: non-static method getId() cannot be referenced from a static context
File: C:\Users\HiTechRedneck\Desktop\Summer II 2014\Computer Programming Principle\Program 5\SavingsAccount.java  [line: 6]
Error: non-static method getBalance() cannot be referenced from a static context
File: C:\Users\HiTechRedneck\Desktop\Summer II 2014\Computer Programming Principle\Program 5\SavingsAccount.java  [line: 6]
Error: non-static method getAnnualInterestRate() cannot be referenced from a static context

A: From the docs:

Every class has Object as a superclass.

And the java.lang.Object class has the method toString() in it. This means that every class you create can use that method, even if it's not overridden (it's inherited). When you print the object, it prints the return of that method, toString().
So for example, when you write this:
Account account1 = new Account();
System.out.println(account1);

It's the same as this:
Account account1 = new Account();
System.out.println(account1.toString());

What your instructor wants you to do is override that toString() method that is automatically inherited so that you may customize what happens when you print out the object.
For example (add this to your Account class):
@Override
public String toString() {
    return "ID: "+id+" "+"Balance: "+balance+" "+"Rate: "+annualInterestRate;
}

Normally the toString() method (if not overridden) prints this:
getClass().getName() + '@' + Integer.toHexString(hashCode())

But now that you've overridden it, it should print this:
"ID: " + id + " " + "Balance: " + balance + " " + "Rate: " + annualInterestRate


text:
Q: Parse a CSS file to to get individual declarations of selectors containing a right or left word I need to parse a CSS file to to get individual selectors that contain a right or left word in their declarations(block). And add the selectors and their corresponding declarations(block) to an Array or Hash. For example:
.selector-one { /* This selector and its declaration will be added */
  .
  .
float: right;
  .
  .
}

#selector-two { /* This selector and its declaration will be added */
  .
  .
margin-left: 20%;
  .
  .
}

I'm trying to write it using the scan method, This way:
content.scan(/.*?\{.*?(right|left).*?\}/)

Or
content.scan(/[^}]\{[^}](right|left)[^}]\}/)

But non of them work.
I should mention that:

*

*It dosn't matter if the name of the selector contains the word left or right, We just need to check the blocks.

*The name of the selectors may start with anything other than { or }

*Selectors can be grouped, So we could have something like this:

.
h1, h2, p {
    text-align: right;
    color: red;
}

A: I don't know ruby but the regexp should be :
[{]([^}]*(right|left)[^}]*)[}]

With ungreedy,insensitive and global flags

A: Based on your sample, and if they aren't nested.
 #  \.(selector-[^{}]*?)\s*\{([^{}]*:[ ]*(?:right|left)[ ]*;[^{}]*)\}

 \.
 ( selector- [^{}]*? )       # (1), Selector
 \s*
 \{
 (                           # (2 start), Block
      [^{}]*
      : [ ]*
      (?: right | left )
      [ ]* ;
      [^{}]*
 )                           # (2 end)
 \}

Output:
 **  Grp 0 -  ( pos 0 , len 105 )
.selector-one { /* This block will be added to the array */
    .
    .
float: right;
    .
    .
}
 **  Grp 1 -  ( pos 1 , len 12 )
selector-one
 **  Grp 2 -  ( pos 15 , len 89 )
 /* This block will be added to the array */
    .
    .
float: right;
    .
    .

----------------------

 **  Grp 0 -  ( pos 196 , len 106 )
.selector-three { /* This block will be added to the array */
    .
    .
float: left;
    .
    .
}
 **  Grp 1 -  ( pos 197 , len 14 )
selector-three
 **  Grp 2 -  ( pos 213 , len 88 )
 /* This block will be added to the array */
    .
    .
float: left;
    .
    .

A: Ruby's slice_before is handy for this:
blocks = DATA.each_line
             .slice_before(/^\./)
             .map(&:join)
             .select{ |block| block[/\b(?:left|right)\b/] }
blocks
# => [".selector-one { /* This block will be added to the array */\n    .\n    .\nfloat: right;\n    .\n    .\n}\n\n",
#     ".selector-three { /* This block will be added to the array */\n    .\n    .\nfloat: left;\n    .\n    .\n}\n"]

__END__
.selector-one { /* This block will be added to the array */
    .
    .
float: right;
    .
    .
}

.selector-two { /* This block wont be added to the array */
    .
    .
    .
}

.selector-three { /* This block will be added to the array */
    .
    .
float: left;
    .
    .
}

*

*each_line iterates over the lines in the file.

*slice_before looks through the resulting array, and creates sub-arrays when the regular expression /^\./ matches a line that starts with ..

*map(&:join) converts the contents of each sub-array back into a text string.

*select looks inside each string and if /\b(?:left|right)\b/ matches the word "left" or "right", then the string is passed on.

It's important to use a pattern like /\b(?:left|right)\b/, because the string being searched for could be embedded in a longer string like 'leftover' or 'bright' and you don't want to get a false-positive.
You might not have seen __END__ and DATA before, but they're handy for test code like this. __END__ marks the end of the script, and anything after it can be treated as a pseudo data file, which is accessible via DATA. So consider the code to be reading from a file.

A: You could also use a CSS parser like Crass and scan the parse tree.
Spitballing code now...
tree = Crass.parse(css)
nodes_with_right_or_left = tree.select do |node|
  node[:children] and node[:children].detect do |child|
    child[:value] == "right" or child[:value] == "left"
  end
end

YMMV :-)

A: Thanks to all the people answered to my question. Unfortunately non of them solve the problem. Here is how I implemented it:
input.scan(/[^{}]*\{[^}]*?(?:\Wright\W|\Wleft\W)[^}]*\}/)

The key was that the parentheses in scan method make a capture group. So we need to turn it into a non-capturing group, using ?:


text:
Q: An issue regarding multiple drivers on a wire, error: [DRC MDRV-1] Multiple Driver Nets: Net led_OBUF[0] has multiple drivers: led_OBUF[0]_inst_i_1/O I am creating a simple VHDL code which should create two 4 bit binary numbers (A and B) using 8 inputs (4 for each), then based on one of three buttons being pressed, a logic function is performed on A and B, either AND, OR, or XOR.
My concern is that I am trying to map multiple input signals to a single port, and multiple output signals to a single port, however my confusion lies in the fact that I have successfully implemented a very similar description without any errors, I will show the non error description at the end. If my suspicions are correct, please could someone explain to me why the error does not occur on the bottom code?
Code with errors:
use IEEE.STD_LOGIC_1164.ALL;

entity Lab_2_Source_File is
port(A : in STD_LOGIC_VECTOR(3 downto 0);
     B : in STD_LOGIC_VECTOR(3 downto 0);
     btnd : in STD_LOGIC;
     btnl : in STD_LOGIC;
     btnr : in STD_LOGIC;
     led : out STD_LOGIC_VECTOR(3 downto 0)
     );
end Lab_2_Source_File;

architecture Behavioral of Lab_2_Source_File is
begin

process(btnd)
begin
led(0) <=A(0) and B(0);
led(1) <=A(1) and B(1);
led(2) <=A(2) and B(2);
led(3) <=A(3) and B(3);
end process;

process(btnl)
begin
led(0) <=A(0) or B(0);
led(1) <=A(1) or B(1);
led(2) <=A(2) or B(2);
led(3) <=A(3) or B(3);
end process;

process(btnr)
begin
led(0) <=A(0) xor B(0);
led(1) <=A(1) xor B(1);
led(2) <=A(2) xor B(2);
led(3) <=A(3) xor B(3);
end process;

end Behavioral;

I modified the constraints file accordingly

set_property -dict { PACKAGE_PIN T14   IOSTANDARD LVCMOS25 } [get_ports { led }]; #IO_L15P_T2_DQS_13 Sch=led[0]

## Switches

set_property -dict { PACKAGE_PIN E22  IOSTANDARD LVCMOS12 } [get_ports { A }]; #IO_L22P_T3_16 Sch=sw[0]

set_property -dict { PACKAGE_PIN F21  IOSTANDARD LVCMOS12 } [get_ports { B }]; #IO_25_16 Sch=sw[1]

Here is the error
[DRC MDRV-1] Multiple Driver Nets: Net led_OBUF[0] has multiple drivers:led_OBUF[0]_inst_i_1/O, led_OBUF[0]_inst_i_3/O, and led_OBUF[0]_inst_i_2/O.
The second code, with no errors. I show this code because I am unsure of how 4 inputs (3 downto 0) can be mapped to a single input. I have named the ports using the original port names in the constraint file.
port(sw0 : in STD_LOGIC_VECTOR(3 downto 0);
led0: out STD_LOGIC_VECTOR(3 downto 0)
);

end Lab_2_Source_File;

architecture Behavioral of Lab_2_Source_File is
begin

process(sw0)
begin

led0<=sw0;

end process;
end Behavioral;

As mentioned above, the error leads me to beleive that it is due to trying to map multiple signals to the led output, however whilst this makes sense, I am confused as the same error does not occur when I map multiple signals to the output on the other code. Please could someone help me explain what's going on?

A:
the error leads me to beleive that it is due to trying to map multiple signals to the led output

This is correct.

however whilst this makes sense, I am confused as the same error does not occur when I map multiple signals to the output on the other code.

In the last example,
led0<=sw0;

the only driver for led0(0) is sw0(0), and the only driver for led0(1) is sw0(1), and so on. So there are no multiple drivers for one net, as in the first example, which is why there is no error.


text:
Q: azure pipeline option selector script I have project that required from me to execute a remote automation on some machine .
so me steps are

*

*checkout the code

*run command line

cd .\MatrixPro\TestFramework python .\main.py -t
  class_test.name_test

As I tried to improve my pipeline I'm trying to build new select parameter that when I'm going to run the pipeline and inject value that I option from the select.
I found that I have few issues at this point

*

*how to build the select option

*how to attach my script to take a list from my api
GET https://dev.azure.com/{organization}/{project}/{team}/_apis/wit/wiql/{id}?api-version=5.1


text:
Q: How can I use Control.Lens to update the ith element of a list? I have some datatypes along the line of
data Outer = Outer { _list :: [ Inner ] }
data Inner = Inner { _bool :: Bool }

using Control.Lens, I can access the _bool of the ith Inner (inside a 'State Outer' monad) like this
boolValue <- gets (^. list . to (!! i) . inner)

I would like to also be able to update this value with something like
list ^. (to (!! i)) ^. inner %= True

However (by my understanding), the 'to' function only creates a getter, not a true lens that can be used as either getter or setter.
So, how can I convert (!! i) into a lens that will allow me to update this field?

A: Use element, which is a Traversal to the specified list element:
list . element i . inner %= True :: Outer -> Outer

If you want to get the list element you must do so using a Maybe since the list element might not be there:
myList :: Outer

myList ^? list . element i . inner :: Maybe Bool

A: You can't* turn (!!) into any lens-like thing other than a Getter -- but there's a function to do this sort of thing: ix, for accessing things at indices. It's actually a Traversal, not a Lens -- which, here, just means that it can fail (if the index is out of bounds) -- but as long as the index is in the list, it'll work.
There's another problem, though -- (^.) is also an operator that's used exclusively for getting values. It's incompatible with e.g. (%=), which takes a lens-like thing as its first argument. And: (%=) is for mapping a function over the existing value; if you just want to set, you can use (.=). So you probably want something like:
list . ix i . inner .= True

* There actually is a function that can do this -- it's called upon -- but it uses wonderful evil black magic and you shouldn't use it, at least not for this (and probably not for any real code).


text:
Q: Не доступен метод PUT Всем привет! Столкнулся с проблемой, что у меня не доступен метод PUT. Я пишу некоторый Api на PHP Slim.
Сервер:
Apache 2.4 x64
PHP 5.6.31
При попытке отправить put запрос на какой-то адрес, я получаю следующий ответ: {"message":"Method not allowed. Must be one of: GET, POST"}.
Запрос я пытался отправлять как через Ajax, так и через Postman. Ответ один и тот же.
Я не понимаю, куда копать нужно, чтобы разрешить метод PUT. Кстати, с методом DELETE всё работает нормально.

A: Оказывается, я ошибся в ссылке запроса... Забавно, я отправлял запрос на /users, а надо было на /users/{id}. Вопрос можно считать закрытым.


text:
Q: Resizing variable sized images for object detection I am using KITTI's object detection dataset to train a Faster R-CNN with ResNet 101, pretrained on MS COCO. KITTI images "mostly" of dimension 375x1242
When I had batch_size: 1, everything was perfect. My keep_aspect_ratio_resizer was like below, as it was proposed by TensorFlow itself.
min_dimension: 600
max_dimension: 1987

But now I want to use batch_size: 5, but I keep getting dimension mismatch errors. Because some of the images have a slightly smaller size, like 370x1224 etc.
I can't find a general keep_aspect_ratio_resizervalues. I tried the below values based one the values I saw in the error messages, but I can't make all images the same size really
min_dimension: 600
max_dimension: 1985

min_dimension: 599
max_dimension: 1985

A: You could resizing the images yourself to get around the rounding error here or you could try to group items of the same size together into batches.
Assuming you have a generator of images, and that the images have a size attribute, you can create a generator that will yield batches of the images which are all the same size as follows:
from itertools import groupby
from collections import deque, defaultdict

def same_size_batches(images, batch_size=5):
    image_cache = defaultdict(deque)

    # We assume the image object has a size parameter we can group by
    for size, images in groupby(images, key=lambda image: image.size):
        for image in images:
            image_cache[size].append(image)

            # Everytime our batch gets big enough, yield it and reset
            if len(image_cache[size]) == batch_size:
                yield iter(image_cache[size])
                image_cache[size].clear()

The main part here is the group by that groups consecutive items by the same key and returns that key and a generator of items matching that key. In our case the key is the size of the image.
We then keep a cache of items of the same size, and every time one of the sizes hits our desired batch size, we yield out a generator for that batch.
We can demonstrate this working with a fake image object which has the required size parameter:
import random

class FakeImage(object):
    def __init__(self, _id):
        self.id = _id
        self.size = (370, 1224) if random.random() < 0.25 else (375, 1242)

    def __repr__(self):
        return "<Image {} {}>".format(self.id, self.size)

images = (FakeImage(_id) for _id in range(100))
for batch in same_size_batches(images, batch_size=5):
    print(list(batch))

This results in something like:
[<Image 0 (375, 1242)>, <Image 2 (375, 1242)>, <Image 3 (375, 1242)>, <Image 4 (375, 1242)>, <Image 6 (375, 1242)>]
[<Image 7 (375, 1242)>, <Image 8 (375, 1242)>, <Image 9 (375, 1242)>, <Image 10 (375, 1242)>, <Image 12 (375, 1242)>]
[<Image 1 (370, 1224)>, <Image 5 (370, 1224)>, <Image 11 (370, 1224)>, <Image 14 (370, 1224)>, <Image 16 (370, 1224)>]
[<Image 13 (375, 1242)>, <Image 15 (375, 1242)>, <Image 18 (375, 1242)>, <Image 19 (375, 1242)>, <Image 20 (375, 1242)>]
[<Image 21 (375, 1242)>, <Image 23 (375, 1242)>, <Image 24 (375, 1242)>, <Image 25 (375, 1242)>, <Image 26 (375, 1242)>]
...

We aren't guaranteed to produce all the images if we don't get enough to fill a block of the batch size, but if the input is an infinite generator this isn't an issue.

A: Fixed by adding tf.image.resize_image_with_crop_or_pad(images, max_height, max_width) to create_input_queue() in https://github.com/tensorflow/models/blob/master/research/object_detection/legacy/trainer.py


text:
Q: Retrieving a list of menu items in an array I am currently am working on a custom theme. In this theme, I have a menu that I registered using register-nav-menu, and then I am displaying the menu to my web page using the wp_nav_menu function.
However, I like to retrieve the list of menu items only (the actual menu item names only that were used in wp-admin area to create the menu, and without any html), and I would like save that list of items to an array (i.e, not display it).
So, a psuedo code would look like this
$menu_items = get_list_of_items($name_of_menu); // $name_of_menu is the result of register-nav-menu, and get_list_of_items is the psuedo function
foreach ($menu_items as $item) {
    // do something with the item
}

Is there a way of doing so? Thanks.

A: Modified version of above with recursive loops.
Add To Functions.php
function wp_get_menu_array($current_menu='Main Menu') {

    $menu_array = wp_get_nav_menu_items($current_menu);

    $menu = array();

    function populate_children($menu_array, $menu_item)
    {
        $children = array();
        if (!empty($menu_array)){
            foreach ($menu_array as $k=>$m) {
                if ($m->menu_item_parent == $menu_item->ID) {
                    $children[$m->ID] = array();
                    $children[$m->ID]['ID'] = $m->ID;
                    $children[$m->ID]['title'] = $m->title;
                    $children[$m->ID]['url'] = $m->url;
                    unset($menu_array[$k]);
                    $children[$m->ID]['children'] = populate_children($menu_array, $m);
                }
            }
        };
        return $children;
    }

    foreach ($menu_array as $m) {
        if (empty($m->menu_item_parent)) {
            $menu[$m->ID] = array();
            $menu[$m->ID]['ID'] = $m->ID;
            $menu[$m->ID]['title'] = $m->title;
            $menu[$m->ID]['url'] = $m->url;
            $menu[$m->ID]['children'] = populate_children($menu_array, $m);
        }
    }

    return $menu;

}

A: As @vancoder mentions, wp_get_nav_menu_items() is the way to go, however I think a better detailed answer would be more helpful for people in the future.
Said function returns an array of WP_Post Object objects (so you access the values with an arrow, eg. $item->title).
For a basic setup, you could use the following:
$menuLocations = get_nav_menu_locations(); // Get our nav locations (set in our theme, usually functions.php)
                                           // This returns an array of menu locations ([LOCATION_NAME] = MENU_ID);

$menuID = $menuLocations['primary']; // Get the *primary* menu ID

$primaryNav = wp_get_nav_menu_items($menuID); // Get the array of wp objects, the nav items for our queried location.

Then you can just loop over that $primaryNav variable, for example:
foreach ( $primaryNav as $navItem ) {

    echo '
url.'" title="'.$navItem->title.'">'.$navItem->title.'
';

}

A: Get simple array of menu.
Add To Functions.php
    function wp_get_menu_array($current_menu) {

    $array_menu = wp_get_nav_menu_items($current_menu);
    $menu = array();
    foreach ($array_menu as $m) {
        if (empty($m->menu_item_parent)) {
            $menu[$m->ID] = array();
            $menu[$m->ID]['ID'] = $m->ID;
            $menu[$m->ID]['title'] = $m->title;
            $menu[$m->ID]['url'] = $m->url;
            $menu[$m->ID]['children'] = array();
        }
    }
    $submenu = array();
    foreach ($array_menu as $m) {
        if ($m->menu_item_parent) {
            $submenu[$m->ID] = array();
            $submenu[$m->ID]['ID'] = $m->ID;
            $submenu[$m->ID]['title'] = $m->title;
            $submenu[$m->ID]['url'] = $m->url;
            $menu[$m->menu_item_parent]['children'][$m->ID] = $submenu[$m->ID];
        }
    }
    return $menu;
}

Go to Your Header And Call Function
<?php
 $a = wp_get_menu_array('top-menu-header');
 print_r($a); exit;

?>

A: wp_get_nav_menu_items would appear to be exactly what you require. It returns an array of menu objects.


text:
Q: What does POSIX mean by "two's complement representation" in stdint.h? It's a well-known fact that signed integer overflow invokes undefined behavior, and that bitwise manipulation of signed integers is unreliable at best.  Thus, I found this line in the POSIX standard rather curious:

The typedef name int N _t designates a signed integer type with width N, no padding bits, and a two's-complement representation. Thus, int8_t denotes a signed integer type with a width of exactly 8 bits.

This is a rather nebulous statement, which could mean any combination of these things:

*

*The range of intN_t is from INTN_MIN to INTN_MAX.

*sizeof(intN_t) == N/8

*Bitwise operations on intN_t behave as expected for a two's complement representation.  -1 ^ x == ~x for every x, after inserting intN_t casts everywhere.

*intN_t cannot have trap representations (and an optimizing compiler must not exploit possible traps).

*Overflow of an intN_t variable is defined behavior (and wraps from INTN_MAX to INTN_MIN).

(1) and (2) both seem pretty obviously true to me, based on the rest of the document.  (1) is explicitly specified by the definition of INTN_MIN/MAX.  (2) is implied by "no padding bits."
Which of (3), (4), and (5) are required by POSIX, if any?

A: TL;DR
1, 3, 4 are true on any C99, C11 compiler where intN_t exists. 2 is true on any C11 compiler where int8_t is present - because the presence of int8_t implies that CHAR_BIT is 8. 5 specifically not required by C - behaviour on signed integer overflow is undefined.
POSIX restricts the allowed C implementations so that CHAR_BIT must be 8 and integer representation is two's complement. Therefore a compliant C99/C11 compiler on a POSIX platform must have int8_t, which makes statements 1, 2, 3 and 4 true on POSIX. Since POSIX does not say anything about signed integer overflow, it remains undefined, therefore 5 is false.

The quoted sentence is taken verbatim from C11 (C99) standard. C11 7.20.1.1p1:

The typedef name intN_t designates a signed integer type with width N, no padding bits, and a two's complement representation. Thus, int8_t denotes such a signed integer type with a width of exactly 8 bits.

int8_t is optional in C, so the mere presence of this fragment in the standard doesn't even require 2's complement representation. C11 7.20.1.1p3:

These types are optional. However, if an implementation provides integer types with widths of 8, 16, 32, or 64 bits, no padding bits, and (for the signed types) that have a two's complement representation, it shall define the corresponding typedef names.

Of your original statements,

*

*is of course true, but such thing doesn't follow from two's complement representation. int ranges from INT_MIN to INT_MAX on any one's complement architecture too. However, what follows from this is that the INTN_MIN has value .

*does not follow from two's complement representation. sizeof(intN_t) is N / CHAR_BIT. However, POSIX requires thatCHAR_BIT is 8 so sizeof(intN_t) indeed is N / 8

*This is the only thing that follows from two's complement  representation

*does not follow from a two's complement representation but the combination of 2's complement and that there are no padding bits.

*does not follow from a two's complement representation, and is required by neither C nor POSIX.

The type int8_t is not specified by POSIX but the C99, C11 that POSIX adopts and augments. POSIX adds two restrictions:
  * that CHAR_BIT must be exactly 8 and not greater, even though allowed by the C programming language
  * that one's complement or the sign and magnitude representations for integer numbers are not allowed, even if they would be allowed by the C programming language
C99, C11 specify that if present, the types intN_t must have exactly so many bits with no padding bits, and 2's complement. If int8_t exists, its sizeof must be 1, because it is a synonym for signed char then and CHAR_BIT is equal to 8.
There will not be a trap representations of intN_t but it doesn't mean that those objects with decidedly indeterminate values must have the same value all over, or that the passing such values to library functions will have defined behaviour. Consider the following fragment:
int32_t *foo = malloc(sizeof(int32_t));
printf(PRId32 "\n", *foo);
printf(PRId32 "\n", *foo);
free(foo);

The compiler need not even call malloc; it could compile this to the equivalent of puts("42\n666"); - even though there are no trap values of type int32_t. This  is because malloc:

[...] allocates space for an object whose size is specified by size and whose value is indeterminate.

And indeterminate really means unstable; indeterminable

Behaviour on signed integer overflow remains always undefined.


text:
Q: how can use in RMI (Client side code) an event that define in server side code? In RMI (client side code), how can I use an event that is defined in server side code?
For example, the following server side code defines PropertyChangeSupport event.
How it can be implemented in the client side?
package rmiservice.services.calculator;

import java.beans.PropertyChangeSupport;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.LinkedList;
import java.util.Queue;

public class CalculatorService extends UnicastRemoteObject implements ICalculator {
private Queue<Integer> numbers = new LinkedList<Integer>();
private Integer result;
***private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);***

public CalculatorService() throws RemoteException {
    super();

}

public void start() throws Exception {
    java.rmi.registry.LocateRegistry.createRegistry(1099);
    Naming.bind("CalculatorService", this);
    System.out.println("Calculator Service is Run  . . .");
}

public void stop() throws Exception {

    Naming.unbind("CalculatorService");
    UnicastRemoteObject.unexportObject(this, true);

    System.out.println("Calculator Service is Stop . . .");

}

//-------------------------------------------------------------------
//------------------------------ Implements ICalculator -------------

public void addNumber(Integer number) throws Exception {
    numbers.add(number);
}

public Integer getResult() throws Exception {
    return this.result;
}

public void setResult(Integer result) throws Exception {
    Integer oldResult = this.getResult();
    this.result = result;
    ***propertyChangeSupport.firePropertyChange("result", oldResult, result);***
}

public void calculate(Operation operation) throws Exception {
    Integer _result = 0;

    if (numbers.size() < 2)
        return;

    switch (operation) {
        case Add: {
            _result = 0;
            while (numbers.size() > 0) {
                _result += numbers.poll();
            }
            break;
        }

        case Substract: {
            _result = numbers.poll();
            while (numbers.size() > 0) {
                _result -= numbers.poll();
            }
            break;
        }

    }

    this.setResult(_result);

}
//-------------------------------------------------------------------

}

A: RMI doesn't support Notification. But, you can go for JMX Beans with Event support which can be used over RMI.
Your MBean interface must extend NotificationEmitter for doing this.

A: This is how it's done
Sorry, my example is already made and won't fit your code exactly, but it should be quite easy to adapt
1. Shared code (a jar that exposes server interfaces to any client)
//The interface that RMI will use to pass event handlers between client and server
public interface ServerEventHandler extends Remote {

    //This is not actually required (using it for testing)
    public void setId(int id) throws RemoteException;

    //This is not actually required (using it for testing)
    public int getId() throws RemoteException;

    // Here we use String as event type.
    // Could be any number of Serializable or Remote arguments
    public void handle(String message) throws RemoteException;

}

// A simple interface that will allow us to remotely (un)register event handlers
public interface ServerObjectWithCallback extends Remote {

    public void addServerEventHandler(ServerEventHandler handler) throws RemoteException;

    public void removeServerEventHandler(ServerEventHandler handler) throws RemoteException;

}

2. Server Code (launching and interface implementation)
public class ServerObjectWithCallBackImpl implements ServerObjectWithCallback {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss,SSS", Locale.ROOT);

    // A counter to automatically assign unique ids to new event handlers
    private int handCount = 0;
    // This will provide references to client-side event handlers and a way to
    //  access their ids with no remote call
    private HashMap<Integer, ServerEventHandler> handlers = new LinkedHashMap<Integer, ServerEventHandler>();
    // A fixed pool of 10 threads for asynchronous event handling
    private ExecutorService threads = Executors.newFixedThreadPool(10);

    // A simple counter that will allow printing a different message each time
    // (for the sake of this test only)
    private int eventcounter = 0;

    @Override
    public synchronized void addServerEventHandler(ServerEventHandler handler) throws RemoteException {
        // Assign a new id to handler and keep a reference to it
        handler.setId(++handCount);
        handlers.put(handCount, handler);
        System.out.println("New handler added with id " + handCount);
    }

    @Override
    public synchronized void removeServerEventHandler(ServerEventHandler handler) throws RemoteException {
        try {
            // Get handler id and forget about it
            int id = handler.getId();
            handlers.remove(id);
            System.out.println("Handler with id " + id + " removed");
        } catch (RemoteException e) {
            System.err.println("#Could not retrieve id for handler to unregister");
        }
        // TODO safer method "removeById" that will avoid unnecessary remote call to getId()
    }

    public synchronized void onServerEvent(Object event) {
        // This is where the remote callbacks take place
        // This method is called from server side and performs asynchronous
        //      callback on each registered client
        // TODO event should actually be of a more meaningfull type than Object
        System.out.println(sdf.format(new Date()) + "> Firing event #" + ++eventcounter + ": " + event + " (" + handlers.size()
                + " registered handlers)");
        for (int id : handlers.keySet()) {
            try {
                ServerEventHandler handler = handlers.get(id);
                threads.execute(new EventRunnable(handler, id, event, eventcounter));
            } catch (Exception e) {
                System.err.println("#Could not execute async callback on handler " + id);
                e.printStackTrace();
            }
        }
    }

    // A private runnable that will suit our needs to perform callbacks asynchronously
    // If we didn't, server might hang because of client behavior or missing client
    // Moreover, one client being slow would delay event dispatch to other clients
    private static class EventRunnable implements Runnable {

        private ServerEventHandler handler;
        private int handlerId;
        private Object event;
        private int eventNum;

        public EventRunnable(ServerEventHandler handler, int handlerId, Object event, int eventNum) {
            this.handler = handler;
            this.handlerId = handlerId;
            this.event = event;
            this.eventNum = eventNum;
        }

        @Override
        public void run() {
            try {
                handler.handle("message #" + eventNum + " sent on " + sdf.format(new Date()) + " = " + event);
            } catch (Exception e) {
                // TODO Better exception management : react depending on cause
                System.err.println("handler " + handlerId + " seems to have gone away: " + e.toString());
                // TODO Self-unregister handler after some unavailability time
                //  and possibly destroy client session as well
            }
        }
    }

}

public class MainCallback {
    private static ServerObjectWithCallBackImpl soc;
    private static ServerObjectWithCallback stub;

    public static void main(String[] args) throws RemoteException, AlreadyBoundException, InterruptedException {

        Registry reg = null;
        try {
            // Startup RMI registry
            reg = LocateRegistry.createRegistry(1099);
            System.out.println("RMI started");

            // Instantiate the RMI entry-point for the client, which will also
            //      be the object sending events
            soc = new ServerObjectWithCallBackImpl();
            stub = (ServerObjectWithCallback) UnicastRemoteObject.exportObject(soc, 0);
            // Bind the remote object's stub in the registry
            reg.bind("CallbackServer", stub);
            System.out.println("ServerObjectWithCallback bound to RMI (CallbackServer). Waiting for client");

            // This will be our event object : a counter
            int count = 0;
            while (true) {
                // Wait between 1 and 5 seconds
                Thread.sleep((int) (Math.random() * 4000 + 1000));
                // Fire event
                soc.onServerEvent(++count);
            }
        } finally {
            try {
                // Close up registry
                UnicastRemoteObject.unexportObject(reg, true);
                System.out.println("RMI registry destroyed");
            } catch (Exception e) {
                System.out.println("Could not destroy RMI registry");
            }
        }
    }
}

3. Client code (launching and handler implementation)
// This is our event handler implementation
// Note how it extends UnicastRemoteObject:
//  this is what allows the magic of calling client methods from server,
//  along with the fact that it implements ServerEventHandler, which is a Remote interface known from server
public class ClientSideEventHandler extends UnicastRemoteObject implements ServerEventHandler {

    private static final long serialVersionUID = 5094195049935134358L;

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss,SSS", Locale.ROOT);

    // id is just a way of discriminating clients for this test
    private int id;

    public ClientSideEventHandler() throws RemoteException {
        super();
    }

    // Make id available to server so it can number clients as it wishes
    @Override
    public int getId() throws RemoteException {
        return id;
    }

    @Override
    public void setId(int id) throws RemoteException {
        this.id = id;
    }

    // This is the actual callback method
    @Override
    public void handle(String message) throws RemoteException {
        System.out.println(sdf.format(new Date()) + "> Message from server: " + message);
    }

    // Overriding toString allows testing whether the handler is a reference or
    //      a serialized copy on server side
    @Override
    public String toString() {
        return this.getClass().getSimpleName() + "[" + id + "]";
    }

}

public class MainCallback {

    public static void main(String[] args) throws InterruptedException, RemoteException {
        // Connect to RMI registry on server
        Registry registry = null;
        try {
            registry = LocateRegistry.getRegistry("localhost", 1099);
            System.out.println("Connected to server");
        } catch (RemoteException e) {
            System.out.println("Error connecting to RMI");
            e.printStackTrace();
            return;
        }

        ServerObjectWithCallback soc = null;
        // Create an event handler on our side
        ClientSideEventHandler handler = new ClientSideEventHandler();
        try {
            // Get RMI server entry-point from remote RMI registry
            soc = (ServerObjectWithCallback) registry.lookup("CallbackServer");
            System.out.println("CallbackServer recovered from server");
            // Register for server events
            soc.addServerEventHandler(handler);
            System.out.println("Handler registered. Waiting for events");
        } catch (RemoteException | NotBoundException e) {
            System.out.println("Error getting MyRemoteInterface");
            e.printStackTrace();
            return;
        }

        // Just wait indefinitely for an event to happen
        while (true) {
            Thread.sleep(1000);
        }
    }

}

So:

*

*Your server exposes its remote interfaces via a shared jar

*One of them will be implemented on server side to provide event firing (that would be your CalculatorService)

*The other one will be implemented on client side to provide event handling (that would be your PropertyChangeSupport I guess)

*

*The client-side event handler also has to be a subclass of UnicastRemoteObject, so that it can be passed by proxy to the server, and that the server can remotely call methods back on it.

*Callbacks should be called asynchronously, to prevent one client from blocking a server thread and/or delaying callbacks to other clients

A: I may have misunderstood the question.
But as far as I know RMI don't involve itself in the kind of event binding you are asking about.
Client will basically look up the objects registered in the RMI Registry and invoke methods in it.
You will have to implement the event handling code on your own.
If you are asking how to invoke a RMI bound object's methods you can find that in
http://en.wikipedia.org/wiki/Java_remote_method_invocation


text:
Q: Vector decomposition into a convex combination of two vectors with constraints on the sum of their elements Given the vector $\mathbb{v}$ of $n$ elements and a scalar $0<q<1$,
how can I find the vectors $\mathbb{v}_1$ and $\mathbb{v}_2$ such that
$$ \mathbb{v} = q\, \mathbb{v}_1 + (1-q)\,\mathbb{v}_2 $$
subject to $\sum \mathbb{v}_{1i} = c_1$ and $\sum \mathbb{v}_{2i} = c_2$,
being $c_1$ and $c_2$ two given integer scalars ?

A: Let $\vec 1$ be a vector for which every element is $1$. We can write your constraints as:
$$\vec 1\cdot\vec v_1=c_1,\ \ \ \vec 1\cdot\vec v_2=c_2$$
It should be clear that these define a pair of parallel (hyper)planes. If $\vec v$ is to be written as a convex combination of a point from each plane (which is to say, it lies on a line segment connecting them), it must lie between them. This gives us a simple feasibility test (assume without loss of generality $c_2>c_1$).
$$\exists\ \vec v_1, \vec v_2\iff c_1\le\vec 1\cdot\vec v\le c_2$$
To actually find $v_1$ and $v_2$, we can draw a line from $\vec v$ that intersects both planes. To do this, choose any $\vec u$ such that $\vec 1\cdot\vec u\neq 0$. The line $\vec v+\vec ut$ must intersect both planes. Solving for the intersections gives:
$$v_1=\vec v+(c_1-\vec 1\cdot\vec v)\frac{\vec u}{\vec 1\cdot\vec u},\ \ \ v_2=\vec v+(c_2-\vec 1\cdot\vec v)\frac{\vec u}{\vec 1\cdot\vec u}$$


text:
Q: Does Apple allow me to reuse their icons in my own application? In my OS X application, I allow the user to open a Finder window. I would like to use the Finder's icon on my "open Finder" button. My application will be going to the App Store, but I would rather preempt any violation of Apple's policy on using their icons.
So, would such reuse be allowed by Apple? And, could anybody provide a corresponding reference to Apple's documentation? (I thought I had read it was not allowed, but I cannot find it now.)
UPDATE:
To handle cases were the application of interest is not running, I used superfell's answer of a previous question, 12166532, as follows:
// Return an application's icon using its bundle identifier
- (NSImage *) applicationIconWithBundleIdentifier: (NSString *) bundleIdentifier
{
    NSImage *image = [NSImage imageNamed:NSImageNameComputer]; // fallback icon

    NSString *path = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:bundleIdentifier];
    if (path) {
        image = [[NSWorkspace sharedWorkspace] iconForFile:path];
    }

    return image;
}

But, I am very grateful to Rob's answers below for putting me on the right track.

A: It's probably fine, in the sense that Apple's unlikely to go after you for such use.  It's also probably fine, in the sense that applications provide icons specifically for other programs (like the Finder) to display for the purposes of manipulating the apps.  Whether you get sued is really up to Apple's legal department, and whether you would win is up to your country's copyright law (and fair use exceptions to that law).  You can ask Apple for explicit permission; details are on their web site.
Anyway, if you fail the App Store review, change the icon.  No big deal.
You probably don't want to hard-code the icon.  Instead, get the icon at runtime like this:
NSImage *imageForAppWithBundleIdentifier(NSString *bundleIdentifier) {
    NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
    NSString *appPath = [workspace absolutePathForAppBundleWithIdentifier:bundleIdentifier];
    return [workspace iconForFile:appPath];
}

Finder's bundle identifier is com.apple.finder.  Terminal's bundle identifier is com.apple.Terminal.
$ osascript -e 'tell app "Finder" to get id'
com.apple.finder
$ osascript -e 'tell app "Terminal" to get id'
com.apple.Terminal

A: http://www.apple.com/legal/intellectual-property/guidelinesfor3rdparties.html

Apple Logo and Apple-owned Graphic Symbols: You may not use the Apple Logo or any other Apple-owned graphic symbol, logo, or icon on or in connection with web sites, products, packaging, manuals, promotional/advertising materials, or for any other purpose except pursuant to an express written trademark license from Apple, such as a reseller agreement.

This basically applies for any company. If you don't have explicit license to use graphics, don't use them.

A:
I don't know about the Finder icon.  We used something similar to the icon above on a toolbar menu.  They rejected a software update by saying the following.
5.1

The app uses the Home icon in the main application window in a manner that is not consistent with Apple's trademark guidelines.
That was late-September, 2011, according to our records.

A: This might not help very much, but considering they have licensing and trademark documents, I would assume that if you could use what you want to market your product, there should be no issue with placing it within your application. I'll see if I can find a more definitive document.
Also found this from a Cocoabuilder forum.


text:
Q: Pythonic conversion of a string into a CSV-file I have a string, a very long string which I would like to import into excel for further treatment.
The string is in such a form as in the dummy code below.
My code is working, doing the job, but I would love to see the pythonic way of handling it since I feel like it is a rather poor non-flexible code.
info = 'de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de
23 de 23 de 23 de 23 de 23 de 23 de 23'
info = [x.strip() for x in info.split(" ")]
file = open('testfile.txt','w')
for i in range (0,len(info),2):
    file.write(info[i])
    file.write(",")
    file.write(info[i+1])
    file.write("\n")
file.close()
print("Done")

The output is supposed to be:
    de, 23
    de, 23
    de, 23

A: Maybe this could be somewhat of an improvement:
info = 'de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de
23 de 23 de 23 de 23 de 23 de 23 de 23'

days = info.split()
output_form = "{},{}\n"

with open('testfile.txt','w') as file:
    for i in range (0,len(days),2):
        file.write(output_form.format(days[i],days[i+1]))
print("Done")

A: A more compact approach would be:
info = 'de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23' +
       'de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23'
info = info.split()
with open('testfile.txt', 'w') as f:
    f.write('\n'.join(a + ',' + b for a, b in zip(info[::2], info[1::2])))

where info[::2] contain all elements with even indices, and info[1::2] contain all elements with odd indices.


text:
Q: SBCL Error Messages When I am using SBCL (my favourite implementation) I often see this sort of error message in the REPL
CL-USER> (vgplot:fred) ; Evaluation aborted on
#<SB-INT:SIMPLE-READER-PACKAGE-ERROR "Symbol ~S not found in the ~A package." {1004289123}>. CL-USER>

I presume the message is meant to say "Symbol FRED not found in the VGPLOT package."
I imagine I have done something wrong in building SBCL (though I can't seem to find what exactly) , just wondering if anyone can offer advice on how to make this go away as it is annoying.

A: You could do this:
(defmethod print-object :around ((condition simple-condition) stream)
  (print-unreadable-object (condition stream)
    (apply #'format stream (simple-condition-format-control condition)
                           (simple-condition-format-arguments condition))
    (terpri stream)
    (call-next-method)))

This will add the formatted description of all simple-conditions (of which sb-int:simple-reader-error is one) to their printed form.  I wouldn't really consider this a "good idea" and it might have some unintended consequences.
A much better solution would be to modify slime/swank to print this information itself, but I couldn't figure out how to do it.


text:
Q: How to cache all backend in the Rails? Is it possible to temporarily cache all requests in the Rails backend?
Sometimes it's helpful to make frontend stuff without waiting for the backend on the page to reload.

A: Your question is very ambiguous. If you don't want to wait on the backend for development then you can cache your requests on the front-end using local storage or other client-specific APIs.
On the other hand, if you need backend caching it won't really serve your purpose because the client will still need to make the API call.
Lastly, if you need to mock your APIs then there are multiple such tools available. One that I like is https://designer.mocky.io/


text:
Q: How doing the exception handling in WCF REST C# I have a Wcf Rest service
    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
    void Import(stringrequest);

My try code:
 public void Import(string request)
    {
        if (request != null)
        {
             //....
        }
        else
        {
            throw new ApplicationException("Empty DATA");
        }
    }

In fact, I want to display a specific error message on the else treatment,when I test my wcf srevice in POSTMAN , if I enter a empty string ---> My objectif to display "Empty DATA",
How can do that? Thanks,

A: If you want to handle exception you should use try-catch.
When you want to handle all possible behavior, like empty strings or string full of numbers etc.. You can use if-else statement as you are doing.
You need to change your return type from void to string :
public string Import(string request) {

    if (String.IsNullOrEmpty(request)) {
        // ...
        return "{ \"Status\" : \"Ok\" }"; // or null if you don't want to return anything
    }
    else
    {
        return "{ \"Status\" : \"Error : Empty DATA\" }";
    }
}

You can also check this link to learn more about how to use Json in C#.
How to use http return code and how to return Json, that could help you understand a bit more how WCF REST works.
Hope this helps.


text:
Q: Javascript calendar not working My JavaScript calender is working in IE but it is not working in Mozilla.
My code:

     <asp:TextBox ID="txtBorderedDate" runat="server" CssClass="TextBoxMandatory" Enabled="false"></asp:TextBox>

A: I'm not sure if this has anything to do with the problem (you should post some more of your code), but you shouldn't hard code the ID of the controls in ASP.NET. Also, I think some quotes might be missing in the showCalendarControl() call.
Replace this:
<a onclick=
 "javascript:showCalendarControl(ctl00_SaralConetentPlaceHolder_txtBorderedDate);" ...

With this:
<a onclick="showCalendarControl('<%= txtBorderedDate.ClientID %>');" ...

Some of the parent controls of txtBorderedDate might get rendered differently in different borders, thus resulting in a different client-side ID of the textbox control.


text:
Q: Unity: Changing the color of object with input and using OnCollisionEnter to check if it's same color with other object I want to change color of player when user press J,K,L /and colors red, green, blue as you can see in the code below.
It works well. When player hit the ground, it has to be same color with the ground.
If it is not level will start again.
With my code i can do that too.
The problem is when the player hit the ground with the same color and when the player still on the same ground, if i change the color of player, it is not starting the level again.
I tried raycast but it didnt worked well.
I know i'm making a logic mistake somewhere but cant find it.
Here my codes;
-Player Code-
var player : Transform;

function Update () {

    //Check if J key Down if it is change player name and color
    if(Input.GetKeyDown(KeyCode.J))

        {

            player.name = "red";
            player.gameObject.renderer.material.color = Color.red;

        }

        //Check if K key Down if it is change player name and color
        if(Input.GetKeyDown(KeyCode.K))
            {
                player.name = "green";
                player.gameObject.renderer.material.color = Color.green;
            }

            //Check if L key Down if it is change player name and color
            if(Input.GetKeyDown(KeyCode.L))
                {
                    player.name = "blue";
                    player.gameObject.renderer.material.color = Color.blue;
                }

}

-Ground Code-
//Prefabs
var player : Transform;
var redLand : Transform;
var greenLand : Transform;
var blueLand : Transform;

//Assigning prefabs on editor
public var isRedLand = false;
public var isGreenLand = false;
public var isBlueLand = false;

private var isColorRed = false;
private var isColorGreen = false;
private var isColorBlue = false;

function OnCollisionEnter () {
ColorChange();

}

function ColorChange ()
{
//Check if the isRedLand true and isGreenLand and isBlueLand false
if (isRedLand && !isGreenLand && !isBlueLand)
{
    //Check if player name red if it is change the tag of it
    if(player.name == "red")
        {

            isColorRed = true;

        //if it is not red restart level
        }else
            {
                Application.LoadLevel ("1");
                isColorRed = false;
            }
}

//Check if the isGreenLand true and isRedLand and isBlueLand false

if(isGreenLand && !isRedLand && !isBlueLand)
{
    //Check if player name red if it is change the tag of it
    if(player.name == "green")
        {

            isColorRed = true;

        //if it is not red restart level
        }else
            {
            Application.LoadLevel ("1");
            isColorGreen = false;
            }
}

//Check if the isBlueLand true and isRedLand and isGreenLand false
if(isBlueLand && !isGreenLand && !isRedLand)

{
    //Check if player name red if it is change the tag of it
    if(player.name == "blue")
        {

            isColorBlue = true;

        //if it is not red restart level
        }else
            {
                Application.LoadLevel ("1");
                isColorBlue = false;
            }
       }
}

A: If I understood your question right the code should be fine if you change
function OnCollisionEnter () {
ColorChange();

}

to
function OnCollisionStay () {
    ColorChange();
}

OnCollisionEnter is called only when collision starts. OnCollisionStay is called on every frame while colliders are touching.


text:
Q: Get Html page after jQuery and Javascript execution with Python I've imported the content of a webpage into a variable in python, but I'm not getting the final structure (the one that's modified by Ajax and jQuery in general).
How could I solve this?
I would like to get the html as the one I see if I save the page from the browser.
That's my code:
import urllib.request

urlAddress = "http:// ... /"
getPage = urllib.request.urlopen(urlAddress)
outputPage = str(getPage.read())
print(outPage)

A: You can't by just getting the page source from the server. You need to do one of the following:

*

*Use the headless browser or similar solution (Selenium, Splash, PhantomJS, ...) to run the JS code in the page itself and see the results.

*Figure out what the JS code actually does, and recreate the same in Python. If it's doing another call to the server, you can see that in the XHR tab in Developer Tools on Chrome.


text:
Q: Crystal Reporting in VS2010 for Desktop Application Dear fellows I am 6 to 8 months old programmer and I do some plain programming like I've created point of sale/purchase inventory etc.
But in my whole programming career, I've never done crystal reporting, I need to know how can I do Crystal Reporting in C# in VS2010 for Desktop Application (like inventory software).
Please guide me in this regards or suggest me any link from where I can learn Crystal Reporting from very basic.
Thanks.

A: *

*Make sure that you have installed Crystal Reports for Visual Studio which can be found here. http://scn.sap.com/docs/DOC-7824

*I usually create views to fetch the data that I want to be displayed. You can add the views to your dataset.

*You can make a new Crystal Reports by going to Add New Item -> Reports -> Crystal Reports.

*In Visual Studio, while your new report is still in view, you should see the the Crystal Reports Menu, click on it and then click on Field Explorer.

*You can then right click on Database Field to setup and set the datasource location of your report. The fields will then be in view to drag and drop.

*You will need to create a report viewer to see the report and code appropriately for it.
There are many articles on how to create CR reports in Visual Studio like these two. http://www.codemag.com/Article/0207021
This one may be based on a ASP.NET project but the procedure for creating one is basically the same. http://www.codeproject.com/Articles/166291/Generate-a-report-using-Crystal-Reports-in-Visual
This is a good one to follow step by step.


text:
Q: System.Reflection.PropertyInfo propertyInfo return NULL? Hi I am passing a datatable to a method "AsJqGridResult", but "GetPropertyValue" method returns error due to "System.Reflection.PropertyInfo propertyInfo" return NULL.
Is there any issue to pass the datatable or any other issue, please help....
Controller
[HttpPost]
    public ActionResult DynamicGridData(string sidx, string sord, int page, int rows)
    {
        var context = GetTable().AsEnumerable();
        return (context.AsQueryable().AsJqGridResult(sidx, sord, page, rows));
    }

    public DataTable GetTable()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Number", typeof(int));
        table.Columns.Add("Abr", typeof(string));
        table.Columns.Add("Country", typeof(string));
        table.Columns.Add("Date", typeof(DateTime));

        table.Rows.Add(1, "AF", "AFGHANISTAN", DateTime.Now);
        table.Rows.Add(2, "AX", "ÅLAND ISLANDS", DateTime.Now);

        return table;
    }

Helper Method
public static JsonResult AsJqGridResult<T>(this IQueryable<T> source, string column, string sortOrder, int page, int pageSize)
{
  int pageIndex = Convert.ToInt32(page) - 1;
  int totalRecords = source.Count();
  int totalPages = (int) Math.Ceiling((float) totalRecords/(float) pageSize);

  var list = (sortOrder.ToLower()=="asc") ?
      source.OrderBy(new Func<T, IComparable>(item => (IComparable) GetPropertyValue(item, column))).Skip(pageIndex*pageSize).Take(pageSize) :
      source.OrderByDescending(new Func<T, IComparable>(item => (IComparable) GetPropertyValue(item, column))).Skip(pageIndex*pageSize).Take(pageSize);

  var jsonData = new
  {
    total = totalPages,
    page,
    records = totalRecords,
    rows = (
            from item in list
            select new
                      {
                        i = Guid.NewGuid(),
                        cell = GetGridCells(item)
                      }).ToArray()
  };

  return new JsonResult {Data = jsonData};
}

/// <summary>
/// Gets the property value.
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="property">The property.</param>
/// <returns></returns>
private static object GetPropertyValue(object obj, string property) {
  System.Reflection.PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
  return propertyInfo.GetValue(obj, null);
}

A: DataTables do not have properties for their columns.
Instead, you need to call TypeDescriptor.GetProperties() on the table, which will use the ITypedList implementation to get PropertyDescriptors for the actual columns.


text:
Q: specializing boost::lexical_cast for enums in boost::property_maps I am trying to use a boost::graph that has an enum inside its bundled vertex property. The problem starts when I try to use the bundled property for a boost::dynamic_property. Looks like I can't get the correct template specialization for boost::lexical_cast to recognize the type.
#include <string>
#include <iostream>
#include <boost/lexical_cast.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/property_map/dynamic_property_map.hpp>

enum MyEnum { A, B, C };

namespace boost{
    template<>
    std::string lexical_cast(const MyEnum & m)
    {
        return std::to_string(int(m));
    }
} /* boost */

struct EnumWrapper
{
    MyEnum e;

    EnumWrapper() = default;
    EnumWrapper(MyEnum e) : e{e}
    {}
};

int main()
{
    using namespace boost;

    // This works
    MyEnum e{MyEnum::B};
    std::cout << lexical_cast<std::string>(e) << std::endl;

    // This doesn't compile
    adjacency_list<vecS, vecS, directedS, EnumWrapper> graph;
    dynamic_properties dp;
    dp.property("test", get(&EnumWrapper::e, graph));

    return 0;
}

If I try writing the enum directly, everything works fine. When try to put it in the dynamic property, the following error appears:
In file included from /usr/include/boost/iterator/iterator_categories.hpp:22:0,
                 from /usr/include/boost/iterator/iterator_facade.hpp:14,
                 from /usr/include/boost/range/iterator_range_core.hpp:27,
                 from /usr/include/boost/lexical_cast.hpp:30,
                 from main.cpp:3:
/usr/include/boost/lexical_cast/detail/converter_lexical.hpp: In instantiation of 'struct boost::detail::deduce_target_char_impl<boost::detail::deduce_character_type_later<MyEnum> >':
/usr/include/boost/lexical_cast/detail/converter_lexical.hpp:270:89:   required from 'struct boost::detail::deduce_target_char<MyEnum>'
/usr/include/boost/lexical_cast/detail/converter_lexical.hpp:407:92:   required from 'struct boost::detail::lexical_cast_stream_traits<std::__cxx11::basic_string<char>, MyEnum>'
/usr/include/boost/lexical_cast/detail/converter_lexical.hpp:468:15:   required from 'struct boost::detail::lexical_converter_impl<MyEnum, std::__cxx11::basic_string<char> >'
/usr/include/boost/lexical_cast/try_lexical_convert.hpp:181:44:   required from 'bool boost::conversion::detail::try_lexical_convert(const Source&, Target&) [with Target = MyEnum; Source = std::__cxx11::basic_string<char>]'
/usr/include/boost/lexical_cast.hpp:41:60:   required from 'Target boost::lexical_cast(const Source&) [with Target = MyEnum; Source = std::__cxx11::basic_string<char>]'
/usr/include/boost/property_map/dynamic_property_map.hpp:44:38:   required from 'Value boost::detail::read_value(const string&) [with Value = MyEnum; std::__cxx11::string = std::__cxx11::basic_string<char>]'
/usr/include/boost/property_map/dynamic_property_map.hpp:158:64:   required from 'void boost::detail::dynamic_property_map_adaptor<PropertyMap>::do_put(const boost::any&, const boost::any&, mpl_::bool_<true>) [with PropertyMap = boost::vec_adj_list_vertex_property_map<boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, EnumWrapper>, boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, EnumWrapper>*, MyEnum, MyEnum&, MyEnum EnumWrapper::*>]'
/usr/include/boost/property_map/dynamic_property_map.hpp:186:11:   required from 'void boost::detail::dynamic_property_map_adaptor<PropertyMap>::put(const boost::any&, const boost::any&) [with PropertyMap = boost::vec_adj_list_vertex_property_map<boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, EnumWrapper>, boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, EnumWrapper>*, MyEnum, MyEnum&, MyEnum EnumWrapper::*>]'
main.cpp:40:1:   required from here
/usr/include/boost/lexical_cast/detail/converter_lexical.hpp:243:13: error: static assertion failed: Target type is neither std::istream`able nor std::wistream`able
             BOOST_STATIC_ASSERT_MSG((result_t::value || boost::has_right_shift<std::basic_istream<wchar_t>, T >::value),

The line Target type is neither std::istreamable nor std::wistreamable suggests to me, that the lexical_cast is not specialized correctly. However, using the lexical cast directly appears to work just fine.

A: Target = MyEnum; Source = std::__cxx11::basic_string<char>. Boost is trying to convert from string to MyEnum; you've only provided the reverse direction.
You need to provide a conversion from string to MyEnum:
namespace boost{
    template<>
    MyEnum lexical_cast(const std::string & s) {
        return MyEnum::A;    // for example
    }
} /* boost */

Example.


text:
Q: Increasing the Titles Limit I want to ask if it's possible to make over 189 titles. I'm aware the maximum limit is 189. I looked around and couldn't find a solution to the matter. Hopefully someone knows something
Mainly taken a look to the CharTitles.dbc structure in the source and then to the Characters.Characters structure as well, initially thought it would be the same as removing the stats limit on items (as in changing uint16 to uint32) but it seems not the case here or atleast as far as i figured out.


text:
Q: Understanding Createview in SQLITE3 I am trying to understand CREATE VIEW command in SQLite, but getting strange view.
I have a CSV file,
table.csv  / tab separated
ID   NAME   AGE ADDRESS     SALARY
1    Paul   32  California  20000.0
2    Allen  25  Texas       15000.0
3    Teddy  23  Norway      20000.0
4    Mark   25  Rich-Mond   65000.0
5    David  27  Texas       85000.0
6    Kim    22  South-Hall  45000.0
7    James  24  Houston     10000.0

*

*run commands*
 sqlite3 sample.db

  .mode csv

  .import table.csv  COMPANY

  CREATE VIEW COMPANY_VIEW AS
  SELECT "ID", "NAME", "AGE"
  FROM  COMPANY;

  SELECT * FROM COMPANY_VIEW;

getting
"1 ",NAME,"32 "
"2 ",NAME,"25 "
"3 ",NAME,"23 "
"4 ",NAME,"25 "
"5 ",NAME,"27 "
"6 ",NAME,"22 "
"7 ",NAME,"24 "

Why I am not getting NAME Column. What I am doing wrong. I am an absolute beginner in SQLITE3.

A: Suggest issuing .schema COMPANY and/or SELECT * FROM COMPANY before the CREATE VIEW command.
From the sqlite doc

Use the ".import" command to import CSV (comma separated value) data into an SQLite table.

The operative term here is comma separated.
Use the .separator command to change the separator to tab.


text:
Q: Disable caching of the config details in Symfony2 We have several sites, each site has its own database and url.
All sites are using an API written by Symfony2. The database configuration in Symfony is in parameter.php file, which set the database parameters according to the current site.
As a result, every request to Symfony can be from different database, which means, the configuration should be loaded every time.
The question is how to disable the caching of the config parameters.
Or, if there is other idea, how to keep caching and to find a way to create caching per site, I would be happy to hear.
Thanks.

A: I ended up creating a separate cache directory for each site. This way the configuration parameters are saved in the cache per site.
Here is how to override the cache directory:
http://symfony.com/doc/2.1/cookbook/configuration/override_dir_structure.html
I just added the following to the AppKernel.php file:
public function getCacheDir()
{
    $request = Request::createFromGlobals();
    return $this->rootDir . '/cache/'. $this->environment .'/' . $request->getHost();
}


text:
Q: How to get a value from a channel without waiting for it In Go, if I try to receive from a channel, the program's execution is going to be stopped until some value is in the channel. However, what I would like to do is let the program execution continue and, if there's a value in the channel, act on it.
The pseudo-code I have in mind is something like this:
mychan := make(chan int, 1)

go someGoRoutine(mychan) // This might put some value in mychan at some point

for {
    if something in "mychan" {
        // Remove the element from "mychan" and process it
    } else {
        // Other code
    }
}

As I understand, I cannot simply use v <- mychan because that would block the program execution until a value is available. What would be the way to do this in Go?

A: That's what select is for. For example:
for {
        select {
        case v := <-c1:
                // process v
        case v, ok := <-c2:
                // Second form, '!ok' -> c2 was closed
        default:
                // receiving was not done
        }
}


text:
Q: Neo4j Server running problems on Linux I am using Neo4j 2.0.3 Community server by installing it on my linux system (by unzipping the tar.gz). I got this error while I tried to start the server

WARNING! You are using an unsupported Java runtime.
process [50690]... waiting for server to be ready.neo4j-community-2.0.3/bin/neo4j: line 147:  lsof : command not found
.neo4j-community-2.0.3/bin/neo4j: line 147: lsof : command not found
.neo4j-community-2.0.3/bin/neo4j: line 147: lsof : command not found
. Failed to start within 120 seconds.
Neo4j Server may have failed to start, please check the logs.

I checked for the solution for this and came to know that /usr/sbin had to be added to the path. On doing so and restarting the server, I got the following message

Another server-process is running with [40903], cannot start a new one. Exiting.

However, when I run the command neo4j staus , it says

Neo4j Server is not running

Can anybody please help me with how should I get started with it?

A: This is very late, but might help others.
If it tells you this, and you check that process id with, for example, ps aux | grep 40903, and it's not neo4j, the problem might be that the port is being used.
By default neo4j uses 7474, but can change this on the neo4j folder /conf/neo4j-server.properties and that was my problem, I had set the port to '22' which was being used. SO make sure it is set to a port that is open and available.
Hope this helps.

A: You might want to examine the startup script.
Another server-process is running with [40903], cannot start a new one. Exiting.
indicates (me to) that there might be a pid file (or the script uses them) which was written and is checked before attempting to start a new instances. This the normal thing to do.

A: I think you need to kill the other process using kill
You can see this answer for how to kill the process:
https://unix.stackexchange.com/questions/8916/when-should-i-not-kill-9-a-process
Otherwise, restarting the operating system will also do the job. For me, I normally start neo4j in the console, as in ./neo4j console. This makes it easier to stop the process.


text:
Q: Camera gets frozen when I come back to the app (Obj-C) I'm making a custom camera function for my app, but when I go out from the app and come back, the camera is frozen. How can I fix this?
I want the camera to resume when the user opens the app again, instead of having to close the app and re-open it again.
Code:
AVCaptureSession *session;
AVCaptureStillImageOutput *stillImageOutput;

- (void)viewWillAppear:(BOOL)animated
{
    session = [[AVCaptureSession alloc] init];
    [session setSessionPreset:AVCaptureSessionPresetPhoto];

    AVCaptureDevice *inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error;
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:&error];

    if ([session canAddInput:deviceInput]) {
        [session addInput:deviceInput];
    }

    AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    [previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    CALayer *rootLayer = [[self view] layer];
    [rootLayer setMasksToBounds:YES];
    CGRect frame = frameForCapture.frame;

    [previewLayer setFrame:frame];
    [rootLayer insertSublayer:previewLayer atIndex:0];

    stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG, AVVideoCodecKey, nil];
    [stillImageOutput setOutputSettings:outputSettings];

    [session addOutput:stillImageOutput];
    [session startRunning];

    crossButton.hidden = YES;
}

- (IBAction)takePhoto:(id)sender
{
    AVCaptureConnection *videoConnection = nil;

    for (AVCaptureConnection *connection in stillImageOutput.connections) {

        for (AVCaptureInputPort *port in [connection inputPorts]) {

            if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
                videoConnection = connection;
                crossButton.hidden = NO;
                cameraButton.hidden = YES;
                break;

            }

        }

    }

    [stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {

        if (imageDataSampleBuffer != NULL) {

            NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            UIImage *image = [UIImage imageWithData:imageData];
            imageView.image = image;

        }
    }];
}

A: probably you are using viewWillAppear or viewDidAppear methods to configure your camera in your application.
use viewDidLoad method to configure camera this will called once whenever the view controller needs to load its view hierarchy.
Reason: Methods viewDidAppear and viewWillAppear called every time whenever app navigate back to the same viewController.


text:
Q: Sorting data order by duration between start_date and end_date I'm using Laravel 7. I have a table named assistances witch has some columns and those two columns:
- start_date
- end_date

I'd like to sort data order by the duration between start_date and end_date:
 $query = Assistance::join('users', 'assistances.user_id', '=', 'users.id')
        ->select('assistances.*')
        ->orderBy('duration between start_date and end_date');
 ;

How can I do this ?

A: Please try the following - bare in mind that this is not hugely efficient
DATEDIFF returns the days between two dates. You may also want to use TIMESTAMPDIFF which accepts a first parameter such as 'hour' where you can get more granular control
$query = Assistance::join('users', 'assistances.user_id', '=', 'users.id')
        ->select('assistances.*')
        ->orderBy(DB::raw('DATEDIFF(start_date, end_date)'))
        ->get();

Please also use DB; in your class.


text:
Q: How does one find prices from Amazon's site programmatically? So Amazon has lots of different APIs for different things, and it's hard to find the one I'm looking for.
I have a client that sells things and checks Amazon's lowest price to know where to price their things (slightly under the lowest thing there). They want functionality integrated into their inventory system that would automatically find the product's lowest price on Amazon and display that. I was wondering which AWS service is best suited to this task.
I see the Product Advertising API, and that looks like the closest thing right now. Is that so?
I don't really want to rely on a scraper when Amazon provides a programmatic interface to this information somewhere, which I know they do because many other products have this. Some say that they can just download a dump of Amazon's products and use that locally -- I'm open to that option too if anyone can point me in its direction.

A: You can use the Amazon Marketplace Web Service (api, description)
This service can group all of the available offers into 'buckets' and shows the lowest price from each bucket bucket.
Each bucket has a unique combination of:

*

*Sub-Condition (New, Like New, Very Good, Good, Acceptable)

*FulfillmentChannel (FBA or Merchant-Fulfilled)

*ShipsDomestically (True, False, Unknown)

*ShippingTime (0-2 days, 3-7 days, 8-13 days, 14 or more days)

*SellerPositiveFeedbackRating (98-100%, 95-97%, 90-94%, 80-89%,
70-79%, Less than 70%, Just launched)

Someone made a really cool demo of the API here

A: We cannot get the entire amazon products using API.They had made certain restrictions to the usage of API such that it would be more relevant to advertising use case only.

A: Yes, the technically appropriate API is the Product Advertising API, using the ItemLookup/ItemSearch operations or the Seller* operations.
https://affiliate-program.amazon.com/gp/advertising/api/detail/main.html
I would also advise you to check the licensing agreement for this API, notably clause 4 (i).

A: I wrote that small python module to achieve such a task: https://github.com/iMilnb/awstools/blob/master/mods/awsprice.py
Basically, it fetches the prices from Amazon's website and convert them to a nice and parsable python dict.
I wrote two example functions that show how to use the resulting dict to dump an instance price on various terms along with a CSV converter.

A: There is a reply to a similar question which lists all the .js files containing the prices, which are barely JSON files (with only a callback(...); statement to remove).
Here is an exemple for Linux On Demand prices : http://aws-assets-pricing-prod.s3.amazonaws.com/pricing/ec2/linux-od.js
(Get the full list directly on that reply)


text:
Q: Can't get Chrome Context Menu item to show on Chrome Extension I have a Chrome extension that opens a KML/KMZ file in Google Maps. The extension is triggered when the user right-clicks a link to the KML document. But the context menu does not appear. It uses a background script. Here is the manifest.json:
{
  "manifest_version": 2,
  "name": "KML/KMZ Viewer",
  "version": "1.0.0",
  "description": "Can be used to view KML/KMZ Files.",
  "icons": {
    "19": "tiny.jpg",
    "24": "icon.png",
    "128": "image.png"
  },
  "permissions": [
    "tabs",
    "contextMenus",
    "activeTab",
    "background"
  ],
  "background": {
    "scripts": ["background.js"]
  }
}

Here is the background.js:
// Set up context menu at install time.
chrome.runtime.onInstalled.addListener(function() {
    menuCreate();
    console.log('Issued function');
});

// add click event
chrome.contextMenus.onClicked.addListener(onClickHandler);

// The onClicked callback function.
function onClickHandler(info, tab) {
    var url = info.selectionText;
    openWin(url);
};

function openWin(kml) {
    chrome.windows.create({"url":"http://www.nearby.org.uk/google/fake-kmlgadget.html?    up_kml_url="+kml+"&up_view_mode=earth&up_lat=&up_lng=&up_zoom=&up_earth_2d_fallback=1&up_earth_fly_from_space=1&up_earth_show_nav_controls=1&up_earth_show_buildings=1&up_earth_show_terrain=1&up_earth_show_roads=1&up_earth_show_borders=1&up_earth_sphere=earth&up_maps_streetview=1&up_maps_default_type=hybrid"});
}

function menuCreate() {
    chrome.contextMenus.create({"title": "Open KML/KMZ", "contexts": ["link"], "id": "kmlopen", "targetUrlPatterns": ["*.kml", "*.kmz"]});
    console.log('Function ran');
}

Yet when I right-click on a link to a KML or KMZ file, the context menu doesn't show. According to the JavaScript console, the functions ran. This is what the console outputs when I run chrome.contextMenus.create({"title": "Open KML/KMZ", "contexts": ["link"], "id": "kmlopen", "targetUrlPatterns": ["*.kml", "*.kmz"]}); manually under _generated_background_page.html I get the kmlopen, the id of the menu item. What am I doing wrong? The openWin(/*some url*/); function works fine.

A: Wrong pattern.
The patterns follow the standard Match pattern format.
So you should use the patterns
"targetUrlPatterns": ["*://*/*.kml", "*://*/*.kmz"]

However, be mindful of query strings.