问:
how to pass parameters of a function when using timeit.Timer()
This is the outline of a simple program

```<code># some pre-defined constants
A = 1
B = 2

# function that does something critical
def foo(num1, num2):
    # do something

# main program.... do something to A and B
for i in range(20):
    # do something to A and B
    # and update A and B during each iteration

import timeit
t = timeit.Timer(stmt="foo(num1,num2)")
print t.timeit(5)
</code>```

I just keep getting "global name foo is not defined".....
Can anyone help me on this? Thanks!

答:
I prefer creating a static class with all the Data ready to be picked up prior of running the timer.

Another note, it is better to do test runs in  function rather then in the global space, as the global space isn't taking advantage of FAST_LOAD Why does Python code run faster in a function?

```<code>class Data(object):
    """Data Creation"""
    x = [i for i in range(0, 10000)]
    y = tuple([i for i in range(0, 10000)])
    def __init__(self):
        pass

import timeit

def testIterator(x):
    for i in range(10000):
        z = i

print timeit.timeit("testIterator(Data.x)", setup="from __main__ import testIterator, Data", number=50)
print timeit.timeit("testIterator(Data.y)", setup="from __main__ import testIterator, Data", number=50)
</code>```

Body:
This is the outline of a simple program

# some pre-defined constants
A = 1
B = 2

# function that does something critical
def foo(num1, num2):
    # do something

# main program.... do something to A and B
for i in range(20):
    # do something to A and B
    # and update A and B during each iteration

import timeit
t = timeit.Timer(stmt="foo(num1,num2)")
print t.timeit(5)

I just keep getting "global name foo is not defined".....
Can anyone help me on this? Thanks!

Body:
I prefer creating a static class with all the Data ready to be picked up prior of running the timer.

Another note, it is better to do test runs in  function rather then in the global space, as the global space isn't taking advantage of FAST_LOAD Why does Python code run faster in a function?

class Data(object):
    """Data Creation"""
    x = [i for i in range(0, 10000)]
    y = tuple([i for i in range(0, 10000)])
    def __init__(self):
        pass

import timeit

def testIterator(x):
    for i in range(10000):
        z = i

print timeit.timeit("testIterator(Data.x)", setup="from __main__ import testIterator, Data", number=50)
print timeit.timeit("testIterator(Data.y)", setup="from __main__ import testIterator, Data", number=50)


来源: stackexchange

问:
Add non chart content in highchart pdf
Can we add non-svg chart related content in the PDF we create using highcharts?

I used this example for creating PDF of multiple highcharts.

I want to add custom logo and some title at the top of the graph PDF. For example logo of website with title "Graph for life cycle"

Can anyone tell me how to do it?

答:
I'm assuming you want the image and text to appear in the PDF, but not on the screen.  To achieve that, just add a class to the elements that is limited to a print media query.

```<code>@media print {
  .noScreen {
    display: block;
  }
}

@media screen {
  .noScreen {
    display: none;
  }
}
</code>```

HTML

```<code>  <img src='http://via.placeholder.com/350x150?text=MyLogo' class='noScreen'>
  <h1 class='noScreen'>Graph for life cycle</h1>
</code>```

I've modified the sample fiddle from that answer to illustrate: http://jsfiddle.net/zvx6eb7e/646/

ContentLicense: CC BY-SA 3.0

Title: Add non chart content in highchart pdf

Body:
I'm assuming you want the image and text to appear in the PDF, but not on the screen.  To achieve that, just add a class to the elements that is limited to a print media query.

@media print {
  .noScreen {
    display: block;
  }
}

@media screen {
  .noScreen {
    display: none;
  }
}

HTML

  <img src='http://via.placeholder.com/350x150?text=MyLogo' class='noScreen'>
  <h1 class='noScreen'>Graph for life cycle</h1>

I've modified the sample fiddle from that answer to illustrate: http://jsfiddle.net/zvx6eb7e/646/


