问:
function parameter to xmm0
I'm trying to move ALIGNED float array into xmm register

```<code>#define ALIGNED16 __declspec(align(16))

ALIGNED16 float vector1[4] = { 1.0f, 2.0f, 3.0f, 4.0f };
ALIGNED16 float vector2[4] = { 1.0f, 2.0f, 3.0f, 4.0f };
ALIGNED16 float result[4];

_add_vector(vector1, vector2, result);
....

_add_vector(float *__restrict v1, float * __restrict v2, float * __restrict rvec)
{
  __asm
  {
    movaps xmm0, xmmword ptr [v1]
    movaps xmm1, xmmword ptr [v2]

    addps xmm0, xmm1

    movaps xmmword ptr [rvec], xmm0
  };
}
</code>```

so when compiler trying to copy from v1 to xmm0 I have "read access violation" v1 was0xFFFFFFFF

But if I'm doing

```<code>__asm
  {
    movaps xmm0, xmmword ptr [v1]
  };
</code>```

AFTER vector1 declaration then it works. why?

答:
The issue is that v1, v2, and vrec are pointers to an array of floats. You need to dereference each of those pointers to get the actual arrays. Something like this may work:

```<code>void _add_vector(float *__restrict v1, float * __restrict v2, float * __restrict rvec);

void _add_vector(float *__restrict v1, float * __restrict v2, float * __restrict rvec)
{
    __asm
    {
        mov ecx, [v1]
        mov edx, [v2]
        mov eax, [rvec]

        movaps xmm0, xmmword ptr [ecx]
        movaps xmm1, xmmword ptr [edx]

        addps xmm0, xmm1

        movaps xmmword ptr [eax], xmm0
    };
}
</code>```

In this case I use the caller saved registers of EAX, ECX, and EDX to do dereference the variables.

Title: function parameter to xmm0

Body:
I'm trying to move ALIGNED float array into xmm register

#define ALIGNED16 __declspec(align(16))

ALIGNED16 float vector1[4] = { 1.0f, 2.0f, 3.0f, 4.0f };
ALIGNED16 float vector2[4] = { 1.0f, 2.0f, 3.0f, 4.0f };
ALIGNED16 float result[4];

_add_vector(vector1, vector2, result);
....

_add_vector(float *__restrict v1, float * __restrict v2, float * __restrict rvec)
{
  __asm
  {
    movaps xmm0, xmmword ptr [v1]
    movaps xmm1, xmmword ptr [v2]

    addps xmm0, xmm1

    movaps xmmword ptr [rvec], xmm0
  };
}

so when compiler trying to copy from v1 to xmm0 I have "read access violation" v1 was0xFFFFFFFF

But if I'm doing

__asm
  {
    movaps xmm0, xmmword ptr [v1]
  };

AFTER vector1 declaration then it works. why?

Body:
The issue is that v1, v2, and vrec are pointers to an array of floats. You need to dereference each of those pointers to get the actual arrays. Something like this may work:

void _add_vector(float *__restrict v1, float * __restrict v2, float * __restrict rvec);

void _add_vector(float *__restrict v1, float * __restrict v2, float * __restrict rvec)
{
    __asm
    {
        mov ecx, [v1]
        mov edx, [v2]
        mov eax, [rvec]

        movaps xmm0, xmmword ptr [ecx]
        movaps xmm1, xmmword ptr [edx]

        addps xmm0, xmm1

        movaps xmmword ptr [eax], xmm0
    };
}

In this case I use the caller saved registers of EAX, ECX, and EDX to do dereference the variables.


来源: stackexchange

问:
List Comprehension with Instances
I am trying out list comprehension and I am stuck with the below problem.

```<code>class Programmer():
    def __init__(self, name, years_at_umich=1, programs_written=0):
        self.name = name
        self.seniority = years_at_umich
        self.bonus_points = random.randrange(1000)
        self.programs_written = programs_written

    def shout(self, phrase_to_shout):
        print phrase_to_shout  # print is for ppl!

    def __str__(self):
        return "My name is {}, and I've been at UMich for about {} years.".format(self.name,self.seniority)

    def year_at_umich(self):
        return self.seniority

prog_tups = zip(names, seniority,programs_written)
print prog_tups
</code>```

prints output

```<code>[('Albert', 1, 10), ('Bisi', 5, 500), ('Cai', 2, 20), ('Dinesh', 4, 131), ('Euijin', 1, 46)]
</code>```

I am trying to use list Comprehension to create a list of Programmer instances out of the prog_tups list from above and save that list in the variable programmers.

My current code is below, I am not getting a traceback, but nothing happens:

```<code>programmers = [item for item in prog_tups]
</code>```

答:
In case if you don't have a custom Programmer class yet consider using collections.namedtuple subclass:

```<code>import collections

Programmer = collections.namedtuple('Programmer', 'name seniority programs_written')
prog_tups = [('Albert', 1, 10), ('Bisi', 5, 500), ('Cai', 2, 20), ('Dinesh', 4, 131), ('Euijin', 1, 46)]
programmers = [Programmer(n, s, p) for n,s,p in prog_tups]

# the first programmer
print programmers[0]
</code>```

The output:

```<code>Programmer(name='Albert', seniority=1, programs_written=10)
</code>```

To deal with your existing custom class, use the following approach:

```<code>prog_tups = [('Albert', 1, 10), ('Bisi', 5, 500), ('Cai', 2, 20), ('Dinesh', 4, 131), ('Euijin', 1, 46)]
programmers = [Programmer(*t) for t in prog_tups]

# the first programmer
print programmers[0]
</code>```

The output:

```<code>My name is Albert, and I've been at UMich for about 1 years.
</code>```

ContentLicense: CC BY-SA 3.0

Title: List Comprehension with Instances

Body:
I am trying out list comprehension and I am stuck with the below problem.

class Programmer():
    def __init__(self, name, years_at_umich=1, programs_written=0):
        self.name = name
        self.seniority = years_at_umich
        self.bonus_points = random.randrange(1000)
        self.programs_written = programs_written

    def shout(self, phrase_to_shout):
        print phrase_to_shout  # print is for ppl!

    def __str__(self):
        return "My name is {}, and I've been at UMich for about {} years.".format(self.name,self.seniority)

    def year_at_umich(self):
        return self.seniority

prog_tups = zip(names, seniority,programs_written)
print prog_tups

prints output

[('Albert', 1, 10), ('Bisi', 5, 500), ('Cai', 2, 20), ('Dinesh', 4, 131), ('Euijin', 1, 46)]

I am trying to use list Comprehension to create a list of Programmer instances out of the prog_tups list from above and save that list in the variable programmers.

My current code is below, I am not getting a traceback, but nothing happens:

programmers = [item for item in prog_tups]

Body:
In case if you don't have a custom Programmer class yet consider using collections.namedtuple subclass:

import collections

Programmer = collections.namedtuple('Programmer', 'name seniority programs_written')
prog_tups = [('Albert', 1, 10), ('Bisi', 5, 500), ('Cai', 2, 20), ('Dinesh', 4, 131), ('Euijin', 1, 46)]
programmers = [Programmer(n, s, p) for n,s,p in prog_tups]

# the first programmer
print programmers[0]

The output:

Programmer(name='Albert', seniority=1, programs_written=10)

To deal with your existing custom class, use the following approach:

prog_tups = [('Albert', 1, 10), ('Bisi', 5, 500), ('Cai', 2, 20), ('Dinesh', 4, 131), ('Euijin', 1, 46)]
programmers = [Programmer(*t) for t in prog_tups]

# the first programmer
print programmers[0]

The output:

My name is Albert, and I've been at UMich for about 1 years.


问:
Unity - How to make the accelerometer of object move more smoothly in smartphone?
I want to make my character to move smoothly when I tilt my phone. How I can make it to move smoothly and the velocity and the speed increases as the slope of the phone?</p>

```<code>void AccelerometerMove(){

float x = Input.acceleration.x;
Debug.Log("X = " + x);

if (x < -0.1f)
{
    MoveLeft();
}
else if (x > 0.1f)
{
    MoveRight();
}
else
{
    SetVelocityZero();
}
}
public void SetVelocityZero()
{
     rb.velocity = Vector2.zero;
}

public void MoveLeft()
{
rb.velocity = new Vector2(-speed, 0);
//transform.Translate(Vector2.right * speed * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 180);
}

public void MoveRight()
{
rb.velocity = new Vector2(speed, 0);
//transform.Translate(Vector2.right * speed * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 0);
}
</code>```

答:
You can directly use the input of the accelerometer to set the speed of your object :

```<code>void AccelerometerMove()
{
    float x = Input.acceleration.x;
    Debug.Log("X = " + x);

    if (x < -0.1f)
    {
        MoveLeft(x);
    }
    else if (x > 0.1f)
    {
        MoveRight(x);
    }
    else
    {
        SetVelocityZero();
    }
}
public void SetVelocityZero()
{
     rb.velocity = Vector2.zero;
}

public void MoveLeft( float s )
{
    rb.velocity = new Vector2(s, 0);
    transform.eulerAngles = new Vector2(0, 180);
}

public void MoveRight( float s )
{
    rb.velocity = new Vector2(s, 0);
    transform.eulerAngles = new Vector2(0, 0);
}
</code>```

And / or use the Mathf.Lerp function to compute the speed :

```<code>void AccelerometerMove()
{
    float x = Input.acceleration.x;
    Debug.Log("X = " + x);

    if (x < -0.1f)
    {
        MoveLeft();
    }
    else if (x > 0.1f)
    {
        MoveRight();
    }
    else
    {
        SetVelocityZero();
    }
}
public void SetVelocityZero()
{
     rb.velocity = Vector2.zero;
}

public void MoveLeft()
{
    rb.velocity = new Vector2( Mathf.Lerp( rb.velocity.x, -speed, Time.deltaTime ), 0);
    transform.eulerAngles = new Vector2(0, 180);
}

public void MoveRight()
{
    rb.velocity = new Vector2( Mathf.Lerp( rb.velocity.x, speed, Time.deltaTime ), 0);
    transform.eulerAngles = new Vector2(0, 0);
}
</code>```

Body:
I want to make my character to move smoothly when I tilt my phone. How I can make it to move smoothly and the velocity and the speed increases as the slope of the phone?

void AccelerometerMove(){

float x = Input.acceleration.x;
Debug.Log("X = " + x);

if (x < -0.1f)
{
    MoveLeft();
}
else if (x > 0.1f)
{
    MoveRight();
}
else
{
    SetVelocityZero();
}
}
public void SetVelocityZero()
{
     rb.velocity = Vector2.zero;
}

public void MoveLeft()
{
rb.velocity = new Vector2(-speed, 0);
//transform.Translate(Vector2.right * speed * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 180);
}

public void MoveRight()
{
rb.velocity = new Vector2(speed, 0);
//transform.Translate(Vector2.right * speed * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 0);
}

Body:
You can directly use the input of the accelerometer to set the speed of your object :

void AccelerometerMove()
{
    float x = Input.acceleration.x;
    Debug.Log("X = " + x);

    if (x < -0.1f)
    {
        MoveLeft(x);
    }
    else if (x > 0.1f)
    {
        MoveRight(x);
    }
    else
    {
        SetVelocityZero();
    }
}
public void SetVelocityZero()
{
     rb.velocity = Vector2.zero;
}

public void MoveLeft( float s )
{
    rb.velocity = new Vector2(s, 0);
    transform.eulerAngles = new Vector2(0, 180);
}

public void MoveRight( float s )
{
    rb.velocity = new Vector2(s, 0);
    transform.eulerAngles = new Vector2(0, 0);
}

And / or use the Mathf.Lerp function to compute the speed :

void AccelerometerMove()
{
    float x = Input.acceleration.x;
    Debug.Log("X = " + x);

    if (x < -0.1f)
    {
        MoveLeft();
    }
    else if (x > 0.1f)
    {
        MoveRight();
    }
    else
    {
        SetVelocityZero();
    }
}
public void SetVelocityZero()
{
     rb.velocity = Vector2.zero;
}

public void MoveLeft()
{
    rb.velocity = new Vector2( Mathf.Lerp( rb.velocity.x, -speed, Time.deltaTime ), 0);
    transform.eulerAngles = new Vector2(0, 180);
}

public void MoveRight()
{
    rb.velocity = new Vector2( Mathf.Lerp( rb.velocity.x, speed, Time.deltaTime ), 0);
    transform.eulerAngles = new Vector2(0, 0);
}


问:
Laravel: why does this cause error - call to undefined method?
Why calling a method with parenthesis in a template causes error, but without doesn't? How would I pass a parameter then?

Error:

```<code>Call to undefined method Illuminate\Database\Query\Builder::test()
</code>```

index.blade.php

```<code>...
<p class="product-price-old"><s>{{ $product->test("123") }}</s></p>
...
</code>```

Product.php

```<code>...
public function getTestAttribute($value)
{
    return $value;
}
...
</code>```

but if I do something like this it works fine:

index.blade.php

```<code>...
<p class="product-price-old"><s>{{ $product->test }}</s></p>
...
</code>```

Product.php

```<code>...
public function getTestAttribute()
{
    return "123";
}
...
</code>```

答:
The getTestAttribute is accessor, so it's not a real function. It rather shows how you can get attribute of model.

That's why for getTestAttribute method you should use:

```<code>$product->test
</code>```

Body:
Why calling a method with parenthesis in a template causes error, but without doesn't? How would I pass a parameter then?

Error:

Call to undefined method Illuminate\Database\Query\Builder::test()

index.blade.php

...

<s>{{ $product->test("123") }}</s>

...

Product.php

...
public function getTestAttribute($value)
{
    return $value;
}
...

but if I do something like this it works fine:

index.blade.php

...

<s>{{ $product->test }}</s>

...

Product.php

...
public function getTestAttribute()
{
    return "123";
}
...

Body:
The getTestAttribute is accessor, so it's not a real function. It rather shows how you can get attribute of model.

That's why for getTestAttribute method you should use:

$product->test


问:
min{wi, W − w} function in knapsack algorithm
```<code>Algorithm FractionalKnapsack(S, W ):
Input: Set S of items, such that each item i ∈ S has a positive benefit bi and a
positive weight wi; positive maximum total weight W
Output: Amount xi of each item i ∈ S that maximizes the total benefit while
not exceeding the maximum total weight W
for each item i ∈ S do
 xi ← 0
 vi ← bi/wi // value index of item i
w ← 0 // total weight
while w < W and S ̸= ∅ do
 remove from S an item i with highest value index
 a ← min{wi, W − w} // more than W − w causes a weight overflow
 xi ← a
 w←w+a
</code>```

I am trying to implement the above pseudocode in Ruby, I have successfully implemented a priority queue but I just need someone to explain this line for me:

a ← min{wi, W − w} // more than W − w causes a weight overflow

what the min function is supposed to do exactly? and how should it be implemented?

答:
The line a ← min{wi, W − w} actually gives a value to 'a' which is minimum value of w[i] and W-w. </p>

```<code>if w[i] < W-w then a ← w[i]
otherwise a ← W-w
</code>```

<p>For the implementation you can do </p>

```<code>[w[i], W-w].min
</code>```

Body:
Algorithm FractionalKnapsack(S, W ):
Input: Set S of items, such that each item i ∈ S has a positive benefit bi and a
positive weight wi; positive maximum total weight W
Output: Amount xi of each item i ∈ S that maximizes the total benefit while
not exceeding the maximum total weight W
for each item i ∈ S do
 xi ← 0
 vi ← bi/wi // value index of item i
w ← 0 // total weight
while w < W and S ̸= ∅ do
 remove from S an item i with highest value index
 a ← min{wi, W − w} // more than W − w causes a weight overflow
 xi ← a
 w←w+a

I am trying to implement the above pseudocode in Ruby, I have successfully implemented a priority queue but I just need someone to explain this line for me:

a ← min{wi, W − w} // more than W − w causes a weight overflow

what the min function is supposed to do exactly? and how should it be implemented?

Body:
The line a ← min{wi, W − w} actually gives a value to 'a' which is minimum value of w[i] and W-w.

if w[i] < W-w then a ← w[i]
otherwise a ← W-w

For the implementation you can do

[w[i], W-w].min


问:
Swift segue not working?
My Swift segue is not working at all and isn't throwing any errors. The breakpoint shows me that the app lands on this line but nothing happens:

```<code>self.performSegueWithIdentifier("SignupSegue", sender: self)
</code>```

The code block is a login form with Facebook:

```<code>if let accessToken: FBSDKAccessToken = FBSDKAccessToken.currentAccessToken() {
    PFFacebookUtils.logInInBackgroundWithAccessToken(result.token, block: {
        (user: PFUser ? , error : NSError ? ) - > Void in
        if user!.isNew {
            self.performSegueWithIdentifier("SignupSegue", sender: self)
        } else {
            self.navigateToInGame(true)
        }
    })
}
</code>```

Here's the segue function it should call, but doesn't even get to it:

```<code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
    {
        if (segue.identifier == "SignupSegue") {
            let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewControllerWithIdentifier("SignUpViewController")
            self.showViewController(vc, sender: self)
        }
    }
</code>```

Any ideas?

答:
Swift 3 solved:</p>

```<code>    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if (segue.identifier == "SignupSegue") {
                DispatchQueue.main.async {
                    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                    let vc = storyboard.instantiateViewController(withIdentifier: "SignUpViewController")
                    self.show(vc, sender: self)
                }
          }
    }
</code>```

Title: Swift segue not working?

Body:
My Swift segue is not working at all and isn't throwing any errors. The breakpoint shows me that the app lands on this line but nothing happens:

self.performSegueWithIdentifier("SignupSegue", sender: self)

The code block is a login form with Facebook:

if let accessToken: FBSDKAccessToken = FBSDKAccessToken.currentAccessToken() {
    PFFacebookUtils.logInInBackgroundWithAccessToken(result.token, block: {
        (user: PFUser ? , error : NSError ? ) - > Void in
        if user!.isNew {
            self.performSegueWithIdentifier("SignupSegue", sender: self)
        } else {
            self.navigateToInGame(true)
        }
    })
}

Here's the segue function it should call, but doesn't even get to it:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
    {
        if (segue.identifier == "SignupSegue") {
            let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewControllerWithIdentifier("SignUpViewController")
            self.showViewController(vc, sender: self)
        }
    }

Any ideas?

Body:
Swift 3 solved:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if (segue.identifier == "SignupSegue") {
                DispatchQueue.main.async {
                    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                    let vc = storyboard.instantiateViewController(withIdentifier: "SignUpViewController")
                    self.show(vc, sender: self)
                }
          }
    }


问:
is it possible to dynamically change field name within django-rest-framework serializer?
I have Product and ProductCategory models.

Let's say I have ProductCategory TV, which has
Sony, Samsung as its products. I also have MobilePhone category with Apple and Nokia as its products.
Using DRF, I would like to get JSON output using serializers, which is similar to the below:

```<code>{
    'TV':
        [
            'Sony':
                {
                    'price': '$100',
                    'country': 'Japan',
                },
            'Samsung':
                {
                    'price': '$110',
                    'country': 'Korea',
                }
        ]

    'mobile_phone':
        [
            'Apple':
                {
                    'price': '$300',
                    'country': 'USA',
                },
            'Nokia':
                {
                    'price': '$210',
                    'country': 'Finland',
                }
        ]
}
</code>```

The problem here is that the field names('TV', 'mobile_phone') in serializer have to be dynamic.

I know I can get the following JSON type

```<code>{
    [
            {
                'product_category': 'TV',
                'manufacturer: 'Sony',
                'price': '$100',
                'country': 'Japan',
            },
            {
                'product_category': 'TV',
                'manufacturer: 'Samgsung',
                'price': '$110',
                'country': 'Korea',
            }
    ]

    [
            {
                'product_category': 'mobile_phone',
                'manufacturer: 'Samgsung',
                'price': '$300',
                'country': 'USA',
            },
            {
                'product_category': 'mobile_phone',
                'manufacturer: 'Apple',
                'price': '$210',
                'country': 'Finland',
            }
    ]
}
</code>```

with

```<code>class CategorySerializer(serializers.Serializer):
    product_category = serializer.CharField()
    manufacturer = serializer.CharField()
    price = serializer.CharField()
    country = serializer.CharField()
</code>```

But the dynamically-changing-field-names is difficult to achieve. Is there any way I can do this?

答:
You can support this kind of custom format by overriding to_representation of your Serializer and of the default ListSerializer:

First, you override to_representation of your serializer:

```<code>class CategorySerializer(serializers.Serializer):
    # your fields here

    def to_representation(self, obj):
      return {
          obj.manufacturer: {
             'price': obj.price,
             'country': obj.country
          }
      }
</code>```

So that your serialized categories are of this form:

```<code>{
    'Sony': {
      'price': '$100',
      'country': 'Japan'
    }
}
</code>```

Then to prepend the product_category in front of your list, you can use a custom ListSerializer with a custom to_representation:

```<code>class CategoryListSerializer(serializers.ListSerializer):

    def to_representation(self, data):
        # Group your data entries by category here
        ...
        return {
            'TV': tv_data
            'mobile_phone': mobile_data
        }

class CategorySerializer(serializers.Serializer):
    ...
    class Meta:
      list_serializer_class = CategoryListSerializer
</code>```

Body:
I have Product and ProductCategory models.

Let's say I have ProductCategory TV, which has
Sony, Samsung as its products. I also have MobilePhone category with Apple and Nokia as its products.
Using DRF, I would like to get JSON output using serializers, which is similar to the below:

{
    'TV':
        [
            'Sony':
                {
                    'price': '$100',
                    'country': 'Japan',
                },
            'Samsung':
                {
                    'price': '$110',
                    'country': 'Korea',
                }
        ]

    'mobile_phone':
        [
            'Apple':
                {
                    'price': '$300',
                    'country': 'USA',
                },
            'Nokia':
                {
                    'price': '$210',
                    'country': 'Finland',
                }
        ]
}

The problem here is that the field names('TV', 'mobile_phone') in serializer have to be dynamic.

I know I can get the following JSON type