问:
Run chrome lighthouse's audit from command line
I would like to write a script which run (from the chrome's binary) its lighthouse's audit with a url given.
I didn't manage to find how to do it, but since there is even a chrome extension doing I assume it should be feasible right ?

答:
Google Lighthouse can be ran using the command line. To run it from the command line, you must first install:

Google Chrome for Desktop

Node.js v6 or later.

To install the Lighthouse CLI, open a command line and type the following command:

npm install -g lighthouse
```

<p>To run an audit with Lighthouse, type:</p>

<pre class="lang-sh prettyprint-override"><code>lighthouse https://example.com
</code>```

By default, Lighthouse writes the report to an HTML file. You can control the output format by passing flags.

You will notice that a Chrome window is opened every time you run Lighthouse. If you don't want a window to be opened, you can run it in headless mode:

lighthouse https://example.com/ --chrome-flags="--headless"
```

<p>For the complete list of options, type:</p>

<pre class="lang-sh prettyprint-override"><code>lighthouse --help
</code>```

Take a look at the Lighthouse source code repository for additional documentation and examples.

Body:
Google Lighthouse can be ran using the command line. To run it from the command line, you must first install:

Google Chrome for Desktop

Node.js v6 or later.

To install the Lighthouse CLI, open a command line and type the following command:

npm install -g lighthouse

To run an audit with Lighthouse, type:

lighthouse https://example.com

By default, Lighthouse writes the report to an HTML file. You can control the output format by passing flags.

You will notice that a Chrome window is opened every time you run Lighthouse. If you don't want a window to be opened, you can run it in headless mode:

lighthouse https://example.com/ --chrome-flags="--headless"

For the complete list of options, type:

lighthouse --help

Take a look at the Lighthouse source code repository for additional documentation and examples.


问:
enabling/ disabling combobox when selected index is selected
I'm trying to enable comboxbox when specific country is selected, otherwise should be disabled. </p>

```<code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    cboCountry.Items.AddRange(File.ReadAllLines("..\..\TextFiles\countries.txt"))
    cboCounty.Items.AddRange(File.ReadAllLines("..\..\TextFiles\county.txt"))

End Sub

Private Sub cboCountry_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCountry.SelectedIndexChanged
    If cboCountry.SelectedIndex = cboCountry.Items.IndexOf("Ireland") Then

        cboCounty.Enabled = True

    Else
        cboCounty.Enabled = False

    End If
End Sub
</code>```

<p>When I select any country including "Ireland" combobox is disabled </p>

答:
I literally tried the exact same code you posted and it worked for me. I created a Windows Form with two comboboxes, changed their names to cboCountry and cboCounty, changed their dropdownstyle to DropDownList, and disabled cboCounty.

```<code>Private Sub cboCountry_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCountry.SelectedIndexChanged
   If cboCountry.SelectedIndex = cboCountry.Items.IndexOf("Ireland") Then
      cboCounty.Enabled = True
   Else
      cboCounty.Enabled = False
   End If
End Sub
</code>```

I also tried @Charles May's solution and that worked as well.

Body:
I'm trying to enable comboxbox when specific country is selected, otherwise should be disabled.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    cboCountry.Items.AddRange(File.ReadAllLines("..\..\TextFiles\countries.txt"))
    cboCounty.Items.AddRange(File.ReadAllLines("..\..\TextFiles\county.txt"))

End Sub

Private Sub cboCountry_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCountry.SelectedIndexChanged
    If cboCountry.SelectedIndex = cboCountry.Items.IndexOf("Ireland") Then

        cboCounty.Enabled = True

    Else
        cboCounty.Enabled = False

    End If
End Sub

When I select any country including "Ireland" combobox is disabled

Body:
I literally tried the exact same code you posted and it worked for me. I created a Windows Form with two comboboxes, changed their names to cboCountry and cboCounty, changed their dropdownstyle to DropDownList, and disabled cboCounty.

Private Sub cboCountry_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCountry.SelectedIndexChanged
   If cboCountry.SelectedIndex = cboCountry.Items.IndexOf("Ireland") Then
      cboCounty.Enabled = True
   Else
      cboCounty.Enabled = False
   End If
End Sub

I also tried @Charles May's solution and that worked as well.


问:
How can I access every 5th Div, from a container so i can then use jQuery's add Class
Hey Everyone,
Here's what i'm trying to do..

i have div that will contain numerous other div (products in a shopping cart), say
up 50.

of these contained divs, i need to access every 5th div begging with 1, so it'd be div # 1, 6, 11, 16, 21 etc. and then use jQuery to Add Class to these divs.

can someone point me in the right direction on how to do this?

it would be hugely appreciated, thanks

答: I think it will be useful:http://api.jquery.com/nth-child-selector/</p>

ContentLicense: CC BY-SA 2.5


问:
Why is the pointer in this nested class missing?
Question in short:

class B has a ptr to class C, which has a class D having a ptr to class B

assign class B to an array in class A by copying, expecting to see to ptr points to new instance in the array not original instance, but failed.

I am already able to do some workaround, but I want to know why my original approach fails.

More detailed explainations are as follows, and the code to reproduce the problem is posted as well

Anyone who is able to explain what is going on is appreciated.

There are 6 classes:

class CastInfo //contains a Character*

class Skill  //abstract class, contains CastInfo

class Movvement : public Skill

class Move1 : public Movement

class Character //contains a Movement*, which will be Move1* in practice

class Squad //contains an array of Character

with the following relationships:

Character* in CastInfo should point to the Character who owns the Skill which
is the owner of CastInfo

when assigning the Skill to Character, the Character* in CastInfo points to that Character

the Character in Squad's array should be copied, so there will be 2 instances and the Character* in CastInfo should also point to Character in Squad's array not original instance

The expecting result is:

move1 != ch1.move1 != squad.ch[0].move1 (this is already satisfied)

ch1.move1->cast_info.caster == &ch1 != squad.ch[0].move1->caster_info.caster (this is the problem)

There are 2 cases (tried) of the output:

In the Squad's constructor,:
if using

```<code>characters_[i] = characters[i];
</code>```

the character is correctly copied, but the skill is at same address

```<code>move1: 00000270E6093500
ch1: 000000BC6DCFF378
ch1.move1: 00000270E6093E60
ch1.move1->cast_info.caster: 000000BC6DCFF378
squad.ch[0]: 000000BC6DCFF3E0
squad.ch[0].move1: 00000270E6093E60
squad.ch[0].move1->cast_info.caster: 000000BC6DCFF378
</code>```

if using

```<code>characters_[i] = Character(characters[i]);
</code>```

the character is correctly copied, but the skill is missing (pointing to some weird location)

```<code>move1: 00000230FDCEF080
ch1: 00000058A11DF548
ch1.move1: 00000230FDCEF260
ch1.move1->cast_info.caster: 00000058A11DF548
squad.ch[0]: 00000058A11DF5B0
squad.ch[0].move1: 00000230FDCEF0E0
squad.ch[0].move1->cast_info.caster: 00000058A11DF378
</code>```

In the first case, I guess it is probably because I did not overload operator=, so only address is copied. I tried to overload it but it caused more problem. (Such as when using Builder.Build() )

In the second case, I expect it first call copy constructor, which triggers SetMove1(), which calls SetCaster(). move1 is cloned as shown, but I cannot understand why caster is not updated correctly. (Though is calls operator= after construnction, the address should remain the same.)

The following code should reproduce the problem:

motion.h

```<code>#pragma once
class Character;

struct CastInfo
{
    Character* caster;
    int coeff;
};

class Skill
{
public:
    CastInfo cast_info;
    Skill() {};
    ~Skill() {};
    virtual void DoSomething() = 0;
};

class Movement : public Skill
{
public:
    Movement();
    ~Movement();
    virtual void DoSomething() { ; }
    virtual Movement* Clone() const { return new Movement(*this); }
};

class Move1 : public Movement
{
public:
    Move1() { cast_info.coeff = 123; }
    void DoSomething() { ; }
    virtual Move1* Clone() const { return new Move1(*this); }
};

class Move2 : public Movement
{
public:
    void DoSomething() { ; }
};
</code>```

motion.cpp:

```<code>#include "motion.h"
Movement::Movement() { }
Movement::~Movement() { }
</code>```

test.h:

```<code>#pragma once
#include <string>
#include <vector>
#include "motion.h"
#define SQUAD_SIZE 6

extern Movement* null_movement;
class Character
{
public:
    class Builder;
    Character();
    ~Character();
    Character(const Character& character);
    Character& SetMove1(Movement* skill);
public:
    int id_;
    Movement* move1_ = null_movement;
    Movement* move2_ = null_movement;
    Character(int id) : id_(id) { ; }
    void SetCaster();
};

class Character::Builder : public Character
{
public:
    Builder& SetId(int i) { id_ = i; return *this; }
    Character Build() { return Character(id_); }
};

class Squad
{
public:
    class Builder;
    Squad() { }
    Squad(const Squad& squad);
    ~Squad() { }
public:
    Character characters_[SQUAD_SIZE];
    Squad(Character* characters);
};

class Squad::Builder :public Squad
{
public:
    Builder& SetCharacter(const Character& character, const int position) { characters_[position] = character; return *this; }
    Squad Build() { return Squad(characters_); }
};
</code>```

test.cpp

```<code>#include <iostream>
#include "test.h"

Movement* null_movement = new Move2();
Character::Character() : id_(0) { }
Character::~Character() {}
Character::Character(const Character& character) {
    id_ = character.id_;
    SetMove1(character.move1_);
}

Character& Character::SetMove1(Movement* move1) {
    if (!move1) return *this;
    move1_ = move1->Clone();
    SetCaster();
    return *this;
}

void Character::SetCaster() {
    if (move1_ != NULL) move1_->cast_info.caster = this;
}

Squad::Squad(const Squad& squad) {
    *this = squad;
}

Squad::Squad(Character* characters) {
    for (int i = 0; i < SQUAD_SIZE; i++) {
        //characters_[i] = characters[i];  //character copied, skill same address
        characters_[i] = Character(characters[i]); //character copied, skill missing
    }
}
</code>```

main.cpp

```<code>#include <iostream>
#include "test.h"
#include "motion.h"
int main() {

    Move1* move1 = new Move1();
    std::cout << "move1: " << move1 << std::endl;

    Character ch1 = Character::Builder().SetId(1).Build();
    Character ch2 = Character::Builder().SetId(2).Build();
    ch1.SetMove1(move1);

    std::cout << "ch1: " << &ch1 << std::endl;
    std::cout << "ch1.move1: " << (ch1.move1_) << std::endl;
    std::cout << "ch1.move1->cast_info.caster: " << (ch1.move1_->cast_info.caster) << std::endl;

    Squad squad = Squad::Builder().SetCharacter(ch1, 0).SetCharacter(ch2, 1).Build();

    std::cout << "squad.ch[0]: " << &(squad.characters_[0]) << std::endl;
    std::cout << "squad.ch[0].move1: " << (squad.characters_[0].move1_) << std::endl;
    std::cout << "squad.ch[0].move1->cast_info.caster: " << (squad.characters_[0].move1_->cast_info.caster) << std::endl;

    system("PAUSE");
    return 0;
}
</code>```

As previously mentioned, I have a workaround to reach my goal:

By creating another method, which iterates through the array in Squad, and call each Character's SetCaster() method.

```<code>void Squad::SetCaster() {
    for (int i = 0; i < SQUAD_SIZE; i++) {
        characters_[i].SetCaster();
    }
}
</code>```

But I think this is dirty because every time after Builder::Builder(), SetCaster() must be called, which is unintuitive and error-prone.

答:
I think I found the problem, as illustrated below:

The problem is in

```<code>Squad::Squad(Character* characters) {
    for (int i = 0; i < SQUAD_SIZE; i++) {
        //characters_[i] = characters[i];  //character copied, skill same address
        characters_[i] = Character(characters[i]); //character copied, skill missing
    }
}
</code>```

As mentioned in question, using the commented line is just copying the values, which is incorrect.

What

```<code>characters_[i] = Character(characters[i]); //character copied, skill missing
</code>```

does is as follows:

create a Character, by calling Character's constructer, this object is at address A. SetMove1() is called, SetCaster() is called. The pointer in cast_info is pointing at A correctly.

assign the object to characters_[i], whose address is at address B because the address of characters_ is assigned when Squad is created. As I did not overload Character::operator=, the pointer is still pointing to address A

Constructor done, Squad returned.

This is the reason

```<code>std::cout << "squad.ch[0].move1->cast_info.caster: " << (squad.characters_[0].move1_->cast_info.caster) << std::endl;
</code>```

shows a third address (address A) which is neither &(character[0]) (address B) nor &ch1 (original character's address)

The solution is either to overload operator= or put my "workaround" (Squad::SetCaster()) in constructor right after the for loop.

Please correct me if there is anything wrong, or if there is any better solution.

Body:
Question in short:

class B has a ptr to class C, which has a class D having a ptr to class B

assign class B to an array in class A by copying, expecting to see to ptr points to new instance in the array not original instance, but failed.

I am already able to do some workaround, but I want to know why my original approach fails.

More detailed explainations are as follows, and the code to reproduce the problem is posted as well

Anyone who is able to explain what is going on is appreciated.

There are 6 classes:

class CastInfo //contains a Character*

class Skill  //abstract class, contains CastInfo

class Movvement : public Skill

class Move1 : public Movement

class Character //contains a Movement*, which will be Move1* in practice

class Squad //contains an array of Character

with the following relationships:

Character* in CastInfo should point to the Character who owns the Skill which
is the owner of CastInfo

when assigning the Skill to Character, the Character* in CastInfo points to that Character

the Character in Squad's array should be copied, so there will be 2 instances and the Character* in CastInfo should also point to Character in Squad's array not original instance

The expecting result is:

move1 != ch1.move1 != squad.ch[0].move1 (this is already satisfied)

ch1.move1->cast_info.caster == &ch1 != squad.ch[0].move1->caster_info.caster (this is the problem)

There are 2 cases (tried) of the output:

In the Squad's constructor,:
if using

characters_[i] = characters[i];

the character is correctly copied, but the skill is at same address

move1: 00000270E6093500
ch1: 000000BC6DCFF378
ch1.move1: 00000270E6093E60
ch1.move1->cast_info.caster: 000000BC6DCFF378
squad.ch[0]: 000000BC6DCFF3E0
squad.ch[0].move1: 00000270E6093E60
squad.ch[0].move1->cast_info.caster: 000000BC6DCFF378

if using

characters_[i] = Character(characters[i]);

the character is correctly copied, but the skill is missing (pointing to some weird location)

move1: 00000230FDCEF080
ch1: 00000058A11DF548
ch1.move1: 00000230FDCEF260
ch1.move1->cast_info.caster: 00000058A11DF548
squad.ch[0]: 00000058A11DF5B0
squad.ch[0].move1: 00000230FDCEF0E0
squad.ch[0].move1->cast_info.caster: 00000058A11DF378

In the first case, I guess it is probably because I did not overload operator=, so only address is copied. I tried to overload it but it caused more problem. (Such as when using Builder.Build() )

In the second case, I expect it first call copy constructor, which triggers SetMove1(), which calls SetCaster(). move1 is cloned as shown, but I cannot understand why caster is not updated correctly. (Though is calls operator= after construnction, the address should remain the same.)

The following code should reproduce the problem:

motion.h

#pragma once
class Character;

struct CastInfo
{
    Character* caster;
    int coeff;
};

class Skill
{
public:
    CastInfo cast_info;
    Skill() {};
    ~Skill() {};
    virtual void DoSomething() = 0;
};

class Movement : public Skill
{
public:
    Movement();
    ~Movement();
    virtual void DoSomething() { ; }
    virtual Movement* Clone() const { return new Movement(*this); }
};

class Move1 : public Movement
{
public:
    Move1() { cast_info.coeff = 123; }
    void DoSomething() { ; }
    virtual Move1* Clone() const { return new Move1(*this); }
};

class Move2 : public Movement
{
public:
    void DoSomething() { ; }
};

motion.cpp:

#include "motion.h"
Movement::Movement() { }
Movement::~Movement() { }

test.h:

#pragma once
#include <string>
#include <vector>
#include "motion.h"
#define SQUAD_SIZE 6

extern Movement* null_movement;
class Character
{
public:
    class Builder;
    Character();
    ~Character();
    Character(const Character& character);
    Character& SetMove1(Movement* skill);
public:
    int id_;
    Movement* move1_ = null_movement;
    Movement* move2_ = null_movement;
    Character(int id) : id_(id) { ; }
    void SetCaster();
};

class Character::Builder : public Character
{
public:
    Builder& SetId(int i) { id_ = i; return *this; }
    Character Build() { return Character(id_); }
};

class Squad
{
public:
    class Builder;
    Squad() { }
    Squad(const Squad& squad);
    ~Squad() { }
public:
    Character characters_[SQUAD_SIZE];
    Squad(Character* characters);
};

class Squad::Builder :public Squad
{
public:
    Builder& SetCharacter(const Character& character, const int position) { characters_[position] = character; return *this; }
    Squad Build() { return Squad(characters_); }
};

test.cpp

#include <iostream>
#include "test.h"

Movement* null_movement = new Move2();
Character::Character() : id_(0) { }
Character::~Character() {}
Character::Character(const Character& character) {
    id_ = character.id_;
    SetMove1(character.move1_);
}

Character& Character::SetMove1(Movement* move1) {
    if (!move1) return *this;
    move1_ = move1->Clone();
    SetCaster();
    return *this;
}

void Character::SetCaster() {
    if (move1_ != NULL) move1_->cast_info.caster = this;
}

Squad::Squad(const Squad& squad) {
    *this = squad;
}

Squad::Squad(Character* characters) {
    for (int i = 0; i < SQUAD_SIZE; i++) {
        //characters_[i] = characters[i];  //character copied, skill same address
        characters_[i] = Character(characters[i]); //character copied, skill missing
    }
}

main.cpp

#include <iostream>
#include "test.h"
#include "motion.h"
int main() {

    Move1* move1 = new Move1();
    std::cout << "move1: " << move1 << std::endl;

    Character ch1 = Character::Builder().SetId(1).Build();
    Character ch2 = Character::Builder().SetId(2).Build();
    ch1.SetMove1(move1);

    std::cout << "ch1: " << &ch1 << std::endl;
    std::cout << "ch1.move1: " << (ch1.move1_) << std::endl;
    std::cout << "ch1.move1->cast_info.caster: " << (ch1.move1_->cast_info.caster) << std::endl;

    Squad squad = Squad::Builder().SetCharacter(ch1, 0).SetCharacter(ch2, 1).Build();

    std::cout << "squad.ch[0]: " << &(squad.characters_[0]) << std::endl;
    std::cout << "squad.ch[0].move1: " << (squad.characters_[0].move1_) << std::endl;
    std::cout << "squad.ch[0].move1->cast_info.caster: " << (squad.characters_[0].move1_->cast_info.caster) << std::endl;

    system("PAUSE");
    return 0;
}

As previously mentioned, I have a workaround to reach my goal:

By creating another method, which iterates through the array in Squad, and call each Character's SetCaster() method.

void Squad::SetCaster() {
    for (int i = 0; i < SQUAD_SIZE; i++) {
        characters_[i].SetCaster();
    }
}

But I think this is dirty because every time after Builder::Builder(), SetCaster() must be called, which is unintuitive and error-prone.

Body:
I think I found the problem, as illustrated below:

The problem is in

Squad::Squad(Character* characters) {
    for (int i = 0; i < SQUAD_SIZE; i++) {
        //characters_[i] = characters[i];  //character copied, skill same address
        characters_[i] = Character(characters[i]); //character copied, skill missing
    }
}

As mentioned in question, using the commented line is just copying the values, which is incorrect.

What

characters_[i] = Character(characters[i]); //character copied, skill missing

does is as follows:

create a Character, by calling Character's constructer, this object is at address A. SetMove1() is called, SetCaster() is called. The pointer in cast_info is pointing at A correctly.

assign the object to characters_[i], whose address is at address B because the address of characters_ is assigned when Squad is created. As I did not overload Character::operator=, the pointer is still pointing to address A

Constructor done, Squad returned.

This is the reason

std::cout << "squad.ch[0].move1->cast_info.caster: " << (squad.characters_[0].move1_->cast_info.caster) << std::endl;

shows a third address (address A) which is neither &(character[0]) (address B) nor &ch1 (original character's address)

The solution is either to overload operator= or put my "workaround" (Squad::SetCaster()) in constructor right after the for loop.

Please correct me if there is anything wrong, or if there is any better solution.


问:
Making an If Statement for first round of Switch Java
Im trying to set a specific image for only the first iteration of a for loop through a switch. For case 'f' I would like to add a different image on the first iteration.

How would I do this? Is it even possible to keep track of within a switch?

```<code>    for (char c : symbols) {
            switch (c) {
            case 'X':
                g2.setColor(Color.BLACK);
                g2.drawImage(wallImg, x, y, width, height, null);
                break;
            case 's':
                g2.setColor(Color.GREEN);
                g2.drawImage(snakeImg, x, y, width, height, null);
                break;
            case 'f':
                g2.setColor(Color.ORANGE);
                g2.drawImage(burgerImg, x, y, width, height, null);
                break;
            case '.':
                g2.setColor(Color.WHITE);
                g2.fillRect(x, y, width, height);
                break;
            case '\n':
                y += height;
            }
</code>```

答:
Add a flag to see if you have iterated yet or not, then adopt an if statement into your switch-case to account for it like this:</p>

```<code>        boolean flag = false;

        for (char c : symbols) {
            switch (c) {
            case 'X':
                g2.setColor(Color.BLACK);
                g2.drawImage(wallImg, x, y, width, height, null);
                break;
            case 's':
                g2.setColor(Color.GREEN);
                g2.drawImage(snakeImg, x, y, width, height, null);
                break;
            case 'f':
                //check to see if your flag is true/false
                if(flag){
                    g2.setColor(Color.ORANGE);
                    g2.drawImage(burgerImg, x, y, width, height, null);
                }else{
                    //set first image
                    flag = true;
                }
                break;
            case '.':
                g2.setColor(Color.WHITE);
                g2.fillRect(x, y, width, height);
                break;
            case '\n':
                y += height;
                break;
        }
</code>```

Body:
Im trying to set a specific image for only the first iteration of a for loop through a switch. For case 'f' I would like to add a different image on the first iteration.

How would I do this? Is it even possible to keep track of within a switch?

    for (char c : symbols) {
            switch (c) {
            case 'X':
                g2.setColor(Color.BLACK);
                g2.drawImage(wallImg, x, y, width, height, null);
                break;
            case 's':
                g2.setColor(Color.GREEN);
                g2.drawImage(snakeImg, x, y, width, height, null);
                break;
            case 'f':
                g2.setColor(Color.ORANGE);
                g2.drawImage(burgerImg, x, y, width, height, null);
                break;
            case '.':
                g2.setColor(Color.WHITE);
                g2.fillRect(x, y, width, height);
                break;
            case '\n':
                y += height;
            }

Body:
Add a flag to see if you have iterated yet or not, then adopt an if statement into your switch-case to account for it like this:

        boolean flag = false;

        for (char c : symbols) {
            switch (c) {
            case 'X':
                g2.setColor(Color.BLACK);
                g2.drawImage(wallImg, x, y, width, height, null);
                break;
            case 's':
                g2.setColor(Color.GREEN);
                g2.drawImage(snakeImg, x, y, width, height, null);
                break;
            case 'f':
                //check to see if your flag is true/false
                if(flag){
                    g2.setColor(Color.ORANGE);
                    g2.drawImage(burgerImg, x, y, width, height, null);
                }else{
                    //set first image
                    flag = true;
                }
                break;
            case '.':
                g2.setColor(Color.WHITE);
                g2.fillRect(x, y, width, height);
                break;
            case '\n':
                y += height;
                break;
        }


问:
Error Running React Native App From Terminal (iOS)
I am following the tutorial on the official React Native website.

Using the following to build my project:

```<code>react-native run-ios
</code>```

I get the error:

```<code>Found Xcode project TestProject.xcodeproj
xcrun: error: unable to find utility "instruments", not a developer
tool or in PATH

Command failed: xcrun instruments -s
xcrun: error: unable to find utility "instruments", not a developer
tool or in PATH
</code>```

Although, when I run the app from the .xcodeproj, everything works fine.

Any suggestions?

答: For those like me who come to this page with this problem after updating Xcode but don't have an issue with the location setting, restarting my computer did the trick.</p>

Body:
I am following the tutorial on the official React Native website.

Using the following to build my project:

react-native run-ios

I get the error:

Found Xcode project TestProject.xcodeproj
xcrun: error: unable to find utility "instruments", not a developer
tool or in PATH

Command failed: xcrun instruments -s
xcrun: error: unable to find utility "instruments", not a developer
tool or in PATH

Although, when I run the app from the .xcodeproj, everything works fine.

Any suggestions?


问:
how to use curl to pass parameters to the form of the https://www.worldtimeserver.com/ website
I am trying to write a bash program that given a country name
displays the time in that country. For that I am using the https://www.worldtimeserver.com/

The idea is the get the country as a parameter to the bash program and pass it
to the web site to search for it. I am using curl and I tried many possible
ways to pass a parameter to the web site, but nothing worked.

The relevant html code of the web site looks as follows:

```<code>Choose a location to see current local time right now:<br />
<select name="ctl00$ContentPlaceHolderMain$locationddl" id="ContentPlaceHolderMain_locationddl" onchange="gotocurrenttime(this);" style="max-width:100%">
<option value="">select a location</option>
<option value="UTC">(UTC/GMT)</option>
<option value="AF">Afghanistan</option>
<option value="AX">Åland Islands</option>
</code>```

So, I tried the following code in bash to try to pass "AF"
which is the code for Afghanistan, to the web site for a search.

I typed the following from the command line:

curl -X POST -F 'ctl00$ContentPlaceHolderMain$locationddl=AF'
  https://www.worldtimeserver.com/ >| tmp

Then I looked at the tmp file created and it is as if no parameter is
given for the search.

So, the question is how to pass correctly the parameter of the country
Afghanistan so that I will get as a reply the html file that shows
the time in Afghanistan.

Thanks a lot for any help.

答:
this should work, but if you don't use an official API it may break without notice

```<code>code=TR; curl -s https://www.worldtimeserver.com/current_time_in_$code.aspx
</code>```

the file is very large, may not have much practical value.  I piped to grep -A1 'id="theTime"' to get the time only...

Body:
I am trying to write a bash program that given a country name
displays the time in that country. For that I am using the https://www.worldtimeserver.com/

The idea is the get the country as a parameter to the bash program and pass it
to the web site to search for it. I am using curl and I tried many possible
ways to pass a parameter to the web site, but nothing worked.

The relevant html code of the web site looks as follows:

Choose a location to see current local time right now:

<select name="ctl00$ContentPlaceHolderMain$locationddl" id="ContentPlaceHolderMain_locationddl" onchange="gotocurrenttime(this);" style="max-width:100%">
<option value="">select a location</option>
<option value="UTC">(UTC/GMT)</option>
<option value="AF">Afghanistan</option>
<option value="AX">Åland Islands</option>

So, I tried the following code in bash to try to pass "AF"
which is the code for Afghanistan, to the web site for a search.

I typed the following from the command line:

curl -X POST -F 'ctl00$ContentPlaceHolderMain$locationddl=AF'
  https://www.worldtimeserver.com/ >| tmp

Then I looked at the tmp file created and it is as if no parameter is
given for the search.

So, the question is how to pass correctly the parameter of the country
Afghanistan so that I will get as a reply the html file that shows
the time in Afghanistan.

Thanks a lot for any help.

Body:
this should work, but if you don't use an official API it may break without notice

code=TR; curl -s https://www.worldtimeserver.com/current_time_in_$code.aspx

the file is very large, may not have much practical value.  I piped to grep -A1 'id="theTime"' to get the time only...


问:
TypeError: Cannot read property "price" from undefined in <eval> at line number
someone wrote this JS for me and it worked earlier but now it does not; I cannot get hold of that person so I am reaching out for assistance. I had spent numerous hours trying to correct this but I am not experienced enough with JS .

I am receiving this error:

TypeError: Cannot read property "price" from undefined in  at line number 67

```<code>// Create input variables
var orderItems = [];
var rowsArray = ${rows([]);object(of=json)};
var auxObj = {
'Lip Balm - Orange Coconut': ${lipBalmOrangeCoconut(0)},
'Lip Balm - Raspberry Vanilla': ${lipBalmRaspberryVanilla(0)},
'Bath Bomb - Assorted - 50 mg THC': ${bathBombAssorted50MgThc(0)},
'Buddha Buddha - 200 mg THC': ${buddhaBuddha200MgThc(0)},
'Top Lemon Balm Salve': ${topLemonBalmSalve(0)},
'Buddha Bar - 300 mg THC': ${buddhaBar300MgThc(0)},
'BC Skunk - Hybrid': ${bcSkunkHybrid(0)},
'Blue King - Hybrid': ${blueKingHybrid(0)},
'CBD Treat - Hybrid': ${cbdTreatHybrid(0)},
'Dr. Krippling - Indica': ${drKripplingIndica(0)},
"God's Blue Cough - Hybrid": ${godsBlueCoughHybrid(0)},
'Island Sweet Skunk - Sativa': ${islandSweetSkunkSativa(0)},
'Lemon Sour Diesel - Hybrid': ${lemonSourDieselHybrid(0)},
'MI-O - Sativa': ${mioSativa(0)},
'OG Kush - Hybrid': ${ogKushHybrid(0)},
'Strawberry Skunk - Hybrid': ${strawberrySkunkHybrid(0)},
'Bubble Hash ': ${bubbleHash(0)},
'CBD - 2 capsules per package': ${cbd2CapsulesPerPackage(0)},
'CBD - 30 capsules per bottle': ${cbd30CapsulesPerBottle(0)},
'CBD Phoenix Tears ': ${cbdPhoenixTears(0)},
'THC Phoenix Tears ': ${thcPhoenixTears(0)},
'THC grape seed oil (indica) 900 mg / 30 ml':
${thcGrapeSeedOilindica900Mg30Ml(0)},
'THC grape seed oil (sativa) 900 mg / 30 ml':
${thcGrapeSeedOilsativa900Mg30Ml(0)},
'1:1 THC:CBD grape seed oil 200 mg / 30 ml':
${11ThccbdGrapeSeedOil200Mg30Ml(0)},
'CBD grape seed oil 150 mg / 30 ml': ${cbdGrapeSeedOil150Mg30Ml(0)},
'Chocolate Chip Cookie - 15 mg THC': ${chocolateChipCookie15MgThc(0)},
'Ginger Chew Cookie - 30 mg THC': ${gingerChewCookie30MgThc(0)},
'Red Licorice Bites - 125 mg THC': ${redLicoriceBites125MgThc(0)},
'Double Dose Peanut Butter Cup - 200 mg THC':
${doubleDosePeanutButterCup200MgThc(0)},
'Cherry - 125 mg THC (hybrid)': ${cherry125MgThchybrid(0)},
'Rootbeer - 125 mg THC (sativa)': ${rootbeer125MgThcsativa(0)},
'Watermelon - 125 mg THC (hybrid)': ${watermelon125MgThchybrid(0)},
'Cherry - 120 mg (indica)': ${cherry120Mgindica(0)},
'Blue Raspberry - 120 mg (indica)': ${blueRaspberry120Mgindica(0)},
'Peach  - 120 mg (sativa)': ${peach120Mgsativa(0)},
'Strawberry Banana - 120 mg (sativa)': ${strawberryBanana120Mgsativa(0)},
'Lollipops - Assorted Flavors - 150 mg THC':
${lollipopsAssortedFlavors150MgThc(0)},
'Cotton Candy - Original - 180 mg THC': ${cottonCandyOriginal180MgThc(0)},
'Cotton Candy - Tutti Fruitti - 180 mg THC':
${cottonCandyTuttiFruitti180MgThc(0)},
'Cranberry Ice Tea Apothecary - 60 mg THC':
${cranberryIceTeaApothecary60MgThc(0)},
'Lemon Ice Tea Apothecary - 60 mg THC': ${lemonIceTeaApothecary60MgThc(0)},
'Mango Ice Tea Apothecary - 60 mg THC': ${mangoIceTeaApothecary60MgThc(0)},
'Peach Ice Tea Apothecary - 60 mg THC': ${peachIceTeaApothecary60MgThc(0)},
'Coconut Oil - 500 mg THC': ${coconutOil500MgThc(0)},
'Olive Oil - 400 mg THC': ${oliveOil400MgThc(0)},
'House Strain - Hybrid': ${houseStrainHybrid(0)},
};

// Create a "lookup table" for stock nr. and price
var lookup = {};
for (var i = 0, len = rowsArray.length; i < len; i++) {
lookup[rowsArray[i].formName] = rowsArray[i];
}

var amount = 0,
subtotal = 0,
tax = 0,
shipping = 20,
total = 0;

for (var key in auxObj) {
if (auxObj[key] !== 0) {
    amount = auxObj[key] * lookup[key].price;
    orderItems.push({
        'value': auxObj[key],
        'name': key,
        'stock': lookup[key].stock,
        'price': lookup[key].price,
        'amount': amount
    });
    subtotal += amount;
}
}
tax = subtotal * 0.05;
total = subtotal + tax + shipping;

// Return output variables
var result = {
'orderItems' : orderItems,
'subtotal': subtotal,
'tax': tax,
'total': total
};
result;
</code>```

Line 67 'price' has the error.
I don't know if this amount of code is enough, if you need the full code then please ask.
I don't know why the error is happening (keep in mind I'm not exp. w/JS) and how to fix it to run.

答:
I think the price index in the lookup object is undefined. Try checking for the index before you access it in the object.</p>

```<code>var price, stock;
for (var key in auxObj) {
    if (auxObj[key] !== 0) {

        price = ( typeof lookup[key].price !== 'undefined' ? lookup[key].price : 0 );

        stock = ( typeof lookup[key].stock !== 'undefined' ? lookup[key].stock : 'Not in stock' );

        amount = auxObj[key] * lookup[key].price;
        orderItems.push({
             'value': auxObj[key],
             'name': key,
             'stock': lookup[key].stock,
             'price': lookup[key].price,
             'amount': amount
        });
     }
}
</code>```

Body:
someone wrote this JS for me and it worked earlier but now it does not; I cannot get hold of that person so I am reaching out for assistance. I had spent numerous hours trying to correct this but I am not experienced enough with JS .

I am receiving this error:

TypeError: Cannot read property "price" from undefined in  at line number 67

// Create input variables
var orderItems = [];
var rowsArray = ${rows([]);object(of=json)};
var auxObj = {
'Lip Balm - Orange Coconut': ${lipBalmOrangeCoconut(0)},
'Lip Balm - Raspberry Vanilla': ${lipBalmRaspberryVanilla(0)},
'Bath Bomb - Assorted - 50 mg THC': ${bathBombAssorted50MgThc(0)},
'Buddha Buddha - 200 mg THC': ${buddhaBuddha200MgThc(0)},
'Top Lemon Balm Salve': ${topLemonBalmSalve(0)},
'Buddha Bar - 300 mg THC': ${buddhaBar300MgThc(0)},
'BC Skunk - Hybrid': ${bcSkunkHybrid(0)},
'Blue King - Hybrid': ${blueKingHybrid(0)},
'CBD Treat - Hybrid': ${cbdTreatHybrid(0)},
'Dr. Krippling - Indica': ${drKripplingIndica(0)},
"God's Blue Cough - Hybrid": ${godsBlueCoughHybrid(0)},
'Island Sweet Skunk - Sativa': ${islandSweetSkunkSativa(0)},
'Lemon Sour Diesel - Hybrid': ${lemonSourDieselHybrid(0)},
'MI-O - Sativa': ${mioSativa(0)},
'OG Kush - Hybrid': ${ogKushHybrid(0)},
'Strawberry Skunk - Hybrid': ${strawberrySkunkHybrid(0)},
'Bubble Hash ': ${bubbleHash(0)},
'CBD - 2 capsules per package': ${cbd2CapsulesPerPackage(0)},
'CBD - 30 capsules per bottle': ${cbd30CapsulesPerBottle(0)},
'CBD Phoenix Tears ': ${cbdPhoenixTears(0)},
'THC Phoenix Tears ': ${thcPhoenixTears(0)},
'THC grape seed oil (indica) 900 mg / 30 ml':
${thcGrapeSeedOilindica900Mg30Ml(0)},
'THC grape seed oil (sativa) 900 mg / 30 ml':
${thcGrapeSeedOilsativa900Mg30Ml(0)},
'1:1 THC:CBD grape seed oil 200 mg / 30 ml':
${11ThccbdGrapeSeedOil200Mg30Ml(0)},
'CBD grape seed oil 150 mg / 30 ml': ${cbdGrapeSeedOil150Mg30Ml(0)},
'Chocolate Chip Cookie - 15 mg THC': ${chocolateChipCookie15MgThc(0)},
'Ginger Chew Cookie - 30 mg THC': ${gingerChewCookie30MgThc(0)},
'Red Licorice Bites - 125 mg THC': ${redLicoriceBites125MgThc(0)},
'Double Dose Peanut Butter Cup - 200 mg THC':
${doubleDosePeanutButterCup200MgThc(0)},
'Cherry - 125 mg THC (hybrid)': ${cherry125MgThchybrid(0)},
'Rootbeer - 125 mg THC (sativa)': ${rootbeer125MgThcsativa(0)},
'Watermelon - 125 mg THC (hybrid)': ${watermelon125MgThchybrid(0)},
'Cherry - 120 mg (indica)': ${cherry120Mgindica(0)},
'Blue Raspberry - 120 mg (indica)': ${blueRaspberry120Mgindica(0)},
'Peach  - 120 mg (sativa)': ${peach120Mgsativa(0)},
'Strawberry Banana - 120 mg (sativa)': ${strawberryBanana120Mgsativa(0)},
'Lollipops - Assorted Flavors - 150 mg THC':
${lollipopsAssortedFlavors150MgThc(0)},
'Cotton Candy - Original - 180 mg THC': ${cottonCandyOriginal180MgThc(0)},
'Cotton Candy - Tutti Fruitti - 180 mg THC':
${cottonCandyTuttiFruitti180MgThc(0)},
'Cranberry Ice Tea Apothecary - 60 mg THC':
${cranberryIceTeaApothecary60MgThc(0)},
'Lemon Ice Tea Apothecary - 60 mg THC': ${lemonIceTeaApothecary60MgThc(0)},
'Mango Ice Tea Apothecary - 60 mg THC': ${mangoIceTeaApothecary60MgThc(0)},
'Peach Ice Tea Apothecary - 60 mg THC': ${peachIceTeaApothecary60MgThc(0)},
'Coconut Oil - 500 mg THC': ${coconutOil500MgThc(0)},
'Olive Oil - 400 mg THC': ${oliveOil400MgThc(0)},
'House Strain - Hybrid': ${houseStrainHybrid(0)},
};

// Create a "lookup table" for stock nr. and price
var lookup = {};
for (var i = 0, len = rowsArray.length; i < len; i++) {
lookup[rowsArray[i].formName] = rowsArray[i];
}

var amount = 0,
subtotal = 0,
tax = 0,
shipping = 20,
total = 0;

for (var key in auxObj) {
if (auxObj[key] !== 0) {
    amount = auxObj[key] * lookup[key].price;
    orderItems.push({
        'value': auxObj[key],
        'name': key,
        'stock': lookup[key].stock,
        'price': lookup[key].price,
        'amount': amount
    });
    subtotal += amount;
}
}
tax = subtotal * 0.05;
total = subtotal + tax + shipping;

// Return output variables
var result = {
'orderItems' : orderItems,
'subtotal': subtotal,
'tax': tax,
'total': total
};
result;

Line 67 'price' has the error.
I don't know if this amount of code is enough, if you need the full code then please ask.
I don't know why the error is happening (keep in mind I'm not exp. w/JS) and how to fix it to run.

Body:
I think the price index in the lookup object is undefined. Try checking for the index before you access it in the object.

var price, stock;
for (var key in auxObj) {
    if (auxObj[key] !== 0) {

        price = ( typeof lookup[key].price !== 'undefined' ? lookup[key].price : 0 );

        stock = ( typeof lookup[key].stock !== 'undefined' ? lookup[key].stock : 'Not in stock' );

        amount = auxObj[key] * lookup[key].price;
        orderItems.push({
             'value': auxObj[key],
             'name': key,
             'stock': lookup[key].stock,
             'price': lookup[key].price,
             'amount': amount
        });
     }
}


问:
Rename master branch for both local and remote Git repositories
I have the branch master which tracks the remote branch origin/master.

I want to rename them to master-old both locally and on the remote. Is this possible?

For other users who tracked origin/master (and who always updated their local master branch via git pull), what would happen after I renamed the remote branch?

Would their git pull still work or would it throw an error that it couldn't find origin/master anymore?

Then, further on, I want to create a new master branch (both locally and remote). Again, after I did this, what would happen now if the other users do git pull?

I guess all this would result in a lot of trouble. Is there a clean way to get what I want? Or should I just leave master as it is and create a new branch master-new and just work there further on?

答:
This is the simplest and most 'readable' way I know of:

'Move' local branch using -m

```<code>git branch -m my_old_branch_name my_new_branch_name
</code>```

Push the 'moved' branch to the remote, set 'upstream' using -u

```<code>git push origin -u my_new_branch_name
</code>```

Setting 'upstream' essentially 'connects' your local branch to the remote, so that things like fetch, pull and push will work.

Delete the old branch from the remote

```<code>git push origin -D <old_name>
</code>```

Your local branch is already gone, because you 'moved' it in the first step.

ContentLicense: CC BY-SA 4.0

Body:
This is the simplest and most 'readable' way I know of:

'Move' local branch using -m

git branch -m my_old_branch_name my_new_branch_name

Push the 'moved' branch to the remote, set 'upstream' using -u

git push origin -u my_new_branch_name

Setting 'upstream' essentially 'connects' your local branch to the remote, so that things like fetch, pull and push will work.

Delete the old branch from the remote

git push origin -D <old_name>

Your local branch is already gone, because you 'moved' it in the first step.


问:
How do make a reduced size video using AVAssetWriter?
I would make reduced size video, maybe 50 pixel across and 75 pixels for length.  Those are the physical dimension.

How do you set that? in the videosettings?  I think AVVideoWidthKey and AVVideoHeightKey are more for resolution not for physically dimension which what I needed.

```<code>NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                               AVVideoCodecH264, AVVideoCodecKey,
                               [NSNumber numberWithInt: 320], AVVideoWidthKey,
                               [NSNumber numberWithInt:480], AVVideoHeightKey,
                               nil];
AVAssetWriterInput* writerInput = [[AVAssetWriterInput
                                    assetWriterInputWithMediaType:AVMediaTypeVideo
                                    outputSettings:videoSettings] retain
</code>```

答:
You need to set video codec parameters:</p>

```<code>NSDictionary *videoCleanApertureSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                           [NSNumber numberWithInt:320], AVVideoCleanApertureWidthKey,
                                           [NSNumber numberWithInt:480], AVVideoCleanApertureHeightKey,
                                           [NSNumber numberWithInt:10], AVVideoCleanApertureHorizontalOffsetKey,
                                           [NSNumber numberWithInt:10], AVVideoCleanApertureVerticalOffsetKey,
                                            nil];

NSDictionary *videoAspectRatioSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                             [NSNumber numberWithInt:3], AVVideoPixelAspectRatioHorizontalSpacingKey,
                                             [NSNumber numberWithInt:3],AVVideoPixelAspectRatioVerticalSpacingKey,
                                                    nil];

NSDictionary *codecSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                               [NSNumber numberWithInt:960000], AVVideoAverageBitRateKey,
                               [NSNumber numberWithInt:1],AVVideoMaxKeyFrameIntervalKey,
                               videoCleanApertureSettings, AVVideoCleanApertureKey,
                               //videoAspectRatioSettings, AVVideoPixelAspectRatioKey,
                               //AVVideoProfileLevelH264Main30, AVVideoProfileLevelKey,
                               nil];

NSString *targetDevice = [[UIDevice currentDevice] model];

NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                               AVVideoCodecH264, AVVideoCodecKey,
                               codecSettings,AVVideoCompressionPropertiesKey,
                               [NSNumber numberWithInt:320], AVVideoWidthKey,
                               [NSNumber numberWithInt:480], AVVideoHeightKey,
                               nil];
</code>```

Body:
I would make reduced size video, maybe 50 pixel across and 75 pixels for length.  Those are the physical dimension.

How do you set that? in the videosettings?  I think AVVideoWidthKey and AVVideoHeightKey are more for resolution not for physically dimension which what I needed.

NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                               AVVideoCodecH264, AVVideoCodecKey,
                               [NSNumber numberWithInt: 320], AVVideoWidthKey,
                               [NSNumber numberWithInt:480], AVVideoHeightKey,
                               nil];
AVAssetWriterInput* writerInput = [[AVAssetWriterInput
                                    assetWriterInputWithMediaType:AVMediaTypeVideo
                                    outputSettings:videoSettings] retain

Body:
You need to set video codec parameters:

NSDictionary *videoCleanApertureSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                           [NSNumber numberWithInt:320], AVVideoCleanApertureWidthKey,
                                           [NSNumber numberWithInt:480], AVVideoCleanApertureHeightKey,
                                           [NSNumber numberWithInt:10], AVVideoCleanApertureHorizontalOffsetKey,
                                           [NSNumber numberWithInt:10], AVVideoCleanApertureVerticalOffsetKey,
                                            nil];

NSDictionary *videoAspectRatioSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                             [NSNumber numberWithInt:3], AVVideoPixelAspectRatioHorizontalSpacingKey,
                                             [NSNumber numberWithInt:3],AVVideoPixelAspectRatioVerticalSpacingKey,
                                                    nil];

NSDictionary *codecSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                               [NSNumber numberWithInt:960000], AVVideoAverageBitRateKey,
                               [NSNumber numberWithInt:1],AVVideoMaxKeyFrameIntervalKey,
                               videoCleanApertureSettings, AVVideoCleanApertureKey,
                               //videoAspectRatioSettings, AVVideoPixelAspectRatioKey,
                               //AVVideoProfileLevelH264Main30, AVVideoProfileLevelKey,
                               nil];