{
    [
            {
                'product_category': 'TV',
                'manufacturer: 'Sony',
                'price': '$100',
                'country': 'Japan',
            },
            {
                'product_category': 'TV',
                'manufacturer: 'Samgsung',
                'price': '$110',
                'country': 'Korea',
            }
    ]

    [
            {
                'product_category': 'mobile_phone',
                'manufacturer: 'Samgsung',
                'price': '$300',
                'country': 'USA',
            },
            {
                'product_category': 'mobile_phone',
                'manufacturer: 'Apple',
                'price': '$210',
                'country': 'Finland',
            }
    ]
}

with

class CategorySerializer(serializers.Serializer):
    product_category = serializer.CharField()
    manufacturer = serializer.CharField()
    price = serializer.CharField()
    country = serializer.CharField()

But the dynamically-changing-field-names is difficult to achieve. Is there any way I can do this?

Body:
You can support this kind of custom format by overriding to_representation of your Serializer and of the default ListSerializer:

First, you override to_representation of your serializer:

class CategorySerializer(serializers.Serializer):
    # your fields here

    def to_representation(self, obj):
      return {
          obj.manufacturer: {
             'price': obj.price,
             'country': obj.country
          }
      }

So that your serialized categories are of this form:

{
    'Sony': {
      'price': '$100',
      'country': 'Japan'
    }
}

Then to prepend the product_category in front of your list, you can use a custom ListSerializer with a custom to_representation:

class CategoryListSerializer(serializers.ListSerializer):

    def to_representation(self, data):
        # Group your data entries by category here
        ...
        return {
            'TV': tv_data
            'mobile_phone': mobile_data
        }

class CategorySerializer(serializers.Serializer):
    ...
    class Meta:
      list_serializer_class = CategoryListSerializer


问:
error: Unexpected token function
I am making a sequence game and for the past hour I keep getting this error Uncaught SyntaxError: Unexpected token function.

I thought at first and after reading some StackOverFlow messages that I might not of closed my document ready properly? However, Low and behold I still can't figure it out.

I am new to coding so bere with me :)

HTML

```<code><body>
<div class="row">
<div class="col-md-12">
<div class="gamefield">
<div class="top-row">
<div id="blue" class="gamebutton"></div>
</div>
<div class="middle-row">
<div id="green"  class="gamebutton"></div>
<div id="gameNumber">
<h2 id="clickNumber">0</h2></div>
<div id="red" class="gamebutton"></div>
</div>
<div class="bottom-row">
<div id="dark" class="gamebutton"></div>
<div>
</div>
</div>
</div>
</div>
</div>

</body>
</html>
</code>```

JS

```<code>$(document).ready(function(e){
console.log('hello');

var game = {
count: 0,
possibilities: ['#green','#blue', '#red', '#dark'],
currentGame: [],
player: [],
playGame:

game.clearGame = function clearGame() {
  game.currentGame = [];
  game.count = 0;
  addCount();
}

 function newGame() {
  clearGame();
}

game.Strict = function strict() {
  if (game.strict === false) {
    game.strict === true;
    $('#strict').html('Is currently On').removeClass('btn-primary').addClass('btn-danger');
  } else {
    game.strict = false;
    $('#strict').html('Is currently Off').removeClass('btn-danger').addClass('btn-primary');
  }

  newGame();
}

game.ShowMoves = function showMoves() {
  var i = 0;
  var moves = setInterval(function(){
    playGame(game.currentGame[i]);
    i++;
    if (i >= game.currentGame.length) {
      clearInterval(moves);
    }
  }, 600)

  clearPlayer();
}

Game.Shade = function shade(name) {
  switch(name) {
    case'#green':
      game.shade.green.show();
      break;
    case '#blue':
      game.shade.blue.show();
      break;
    case '#red':
      game.shade.red.show();
      break;
    case '#dark':
      game.shade.dark.show();
      break;
  };
}

game.playGame = function playGame(field) {
  $(field).addClass('hover');
  shade(field);
  setTimeout(function(){
      $(field).removeClass('hover');
  }, 300);
}

game.clearPlayer = function clearPlayer() {
  game.player = [];
}

game.addToPlayer = function addToPlayer(id) {
  var field = "#"+id
  console.log(field);
  game.player.push(field);
  playerTurn(field);
}

game.playerTurn = function playerTurn(x) {
  if (game.player[game.player.length - 1] !== game.currentGame[game.player.length - 1]) {
    if(game.strict){
      alert('Sorry not right');
      newGame();
    } else {
      alert('Wrong!');
      showMoves();
    }
   } else {
      shade(x);
      var check = game.player.length === game.currentGame.length;
      if (check) {
        if(game.count === 20){
          alert('Aced it!');
        } else {
          alert('Nice one, new round');
          nextLevel();
        }
      }
    }
}

game.nextLevel = function nextLevel() {
  addCount();
}

game.generateMove = function generateMove(){
  game.currentGame.push(game.possibilities[(Math.floor(Math.random()*4))]);
  //alert(game.currentGame.length);
  showMoves();
}

game.addCount = function addCount() {
  game.count++;
  $('#clickNumber').addClass('animated fadeOutDown');

  setTimeout(function(){
    $('#clickNumber').removeClass('fadeOutDown').html(game.count).addClass('fadeInDown');
  }, 200);

  generateMove();
}

newGame();
});
</code>```

Any ideas would be ace.

答:
```<code>var game = {
count: 0,
possibilities: ['#green','#blue', '#red', '#dark'],
currentGame: [],
player: [],
playGame:
</code>```

You probably want to close the object there like this:

```<code>var game = {
count: 0,
possibilities: ['#green','#blue', '#red', '#dark'],
currentGame: [],
player: [],
playGame:
}
</code>```

Also game is not the same as Game. So fix that Game.Shade as well. Also keep the code properly indented and formatted. Helps ward off any obvious errors errors.

Title: error: Unexpected token function

Body:
I am making a sequence game and for the past hour I keep getting this error Uncaught SyntaxError: Unexpected token function.

I thought at first and after reading some StackOverFlow messages that I might not of closed my document ready properly? However, Low and behold I still can't figure it out.

I am new to coding so bere with me :)

HTML

0

JS