NSString *targetDevice = [[UIDevice currentDevice] model];

NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                               AVVideoCodecH264, AVVideoCodecKey,
                               codecSettings,AVVideoCompressionPropertiesKey,
                               [NSNumber numberWithInt:320], AVVideoWidthKey,
                               [NSNumber numberWithInt:480], AVVideoHeightKey,
                               nil];


问:
Making SharePoint folder accessible over internet
I have a SharePoint document library on my intranet and I want o make this library accessible to users on internet. I know easier option is to just make the website internet facing but that is not possible for some reasons.
To workaround the thing I was thinking to map this document library to a folder on another server on intranet and make it a virtual directory; this server is internet facing and so the virtual directory can be accessed by the users.
Just wondering have any one got a better option or see any issues with this said approach?

Thank you!

答: You can extend the web application and essentially create an extranet web application that still require permissions.  Then you can grant the external users access to either the site or that document library with unique permissions.  Might be overkill but that could do it.  </p>


问:
PHP users local time
Hey Stackfriends =P
I know about the time() and the date() functuions,
but what I want to achieve is that the user from china gets another time shown than the user from France.
I cannot use JavaScript, because I am also using the local time for some calculations.</p>

答:
There are two good solutions:

Ask the user for his timezone; pre-select a default one either based on the timezone where the majority of your users come from and/or on the local timezone detected via JavaScript

Simply use UTC (GMT) on your website.

Obviously it highly depends on your website which option is appropriate. On a site like stackoverflow option 2 is used and makes the most sense as there are various events which are day-based so days need to change at the same time for all users.

Title: PHP users local time


问:
Extract username from AdminInitiateAuthResult in Amazon Cognito
Given a "refresh token" I am looking to extract the username using "AdminInitiateAuthResult" object.

Here is what my code looks like:

```<code>Map<String,String> authParams = new HashMap<String,String>();
authParams.put("REFRESH_TOKEN", refreshToken);

final AdminInitiateAuthRequest authRequest = new AdminInitiateAuthRequest().withAuthFlow(AuthFlowType.REFRESH_TOKEN).withAuthParameters(authParams).withClientId("XXXX").withUserPoolId("YYY");
final AdminInitiateAuthResult authResponse = getAWSCognitoIdentityProviderClient().adminInitiateAuth(authRequest);
</code>```

答: There is no username returned in the case of the refresh token flow. However, you could find the username by cracking open the tokens you retrieved.</p>

Body:
Given a "refresh token" I am looking to extract the username using "AdminInitiateAuthResult" object.

Here is what my code looks like:

Map<String,String> authParams = new HashMap<String,String>();
authParams.put("REFRESH_TOKEN", refreshToken);