$(document).ready(function(e){
console.log('hello');

var game = {
count: 0,
possibilities: ['#green','#blue', '#red', '#dark'],
currentGame: [],
player: [],
playGame:

game.clearGame = function clearGame() {
  game.currentGame = [];
  game.count = 0;
  addCount();
}

 function newGame() {
  clearGame();
}

game.Strict = function strict() {
  if (game.strict === false) {
    game.strict === true;
    $('#strict').html('Is currently On').removeClass('btn-primary').addClass('btn-danger');
  } else {
    game.strict = false;
    $('#strict').html('Is currently Off').removeClass('btn-danger').addClass('btn-primary');
  }

  newGame();
}

game.ShowMoves = function showMoves() {
  var i = 0;
  var moves = setInterval(function(){
    playGame(game.currentGame[i]);
    i++;
    if (i >= game.currentGame.length) {
      clearInterval(moves);
    }
  }, 600)

  clearPlayer();
}

Game.Shade = function shade(name) {
  switch(name) {
    case'#green':
      game.shade.green.show();
      break;
    case '#blue':
      game.shade.blue.show();
      break;
    case '#red':
      game.shade.red.show();
      break;
    case '#dark':
      game.shade.dark.show();
      break;
  };
}

game.playGame = function playGame(field) {
  $(field).addClass('hover');
  shade(field);
  setTimeout(function(){
      $(field).removeClass('hover');
  }, 300);
}

game.clearPlayer = function clearPlayer() {
  game.player = [];
}

game.addToPlayer = function addToPlayer(id) {
  var field = "#"+id
  console.log(field);
  game.player.push(field);
  playerTurn(field);
}

game.playerTurn = function playerTurn(x) {
  if (game.player[game.player.length - 1] !== game.currentGame[game.player.length - 1]) {
    if(game.strict){
      alert('Sorry not right');
      newGame();
    } else {
      alert('Wrong!');
      showMoves();
    }
   } else {
      shade(x);
      var check = game.player.length === game.currentGame.length;
      if (check) {
        if(game.count === 20){
          alert('Aced it!');
        } else {
          alert('Nice one, new round');
          nextLevel();
        }
      }
    }
}

game.nextLevel = function nextLevel() {
  addCount();
}

game.generateMove = function generateMove(){
  game.currentGame.push(game.possibilities[(Math.floor(Math.random()*4))]);
  //alert(game.currentGame.length);
  showMoves();
}

game.addCount = function addCount() {
  game.count++;
  $('#clickNumber').addClass('animated fadeOutDown');

  setTimeout(function(){
    $('#clickNumber').removeClass('fadeOutDown').html(game.count).addClass('fadeInDown');
  }, 200);

  generateMove();
}

newGame();
});

Any ideas would be ace.

Body:
var game = {
count: 0,
possibilities: ['#green','#blue', '#red', '#dark'],
currentGame: [],
player: [],
playGame:

You probably want to close the object there like this:

var game = {
count: 0,
possibilities: ['#green','#blue', '#red', '#dark'],
currentGame: [],
player: [],
playGame:
}

Also game is not the same as Game. So fix that Game.Shade as well. Also keep the code properly indented and formatted. Helps ward off any obvious errors errors.


问:
How to get the 0th index key values in array object
I have one array object in that object galleryImages i having like json string , in this galleryImages i want display onely the first image value , how can get the only first image value?

My array check below

```<code>$data=Array
(
    [dbResultgallery] => Array
        (
            [0] => stdClass Object
                (
                    [gallery_id] => 1
                    [className] => 1
                    [sectionName] => 1
                    [title] => Title 1
                    [description] => gfhfg
                    [galleryImages] => ["1.jpeg","2.jpg"]
                    [reg_on] => 2017-04-03 12:21:59
                    [created_by] => soupranjali@gmail.com
                    [school_id] => 2
                    [status] => 0
                )

            [1] => stdClass Object
                (
                    [gallery_id] => 2
                    [className] => 1
                    [sectionName] => 1
                    [title] => Title 2
                    [description] => sdfdsfsdfsdfsdf
                    [galleryImages] => ["3.jpeg","4.jpg","5.jpg"]
                    [reg_on] => 2017-04-03 12:23:37
                    [created_by] => soupranjali@gmail.com
                    [school_id] => 2
                    [status] => 0
                )

        )

)
</code>```

now i am using json_decode ,see below my code

```<code>foreach ($dbResultgallery as $gal) :
    $role = json_decode($gal->galleryImages,true);
 endforeach;
</code>```

Now i am getting array format like

```<code>Array
    (
        [0] => 1.jpeg
        [1] => 2.jpg
    )

    Array
    (
        [0] => 3.jpeg
        [1] => 4.jpg
        [2] => 5.jpg
    )
</code>```

Expected results

I need only the first images value like 1.jpeg and 3.jpeg, each array i need only the 0 th key values

Updated code

var_dump(json_decode($gal->galleryImages,true))

```<code>array(2) {

 [0]=>
  string(37) "6be1954c4bec91fe26fb7447fc551782.jpeg"
  [1]=>
  string(36) "153651d989591e76444c92cf037d5ac4.jpg"
}

array(3) {
  [0]=>
  string(37) "f356ceafa408e61cd1c62cfc39752b32.jpeg"
  [1]=>
  string(36) "a4fd29005696d92e0fc4cd3931454609.jpg"
  [2]=>
  string(36) "8eaaecdac1ff219192806acba7978a1b.jpg"
}
</code>```

答:
```<code>   foreach ($dbResultgallery as $gal) :
       if(strpos(json_decode($gal->galleryImages,true) ,"jpeg")!== false){
         echo 'found'; // do your stuff here
       $role = json_decode($gal->galleryImages[0],true);
        }
    endforeach
</code>```

Body:
I have one array object in that object galleryImages i having like json string , in this galleryImages i want display onely the first image value , how can get the only first image value?

My array check below

$data=Array
(
    [dbResultgallery] => Array
        (
            [0] => stdClass Object
                (
                    [gallery_id] => 1
                    [className] => 1
                    [sectionName] => 1
                    [title] => Title 1
                    [description] => gfhfg
                    [galleryImages] => ["1.jpeg","2.jpg"]
                    [reg_on] => 2017-04-03 12:21:59
                    [created_by] => soupranjali@gmail.com
                    [school_id] => 2
                    [status] => 0
                )

            [1] => stdClass Object
                (
                    [gallery_id] => 2
                    [className] => 1
                    [sectionName] => 1
                    [title] => Title 2
                    [description] => sdfdsfsdfsdfsdf
                    [galleryImages] => ["3.jpeg","4.jpg","5.jpg"]
                    [reg_on] => 2017-04-03 12:23:37
                    [created_by] => soupranjali@gmail.com
                    [school_id] => 2
                    [status] => 0
                )

        )

)

now i am using json_decode ,see below my code

foreach ($dbResultgallery as $gal) :
    $role = json_decode($gal->galleryImages,true);
 endforeach;

Now i am getting array format like

Array
    (
        [0] => 1.jpeg
        [1] => 2.jpg
    )

    Array
    (
        [0] => 3.jpeg
        [1] => 4.jpg
        [2] => 5.jpg
    )

Expected results

I need only the first images value like 1.jpeg and 3.jpeg, each array i need only the 0 th key values

Updated code

var_dump(json_decode($gal->galleryImages,true))

array(2) {

 [0]=>
  string(37) "6be1954c4bec91fe26fb7447fc551782.jpeg"
  [1]=>
  string(36) "153651d989591e76444c92cf037d5ac4.jpg"
}

array(3) {
  [0]=>
  string(37) "f356ceafa408e61cd1c62cfc39752b32.jpeg"
  [1]=>
  string(36) "a4fd29005696d92e0fc4cd3931454609.jpg"
  [2]=>
  string(36) "8eaaecdac1ff219192806acba7978a1b.jpg"
}


问:
How to point a custom sub-domain to a sub-directory of a Github repository
Say I have custom subdomain x.site.com, configured it via my DNS provider to point to one of my Github repos, say repo. What x.site.com is pointing to - now - is the root of the repo where CNAME  file exists containing x.site.com. My question, How to make that subdomain points to a subdirectory say repo/docs and not to the root of the repo ?

答:
Step #1

Push the target sub-directory to gh-pages branch via the next command:

```<code>git subtree push --prefix dist origin gh-pages
</code>```

Step #2

Include CNAME file in the target sub-directory containing x.site.com.

Notes

Make sure that target sub-directory isn't included in .gitignore file and also committed.

Make sure to replace dist in the previous command with your sub-directory name (e.g. build, public).

Each time you make a change you have to repeat the previous command.

For more details about the process and how to automate it and sync between the master branch and gh-pages branch, view this gist

Body:
Step #1

Push the target sub-directory to gh-pages branch via the next command:

git subtree push --prefix dist origin gh-pages

Step #2

Include CNAME file in the target sub-directory containing x.site.com.

Notes

Make sure that target sub-directory isn't included in .gitignore file and also committed.

Make sure to replace dist in the previous command with your sub-directory name (e.g. build, public).

Each time you make a change you have to repeat the previous command.

For more details about the process and how to automate it and sync between the master branch and gh-pages branch, view this gist


问:
Saving by month to include week number
I am looking to save data from one file to another based on Month, but if a week falls in to another month part way through, I still would like to save the data with the current week. Here's the codes as it stands which works fine for saving by month:</p>

```<code>'Copy Data to Workbook Weekly Monthly

Rows("2:2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

Application.DisplayAlerts = True

FileMonth = Month(Date)
StrFileMonth = Format(Date, "MMM")

Filepath = "F:\Customer Services\UK Order File\Monthly Figures\" & StrFileMonth & "\" & "UK_Orders_Monthly.xlsm"

Workbooks.Open (Filepath), _
UpdateLinks:=True

Worksheets("Data").Activate
Range("A1").End(xlDown).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues
</code>```

答:
A True in VBA is considered -1 when used mathematically (contrary to a worksheet's TRUE which is +1).

If the weekday(Date) is greater then the day(Date) then the month should be last month; e.g. dateadd("m", -1, Date). If it is equal to or less than the day of the month then the month is the current month; e.g. dateadd("m", 0, Date).

```<code>StrFileMonth = Format(dateadd("m", weekday(date, vbmonday) > day(date), date), "mmm")
</code>```

I've used vbMonday where Monday = 1; the WeekDay VBA function defaults to Sunday = 1.

Title: Saving by month to include week number

Body:
I am looking to save data from one file to another based on Month, but if a week falls in to another month part way through, I still would like to save the data with the current week. Here's the codes as it stands which works fine for saving by month:

'Copy Data to Workbook Weekly Monthly

Rows("2:2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

Application.DisplayAlerts = True

FileMonth = Month(Date)
StrFileMonth = Format(Date, "MMM")

Filepath = "F:\Customer Services\UK Order File\Monthly Figures\" & StrFileMonth & "\" & "UK_Orders_Monthly.xlsm"

Workbooks.Open (Filepath), _
UpdateLinks:=True

Worksheets("Data").Activate
Range("A1").End(xlDown).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues

Body:
A True in VBA is considered -1 when used mathematically (contrary to a worksheet's TRUE which is +1).

If the weekday(Date) is greater then the day(Date) then the month should be last month; e.g. dateadd("m", -1, Date). If it is equal to or less than the day of the month then the month is the current month; e.g. dateadd("m", 0, Date).

StrFileMonth = Format(dateadd("m", weekday(date, vbmonday) > day(date), date), "mmm")

I've used vbMonday where Monday = 1; the WeekDay VBA function defaults to Sunday = 1.


问:
Unable to access unescaped html in an RSS feed
I'm using the built in RSS capabilities of Ruby (RSS::Parser.parse) in a new rails app.  The app reads several different sources of rss feeds that are outside of my control (public facing, built by others).  One of the feeds I am trying to access contains unescaped html in its description fields within the items collection.  I am able to access the feed, but when I try to access the description field within my view it appears as if nothing is there.  I at first thought I needed to use the raw helper, but the end result is the same.  Is there some special way I need to request the data or access it in the view?  The code in my controller is as follows:

```<code>@recent_activity = RSS::Parser.parse(open('http://someurl').read, false)
</code>```

The code in my view is as follows

```<code><% @recent_activity.items.each do |itm| %>
    <%= raw itm.description %>
<% end %>
</code>```

I know I could probably make this work by utilizing the raw xml capabilities and bypass the RSS object, but I'm trying to see if there is something I can do with the RSS object before going that route.

Thanks in advance for any help or suggestions.

答:
Instead of RSS::Parser try the totally awesome feedzirra. I use it in an app that pulls in about 200 different feeds without any problems. Oh, and it uses Nokogiri, so it's fast as well.

FeedZirra description: A feed fetching and parsing library that treats the internet like Godzilla treats Japan: it dominates and eats all.

ContentLicense: CC BY-SA 2.5

Body:
I'm using the built in RSS capabilities of Ruby (RSS::Parser.parse) in a new rails app.  The app reads several different sources of rss feeds that are outside of my control (public facing, built by others).  One of the feeds I am trying to access contains unescaped html in its description fields within the items collection.  I am able to access the feed, but when I try to access the description field within my view it appears as if nothing is there.  I at first thought I needed to use the raw helper, but the end result is the same.  Is there some special way I need to request the data or access it in the view?  The code in my controller is as follows:

@recent_activity = RSS::Parser.parse(open('http://someurl').read, false)

The code in my view is as follows

<% @recent_activity.items.each do |itm| %>
    <%= raw itm.description %>
<% end %>

I know I could probably make this work by utilizing the raw xml capabilities and bypass the RSS object, but I'm trying to see if there is something I can do with the RSS object before going that route.

Thanks in advance for any help or suggestions.


问:
Issue with a double value
Whenever the deposit or withdraw method is used it will add or subtract from the original balance but if you try to add or subtract again it does not recognize the previous transactions and will add or subtract from the original balance again instead of the new balance after a transaction has been made.

For example: If I deposit $10 into a $20 account it will equal $30. If I then try to deposit another $5, it will equal $25 instead of $35. It bases all transactions of the original balance and that is the issue. I am not sure how to fix it.

```<code>//This program will create a functioning mock ATM with the usual features of a real ATM.

import java.util.*;

public class ATM {

    public static Scanner kbd;

    /**
     * This is the main method, everything that is returned from other methods is sent here to be processed and initialized into the atm.
     * @param args
     */
    public static void main(String[] args) {
        String acctNum, acctPword;
        String balance;
        boolean menu = false;
        double depAmnt = 0.0, withAmnt = 0.0;
        int x = 1;
        kbd = new Scanner(System.in);
        //getting the user account username
        System.out.print("Enter your account number: ");
        acctNum = kbd.nextLine();
        //getting the users password
        System.out.print("Enter your account password: ");
        acctPword = kbd.nextLine();
        //incase the user enters invalid information
        balance = checkID(acctNum, acctPword);
        while (balance.equals("error") && x <4){
            System.out.println("Wrong password try again.");
            System.out.print("Enter your account password: ");
            acctPword = kbd.nextLine();
            x++;
        }
        //once they gained access to the atm machine, the balance will print for informative purposes.
        double balance1 = Double.parseDouble(balance);
        System.out.println("You currently have $" + String.format("%.2f",balance1));
        //they only get 3 attempts to enter the correct password.
        if (x == 4)
            System.out.println("Maximum number of attempts reached, Please try again later.");
        //This switch and while statement controls the main menu of the atm machine and is capable of calling all methods.
        while (menu == false){
        switch (menu()) {
        case 1:
            System.out.println("Your balance is $" + String.format("%.2f",balance1));
            break;
        case 2:
            deposit(balance1, depAmnt);
            break;
        case 3:
            withdraw(balance1, withAmnt);
            break;
        case 4:
            System.out.println("Have a nice day.");
            menu = true;
            break;
        }
        }
        kbd.close();
    }

    /**
     * Determines if acctNum is a valid account number, and pwd is the correct
     * password for the account.
     * @param acctNum The account number to be checked
     * @param pwd The password to be checked
     * @return If the account information is valid, returns the current account
     * balance, as a string. If the account information is invalid, returns
     * the string "error".
     */
    public static String checkID(String acctNum, String pwd)
    {
        String result = "error";

        // Strings a, b, and c contain the valid account numbers and passwords.
        // For each string, the account number is listed first, followed by
        // a space, followed by the password for the account, followed by a space,
        // followed by the current balance.
        String a = "44567-5 mypassword 520.36";
        String b = "1234567-6 anotherpassword 48.20";
        String c = "4321-0 betterpassword 96.74";
        //these 3 if statements and everything declared right before the if statements, first checks the users name and pword for gained access and allows the user to enter the code and change the password and username if they so please.
        int pos1, pos2;
        pos1 = a.indexOf(" ");
        pos2 = a.lastIndexOf(" ");
        String account, password;
        account = a.substring(0, pos1);
        password = a.substring(pos1+1,pos2);
        if (acctNum.equals(account) && pwd.equals(password)){
            result = a.substring(pos2+1);
            return result;
        }

        int pos1b, pos2b;
        pos1b = b.indexOf(" ");
        pos2b = b.lastIndexOf(" ");
        String accountb, passwordb;
        accountb = b.substring(0, pos1b);
        passwordb = b.substring(pos1b+1,pos2b);
        if (acctNum.equals(accountb) && pwd.equals(passwordb)){
            result = b.substring(pos2b+1);
            return result;
        }

        int pos1c, pos2c;
        pos1c = c.indexOf(" ");
        pos2c = c.lastIndexOf(" ");
        String accountc, passwordc;
        accountc = c.substring(0, pos1c);
        passwordc = c.substring(pos1c+1,pos2c);
        if (acctNum.equals(accountc) && pwd.equals(passwordc)){
            result = c.substring(pos2c+1);
            return result;
        }

        return result;
    }

    /**
     * This menu method will get the users input and allow them to choose 4 options otherwise they will receive an error message.
     * @return x is returned as the users input and will dictate which option they choose.
     */
    public static int menu(){
        int x = 1;

            // the physical aspect of the menu
            System.out.println("1. Display Balance \n2. Deposit\n3. Withdraw\n4. Log Out");
            x = kbd.nextInt();

        //incase they dont enter valid info
        if(x > 4){
            System.out.println("That is not an option.");
            x = 0;
            x = kbd.nextInt();
        }
        return x;
    }
    /**
     * This method will allow the user to use a deposit feature found on every atm if they wish to deposit money into their account.
     * @param acctBal this is the account balance and will dictate how much they have before and after the deposit
     * @param depAmnt this is how much they so choose to deposit to their accounts
     * @return the account balance is returned and revised to what ever amount they chose to add.
     */
    public static double deposit(double acctBal, double depAmnt){

        System.out.print("How much money would you like to deposit? $");
        depAmnt = kbd.nextDouble();
        acctBal = acctBal + depAmnt;
        System.out.println("Your balance is now at $" + String.format("%.2f", acctBal));
        return acctBal;
    }

    /**
     * This allows the user to take money from their account if they have money in the first place.
     * @param acctBal the account balance will be returned as a new lesser value once the withdraw is made
     * @param withAmnt this dictates how much is taken from the acct.
     * @return the now lesser acct balance is returned
     */
    public static double withdraw(double acctBal, double withAmnt){

        System.out.print("How much money would you like to withdraw? $");
        withAmnt = kbd.nextDouble();

        if (acctBal <= 0){
            System.out.println("You do not have any money.");
            return acctBal;
        }

        if (acctBal < withAmnt){
            System.out.print("You do not have enough money.\nHow much money would you like to withdraw? $");
            withAmnt = kbd.nextDouble();
        }
        else{
            acctBal = acctBal - withAmnt;
        }
        System.out.println("You now have $" + String.format("%.2f",acctBal));
        return acctBal;
    }

    /**
     * all this does is simply display the current balance of the user
     * @param balance the balance as it stands during the program.
     * @return
     */
    public static double displayBalance(double balance){
        System.out.println("Your balance is $" + String.format("%.2f", balance));
        return balance;
    }

}
</code>```

答:
The problem is in your switch statement:

```<code>switch (menu()) {
    case 1:
        System.out.println("Your balance is $" + String.format("%.2f",balance1));
        break;
    case 2:
        deposit(balance1, depAmnt);
        break;
    case 3:
        withdraw(balance1, withAmnt);
        break;
    case 4:
        System.out.println("Have a nice day.");
        menu = true;
        break;
}
</code>```

Your deposit and withdraw functions both return the new balance but do not update it. Hence you have to store the new value in balance1. Just do balance1 = deposit(...) and balance1 = withdraw(...).

Title: Issue with a double value

Body:
Whenever the deposit or withdraw method is used it will add or subtract from the original balance but if you try to add or subtract again it does not recognize the previous transactions and will add or subtract from the original balance again instead of the new balance after a transaction has been made.

For example: If I deposit $10 into a $20 account it will equal $30. If I then try to deposit another $5, it will equal $25 instead of $35. It bases all transactions of the original balance and that is the issue. I am not sure how to fix it.

//This program will create a functioning mock ATM with the usual features of a real ATM.

import java.util.*;

public class ATM {

    public static Scanner kbd;

    /**
     * This is the main method, everything that is returned from other methods is sent here to be processed and initialized into the atm.
     * @param args
     */
    public static void main(String[] args) {
        String acctNum, acctPword;
        String balance;
        boolean menu = false;
        double depAmnt = 0.0, withAmnt = 0.0;
        int x = 1;
        kbd = new Scanner(System.in);
        //getting the user account username
        System.out.print("Enter your account number: ");
        acctNum = kbd.nextLine();
        //getting the users password
        System.out.print("Enter your account password: ");
        acctPword = kbd.nextLine();
        //incase the user enters invalid information
        balance = checkID(acctNum, acctPword);
        while (balance.equals("error") && x <4){
            System.out.println("Wrong password try again.");
            System.out.print("Enter your account password: ");
            acctPword = kbd.nextLine();
            x++;
        }
        //once they gained access to the atm machine, the balance will print for informative purposes.
        double balance1 = Double.parseDouble(balance);
        System.out.println("You currently have $" + String.format("%.2f",balance1));
        //they only get 3 attempts to enter the correct password.
        if (x == 4)
            System.out.println("Maximum number of attempts reached, Please try again later.");
        //This switch and while statement controls the main menu of the atm machine and is capable of calling all methods.
        while (menu == false){
        switch (menu()) {
        case 1:
            System.out.println("Your balance is $" + String.format("%.2f",balance1));
            break;
        case 2:
            deposit(balance1, depAmnt);
            break;
        case 3:
            withdraw(balance1, withAmnt);
            break;
        case 4:
            System.out.println("Have a nice day.");
            menu = true;
            break;
        }
        }
        kbd.close();
    }

    /**
     * Determines if acctNum is a valid account number, and pwd is the correct
     * password for the account.
     * @param acctNum The account number to be checked
     * @param pwd The password to be checked
     * @return If the account information is valid, returns the current account
     * balance, as a string. If the account information is invalid, returns
     * the string "error".
     */
    public static String checkID(String acctNum, String pwd)
    {
        String result = "error";

        // Strings a, b, and c contain the valid account numbers and passwords.
        // For each string, the account number is listed first, followed by
        // a space, followed by the password for the account, followed by a space,
        // followed by the current balance.
        String a = "44567-5 mypassword 520.36";
        String b = "1234567-6 anotherpassword 48.20";
        String c = "4321-0 betterpassword 96.74";
        //these 3 if statements and everything declared right before the if statements, first checks the users name and pword for gained access and allows the user to enter the code and change the password and username if they so please.
        int pos1, pos2;
        pos1 = a.indexOf(" ");
        pos2 = a.lastIndexOf(" ");
        String account, password;
        account = a.substring(0, pos1);
        password = a.substring(pos1+1,pos2);
        if (acctNum.equals(account) && pwd.equals(password)){
            result = a.substring(pos2+1);
            return result;
        }

        int pos1b, pos2b;
        pos1b = b.indexOf(" ");
        pos2b = b.lastIndexOf(" ");
        String accountb, passwordb;
        accountb = b.substring(0, pos1b);
        passwordb = b.substring(pos1b+1,pos2b);
        if (acctNum.equals(accountb) && pwd.equals(passwordb)){
            result = b.substring(pos2b+1);
            return result;
        }

        int pos1c, pos2c;
        pos1c = c.indexOf(" ");
        pos2c = c.lastIndexOf(" ");
        String accountc, passwordc;
        accountc = c.substring(0, pos1c);
        passwordc = c.substring(pos1c+1,pos2c);
        if (acctNum.equals(accountc) && pwd.equals(passwordc)){
            result = c.substring(pos2c+1);
            return result;
        }

        return result;
    }

    /**
     * This menu method will get the users input and allow them to choose 4 options otherwise they will receive an error message.
     * @return x is returned as the users input and will dictate which option they choose.
     */
    public static int menu(){
        int x = 1;

            // the physical aspect of the menu
            System.out.println("1. Display Balance \n2. Deposit\n3. Withdraw\n4. Log Out");
            x = kbd.nextInt();

        //incase they dont enter valid info
        if(x > 4){
            System.out.println("That is not an option.");
            x = 0;
            x = kbd.nextInt();
        }
        return x;
    }
    /**
     * This method will allow the user to use a deposit feature found on every atm if they wish to deposit money into their account.
     * @param acctBal this is the account balance and will dictate how much they have before and after the deposit
     * @param depAmnt this is how much they so choose to deposit to their accounts
     * @return the account balance is returned and revised to what ever amount they chose to add.
     */
    public static double deposit(double acctBal, double depAmnt){

        System.out.print("How much money would you like to deposit? $");
        depAmnt = kbd.nextDouble();
        acctBal = acctBal + depAmnt;
        System.out.println("Your balance is now at $" + String.format("%.2f", acctBal));
        return acctBal;
    }

    /**
     * This allows the user to take money from their account if they have money in the first place.
     * @param acctBal the account balance will be returned as a new lesser value once the withdraw is made
     * @param withAmnt this dictates how much is taken from the acct.
     * @return the now lesser acct balance is returned
     */
    public static double withdraw(double acctBal, double withAmnt){

        System.out.print("How much money would you like to withdraw? $");
        withAmnt = kbd.nextDouble();

        if (acctBal <= 0){
            System.out.println("You do not have any money.");
            return acctBal;
        }

        if (acctBal < withAmnt){
            System.out.print("You do not have enough money.\nHow much money would you like to withdraw? $");
            withAmnt = kbd.nextDouble();
        }
        else{
            acctBal = acctBal - withAmnt;
        }
        System.out.println("You now have $" + String.format("%.2f",acctBal));
        return acctBal;
    }

    /**
     * all this does is simply display the current balance of the user
     * @param balance the balance as it stands during the program.
     * @return
     */
    public static double displayBalance(double balance){
        System.out.println("Your balance is $" + String.format("%.2f", balance));
        return balance;
    }

}

Body:
The problem is in your switch statement:

switch (menu()) {
    case 1:
        System.out.println("Your balance is $" + String.format("%.2f",balance1));
        break;
    case 2:
        deposit(balance1, depAmnt);
        break;
    case 3:
        withdraw(balance1, withAmnt);
        break;
    case 4:
        System.out.println("Have a nice day.");
        menu = true;
        break;
}

Your deposit and withdraw functions both return the new balance but do not update it. Hence you have to store the new value in balance1. Just do balance1 = deposit(...) and balance1 = withdraw(...).


问:
Mail script needs running every hour, but cron not working
Below is the fully functioning code. It works when I call it via the browser. However, I can't get my Cron job to run it. I have tried coming up with any solution and am open to any ideas that will make this script fire off once every hour 24/7 365 so to speak.

Info:

Hostgator

PHP 5.4

Link for Hostgator Cron commands: http://support.hostgator.com/articles/cpanel/what-do-i-put-for-the-cron-job-command?utm_source=cPanel&utm_medium=message&utm_campaign=Cron%20Jobs

I have tried the following:

When doing any of these I have yet to have it add a sale to the database or send a single email:

/opt/php54/bin/php /home1/user/public_html/Sales/scripts/sales-notif_em.php - Could not open input file: /home1/user/public_html/scripts/sales-notif_em.php

php /home1/user/public_html/Sales/scripts/sales-notif_em.php - blank email with nothing but this showing: Content-type: text/html

php -q /home1/lotscav1/public_html/Sales/scripts/sales_notif_em.php - I don't get any emails from the system of course

/usr/bin/curl home1/user/public_html/scripts/sales-notif_em.php - curl: (3)  malformed

any command (like php or /usr/bin/curl) that has the second half with http://website.c0m/Sales/scripts/sales_notif_em.php - causes a JSON Error when trying to add the Cron job

I have checked the following things:

File permissions are 655

Timestamp is less than an hour old under the customers table

Here is my code:

```<code><?php
//find out current time and 1 hour ago
date_default_timezone_set('America/New_York');
$current_time = strtotime("now");
$hour_ago = strtotime('-1 hour');

//////////////////////////////////////////////////////////////////
/////////////////l// Connect to Sales Database  ///////////////////
//////////////////////////////////////////////////////////////////

$mysqli_s = new mysqli("localhost", "user", "password",
"server_sales_data");
if ($mysqli_s->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli_s->connect_errno . ")
" . $mysqli_s->connect_error;
}

//////////////////////////////////////////////////////////////////
///////////////////// Connect to EM Database  ////////////////////
//////////////////////////////////////////////////////////////////

$mysqli_em = new mysqli("localhost", "user", "password",
"server_dlgEM");
if ($mysqli_em->connect_errno) {
echo "Failed to connect to MySQL_EM: (" . $mysqli_em->connect_errno .
") " . $mysqli_em->connect_error;
}

//Grab store name
$dlg_store = "EM";

$em_request = "SELECT * FROM customers WHERE date BETWEEN '$hour_ago'
AND '$current_time'";
$em_result = mysqli_query($mysqli_em, $em_request) or die("Error No
Sales EM");
while ($em_row = mysqli_fetch_array($em_result)) {
$em_prod_num = $em_row["prod_num"];
$em_receipt = $em_row["receipt"];

//////////////////////////////////////////////////////////////////
///////////////////// Grab info for EM Sales  ////////////////////
//////////////////////////////////////////////////////////////////

$request_s = "SELECT * FROM all_products WHERE
dlgprod_num='$em_prod_num' AND dlg_store='$dlg_store'";
$result_s = mysqli_query($mysqli_s, $request_s) or die("Error dlg
prod num EM");
while ($row_s = mysqli_fetch_array($result_s)) {
        $sku_s = $row_s["sku"];
        $dlgprod_num_s = $row_s["dlgprod_num"];
        $book_title_s = addslashes($row_s["book_title"]);
        $dlgprod_price_s = $row_s["dlgprod_price"];
        $author_name_s = addslashes($row_s["author_name"]);
        $author_email_s = $row_s["author_email"];
        $publisher_s = $row_s["publisher"];
        $dlg_store_s = $row_s["dlg_store"];

            $add_sql_s  = "INSERT INTO all_author_sales SET
            `sku`='$sku_s',
            `dlgprod_num`='$dlgprod_num_s',
            `dlgprod_nam`='$book_title_s',
            `dlgprod_price`='$dlgprod_price_s',
            `author_name`='$author_name_s',
            `author_email`='$author_email_s',
            `publisher`='$publisher_s',
            `dlg_store`='$dlg_store_s',
            `dlgcustomer_receipt`='$em_receipt' ";

//create signature
$sig = "The Admin Team at www.website.com";
//to
$admin_email = "admin@website.com";
$to = array($author_email_s, $admin_email);

//setup email headers
$headers='From: ' . $admin_email . "\r\n" .
'Reply-To: ' . $admin_email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= $emailbody."\n\n";

//email subject and body
$subject = "Your book stats";
$message = "
Hi $author_name_s,<br />
I just wanted to send you a message and let you know that the book or
books below have just been purchased.<br /><br />

Store: $dlg_store_s<br />
Receipt: $em_receipt<br />
Sku Number: $sku_s<br /><br />

Book Title: $book_title_s<br />
Publisher: $publisher_s<br />
Product Number: $dlgprod_num_s<br />
Price: $dlgprod_price_s<br /><br />

Sincerely,<br />
$sig<br /><br />

To remove yourself from this notification, please send an email to
$admin_email with Unsubscribe in the subject line.
";

            if ($mysqli_s->multi_query($add_sql_s) === TRUE) {
            mail (implode(',', $to), $subject, $message, $headers);
            } else {
                echo "Error: " . $add_sql_s . "<br>" . $mysqli_s-
>error . "<br>" . $string;
            }

    }

}

?>
</code>```

答:
(Posted on behalf of the OP).

Thank you for all your help. I made a custom product with my email as the author for testing purposes. In the customers table I inserted products 111111 and 111110. However, in all_products I gave products 11111111 and 11111110. tHE end result is I made a mistake.

I hope you are able to learn something from this event. Knowledge is more important than my ego. Thank you!

Body:
Below is the fully functioning code. It works when I call it via the browser. However, I can't get my Cron job to run it. I have tried coming up with any solution and am open to any ideas that will make this script fire off once every hour 24/7 365 so to speak.

Info:

Hostgator

PHP 5.4

Link for Hostgator Cron commands: http://support.hostgator.com/articles/cpanel/what-do-i-put-for-the-cron-job-command?utm_source=cPanel&utm_medium=message&utm_campaign=Cron%20Jobs

I have tried the following:

When doing any of these I have yet to have it add a sale to the database or send a single email:

/opt/php54/bin/php /home1/user/public_html/Sales/scripts/sales-notif_em.php - Could not open input file: /home1/user/public_html/scripts/sales-notif_em.php

php /home1/user/public_html/Sales/scripts/sales-notif_em.php - blank email with nothing but this showing: Content-type: text/html

php -q /home1/lotscav1/public_html/Sales/scripts/sales_notif_em.php - I don't get any emails from the system of course

/usr/bin/curl home1/user/public_html/scripts/sales-notif_em.php - curl: (3)  malformed

any command (like php or /usr/bin/curl) that has the second half with http://website.c0m/Sales/scripts/sales_notif_em.php - causes a JSON Error when trying to add the Cron job

I have checked the following things:

File permissions are 655

Timestamp is less than an hour old under the customers table

Here is my code:

<?php
//find out current time and 1 hour ago
date_default_timezone_set('America/New_York');
$current_time = strtotime("now");
$hour_ago = strtotime('-1 hour');

//////////////////////////////////////////////////////////////////
/////////////////l// Connect to Sales Database  ///////////////////
//////////////////////////////////////////////////////////////////

$mysqli_s = new mysqli("localhost", "user", "password",
"server_sales_data");
if ($mysqli_s->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli_s->connect_errno . ")
" . $mysqli_s->connect_error;
}

//////////////////////////////////////////////////////////////////
///////////////////// Connect to EM Database  ////////////////////
//////////////////////////////////////////////////////////////////

$mysqli_em = new mysqli("localhost", "user", "password",
"server_dlgEM");
if ($mysqli_em->connect_errno) {
echo "Failed to connect to MySQL_EM: (" . $mysqli_em->connect_errno .
") " . $mysqli_em->connect_error;
}

//Grab store name
$dlg_store = "EM";

$em_request = "SELECT * FROM customers WHERE date BETWEEN '$hour_ago'
AND '$current_time'";
$em_result = mysqli_query($mysqli_em, $em_request) or die("Error No
Sales EM");
while ($em_row = mysqli_fetch_array($em_result)) {
$em_prod_num = $em_row["prod_num"];
$em_receipt = $em_row["receipt"];

//////////////////////////////////////////////////////////////////
///////////////////// Grab info for EM Sales  ////////////////////
//////////////////////////////////////////////////////////////////

$request_s = "SELECT * FROM all_products WHERE
dlgprod_num='$em_prod_num' AND dlg_store='$dlg_store'";
$result_s = mysqli_query($mysqli_s, $request_s) or die("Error dlg
prod num EM");
while ($row_s = mysqli_fetch_array($result_s)) {
        $sku_s = $row_s["sku"];
        $dlgprod_num_s = $row_s["dlgprod_num"];
        $book_title_s = addslashes($row_s["book_title"]);
        $dlgprod_price_s = $row_s["dlgprod_price"];
        $author_name_s = addslashes($row_s["author_name"]);
        $author_email_s = $row_s["author_email"];
        $publisher_s = $row_s["publisher"];
        $dlg_store_s = $row_s["dlg_store"];

            $add_sql_s  = "INSERT INTO all_author_sales SET
            `sku`='$sku_s',
            `dlgprod_num`='$dlgprod_num_s',
            `dlgprod_nam`='$book_title_s',
            `dlgprod_price`='$dlgprod_price_s',
            `author_name`='$author_name_s',
            `author_email`='$author_email_s',
            `publisher`='$publisher_s',
            `dlg_store`='$dlg_store_s',
            `dlgcustomer_receipt`='$em_receipt' ";

//create signature
$sig = "The Admin Team at www.website.com";
//to
$admin_email = "admin@website.com";
$to = array($author_email_s, $admin_email);

//setup email headers
$headers='From: ' . $admin_email . "\r\n" .
'Reply-To: ' . $admin_email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= $emailbody."\n\n";

//email subject and body
$subject = "Your book stats";
$message = "
Hi $author_name_s,

I just wanted to send you a message and let you know that the book or
books below have just been purchased.

Store: $dlg_store_s

Receipt: $em_receipt

Sku Number: $sku_s

Book Title: $book_title_s

Publisher: $publisher_s

Product Number: $dlgprod_num_s

Price: $dlgprod_price_s

Sincerely,

$sig

To remove yourself from this notification, please send an email to
$admin_email with Unsubscribe in the subject line.
";

            if ($mysqli_s->multi_query($add_sql_s) === TRUE) {
            mail (implode(',', $to), $subject, $message, $headers);
            } else {
                echo "Error: " . $add_sql_s . "
" . $mysqli_s-
>error . "
" . $string;
            }

    }

}

?>


问:
getpwuid and getgrgid causes segfault when user does not exist for given UID
I am running a C program in linux, which prints filename plus its user and group ownership. I am using getpwuid and getgrgid.

When file is owned by non-existent user (ie, there is no entry in /etc/passwd for given UID on my machine), my program segfaults with "terminated by signal 11".

How can I make my program behave same as ls, so that it prints numerical UID when user does not exist, instead of segfaulting?

Relevant code snippet is below:

```<code>lstat(filename,&fileStat)

struct group *grp;
struct passwd *pwd;

pwd = getpwuid(fileStat.st_uid);
printf(" %s", pwd->pw_name);

grp = getgrgid(fileStat.st_gid);
printf(" %s", grp->gr_name);
</code>```

答:
Looking at the man page GETPWUID(3P)

RETURN VALUE

The getpwuid() function shall return a pointer to a struct passwd
         with the structure as defined in  with a matching entry if
         found. A null pointer shall be returned if the requested entry is not
         found, or an error occurs. On error, errno shall be set to indicate
         the error.

Check for a null pointer before accessing anything, e.g.

```<code>pwd = getpwuid(fileStat.st_uid);
if (pwd) {
    printf(" %s", pwd->pw_name);
} else {
    // handle non-existing user entry
}
</code>```

Body:
I am running a C program in linux, which prints filename plus its user and group ownership. I am using getpwuid and getgrgid.

When file is owned by non-existent user (ie, there is no entry in /etc/passwd for given UID on my machine), my program segfaults with "terminated by signal 11".

How can I make my program behave same as ls, so that it prints numerical UID when user does not exist, instead of segfaulting?

Relevant code snippet is below:

lstat(filename,&fileStat)

struct group *grp;
struct passwd *pwd;

pwd = getpwuid(fileStat.st_uid);
printf(" %s", pwd->pw_name);

grp = getgrgid(fileStat.st_gid);
printf(" %s", grp->gr_name);

Body:
Looking at the man page GETPWUID(3P)

RETURN VALUE

The getpwuid() function shall return a pointer to a struct passwd
         with the structure as defined in  with a matching entry if
         found. A null pointer shall be returned if the requested entry is not
         found, or an error occurs. On error, errno shall be set to indicate
         the error.

Check for a null pointer before accessing anything, e.g.

pwd = getpwuid(fileStat.st_uid);
if (pwd) {
    printf(" %s", pwd->pw_name);
} else {
    // handle non-existing user entry
}


问:
SQL query from time_in column but not from time_out column
I'm using mysql. I have a table time_record. There are four columns namely id, time_in, time_out and students_id. I only want to query the record of the latest time_in of the student but if the latest record of the student is in time_out, it will not query. How do I query the student's latest time_in record if given that the student still does not times out?

Thanks

Here is my sample code (though it returns both records from timein and timeout)

```<code>select concat (
        st.student_fname,
        ' ',
        st.student_lname
        ) as 'Name',
    t.students_id,
    t.time_in,
    t.time_out,
    case
        when t.time_in > t.time_out
            then t.time_in
        else t.time_out
        end as MostRecentDate
from classes c
join student_classes s on c.id = s.classes_id
join timerecords t on t.students_id = s.students_id
join students st on s.students_id = st.student_id
where c.employees_id = 'sessionvalue2'
    and
where date (t.time_in) between date (now()) and date (now())
</code>```

答:
From what I understand, you want to query all results in which time_in is the latest entry and exclude results where time_out is the latest entry.

Try this:

SELECT DISTINCT(tr.id), tr.time_in
FROM time_record tr
WHERE tr.time_in > tr.time_out
ORDER BY tr.time_in DESC

Body:
I'm using mysql. I have a table time_record. There are four columns namely id, time_in, time_out and students_id. I only want to query the record of the latest time_in of the student but if the latest record of the student is in time_out, it will not query. How do I query the student's latest time_in record if given that the student still does not times out?

Thanks

Here is my sample code (though it returns both records from timein and timeout)

select concat (
        st.student_fname,
        ' ',
        st.student_lname
        ) as 'Name',
    t.students_id,
    t.time_in,
    t.time_out,
    case
        when t.time_in > t.time_out
            then t.time_in
        else t.time_out
        end as MostRecentDate
from classes c
join student_classes s on c.id = s.classes_id
join timerecords t on t.students_id = s.students_id
join students st on s.students_id = st.student_id
where c.employees_id = 'sessionvalue2'
    and
where date (t.time_in) between date (now()) and date (now())


问:
List with position of certain values of a matrix
I have a matrix with 1 and 0 in it. For example:

```<code>M1 = matrix(c(1, 0, 1, 0, 1, 0), nrow=2, ncol=3, byrow = TRUE)
row.names(M1) <- c(100, 101)
colnames(M1) <- c("A", "B", "C")
M1

    A B C
100 1 0 1
101 0 1 0
</code>```

Now I want to create a list of all the values=1 in the matrix with the following syntax:

```<code>"row name"."column name", value
</code>```

In this example the solution I'm looking for would be:

```<code>100.A, 1
100.C, 1
101.B, 1
</code>```

答:
Try this:

```<code>paste0(row.names(M1==1), ".", colnames(M1==1))
</code>```

Or if you want to add 1:

```<code>data.frame(result = paste0(row.names(M1==1), ".", colnames(M1==1), ", 1"))
</code>```

EDIT: correct when 1 more than 1 time

```<code>result <- list()
for (i in 1:nrow(M1)){
  result[[i]] <- data.frame(result = paste0(rep(row.names(M1)[i], length(colnames(M1)[M1[i,]==1])), ".", colnames(M1)[M1[i,]==1], ", 1"))
}
result <- do.call(rbind, result)
result <- unique(result)
</code>```

Body:
I have a matrix with 1 and 0 in it. For example:

M1 = matrix(c(1, 0, 1, 0, 1, 0), nrow=2, ncol=3, byrow = TRUE)
row.names(M1) <- c(100, 101)
colnames(M1) <- c("A", "B", "C")
M1

    A B C
100 1 0 1
101 0 1 0

Now I want to create a list of all the values=1 in the matrix with the following syntax:

"row name"."column name", value

In this example the solution I'm looking for would be:

100.A, 1
100.C, 1
101.B, 1

Body:
Try this:

paste0(row.names(M1==1), ".", colnames(M1==1))

Or if you want to add 1:

data.frame(result = paste0(row.names(M1==1), ".", colnames(M1==1), ", 1"))

EDIT: correct when 1 more than 1 time

result <- list()
for (i in 1:nrow(M1)){
  result[[i]] <- data.frame(result = paste0(rep(row.names(M1)[i], length(colnames(M1)[M1[i,]==1])), ".", colnames(M1)[M1[i,]==1], ", 1"))
}
result <- do.call(rbind, result)
result <- unique(result)


问:
Inner / static nested classes in Java - outer class' name
I'd like to ask when it's required to explicitly write the name of the outer class when referring to the inner class or static nested class.

Ex:

```<code>class B {
    static class Inner {
        int a = 10;
    }
}

class Test extends B {
    public static void main(String[] args) {
        Test t = new Test();
        Inner obj = new Inner();
        System.out.println(obj.a);
    }
}
</code>```

What I'd like to ask is under which circumstances it's needed to write:

```<code>B.Inner obj = new B.Inner();
</code>```

instead of

```<code>Inner obj = new Inner();
</code>```

答:
For static nested classes (as G. Fiedler has mentioned in his answer) you can write new Inner() when you are within the scope of B.

You can also directly refer to Inner from within Test because it extends B.

In all other cases you need to say B.Inner and new B.Inner().

Inner classes - which are not static by definition - are initialized differently. Let's look at this example B:

```<code>class B {
    public class Inner {
        ...
    }
}
</code>```

Inner classes are always tied to an instance of the outer class. That means that in this case there has to be an instance of B for us to be able to instantiate Inner. So let's do that:

```<code>B b = new B();
</code>```

I'm by the way assuming we are currently somewhere outside of the scope of B

In order to create an instance of Inner we use our instance of B and write:

```<code>B.Inner inner = b.new Inner();
</code>```

If we were inside of B (in a non-static method) we could, however, simply write

```<code>Inner inner = new Inner();
</code>```

because we - or rather the compiler - know(s) that an instance of B has to exist for this inner to be tied to.

Body:
I'd like to ask when it's required to explicitly write the name of the outer class when referring to the inner class or static nested class.

Ex:

class B {
    static class Inner {
        int a = 10;
    }
}

class Test extends B {
    public static void main(String[] args) {
        Test t = new Test();
        Inner obj = new Inner();
        System.out.println(obj.a);
    }
}

What I'd like to ask is under which circumstances it's needed to write:

B.Inner obj = new B.Inner();

instead of

Inner obj = new Inner();

Body:
For static nested classes (as G. Fiedler has mentioned in his answer) you can write new Inner() when you are within the scope of B.

You can also directly refer to Inner from within Test because it extends B.

In all other cases you need to say B.Inner and new B.Inner().

Inner classes - which are not static by definition - are initialized differently. Let's look at this example B:

class B {
    public class Inner {
        ...
    }
}

Inner classes are always tied to an instance of the outer class. That means that in this case there has to be an instance of B for us to be able to instantiate Inner. So let's do that:

B b = new B();

I'm by the way assuming we are currently somewhere outside of the scope of B

In order to create an instance of Inner we use our instance of B and write:

B.Inner inner = b.new Inner();

If we were inside of B (in a non-static method) we could, however, simply write

Inner inner = new Inner();

because we - or rather the compiler - know(s) that an instance of B has to exist for this inner to be tied to.


答:
When you call deposit(balance1, depAmnt), you do not save the return value anywhere. Note that that method increments the value of the variable balance1 that is local to the deposit() method, not the one that is in main().

You will encounter a lot of problems when using a double to store the value of the account. You should use a long int to save the number of cents instead.

For example, if you add $0.01 one hundred times, you might be surprised what happens when you withdraw $1.00

Title: Issue with a double value


问:
Get selected option and all request data in twig form
I have this form in twig, and I want to get the selected option and the value of the input field from a simple html form:

(PS: Don't say 'You'd better generate a form using the controller!' I know that, but I have a reason why I want to create a form in twig: because that allows me to create as many forms as I want using a for loop.)

I tried to pass arguments in the action path, but that didn't work.

<form action="{{ path('changeProf') }}" method="post" id="form">

             <input type="text" value="{{ user.id }}" disabled="true" id="iduser"style="max-width: 18vmin;"/>

            {% set k=1 %}
                <select id="profil">
                {% for prof in profArr %}
                    <option value="{{ prof }}"> {{ prof }} </option>
                {% endfor %}
                </select>

    <input type="submit" class="btn btn-info btn-xs" style="position: relative;top:18vmin;left:-28%">
</form>
```
<p>This is the action that handles the form :</p>
<pre class="lang-php prettyprint-override"><code>/**
 * @Route("/profile/chProf",name="changeProf")
 * Method ("POST")
 * @Template()
 */
public function changeProfAction(Request $request)
{
    $session = new Session();
    $session->start();
    $search = $session->get('user');
    $gestAcces = $session->get('acces');
    $gestEtat = $session->get('etatUser');
    $gestCont = $session->get('contenu');
    $repMsg = $session->get('repMsg');
    $gestRec = $session->get('Reclam');
    $gestMess = $session->get('gestMess');
    $gestMp = $session->get('gestMp');

    if ($search == Null) {
        return $this->redirectToRoute('empty', array('search' => $search,
            'contenu' => $gestCont,
            'gestAcces' => $gestAcces,
            'gestEtat' => $gestEtat,
            'repMsg' => $repMsg,
            'gestRec' => $gestRec,
            'gestMess' => $gestMess,
            'gestMp' => $gestMp,
        ));
    }

    $em = $this
        ->getDoctrine()
        ->getManager();
    $reposit = $em->getRepository("CNAMCMSBundle:userprof");
    $rep = $em->getRepository("CNAMCMSBundle:profil");

    $userprof=new userprof();
    $libprof=$request->request->get('profil');
    $iduser=$request->request->get('iduser');

    $idprof=$rep->findOneBy(array('libelle'=>$libprof));
    $userprof->setIdUser($iduser);
    $userprof->setIdProfil($idprof);
    $em->persist($userprof);
    $em->flush();

    return $this->render('CNAMCMSBundle:Default:userProf.html.twig', array(
        'search'=>$search,
        'contenu'=>$gestCont,
        'gestAcces'=>$gestAcces,
        'gestEtat'=>$gestEtat,
        'repMsg'=>$repMsg,
        'gestRec'=>$gestRec,
        'gestMess'=>$gestMess,
        'gestMp'=>$gestMp,

    ));

}
</code>```

答:
I think I found out what caused the error you receive.

$request->request->get('profil'); returns NULL.

This means, the form did not send a profil entry.

Look where is the profil in the form:

```<code><input type="text" value="{{ user.id }}" disabled="true" id="iduser"style="max-width: 18vmin;"/>
</code>```

There is no name attribute! Which is actually what is sent with the request. The name attribute, not the id. The id is used only for local styles and javascripts.

The solution:

```<code><input type="text" value="{{ user.id }}" disabled="true" id="iduser" name="iduser" style="max-width: 18vmin;"/>
</code>```

Do the same for profil

Hope this helps.

ContentLicense: CC BY-SA 4.0

Body:
I have this form in twig, and I want to get the selected option and the value of the input field from a simple html form:

(PS: Don't say 'You'd better generate a form using the controller!' I know that, but I have a reason why I want to create a form in twig: because that allows me to create as many forms as I want using a for loop.)

I tried to pass arguments in the action path, but that didn't work.

<form action="{{ path('changeProf') }}" method="post" id="form">

             <input type="text" value="{{ user.id }}" disabled="true" id="iduser"style="max-width: 18vmin;"/>

            {% set k=1 %}
                <select id="profil">
                {% for prof in profArr %}
                    <option value="{{ prof }}"> {{ prof }} </option>
                {% endfor %}
                </select>

    <input type="submit" class="btn btn-info btn-xs" style="position: relative;top:18vmin;left:-28%">
</form>

This is the action that handles the form :

/**
 * @Route("/profile/chProf",name="changeProf")
 * Method ("POST")
 * @Template()
 */
public function changeProfAction(Request $request)
{
    $session = new Session();
    $session->start();
    $search = $session->get('user');
    $gestAcces = $session->get('acces');
    $gestEtat = $session->get('etatUser');
    $gestCont = $session->get('contenu');
    $repMsg = $session->get('repMsg');
    $gestRec = $session->get('Reclam');
    $gestMess = $session->get('gestMess');
    $gestMp = $session->get('gestMp');

    if ($search == Null) {
        return $this->redirectToRoute('empty', array('search' => $search,
            'contenu' => $gestCont,
            'gestAcces' => $gestAcces,
            'gestEtat' => $gestEtat,
            'repMsg' => $repMsg,
            'gestRec' => $gestRec,
            'gestMess' => $gestMess,
            'gestMp' => $gestMp,
        ));
    }

    $em = $this
        ->getDoctrine()
        ->getManager();
    $reposit = $em->getRepository("CNAMCMSBundle:userprof");
    $rep = $em->getRepository("CNAMCMSBundle:profil");

    $userprof=new userprof();
    $libprof=$request->request->get('profil');
    $iduser=$request->request->get('iduser');

    $idprof=$rep->findOneBy(array('libelle'=>$libprof));
    $userprof->setIdUser($iduser);
    $userprof->setIdProfil($idprof);
    $em->persist($userprof);
    $em->flush();

    return $this->render('CNAMCMSBundle:Default:userProf.html.twig', array(
        'search'=>$search,
        'contenu'=>$gestCont,
        'gestAcces'=>$gestAcces,
        'gestEtat'=>$gestEtat,
        'repMsg'=>$repMsg,
        'gestRec'=>$gestRec,
        'gestMess'=>$gestMess,
        'gestMp'=>$gestMp,

    ));

}

Body:
I think I found out what caused the error you receive.

$request->request->get('profil'); returns NULL.

This means, the form did not send a profil entry.

Look where is the profil in the form:

<input type="text" value="{{ user.id }}" disabled="true" id="iduser"style="max-width: 18vmin;"/>

There is no name attribute! Which is actually what is sent with the request. The name attribute, not the id. The id is used only for local styles and javascripts.

The solution:

<input type="text" value="{{ user.id }}" disabled="true" id="iduser" name="iduser" style="max-width: 18vmin;"/>

Do the same for profil

Hope this helps.


问:
lost password for import key file - vs2008
Have the project but the original developer, gone to greener pastures, did not provide the password to import the key file for signing the library. What is the best solution to unlock the file?</p>

答:
Contact the original developer.

Failing that, get a new keyfile.


问:
Why same code builded with javac and gradle behave different?
```<code>switch (readChoice()) {
  //options
}

private static int readChoice() {
    String input;
    int choice = -1;
    try {
        input = scanner.next();
        choice = Integer.parseInt(input);
    } catch (NumberFormatException e) {
        logger.error("Error while trying to read choice from the console", e);
        }
    }
    return choice;

}
</code>```

When i build this code with javac, everything works fine. But when i try to run code builded with gradle, i get this

```<code>Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at edu.java.core.cinema.Main.readChoice(Main.java:207)
    at edu.java.core.cinema.Main.main(Main.java:42)
</code>```

42 - there is switch, 207 - there is scanner.next().
Scanner tries to read choice, when there is nothing to read.
I just started to learn gradle, so maybe i did mistake with building.
I build and run project with gradle wrapper

```<code>$ gradle wrapper --gradle-version 3.4
$ ./gradlew build
$ ./gradlew run
</code>```

UPDATE:
There is build.gradle file

```<code>apply plugin: 'idea'
apply plugin: 'java'
apply plugin: 'application'

mainClassName = 'edu.java.core.cinema.Main'

repositories {
    mavenCentral()
}

jar {
    baseName = 'lab2'
    version =  '0.1.0'
}

sourceSets.main.java.srcDirs = ["src"]

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
   compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0'

   compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.2'

   compile group: 'ch.qos.logback', name: 'logback-core', version: '1.2.2'

   compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'

}
</code>```

答:
In your gradle build file add

```<code>run {
    standardInput = System.in
}
</code>```

to redirect the "gradle input" to system.in. If you don't it's empty and will fail when trying to read input.

Body:
switch (readChoice()) {
  //options
}

private static int readChoice() {
    String input;
    int choice = -1;
    try {
        input = scanner.next();
        choice = Integer.parseInt(input);
    } catch (NumberFormatException e) {
        logger.error("Error while trying to read choice from the console", e);
        }
    }
    return choice;

}

When i build this code with javac, everything works fine. But when i try to run code builded with gradle, i get this

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at edu.java.core.cinema.Main.readChoice(Main.java:207)
    at edu.java.core.cinema.Main.main(Main.java:42)

42 - there is switch, 207 - there is scanner.next().
Scanner tries to read choice, when there is nothing to read.
I just started to learn gradle, so maybe i did mistake with building.
I build and run project with gradle wrapper

$ gradle wrapper --gradle-version 3.4
$ ./gradlew build
$ ./gradlew run

UPDATE:
There is build.gradle file

apply plugin: 'idea'
apply plugin: 'java'
apply plugin: 'application'

mainClassName = 'edu.java.core.cinema.Main'

repositories {
    mavenCentral()
}

jar {
    baseName = 'lab2'
    version =  '0.1.0'
}

sourceSets.main.java.srcDirs = ["src"]

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
   compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0'

   compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.2'

   compile group: 'ch.qos.logback', name: 'logback-core', version: '1.2.2'

   compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'

}

Body:
In your gradle build file add

run {
    standardInput = System.in
}

to redirect the "gradle input" to system.in. If you don't it's empty and will fail when trying to read input.


问:
Django filter by min value
Right now I have this:

```<code>status = request.GET.get('status')
persons = Person.objects.filter(vip_status= status)
</code>```

How do I select all persons with vip_status > status? I tried this:

```<code>persons = Person.objects.filter(vip_status >  status)
</code>```

But it didn't work.

答:
There are a number of different filter lookup clauses:

https://docs.djangoproject.com/en/1.10/ref/models/querysets/#field-lookups

You want to use the gt for greater than, (or gte for greater than or equal to). The syntax is to add it after the field lookup with a double underscore:

```<code>persons = Person.objects.filter(vip_status__gt  status)
</code>```

Title: Django filter by min value

Body:
Right now I have this:

status = request.GET.get('status')
persons = Person.objects.filter(vip_status= status)

How do I select all persons with vip_status > status? I tried this:

persons = Person.objects.filter(vip_status >  status)

But it didn't work.

Body:
There are a number of different filter lookup clauses:

https://docs.djangoproject.com/en/1.10/ref/models/querysets/#field-lookups

You want to use the gt for greater than, (or gte for greater than or equal to). The syntax is to add it after the field lookup with a double underscore:

persons = Person.objects.filter(vip_status__gt  status)


问:
Can I connect to remote DB server from inside docker container?
My app is running against a mssql server 2012 or above,

I tried to set up 2 containers - 1 for my app and one to be a DB server.

But I couldn't use the DB container due to mssql server version windows image is not supported by my app.

So I'm want to connect to a remote DB server that I have which is a different server than the Docker host.

How do I get the container to ping the remote DB server?

From the container-

```<code>C:\Installation>ping  my0134.company.net
Ping request could not find host my0134.company.net. Please check the name and try again.
</code>```

** NOTE - I am using Docker on windows

答:
Maybe you could try adding <IP of my0134.company.net> my0134.company.net to the etc/hosts file. This way the url can be resolved to a IP address. You can also just use

docker run --add-host 'my0134.company.net':<IP of my0134.company.net> <image>

to spin up your container.

Body:
My app is running against a mssql server 2012 or above,

I tried to set up 2 containers - 1 for my app and one to be a DB server.

But I couldn't use the DB container due to mssql server version windows image is not supported by my app.

So I'm want to connect to a remote DB server that I have which is a different server than the Docker host.

How do I get the container to ping the remote DB server?

From the container-

C:\Installation>ping  my0134.company.net
Ping request could not find host my0134.company.net. Please check the name and try again.

** NOTE - I am using Docker on windows


问:
Replacement for GL_LUMINANCE_ALPHA in core profile?
I am making a game engine and only recently updated it to core profile OpenGL. After doing so I discovered that GL_LUMINANCE_ALPHA, which I use for font textures, is deprecated. After replacing it with GL_RG, I have the areas that should be alpha red, and the area that should be white green!

GL_RG result...

This of course is not what I want! Is there any way to swizzle mask this back to the way I want it?

答:
OK, I found the answer by just fooling around with the swizzle mask values, and here is how I reverted it back to normal:

```<code>glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_RED);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_GREEN);
</code>```

This made it look perfectly normal again!

Body:
OK, I found the answer by just fooling around with the swizzle mask values, and here is how I reverted it back to normal:

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_RED);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_GREEN);

This made it look perfectly normal again!