final AdminInitiateAuthRequest authRequest = new AdminInitiateAuthRequest().withAuthFlow(AuthFlowType.REFRESH_TOKEN).withAuthParameters(authParams).withClientId("XXXX").withUserPoolId("YYY");
final AdminInitiateAuthResult authResponse = getAWSCognitoIdentityProviderClient().adminInitiateAuth(authRequest);


问:
How to fix InstantiationException, unable to instantiate Fragment?
This is my first post, so I apologize in advance...

I'm trying to compile a simple Drawer sample/practice app. When I click on the items in the listview, however, it crashes. Logcat says that it's not able to instantiate from android.app.Fragment. I've tried also using the android.support.v4 library -- assuming I implemented it correctly, which is dubious -- with the same results. Frankly I'm not sure what the difference is. I'm totally stumped. Please help!

MainActivity:

```<code>package pac.gazette;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

    private String[] fragmentNames;
    private String[] fragmentAddresses;

    private DrawerLayout drawer;
    private ListView drawerList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fragmentNames = getResources().getStringArray(R.array.fragment_names);
        fragmentAddresses = getResources().getStringArray(
                R.array.fragment_options);
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerList = (ListView) findViewById(R.id.left_drawer);
        drawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list, fragmentNames));
        drawerList.setOnItemClickListener (new CustomClickListener());

    }

    public class CustomClickListener implements OnItemClickListener {

        @SuppressLint("NewApi") @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // drawer close handling
            drawer.closeDrawer(drawerList);
            // title handling (does not wait for drawer close)
            if (position == 0) {
                setTitle(new String("East Asia Gazette"));
            } else {
                setTitle(fragmentNames[position]);
            }
            // new fragment handling
            FragmentTransaction transaction = getFragmentManager()
                    .beginTransaction();
            transaction.replace(R.id.content_frame, Fragment.instantiate(
                    MainActivity.this, fragmentAddresses[position]));
            transaction.commit();
        }
    }

}
</code>```

Xml:

```<code><android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <!-- The main content view -->
    <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    <!-- The navigation drawer -->
    <ListView
            android:id="@+id/left_drawer"
            android:layout_width="200dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="0dp"
            android:background="#940032"/>
</android.support.v4.widget.DrawerLayout>
</code>```

Logcat:

```<code>08-25 12:25:02.579: E/AndroidRuntime(17137): FATAL EXCEPTION: main
08-25 12:25:02.579: E/AndroidRuntime(17137): android.app.Fragment$InstantiationException: Unable to instantiate fragment pac.gazette.fragment_feed.xml: make sure class name exists, is public, and has an empty constructor that is public
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.app.Fragment.instantiate(Fragment.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.app.Fragment.instantiate(Fragment.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at pac.gazette.MainActivity$CustomClickListener.onItemClick(MainActivity.java:56)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.widget.AdapterView.performItemClick(AdapterView.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.widget.AbsListView.performItemClick(AbsListView.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.widget.ListView.performItemClick(ListView.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.widget.AbsListView$PerformClick.run(AbsListView.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.widget.AbsListView$1.run(AbsListView.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.os.Handler.handleCallback(Handler.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.os.Handler.dispatchMessage(Handler.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.os.Looper.loop(Looper.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.app.ActivityThread.main(ActivityThread.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at java.lang.reflect.Method.invokeNative(Native Method)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at java.lang.reflect.Method.invoke(Method.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at dalvik.system.NativeStart.main(Native Method)
08-25 12:25:02.579: E/AndroidRuntime(17137): Caused by: java.lang.ClassNotFoundException: Didn't find class "pac.gazette.fragment_feed.xml" on path: /data/app/pac.gazette-2.apk
08-25 12:25:02.579: E/AndroidRuntime(17137):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at java.lang.ClassLoader.loadClass(ClassLoader.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at java.lang.ClassLoader.loadClass(ClassLoader.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    ... 17 more
</code>```

Manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pac.gazette"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="pac.gazette.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答:
I had similar problem, I fixed it with this

```<code>MyFragment.instantiate(
                    MainActivity.this, "whole.path.to.MyFragment");
</code>```

@param fname The class name of the fragment to instantiate.

Body:
This is my first post, so I apologize in advance...

I'm trying to compile a simple Drawer sample/practice app. When I click on the items in the listview, however, it crashes. Logcat says that it's not able to instantiate from android.app.Fragment. I've tried also using the android.support.v4 library -- assuming I implemented it correctly, which is dubious -- with the same results. Frankly I'm not sure what the difference is. I'm totally stumped. Please help!

MainActivity:

package pac.gazette;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

    private String[] fragmentNames;
    private String[] fragmentAddresses;

    private DrawerLayout drawer;
    private ListView drawerList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fragmentNames = getResources().getStringArray(R.array.fragment_names);
        fragmentAddresses = getResources().getStringArray(
                R.array.fragment_options);
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerList = (ListView) findViewById(R.id.left_drawer);
        drawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list, fragmentNames));
        drawerList.setOnItemClickListener (new CustomClickListener());

    }

    public class CustomClickListener implements OnItemClickListener {

        @SuppressLint("NewApi") @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // drawer close handling
            drawer.closeDrawer(drawerList);
            // title handling (does not wait for drawer close)
            if (position == 0) {
                setTitle(new String("East Asia Gazette"));
            } else {
                setTitle(fragmentNames[position]);
            }
            // new fragment handling
            FragmentTransaction transaction = getFragmentManager()
                    .beginTransaction();
            transaction.replace(R.id.content_frame, Fragment.instantiate(
                    MainActivity.this, fragmentAddresses[position]));
            transaction.commit();
        }
    }

}

Xml:

<android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    <ListView
            android:id="@+id/left_drawer"
            android:layout_width="200dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="0dp"
            android:background="#940032"/>
</android.support.v4.widget.DrawerLayout>

Logcat:

08-25 12:25:02.579: E/AndroidRuntime(17137): FATAL EXCEPTION: main
08-25 12:25:02.579: E/AndroidRuntime(17137): android.app.Fragment$InstantiationException: Unable to instantiate fragment pac.gazette.fragment_feed.xml: make sure class name exists, is public, and has an empty constructor that is public
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.app.Fragment.instantiate(Fragment.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.app.Fragment.instantiate(Fragment.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at pac.gazette.MainActivity$CustomClickListener.onItemClick(MainActivity.java:56)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.widget.AdapterView.performItemClick(AdapterView.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.widget.AbsListView.performItemClick(AbsListView.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.widget.ListView.performItemClick(ListView.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.widget.AbsListView$PerformClick.run(AbsListView.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.widget.AbsListView$1.run(AbsListView.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.os.Handler.handleCallback(Handler.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.os.Handler.dispatchMessage(Handler.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.os.Looper.loop(Looper.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at android.app.ActivityThread.main(ActivityThread.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at java.lang.reflect.Method.invokeNative(Native Method)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at java.lang.reflect.Method.invoke(Method.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at dalvik.system.NativeStart.main(Native Method)
08-25 12:25:02.579: E/AndroidRuntime(17137): Caused by: java.lang.ClassNotFoundException: Didn't find class "pac.gazette.fragment_feed.xml" on path: /data/app/pac.gazette-2.apk
08-25 12:25:02.579: E/AndroidRuntime(17137):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at java.lang.ClassLoader.loadClass(ClassLoader.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    at java.lang.ClassLoader.loadClass(ClassLoader.java)
08-25 12:25:02.579: E/AndroidRuntime(17137):    ... 17 more

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pac.gazette"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="pac.gazette.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Body:
I had similar problem, I fixed it with this

MyFragment.instantiate(
                    MainActivity.this, "whole.path.to.MyFragment");

@param fname The class name of the fragment to instantiate.


问:
Concatenating a Calculated Percentage in Excel
I have a spreadsheet in excel where I am tracking hires, and then breaking down the total counts in a number of ways.  One is internal vs. external (columns) and there is a different row for each recruiter, and these are subtotaled by recruiting unit.  My bottom row should contain not only the total count, but the percentage.  My total row should appear as follows:

I have calculated both the sum and the percentage (in cells that are hidden), however when I concatenate these fields the percentage shows simply as the calculated number despite the fact that the cell which the percentage is calculated in being formatted to show a percentage.

I have tried referencing the cell and the % symbol, but the number always shows as the decimal with a % sign, for example:

Use: =CELL&"%"

Get: 0.748148148148148%

Any help would be greatly appreciated as this is the only calculation that requires manual intervention.

答:
If I understand the question correctly, this should solve your problem:

Formula in cell B17 is:

```<code>=SUM(B2:B15) & "," & TEXT(SUM(B2:B15)/ SUM(B2:B15,C2:C15)*100,"00") &"%"
</code>```

Formula in cell C17 is:

```<code>=SUM(C2:C15) & "," & TEXT(SUM(C2:C15)/ SUM(C2:C15,B2:B15)*100,"00") &"%"
</code>```

Let me know if you need further clarification.

Thanks!

Body:
If I understand the question correctly, this should solve your problem:

Formula in cell B17 is:

=SUM(B2:B15) & "," & TEXT(SUM(B2:B15)/ SUM(B2:B15,C2:C15)*100,"00") &"%"

Formula in cell C17 is:

=SUM(C2:C15) & "," & TEXT(SUM(C2:C15)/ SUM(C2:C15,B2:B15)*100,"00") &"%"

Let me know if you need further clarification.

Thanks!


问:
Ubuntu and Django, no module named 'django'
I have a problem with Django on Ubuntu. When I type python in terminal, terminal returns

Python 3.4.1 (default, Jun  2 2015, 15:13:43) [GCC 4.8.2] on linux

so it's allright. When I type admin-django.py version terminal returns 1.8.2

so it's still allright. But when I go with

python

import django

terminal returns:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'django'

I'm fighting with it whole day, I'm quite new to linux. Do you know any solution?

答:
As a more general case I recomend you to start working with virtual environments. It is a very easy tool to manage diferent projects with their respective dependencies.

After opening the terminal. Type:

```<code>$virtualenv 'name of your virtual environment'
$cd 'name of your virtual environment'
$source bin/activate
</code>```

Afterwards you could use pip install with no trouble.

I recommend you the following blogpost:

http://docs.python-guide.org/en/latest/dev/virtualenvs/

Body:
As a more general case I recomend you to start working with virtual environments. It is a very easy tool to manage diferent projects with their respective dependencies.

After opening the terminal. Type:

$virtualenv 'name of your virtual environment'
$cd 'name of your virtual environment'
$source bin/activate

Afterwards you could use pip install with no trouble.

I recommend you the following blogpost:

http://docs.python-guide.org/en/latest/dev/virtualenvs/


问:
Complex query combining
First of all, thank you for reading my problem. I am very thankful for the people in the community helping others learn more about coding. As this SQL and PHP is part of my hobby, I am limited by Google and fora where I can find answers to my questions. Unfortunately, I can't find a good answer for a problem encountered.

What am I trying to do?

I run a website where you can note your kilometers and liters you filled your car and see your statistics. I want to do a big search in MySQL with a query. I know how to get the results in multiple queries (3 to be exact), but I need it to be in one single query.

What does my table look look like?

For an example I am using this table to make the problem more visual, it's named 'fillings' for now.

```<code>+---------+---------+------------+--------+--------+------------+
| tank_id | user_id | kilometers | liters | car_id | date       |
+---------+---------+------------+--------+--------+------------+
| 1       | 2       | 450        | 20     | 2      | 2017-11-01 |
+---------+---------+------------+--------+--------+------------+
| 2       | 1       | 500        | 30     | 1      | 2017-12-15 |
+---------+---------+------------+--------+--------+------------+
| 3       | 2       | 490        | 25     | 2      | 2017-11-05 |
+---------+---------+------------+--------+--------+------------+
| 4       | 3       | 260        | 19     | 3      | 2017-11-07 |
+---------+---------+------------+--------+--------+------------+
| 5       | 3       | 610        | 30     | 3      | 2017-12-03 |
+---------+---------+------------+--------+--------+------------+
| 6       | 3       | 100        | 4      | 3      | 2017-12-07 |
+---------+---------+------------+--------+--------+------------+
</code>```

This is a basic idea of my main table where all the fill-ups are being registrated. In reality someone can have multiple cars, but for now let's asume that a user only has one car.

What are the SQL queries?

The query that I want to make should have this result:

```<code>+---------+----------------------+---------------------+
| user_id | consumption november | consumption overall |
+---------+----------------------+---------------------+
| 2       | 20,9                 | 20,9                |
+---------+----------------------+---------------------+
| 1       |                      | 16,7                |
+---------+----------------------+---------------------+
| 3       | 13,7                 | 18,3                |
+---------+----------------------+---------------------+
</code>```

As you can see, the fillings of november are taking and a consumption is being calculated. Also, an overall consumption is being calculated of all fillings from a certain type of user. I know how to make this result, devided in two queries. That's:

```<code>SELECT user_id, SUM(kilometers) / SUM(liters) as consumption overall
FROM fillings
GROUP BY user_id
</code>```

And also the query:

```<code>SELECT user_id, SUM(kilometers) / SUM(liters) as consumption november
FROM fillings
WHERE 'date'
BETWEEN '2017-11-01' AND '2017-11-31'
GROUP BY user_id
</code>```

So right now I want to combine the queries into one, so that I can get the result that I want. Note that in the example, someone can have a null consumption in a month, because hé or she did not fill up their car in that month.

I've looked into the options of UNION and JOIN but I can't seem to find a way to make this working.

I hope everything is clear, and if not, don't hesitate to ask and I will explain in further detail.

Thanks in advance.

答:
Since it is possible that the records are not in range within the month, a LEFT JOIN is recommended for the date specific query:

```<code> SELECT
 t1.user_id, t2.consumption_november, t1.consumption_overall
 FROM (
   SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_overall
   FROM fillings
   GROUP BY user_id
 ) t1
 LEFT JOIN
 (
   SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_november
   FROM fillings
   WHERE `date` BETWEEN '2017-11-01' AND '2017-11-31'
   GROUP BY user_id
 ) t2
 ON t1.user_id = t2.user_id;
</code>```

http://sqlfiddle.com/#!9/3fdce84/16

Title: Complex query combining

Body:
First of all, thank you for reading my problem. I am very thankful for the people in the community helping others learn more about coding. As this SQL and PHP is part of my hobby, I am limited by Google and fora where I can find answers to my questions. Unfortunately, I can't find a good answer for a problem encountered.

What am I trying to do?

I run a website where you can note your kilometers and liters you filled your car and see your statistics. I want to do a big search in MySQL with a query. I know how to get the results in multiple queries (3 to be exact), but I need it to be in one single query.

What does my table look look like?

For an example I am using this table to make the problem more visual, it's named 'fillings' for now.

+---------+---------+------------+--------+--------+------------+
| tank_id | user_id | kilometers | liters | car_id | date       |
+---------+---------+------------+--------+--------+------------+
| 1       | 2       | 450        | 20     | 2      | 2017-11-01 |
+---------+---------+------------+--------+--------+------------+
| 2       | 1       | 500        | 30     | 1      | 2017-12-15 |
+---------+---------+------------+--------+--------+------------+
| 3       | 2       | 490        | 25     | 2      | 2017-11-05 |
+---------+---------+------------+--------+--------+------------+
| 4       | 3       | 260        | 19     | 3      | 2017-11-07 |
+---------+---------+------------+--------+--------+------------+
| 5       | 3       | 610        | 30     | 3      | 2017-12-03 |
+---------+---------+------------+--------+--------+------------+
| 6       | 3       | 100        | 4      | 3      | 2017-12-07 |
+---------+---------+------------+--------+--------+------------+

This is a basic idea of my main table where all the fill-ups are being registrated. In reality someone can have multiple cars, but for now let's asume that a user only has one car.

What are the SQL queries?

The query that I want to make should have this result:

+---------+----------------------+---------------------+
| user_id | consumption november | consumption overall |
+---------+----------------------+---------------------+
| 2       | 20,9                 | 20,9                |
+---------+----------------------+---------------------+
| 1       |                      | 16,7                |
+---------+----------------------+---------------------+
| 3       | 13,7                 | 18,3                |
+---------+----------------------+---------------------+

As you can see, the fillings of november are taking and a consumption is being calculated. Also, an overall consumption is being calculated of all fillings from a certain type of user. I know how to make this result, devided in two queries. That's:

SELECT user_id, SUM(kilometers) / SUM(liters) as consumption overall
FROM fillings
GROUP BY user_id

And also the query:

SELECT user_id, SUM(kilometers) / SUM(liters) as consumption november
FROM fillings
WHERE 'date'
BETWEEN '2017-11-01' AND '2017-11-31'
GROUP BY user_id

So right now I want to combine the queries into one, so that I can get the result that I want. Note that in the example, someone can have a null consumption in a month, because hé or she did not fill up their car in that month.

I've looked into the options of UNION and JOIN but I can't seem to find a way to make this working.

I hope everything is clear, and if not, don't hesitate to ask and I will explain in further detail.

Thanks in advance.

Body:
Since it is possible that the records are not in range within the month, a LEFT JOIN is recommended for the date specific query:

 SELECT
 t1.user_id, t2.consumption_november, t1.consumption_overall
 FROM (
   SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_overall
   FROM fillings
   GROUP BY user_id
 ) t1
 LEFT JOIN
 (
   SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_november
   FROM fillings
   WHERE `date` BETWEEN '2017-11-01' AND '2017-11-31'
   GROUP BY user_id
 ) t2
 ON t1.user_id = t2.user_id;

http://sqlfiddle.com/#!9/3fdce84/16


问:
oozie, pass coordinator scheduler time to java action
I need to pass scheduler time to oozie java action.

For example, I set 1 mınute scheduler time. The current time is 15:45 but any delay or error occurs so the current executed java action time is 15:40 (5 mins delay) and I need to log the execution time in my java action so I need to pass 15.40 value to my java code (jar) as an argument.

How can I achive this?

Thanks

答:
You can use the oozie built in EL function "String timestamp()" to get the time stamp and pass to the java code as an argument.
e.g </p>

```<code> <action name='actionJava'>
        <java>
            <job-tracker>${jobTracker}</job-tracker>
            <name-node>${nameNode}</name-node>
            <name>JavaAction</name>
            <main-class>com.oozie.JTestMain</main-class>
            <arg>${timestamp()}</arg>
        </java>
       <ok to="end" />
       <error to="killJob" />
 </action>
</code>```

Body:
You can use the oozie built in EL function "String timestamp()" to get the time stamp and pass to the java code as an argument.
e.g

 <action name='actionJava'>
        <java>
            <job-tracker>${jobTracker}</job-tracker>
            <name-node>${nameNode}</name-node>
            <name>JavaAction</name>
            <main-class>com.oozie.JTestMain</main-class>
            <arg>${timestamp()}</arg>
        </java>
       <ok to="end" />
       <error to="killJob" />
 </action>


问:
Nowadays, is there still any sense in adding prefixes like "-moz" and "-webkit" in front of the properties of some css elements?
For exemple in these following statements:</p>

```<code>animation: closing 3s steps(90) forwards;
-webkit-animation: closing 3s steps(90) forwards;
-moz-animation: closing 3s steps(90) forwards;

background: -webkit-linear-gradient(top, rgba(255,0,0,0.5), rgba(255,255,0,0.5));
background: -o-linear-gradient(top, rgba(255,0,0,0.5), rgba(255,255,0,0.5));
background: -moz-linear-gradient(top, rgba(255,0,0,0.5), rgba(255,255,0,0.5));
background: linear-gradient(to top, rgba(255,0,0,0.65), rgba(255,255,0,0.65));
</code>```

答:
Nowadays, there is absolutely no point in adding them manually. You should write clean (S)CSS and run it through a post-css task in your favorite JavaScript task runner.

Most people use autoprefixer (it's really good), which and adds all the necessary prefixes to your code based on your settings. If running a post-css task seems too complicated (it really isn't!), autoprefixer is also available online.

For maximum compatibility, use > 0% in the filter box (below).

If you're asking if they are still required by browsers, well, yes: there is a considerable amount of proprietary attributes only recognized by one browser.

Body:
For exemple in these following statements:

animation: closing 3s steps(90) forwards;
-webkit-animation: closing 3s steps(90) forwards;
-moz-animation: closing 3s steps(90) forwards;

background: -webkit-linear-gradient(top, rgba(255,0,0,0.5), rgba(255,255,0,0.5));
background: -o-linear-gradient(top, rgba(255,0,0,0.5), rgba(255,255,0,0.5));
background: -moz-linear-gradient(top, rgba(255,0,0,0.5), rgba(255,255,0,0.5));
background: linear-gradient(to top, rgba(255,0,0,0.65), rgba(255,255,0,0.65));


问:
Game controller layout detection - swift
How do I detect the game controllers layout from apple tv? I want to change the controls if the layout is different for the controller which will make the game easier to play. .For example, the apple recommended Nimbus Controller is shaped like a play station controller with two joysticks at the bottom, but I have seem other types of controllers which have a xbox like design with a d-pad and a joystick at the bottom instead, if I can detect which is which, to change to controls for different controllers, it will make the game easier to play

Any help would be appreciated

答: I ended up just simply asking the user for their game controller layout. The answer from Ercell0 is a nice way to connect and use the game controllers, but doesn't really answer my question.</p>


问:
How can I check if my input file is updated?
I am reading a ~2mb CSV file of about 40000 lines and each line defines an object in a list and I need to reflect any changes on the input file to my list and vice-versa... Say if I modify a line on the input file I need to update my object on the list and a modification on the object will be reflected to file immediately.
I know it can be done in an infinite while loop but its quite waste of resources and sounds ridiculous. Is there a function or an update flag which I can check or some other approach that I read the file only when updated?
I am coding in C++ by the way :)

EDITED

I played a while with the code @Jake proposed and come out with a working solution. Here is a better question for you then... the code I wrote seems working instantly sometimes but sometimes it does not updates the modifications I made to file as I save the file and only after saving file 3 or 5 times more I see the update?  What could be the reason for that? Can I improve this solution any further?

```<code>#include <iostream>
#include <fstream>
#include <sys/stat.h>

#define INFILE "test.txt"

using namespace std;

__time_t getFileModifyTime(char *filePath)
{
    struct stat attrib;
    stat(filePath, &attrib);
    __time_t date = attrib.st_mtime ;
    return date;
}

int main(){

    ifstream infile;
    infile.open (INFILE);
    string currentLine;

    __time_t lastUpdateTime = 0;

    while(true)     // start an infinite loop
    {
        if(lastUpdateTime != getFileModifyTime(INFILE)) {

            cout << "last update time  : " << lastUpdateTime << endl;
            cout << "modification time : " << getFileModifyTime(INFILE) << endl;

            infile.close();
            infile.open (INFILE);

            while (getline(infile, currentLine)) {
                cout << currentLine << endl;
            }
        }
        lastUpdateTime = getFileModifyTime(INFILE);
    }

    return  0;
}
</code>```

答:
With Linux you can use the following code to tell if a file was updated:

```<code>auto getFileCreationTime(char *filePath)
{
    struct stat attrib;
    stat(filePath, &attrib);
    char date[10];
    strftime(date, 10, "%d-%m-%y", gmtime(&(attrib.st_ctime)));
    return date;
}
</code>```

So using threads and a while statement you could do something like this

```<code>auto mod_time_first = getLastTime();
while(true)
{
    if(mod_time_first == getLastTime()) {} // Do something now
    mod_time_first = getLastTime();
}
</code>```

Body:
I am reading a ~2mb CSV file of about 40000 lines and each line defines an object in a list and I need to reflect any changes on the input file to my list and vice-versa... Say if I modify a line on the input file I need to update my object on the list and a modification on the object will be reflected to file immediately.
I know it can be done in an infinite while loop but its quite waste of resources and sounds ridiculous. Is there a function or an update flag which I can check or some other approach that I read the file only when updated?
I am coding in C++ by the way :)

EDITED

I played a while with the code @Jake proposed and come out with a working solution. Here is a better question for you then... the code I wrote seems working instantly sometimes but sometimes it does not updates the modifications I made to file as I save the file and only after saving file 3 or 5 times more I see the update?  What could be the reason for that? Can I improve this solution any further?

#include <iostream>
#include <fstream>
#include <sys/stat.h>

#define INFILE "test.txt"

using namespace std;

__time_t getFileModifyTime(char *filePath)
{
    struct stat attrib;
    stat(filePath, &attrib);
    __time_t date = attrib.st_mtime ;
    return date;
}

int main(){

    ifstream infile;
    infile.open (INFILE);
    string currentLine;

    __time_t lastUpdateTime = 0;

    while(true)     // start an infinite loop
    {
        if(lastUpdateTime != getFileModifyTime(INFILE)) {

            cout << "last update time  : " << lastUpdateTime << endl;
            cout << "modification time : " << getFileModifyTime(INFILE) << endl;

            infile.close();
            infile.open (INFILE);

            while (getline(infile, currentLine)) {
                cout << currentLine << endl;
            }
        }
        lastUpdateTime = getFileModifyTime(INFILE);
    }

    return  0;
}

Body:
With Linux you can use the following code to tell if a file was updated:

auto getFileCreationTime(char *filePath)
{
    struct stat attrib;
    stat(filePath, &attrib);
    char date[10];
    strftime(date, 10, "%d-%m-%y", gmtime(&(attrib.st_ctime)));
    return date;
}

So using threads and a while statement you could do something like this

auto mod_time_first = getLastTime();
while(true)
{
    if(mod_time_first == getLastTime()) {} // Do something now
    mod_time_first = getLastTime();
}


问:
Get all SharePoint News from Microsoft Graph
Is there a way to get news from SharePoint online using Microsoft Graph?

On this page from Microsoft they announce that:

If you use the SharePoint app on iOS, you get the first look at the
  mobile experience of team news. When you tap the News tab, you will
  see a list of aggregated news using the intelligence of the Microsoft
  Graph from the sites you work in, the sites you follow and the sites
  your colleagues work in. SharePoint mobile on iOS gives you one place
  to catch up on the news from across your intranet. That’s your news in
  your pocket!

But when looking in Microsoft Graph documentation for SharePoint, it doesn't seem to be any APIs for fetching aggregated news and other items from SharePoint? Am I missing something or is the the office blog just marketing talk?

答: The Microsoft Graph is still a work in progress.  They're probably using the search api to surface news on mobile devices.</p>


问:
Create an array of hashes describing files obtained from a given directory
I need to

Read a list of the files from in a specified directory

Create an array of hashes describing those files

My program fetches the path to a directory from the command line, opens it and reads its contents. Directories and "dot" files are skipped, and the absolute path to every other entry is printed.

```<code>use strict;
use warnings;

use Data::Dumper qw(Dumper);
use File::Spec;
use Digest::SHA qw(sha256_hex);

my $dir = $ARGV[0];

opendir DIR, $dir or die "cannot open dir $dir: $!";

while ( my $file = readdir DIR ) {
    next unless ( -f "${ \File::Spec->catfile($dir, $file) }" );
    next if ( "$file" =~ m/^\./) ;
    print "${ \File::Spec->rel2abs($file) }\n";
}

closedir DIR;
</code>```

Here I take a single file and create a hash with the path, size, and sha256sum.

```<code>my $file = "file1.txt";

my @fileref = (
    {
        path    =>  "Full path: " . File::Spec->rel2abs($file),
        size    =>  "Size (bytes): " . -s $file,
        id      =>  "SHA256SUM: " . sha256_hex($file),
    },
);

print "\n";
print "$fileref[0]{path}\n";
print "$fileref[0]{size}\n";
print "$fileref[0]{id}\n";
</code>```

All of this works, but I cannot figure out how to iterate over each file and add it to the array.

This is what I planned

```<code>for each file
    push file into array
    add the path, size, and id key:value pairs to file
repeat
</code>```

How can I generate the necessary array?

答:
You have all the code, you are creating an array with the first element. Your way to dereference that hints at an easy way to add others:</p>

```<code>my $i = 0;
while(my $file = readdir DIR) {
        next unless(-f "${\File::Spec->catfile($dir, $file)}");
        next if("$file" =~ m/^\./);
        print "${\File::Spec->rel2abs($file)}\n";
        $fileref[$i]{path} = File::Spec->rel2abs($file);
        $fileref[$i]{size} = -s $fileref[0]{path};
        $fileref[$i]{id} = sha256_hex(fileref[0]{path});
        $i++;
}
</code>```

Body:
I need to

Read a list of the files from in a specified directory

Create an array of hashes describing those files

My program fetches the path to a directory from the command line, opens it and reads its contents. Directories and "dot" files are skipped, and the absolute path to every other entry is printed.

use strict;
use warnings;

use Data::Dumper qw(Dumper);
use File::Spec;
use Digest::SHA qw(sha256_hex);

my $dir = $ARGV[0];

opendir DIR, $dir or die "cannot open dir $dir: $!";

while ( my $file = readdir DIR ) {
    next unless ( -f "${ \File::Spec->catfile($dir, $file) }" );
    next if ( "$file" =~ m/^\./) ;
    print "${ \File::Spec->rel2abs($file) }\n";
}

closedir DIR;

Here I take a single file and create a hash with the path, size, and sha256sum.

my $file = "file1.txt";

my @fileref = (
    {
        path    =>  "Full path: " . File::Spec->rel2abs($file),
        size    =>  "Size (bytes): " . -s $file,
        id      =>  "SHA256SUM: " . sha256_hex($file),
    },
);

print "\n";
print "$fileref[0]{path}\n";
print "$fileref[0]{size}\n";
print "$fileref[0]{id}\n";

All of this works, but I cannot figure out how to iterate over each file and add it to the array.

This is what I planned

for each file
    push file into array
    add the path, size, and id key:value pairs to file
repeat

How can I generate the necessary array?

Body:
You have all the code, you are creating an array with the first element. Your way to dereference that hints at an easy way to add others:

my $i = 0;
while(my $file = readdir DIR) {
        next unless(-f "${\File::Spec->catfile($dir, $file)}");
        next if("$file" =~ m/^\./);
        print "${\File::Spec->rel2abs($file)}\n";
        $fileref[$i]{path} = File::Spec->rel2abs($file);
        $fileref[$i]{size} = -s $fileref[0]{path};
        $fileref[$i]{id} = sha256_hex(fileref[0]{path});
        $i++;
}


问:
How to change aspx html heading from code behind?
This is my heading that i want to change from my c# code

```<code> <h3>Please Enter a number between 1 &
                <asp:Label ID="lbl_max" runat="server"></asp:Label>
            </h3>
</code>```

I want to replace it with a string

```<code>string message = "This is new heading...";
</code>```

i was thinking about something like this

```<code>lbl_max.value = message;
</code>```

But it's not working... I am absolutely new to asp.net, so forgive me if it's a stupid question...

答:
You can do it like this:</p>

```<code>this.lbl_max.Text = "This is new heading...";
</code>```

Body:
This is my heading that i want to change from my c# code

Please Enter a number between 1 &
                <asp:Label ID="lbl_max" runat="server"></asp:Label>

I want to replace it with a string

string message = "This is new heading...";

i was thinking about something like this

lbl_max.value = message;

But it's not working... I am absolutely new to asp.net, so forgive me if it's a stupid question...

Body:
You can do it like this:

this.lbl_max.Text = "This is new heading...";