问:
Roku - ButtonGroup advance focus with left and right keys
I am pretty new to Roku world. I smell like its a very simple and straight forward question, but was not able to figure out any solutions. Any help would be much appreciated.

I was trying to create a sample application which includes three button in the UI. So, I chose ButttonGroup to do this usecase.

```<code><ButtonGroup id="btnGroup" layoutDirection="horiz"
                    visible="true" translation="[90,601]"
                    itemSpacings="[20,20]" minWidth="240"
                    maxWidth="240" buttonHeight="80">

                <Button id="button1" text="" iconUri="" focusedIconUri=""
                        focusFootprintBitmapUri="pkg:"
                        focusBitmapUri="pkg"/>

                <Button id="button2" text="" iconUri="" focusedIconUri=""
                        focusFootprintBitmapUri="pkg:"
                        focusBitmapUri="pkg:"/>

                <Button id="button3" text="" iconUri="" focusedIconUri=""
                        focusFootprintBitmapUri="pkg:"
                        focusBitmapUri="pkg:"/>
        </ButtonGroup>
</code>```

The thing is that i am able to advance through this buttons with "up" and "down" key of the remote, where i actually need this to be done with "left" and "right" key.

As i have set the layoutDirection value to horiz, i thought the advance and reverse key would automatically changes to "right" and "left" respectively. Doesn't seems like its working as expected. Am i missing something here? Please help.

答: From Roku Documents: "The ButtonGroup node class manages the layout, visual attributes, and focus management of a VERTICAL list of Button nodes." So it will work only with vertical buttons!Btw, I don't like Roku default ones or ButtonGroup. You can create your own buttons component. And in that component, In onKey event you can define different behaviour for vertical and horizontal button layouts. Based on that, I think your approach is just fine.</p>

Body:
I am pretty new to Roku world. I smell like its a very simple and straight forward question, but was not able to figure out any solutions. Any help would be much appreciated.

I was trying to create a sample application which includes three button in the UI. So, I chose ButttonGroup to do this usecase.

<ButtonGroup id="btnGroup" layoutDirection="horiz"
                    visible="true" translation="[90,601]"
                    itemSpacings="[20,20]" minWidth="240"
                    maxWidth="240" buttonHeight="80">

                <Button id="button1" text="" iconUri="" focusedIconUri=""
                        focusFootprintBitmapUri="pkg:"
                        focusBitmapUri="pkg"/>

                <Button id="button2" text="" iconUri="" focusedIconUri=""
                        focusFootprintBitmapUri="pkg:"
                        focusBitmapUri="pkg:"/>

                <Button id="button3" text="" iconUri="" focusedIconUri=""
                        focusFootprintBitmapUri="pkg:"
                        focusBitmapUri="pkg:"/>
        </ButtonGroup>

The thing is that i am able to advance through this buttons with "up" and "down" key of the remote, where i actually need this to be done with "left" and "right" key.

As i have set the layoutDirection value to horiz, i thought the advance and reverse key would automatically changes to "right" and "left" respectively. Doesn't seems like its working as expected. Am i missing something here? Please help.


来源: stackexchange

问:
CardView with RecyclerView/ListView in ScrollView
tl;dr: How to achieve the layout shown in the screenshot below? Placing ListView to a ScrollView is apparently not recommended, but is there actually any other way to achieve it?

The whole question: I want to have multiple CardViews in my app, and one (or more) of them will have either RecyclerView or ListView in it (it doesn't really matter to me which one of those). The whole view is supposed to be scrollable - not only the ListViews in their parent CardViews. I basically need to achieve similar layout as the Play Store app has.

The first option I tried was this (the code is obviously simplified):

```<code><LinearLayout android:orientation="vertical">
    <CardView>
        <!-- Some content of the first card. -->
    </CardView>
    <CardView>
        <ListView/>
    </CardView>
</LinearLayout>
</code>```

The result was not what I wanted, the ListView was only scrollable in its parent CardView but the whole view wasn't scrollable like it is in the Play Store app. So now I wrapped it all in a ScrollView:

```<code><ScrollView
    android:fillViewport="true"
    android:isScrollContainer="true">
    <LinearLayout orientation="vertical">
        <CardView>
            <!-- Some content of the first card. -->
        </CardView>
        <CardView>
            <ListView/>
        </CardView>
    </LinearLayout>
</ScrollView>
</code>```

And I programmatically set the height of the bottom card to fit the ListView's height (number of elements in the ListView * height of one list item element). Now the whole view is scrollable, and the bottom card's height is the same as the height of the ListView, so the ListView isn't scrollable inside the CardView which is exactly what I wanted.

Now the actual problem: I got it working as described above, but I know this particular issue (ListView in a ScrollView) has been asked about many times before and the answer has always been the same - don't put neither RecyclerView nor ListView in a ScrollView because it causes performance problems. Well, so what's the correct approach then? How did Google do it in the Play Store app? I tried decompiling the Play Store app with APKTool but there weren't any layout files (maybe I did something wrong). Is my approach correct? My ListView will only display a few items (I guess it will be at most 20 items) - will it cause some performance issues in this case?

I wouldn't ask about this if all the answers wouldn't always mention that we shouldn't put ListView in a ScrollView. Is there any other way how to achieve the layout described by the screenshot above?

答:
I would recommend you to use Sectioned RecyclerView for this purpose. Every single item layout would have a cardView in it instead of creating a cardView as a parent.

Refer to this library: https://github.com/luizgrp/SectionedRecyclerViewAdapter

ContentLicense: CC BY-SA 3.0

Body:
tl;dr: How to achieve the layout shown in the screenshot below? Placing ListView to a ScrollView is apparently not recommended, but is there actually any other way to achieve it?

The whole question: I want to have multiple CardViews in my app, and one (or more) of them will have either RecyclerView or ListView in it (it doesn't really matter to me which one of those). The whole view is supposed to be scrollable - not only the ListViews in their parent CardViews. I basically need to achieve similar layout as the Play Store app has.

The first option I tried was this (the code is obviously simplified):

<LinearLayout android:orientation="vertical">
    <CardView>

    </CardView>
    <CardView>
        <ListView/>
    </CardView>
</LinearLayout>

The result was not what I wanted, the ListView was only scrollable in its parent CardView but the whole view wasn't scrollable like it is in the Play Store app. So now I wrapped it all in a ScrollView:

<ScrollView
    android:fillViewport="true"
    android:isScrollContainer="true">
    <LinearLayout orientation="vertical">
        <CardView>

        </CardView>
        <CardView>
            <ListView/>
        </CardView>
    </LinearLayout>
</ScrollView>

And I programmatically set the height of the bottom card to fit the ListView's height (number of elements in the ListView * height of one list item element). Now the whole view is scrollable, and the bottom card's height is the same as the height of the ListView, so the ListView isn't scrollable inside the CardView which is exactly what I wanted.

Now the actual problem: I got it working as described above, but I know this particular issue (ListView in a ScrollView) has been asked about many times before and the answer has always been the same - don't put neither RecyclerView nor ListView in a ScrollView because it causes performance problems. Well, so what's the correct approach then? How did Google do it in the Play Store app? I tried decompiling the Play Store app with APKTool but there weren't any layout files (maybe I did something wrong). Is my approach correct? My ListView will only display a few items (I guess it will be at most 20 items) - will it cause some performance issues in this case?

I wouldn't ask about this if all the answers wouldn't always mention that we shouldn't put ListView in a ScrollView. Is there any other way how to achieve the layout described by the screenshot above?


问:
Recursion with Pointers in C
```<code>    #include <stdio.h>
    int x=2,y=4,z=17,w=3,count=0;

    void p(int z,int *x){
        *x= 3*z - *x;
        int  w=*x+z;
        printf("%d %d %d %d \n",*x,y,z,w);
        if(*x<=y){
           p(*x+1,&w);
           printf("%d %d %d %d \n",*x,y,z,w);
        }
     }

   int main(void){

       p(1,&x);
       printf("%d %d %d %d \n",x,y,z,w);
       return 0;
    }
</code>```

I try to run this code by hand in order to take the output but the results that i produce by hand are different from the output which i have when i compile and execute it.
Can anyone explain to me in detail how the output of the program is created ?

The output that is supposed to give is

```<code>1 4 1 2
4 4 2 6
9 4 5 14
4 4 2 9
1 4 1 4
1 4 17 3
</code>```

答: If you want to process this by hand, you should draw a stack in a paper and push values of x, y, z, w before every recursive call, & pop them in the end. Since we have one recursive call in the procedure, i think that would be easy to do.</p>

Title: Recursion with Pointers in C

Body:
    #include <stdio.h>
    int x=2,y=4,z=17,w=3,count=0;

    void p(int z,int *x){
        *x= 3*z - *x;
        int  w=*x+z;
        printf("%d %d %d %d \n",*x,y,z,w);
        if(*x<=y){
           p(*x+1,&w);
           printf("%d %d %d %d \n",*x,y,z,w);
        }
     }

   int main(void){

       p(1,&x);
       printf("%d %d %d %d \n",x,y,z,w);
       return 0;
    }

I try to run this code by hand in order to take the output but the results that i produce by hand are different from the output which i have when i compile and execute it.
Can anyone explain to me in detail how the output of the program is created ?

The output that is supposed to give is

1 4 1 2
4 4 2 6
9 4 5 14
4 4 2 9
1 4 1 4
1 4 17 3


问:
Terraform template_file get pass all received variables to a function
is there in Terraforom in template_files a way to pass through all the received variables to other place?
I mean something similar than $@ in bash.

For example:

```<code>resource "template_file" "some_template" {
    template = "my_template.tpl")}"
    vars {
        var1 = "value1"
        var2 = "value2"
    }
}
</code>```

and then from the rendered file:

```<code>#!/bin/bash
echo "Var1: ${var1}"
echo "Var2: ${var2}"

echo "But I want it in someway similar to this:"
for v in $@; do
  echo "$v";
done
</code>```

答:
According to the documentation, no.

From https://www.terraform.io/docs/providers/template/d/file.html

Variables for interpolation within the template. Note that variables
  must all be primitives. Direct references to lists or maps will cause
  a validation error.

Primitives in terraform are string, number and boolean.

So it means you can not pass a hash or a list to group all the variables in one.

Body:
is there in Terraforom in template_files a way to pass through all the received variables to other place?
I mean something similar than $@ in bash.

For example:

resource "template_file" "some_template" {
    template = "my_template.tpl")}"
    vars {
        var1 = "value1"
        var2 = "value2"
    }
}

and then from the rendered file:

#!/bin/bash
echo "Var1: ${var1}"
echo "Var2: ${var2}"

echo "But I want it in someway similar to this:"
for v in $@; do
  echo "$v";
done


问:
Cycling images with javascript
Why doesn't the second (hawk) image appear when the button is clicked? It goes straight to the else statement showing the ant image. </p>

```<code><!DOCTYPE html>
<html>
    <body>
        <script>
            function changeImg() {
                if (document.getElementById("cycle").src == "fox.jpg") {
                    document.getElementById("cycle").src = "hawk.jpg";
                } else {
                    document.getElementById("cycle").src = "ant.jpg";
                }
            }
        </script>

        <button onclick = "changeImg()">change image</button>
        <img id ="cycle" src ="fox.jpg"/>
    </body>
</html>
</code>```

答:
document.getElementById("cycle").src always has full url of image (example:https://example.loc/example/fox.jpg) and this is not similar  from fox.jpg.
You need try another solution.Try use
 cycle.getAttribute('src')

Example code:

```<code>function changeImg() {
          let cycle = document.getElementById("cycle");
               console.log(cycle.src,cycle.getAttribute('src')); // show real value and taribute
            if (cycle.getAttribute('src') == "fox.jpg") {
                cycle.src = "hawk.jpg";
            } else {cycle.src = "ant.jpg";
            }
        }
</code>```

Title: Cycling images with javascript

Body:
Why doesn't the second (hawk) image appear when the button is clicked? It goes straight to the else statement showing the ant image.

<!DOCTYPE html>

        <button onclick = "changeImg()">change image</button>

Body:
document.getElementById("cycle").src always has full url of image (example:https://example.loc/example/fox.jpg) and this is not similar  from fox.jpg.
You need try another solution.Try use
 cycle.getAttribute('src')

Example code:

function changeImg() {
          let cycle = document.getElementById("cycle");
               console.log(cycle.src,cycle.getAttribute('src')); // show real value and taribute
            if (cycle.getAttribute('src') == "fox.jpg") {
                cycle.src = "hawk.jpg";
            } else {cycle.src = "ant.jpg";
            }
        }


问:
RPM spec variable for (sub)package name?
RPM spec files have many special variables available within them. Do any of these variables expose the name of the current package being processed?

For single-package RPMs, the answer would be obvious, but a single spec can also produce multiple RPMs. Is there a variable, such as $RPM_PACKAGE_NAME, that rpmbuild automatically updates to align with the current %files or %pre or %post section?

答:
I don't see anything obvious in the RPM source code.  There does not seem to be a possibility to access the current list of defined subpackages using RPM macros, or the package header under construction, neither using RPM macros or Lua.

What we use instead is to generate the entire package stanza in Lua, using the built-in Lua interpreter.  An example is in glibc.spec; search for “Array of languages” and %package langpack-]]..lang..[[.  Note that the syntax highlighting in the Pagure viewer is a bit off, it is confused by this cross-language nesting.


问:
Lambda as apply function for dask dataframe
I am trying to use lambdas as function to apply to a dask dataframe in a for loop creating a list of dask dataframe.
When I compute each dataframe, they all use the last lambda expression instead of the one asigned during the loop.

Example:

```<code>ddf = dataframe.from_pandas(pd.DataFrame([[1, 10],[1, 5],[2, 9],[2, 4]],
columns=['group', 'value']), npartitions=2)
ddfs = []
for val in [2, 100]:
    ddfs.append(ddf.groupby('group').apply(lambda x : x.sum()+val))
</code>```

Output:

```<code>ddfs[0].compute()

group   value
2   104 113
1   102 115

ddfs[1].compute()

group   value
2   104 113
1   102 115
</code>```

I would think that they are not supposed to be the same the first is supposed to be

```<code>group   value
2   6   15
1   4   17
</code>```

What gives?

答:
This is a scoping problem with python itself. When the function is executed, it looks for the value of val in the global scope, it is not bound in the function closure.

To fix, you need to use an optional keyword parameter, which is evaluated at declaration time, and so bound:

```<code>for val in [2, 100]:
   ddfs.append(ddf.groupby('group').apply(lambda x, val=val: x.sum()+val))
</code>```

Body:
I am trying to use lambdas as function to apply to a dask dataframe in a for loop creating a list of dask dataframe.
When I compute each dataframe, they all use the last lambda expression instead of the one asigned during the loop.

Example:

ddf = dataframe.from_pandas(pd.DataFrame([[1, 10],[1, 5],[2, 9],[2, 4]],
columns=['group', 'value']), npartitions=2)
ddfs = []
for val in [2, 100]:
    ddfs.append(ddf.groupby('group').apply(lambda x : x.sum()+val))

Output:

ddfs[0].compute()

group   value
2   104 113
1   102 115

ddfs[1].compute()

group   value
2   104 113
1   102 115

I would think that they are not supposed to be the same the first is supposed to be

group   value
2   6   15
1   4   17

What gives?

Body:
This is a scoping problem with python itself. When the function is executed, it looks for the value of val in the global scope, it is not bound in the function closure.

To fix, you need to use an optional keyword parameter, which is evaluated at declaration time, and so bound:

for val in [2, 100]:
   ddfs.append(ddf.groupby('group').apply(lambda x, val=val: x.sum()+val))


问:
Event Handler on component in Reactjs
This is not firing on the component but when I attach my event handler to a div it works. Do I need to pass a prop types function in my child component?</p>

```<code>const buttonStyle = {
  color: 'red'
};

class Button extends React.Component {
    render() {
        return (
          <a className="social-button twitter">
            <i href="#" className="fa fa-twitter"></i>
          </a>
        )};
}

class PanelButtons extends React.Component {
  constructor(props){
    super(props);
    }

  handleClick() {
    console.log('this is:');
  }

    render() {
        return (
          <div>
          <div onClick={(e) => this.handleClick(e)}> {/*this works attaching it to a div*/}
            CLick me
            </div>
            <div className="social-buttons">
                <Button onClick={(e) => this.handleClick(e)} />{/*does now work attaching it to a component*/}
            </div>
           </div>
        )
    }
}

ReactDOM.render(<PanelButtons />,  document.querySelector('body'));
</code>```

答:
You should pass down the props into <Button /> component

```<code>class Button extends React.Component {
    render() {
        return (
          <a className="social-button twitter" {...this.props}>
            <i href="#" className="fa fa-twitter"></i>
          </a>
        )};
}
</code>```

More reading: JSX spread attributes

Title: Event Handler on component in Reactjs

Body:
This is not firing on the component but when I attach my event handler to a div it works. Do I need to pass a prop types function in my child component?

const buttonStyle = {
  color: 'red'
};

class Button extends React.Component {
    render() {
        return (

        )};
}

class PanelButtons extends React.Component {
  constructor(props){
    super(props);
    }

  handleClick() {
    console.log('this is:');
  }

    render() {
        return (

 this.handleClick(e)}> {/*this works attaching it to a div*/}
            CLick me

                <Button onClick={(e) => this.handleClick(e)} />{/*does now work attaching it to a component*/}

        )
    }
}

ReactDOM.render(<PanelButtons />,  document.querySelector('body'));

Body:
You should pass down the props into <Button /> component

class Button extends React.Component {
    render() {
        return (
          <a className="social-button twitter" {...this.props}>
            <i href="#" className="fa fa-twitter"></i>
          </a>
        )};
}

More reading: JSX spread attributes


问:
Open PDF in new browser full window
How do I open PDF document in new browser window?

The window should be full and withouth menu.

Just a PDF document in a clean full window with native Javascript or jQuery.

答:
I'm going to take a chance here and actually advise against this. I suspect that people wanting to view your PDFs will already have their viewers set up the way they want, and will not take kindly to you taking that choice away from them :-)

Why not just stream down the content with the correct content specifier?

That way, newbies will get whatever their browser developer has a a useful default, and those of us that know how to configure such things will see it as we want to.

Title: Open PDF in new browser full window

ContentLicense: CC BY-SA 2.5


问:
Filter on keyof type parameter in typescript
No need to know React, just some background: in my use case, I want to amplify user specified React.ComponentClass with my custom Higher Order Component. In order to do so, I want user to also send me list of names of the particular props my Higher Order Component will inject. That would be done like this:

```<code>function listToComponentProps<TComponentProps, TKey = keyof TComponentProps>(props: Array<TKey>) {
  // Logic here, not important for the example
}
interface TestProps {a: number, b: Function, c: () => number}
listToComponentProps<TestProps>(['a', 'b', 'c'])
</code>```

The keyof keyword handles the constraint for me.
Example inputs for listToComponentProps<TestProps> would be

valid:  ['b'], ['b', 'c'], ['c']

invalid

['a'], ['a', 'b'], ['a', 'b', 'c'] (a is number, not a function)

['d'], ['d', 'c'] (d is not part of the interface TestProps

The problem is, I want to restrict the props parameter not only to be key of TComponentProps, but also such key that the  corresponding type in TComponentProps is Function (so that 'a' would be an invalid option detected by typescript compiler). How can one achieve such task?

答:
You could do it like this:

```<code>const listToComponentProps = <
  TComponent extends {[P in TKey]: Function },
  TKey extends string = keyof TComponent>
  (props: TKey[]) => { /* ... */ };

interface TestProps {a: number, b: Function, c: () => number}
const result = listToComponentProps<TestProps>(['a', 'b', 'c']) // Type error
</code>```

This results in the type error:

```<code>Type 'TestProps' does not satisfy the constraint '{ a: Function; b: Function; c: Function; }'.
  Types of property 'a' are incompatible.
    Type 'number' is not assignable to type 'Function'.
</code>```

Unfortunately this business of having a default parameter ends up constraining our TComponent to have only Function properties. When you genuinely want to pass something like listToComponentProps<TestProps>(['b', 'c']), which should be valid, you will need to explicitly fill in the second type parameter, i.e. listToComponentProps<TestProps, 'b' | 'c'>(['b', 'c']).

What you really want is not to have a default parameter for TKey, but rather for generic inference to be granular: in a type parameter list, all parameters that can be inferred (e.g. TKey, which can be inferred from the passed array) should be inferred, even if some (in this case, TComponent) have to be specified manually. TypeScript doesn't work this way today, so we're SOL.

There's a bunch of open issues on the TypeScript issue tracker about this, you could go find them and kick up a stink.

If good inference is more important to you than strictly preserving runtime characteristics, you could add a dummy argument to dissociate inference for the two type parameters:

```<code>const listToComponentProps =
    <TKey extends string>
    (props: TKey[]) =>
    <TComponent extends {[P in TKey]: Function }>
    () => { /* ... */ };

interface TestProps { a: number, b: Function, c: () => number }

const result = listToComponentProps(['a', 'b', 'c'])<TestProps>() // Type error
const result2 = listToComponentProps(['b', 'c'])<TestProps>() // OK
</code>```

Body:
No need to know React, just some background: in my use case, I want to amplify user specified React.ComponentClass with my custom Higher Order Component. In order to do so, I want user to also send me list of names of the particular props my Higher Order Component will inject. That would be done like this:

function listToComponentProps<TComponentProps, TKey = keyof TComponentProps>(props: Array<TKey>) {
  // Logic here, not important for the example
}
interface TestProps {a: number, b: Function, c: () => number}
listToComponentProps<TestProps>(['a', 'b', 'c'])

The keyof keyword handles the constraint for me.
Example inputs for listToComponentProps<TestProps> would be

valid:  ['b'], ['b', 'c'], ['c']

invalid

['a'], ['a', 'b'], ['a', 'b', 'c'] (a is number, not a function)

['d'], ['d', 'c'] (d is not part of the interface TestProps

The problem is, I want to restrict the props parameter not only to be key of TComponentProps, but also such key that the  corresponding type in TComponentProps is Function (so that 'a' would be an invalid option detected by typescript compiler). How can one achieve such task?

Body:
You could do it like this:

const listToComponentProps = <
  TComponent extends {[P in TKey]: Function },
  TKey extends string = keyof TComponent>
  (props: TKey[]) => { /* ... */ };

interface TestProps {a: number, b: Function, c: () => number}
const result = listToComponentProps<TestProps>(['a', 'b', 'c']) // Type error

This results in the type error:

Type 'TestProps' does not satisfy the constraint '{ a: Function; b: Function; c: Function; }'.
  Types of property 'a' are incompatible.
    Type 'number' is not assignable to type 'Function'.

Unfortunately this business of having a default parameter ends up constraining our TComponent to have only Function properties. When you genuinely want to pass something like listToComponentProps<TestProps>(['b', 'c']), which should be valid, you will need to explicitly fill in the second type parameter, i.e. listToComponentProps<TestProps, 'b' | 'c'>(['b', 'c']).

What you really want is not to have a default parameter for TKey, but rather for generic inference to be granular: in a type parameter list, all parameters that can be inferred (e.g. TKey, which can be inferred from the passed array) should be inferred, even if some (in this case, TComponent) have to be specified manually. TypeScript doesn't work this way today, so we're SOL.

There's a bunch of open issues on the TypeScript issue tracker about this, you could go find them and kick up a stink.

If good inference is more important to you than strictly preserving runtime characteristics, you could add a dummy argument to dissociate inference for the two type parameters:

const listToComponentProps =
    <TKey extends string>
    (props: TKey[]) =>
    <TComponent extends {[P in TKey]: Function }>
    () => { /* ... */ };

interface TestProps { a: number, b: Function, c: () => number }

const result = listToComponentProps(['a', 'b', 'c'])<TestProps>() // Type error
const result2 = listToComponentProps(['b', 'c'])<TestProps>() // OK


问:
Why is my list of Tuples vertical?
I believe I've made an error in my coding in where my list of tuples prints out vertically instead of the correct way. May someone please tell me what's up?

This is the question being asked:
Enumerate It!
Write a function called enum that takes a sequence and returns a list of 2-tuples with each tuple holding the index and its associated item.

This is the example given:

```<code>>>> enum([45,67,23,34,88,12,90])
[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]

>> enum('hello')
[(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]
</code>```

This is my code:

```<code>def enum(aSequence):
    for i in range(7):
        b=aSequence[i]
        a= [i]
        list1 = [a,b]
       print (list1)

If following the example input is used this is the result:
[[0], 45]
[[1], 67]
[[2], 23]
[[3], 34]
[[4], 88]
[[5], 12]
[[6], 90]
</code>```

The result I would desire is:
[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]

When I take away print(list1) and use return list1 instead this is the result.

```<code>[[0], 13]
</code>```

Why is this the case?

When I put this into the website in which I'm being tutored on, the word "Jack and Jane" is displayed and random numbers are shown if a different test. My second question is how do I get the range loop to fit based on the parameter input. I tried to import math and import random. While both are short term solutions they aren't long term solutions.

I feel like I'm overthinking the problem as the code is there just the basic fundamentals might be missing.

答:
This is how it should be. You need to create the list before starting the loop.Just like below</p>

```<code>    def enum(aSequence):
    list1 = []
    for i in range(len(aSequence)):
        b = aSequence[i]
        a = i
        list1.append((a,b))
    print list1

enum([45,67,23,34,88,12,90])
</code>```

Title: Why is my list of Tuples vertical?

Body:
I believe I've made an error in my coding in where my list of tuples prints out vertically instead of the correct way. May someone please tell me what's up?

This is the question being asked:
Enumerate It!
Write a function called enum that takes a sequence and returns a list of 2-tuples with each tuple holding the index and its associated item.

This is the example given:

>>> enum([45,67,23,34,88,12,90])
[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]

>> enum('hello')
[(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]

This is my code:

def enum(aSequence):
    for i in range(7):
        b=aSequence[i]
        a= [i]
        list1 = [a,b]
       print (list1)

If following the example input is used this is the result:
[[0], 45]
[[1], 67]
[[2], 23]
[[3], 34]
[[4], 88]
[[5], 12]
[[6], 90]

The result I would desire is:
[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]

When I take away print(list1) and use return list1 instead this is the result.

[[0], 13]

Why is this the case?

When I put this into the website in which I'm being tutored on, the word "Jack and Jane" is displayed and random numbers are shown if a different test. My second question is how do I get the range loop to fit based on the parameter input. I tried to import math and import random. While both are short term solutions they aren't long term solutions.

I feel like I'm overthinking the problem as the code is there just the basic fundamentals might be missing.

Body:
This is how it should be. You need to create the list before starting the loop.Just like below

    def enum(aSequence):
    list1 = []
    for i in range(len(aSequence)):
        b = aSequence[i]
        a = i
        list1.append((a,b))
    print list1

enum([45,67,23,34,88,12,90])


问:
Ansible bitbucket clone provisioning ssh error
In summary, When provisioning my vagrant box using Ansible, I get thrown a mysterious error when trying to clone my bitbucket private repo using ssh.
The error states that the "Host key verification failed".

Yet if I vagrant ssh and then run the 'git clone' command, the private repo is successfully cloned. This indicates that the ssh forward agent is indeed working and the vagrant box can access my private key associated with the bitbucket repo.

I have been struggling for two days on this issue and am loosing my mind!
Please, somebody help me!!!

Vagrantfile:

```<code>Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/xenial64"
  config.vm.network "private_network", ip: "192.168.33.10"
  config.ssh.forward_agent = true

  # Only contains ansible dependencies
  config.vm.provision "shell",
    inline: "sudo apt-get install python-minimal -y"

  # Use ansible for all provisioning:
  config.vm.provision "ansible" do |ansible|
    ansible.playbook = "provisioning/playbook.yml"
  end

end
</code>```

My playbook.yml is as follows:

```<code>---

- hosts: all
  become: true

  tasks:
    - name: create /var/www/ directory
      file: dest=/var/www/ state=directory owner=www-data group=www-data mode=0755

    - name: Add the user 'ubuntu' to group 'www-data'
      user:
        name: ubuntu
        shell: /bin/bash
        groups: www-data
        append: yes

    - name: Clone bitbucket repo
      git:
        repo: git@bitbucket.org:gustavmahler/example.com.git
        dest: /var/www/poo
        version: master
        accept_hostkey: yes
</code>```

Error Message:

vagrant provision

TASK [common : Clone bitbucket repo] *******************************************

fatal: [default]: FAILED! => {"changed": false, "cmd": "/usr/bin/git clone --origin origin '' /var/www/poo", "failed": true, "msg": "Cloning into '/var/www/poo'...\nWarning: Permanently added the RSA host key for IP address '104.192.143.3' to the list of known hosts.\r\nPermission denied (publickey).\r\nfatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights\nand the repository exists.", "rc": 128, "stderr": "Cloning into '/var/www/poo'...\nWarning: Permanently added the RSA host key for IP address '104.192.143.3' to the list of known hosts.\r\nPermission denied (publickey).\r\nfatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights\nand the repository exists.\n", "stderr_lines": ["Cloning into '/var/www/poo'...", "Warning: Permanently added the RSA host key for IP address '104.192.143.3' to the list of known hosts.", "Permission denied (publickey).", "fatal: Could not read from remote repository.", "", "Please make sure you have the correct access rights", "and the repository exists."], "stdout": "", "stdout_lines": []}

Additional Info:

ssh-add -l on my machine does contain the associated bitbucket repo key.

ssh-add -l inside the vagrant box does also contain the associated bitbucket repo key (through ssh-forwarding).

Yet cloning works if done manually inside the vagrant box ?:

```<code>vagrant ssh
git clone git@bitbucket.org:myusername/myprivaterepo.com.git
Then type "yes" to allow the RSA fingerprint to be added to ~/.ssh/known_hosts (as its first connection with bitbucket)
</code>```

Possible solution?

I have seen in the Ansible documentation that there is a key_file: option. How would I reference the private key which is located outside the vagrant box and is passed in using ssh forwarding?

I do have multiple ssh keys for different entities inside my ~/.ssh/ Perhaps the git clone command when run by Ansible provisioning isn't selecting the correct key?

Any help is greatly appreciated and thanks for reading my nightmare.

答:
This answer comes direct from techraf's helpful comments.

I changed the owner of the /var/www directory from 'www-data' to
'ubuntu' (the username I use to login via ssh).

I also added "become: false" above the git task.

NOTE: I have since been dealing with the following issue so this answer does not fully resolve my problems:
Ansible bitbucket clone repo provisioning ssh error

Updated working playbook.yml file:

```<code>---

- hosts: all
  become: true

  tasks:
    - name: create /var/www/ directory
      file: dest=/var/www/ state=directory owner=ubuntu group=www-data mode=0755

    - name: Add the user 'ubuntu' to group 'www-data'
      user:
        name: ubuntu
        shell: /bin/bash
        groups: www-data
        append: yes

    - name: Clone bitbucket repo
      become: false
      git:
        repo: git@bitbucket.org:[username]/example.com.git
        dest: /var/www/poo
        version: master
        accept_hostkey: yes
</code>```

Body:
In summary, When provisioning my vagrant box using Ansible, I get thrown a mysterious error when trying to clone my bitbucket private repo using ssh.
The error states that the "Host key verification failed".

Yet if I vagrant ssh and then run the 'git clone' command, the private repo is successfully cloned. This indicates that the ssh forward agent is indeed working and the vagrant box can access my private key associated with the bitbucket repo.

I have been struggling for two days on this issue and am loosing my mind!
Please, somebody help me!!!

Vagrantfile:

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/xenial64"
  config.vm.network "private_network", ip: "192.168.33.10"
  config.ssh.forward_agent = true

  # Only contains ansible dependencies
  config.vm.provision "shell",
    inline: "sudo apt-get install python-minimal -y"

  # Use ansible for all provisioning:
  config.vm.provision "ansible" do |ansible|
    ansible.playbook = "provisioning/playbook.yml"
  end

end

My playbook.yml is as follows:

---

- hosts: all
  become: true

  tasks:
    - name: create /var/www/ directory
      file: dest=/var/www/ state=directory owner=www-data group=www-data mode=0755

    - name: Add the user 'ubuntu' to group 'www-data'
      user:
        name: ubuntu
        shell: /bin/bash
        groups: www-data
        append: yes

    - name: Clone bitbucket repo
      git:
        repo: git@bitbucket.org:gustavmahler/example.com.git
        dest: /var/www/poo
        version: master
        accept_hostkey: yes

Error Message:

vagrant provision

TASK [common : Clone bitbucket repo] *******************************************

fatal: [default]: FAILED! => {"changed": false, "cmd": "/usr/bin/git clone --origin origin '' /var/www/poo", "failed": true, "msg": "Cloning into '/var/www/poo'...\nWarning: Permanently added the RSA host key for IP address '104.192.143.3' to the list of known hosts.\r\nPermission denied (publickey).\r\nfatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights\nand the repository exists.", "rc": 128, "stderr": "Cloning into '/var/www/poo'...\nWarning: Permanently added the RSA host key for IP address '104.192.143.3' to the list of known hosts.\r\nPermission denied (publickey).\r\nfatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights\nand the repository exists.\n", "stderr_lines": ["Cloning into '/var/www/poo'...", "Warning: Permanently added the RSA host key for IP address '104.192.143.3' to the list of known hosts.", "Permission denied (publickey).", "fatal: Could not read from remote repository.", "", "Please make sure you have the correct access rights", "and the repository exists."], "stdout": "", "stdout_lines": []}

Additional Info:

ssh-add -l on my machine does contain the associated bitbucket repo key.

ssh-add -l inside the vagrant box does also contain the associated bitbucket repo key (through ssh-forwarding).

Yet cloning works if done manually inside the vagrant box ?:

vagrant ssh
git clone git@bitbucket.org:myusername/myprivaterepo.com.git
Then type "yes" to allow the RSA fingerprint to be added to ~/.ssh/known_hosts (as its first connection with bitbucket)

Possible solution?

I have seen in the Ansible documentation that there is a key_file: option. How would I reference the private key which is located outside the vagrant box and is passed in using ssh forwarding?

I do have multiple ssh keys for different entities inside my ~/.ssh/ Perhaps the git clone command when run by Ansible provisioning isn't selecting the correct key?

Any help is greatly appreciated and thanks for reading my nightmare.

Body:
This answer comes direct from techraf's helpful comments.

I changed the owner of the /var/www directory from 'www-data' to
'ubuntu' (the username I use to login via ssh).

I also added "become: false" above the git task.

NOTE: I have since been dealing with the following issue so this answer does not fully resolve my problems:
Ansible bitbucket clone repo provisioning ssh error

Updated working playbook.yml file:

---

- hosts: all
  become: true

  tasks:
    - name: create /var/www/ directory
      file: dest=/var/www/ state=directory owner=ubuntu group=www-data mode=0755

    - name: Add the user 'ubuntu' to group 'www-data'
      user:
        name: ubuntu
        shell: /bin/bash
        groups: www-data
        append: yes

    - name: Clone bitbucket repo
      become: false
      git:
        repo: git@bitbucket.org:[username]/example.com.git
        dest: /var/www/poo
        version: master
        accept_hostkey: yes


问:
Pass filename from file upload to text field
I have a part of a form where a user can upload a file. I want only the filename to be sent to a text field in the same form. So if user uploaded "C:/Folder/image.jpg", the text field should show "image.jpg". I tried some code myself but I know it's wrong:

```<code>function ff_uploadimages_action(element, action)
{var m = data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/);
switch (action) {
case 'change':
if (data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/).value)
ff_getElementByName('filename').value = m[2].text;
        default:;
    } // switch
} // ff_uploadimages_action
</code>```

ff_uploadimages is the field to upload file, and filename is the textfield where name should appear. Any help at all is appreciated! Thanks.

答:
A shorter way in jQuery would be the following:

HTML

```<code><input type="file" id="inputFile" class="hidden"/>
<input type="text" id="inputDisplayFileName" readonly/>
<button id="buttonChooseFile">Choose file</button>
</code>```

jQuery

```<code>$("#buttonChooseFile").click(funtion()({
    $("#inputFile").click();
});

$("#inputFile").change(function(){
    var fileName = $("#inputFile").prop('files')[0]["name"];

    $("inputDisplayFileName").val(fileName);
});
</code>```

In this example the default file upload is hidden so that you can style the 'upload file input' as desired. Clicking the button will trigger the original (hidden) file upload. After choosing the file the .onchange() will do the rest of the work, copying the file the 'read only input text'.

Body:
I have a part of a form where a user can upload a file. I want only the filename to be sent to a text field in the same form. So if user uploaded "C:/Folder/image.jpg", the text field should show "image.jpg". I tried some code myself but I know it's wrong:

function ff_uploadimages_action(element, action)
{var m = data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/);
switch (action) {
case 'change':
if (data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/).value)
ff_getElementByName('filename').value = m[2].text;
        default:;
    } // switch
} // ff_uploadimages_action

ff_uploadimages is the field to upload file, and filename is the textfield where name should appear. Any help at all is appreciated! Thanks.

Body:
A shorter way in jQuery would be the following:

HTML

<input type="file" id="inputFile" class="hidden"/>
<input type="text" id="inputDisplayFileName" readonly/>
<button id="buttonChooseFile">Choose file</button>

jQuery

$("#buttonChooseFile").click(funtion()({
    $("#inputFile").click();
});

$("#inputFile").change(function(){
    var fileName = $("#inputFile").prop('files')[0]["name"];

    $("inputDisplayFileName").val(fileName);
});

In this example the default file upload is hidden so that you can style the 'upload file input' as desired. Clicking the button will trigger the original (hidden) file upload. After choosing the file the .onchange() will do the rest of the work, copying the file the 'read only input text'.


问:
Prevent browser from caching Angular views
On my development environment, I have the BrowserLink configured so that whenever I make changes to HTML/JS in an angular app, the browser reloads. I've noticed that sometimes I do not see the latest changes I make. Either/Both of the following fixes it:

Use Ctrl F5 for the browser to force loading the assets

Go to tools -> clear cache

I am concerned that when the app is in production, users will have their views/controllers/services cached as well.

How do I force the browser to load the latest version?

答:
This is called cache busting and there are a number of tricks you can use for it.

Personally I usually work with Laravel and there I use Mix's own versioning system to version each build. That way the links to the assets point to the latest version. If you're using any Javascript build system you should be able to find a plugin for it to do that.

If all else fails a trick I sometimes use with non-Laravel PHP applications is to get a timestamp for when the file last changed and append it to the file path, as in this example:

```<code><img src="<?=$path?>?v=<?=filemtime($path)?>">
</code>```

The principle is applicable in any other language too - here's a Handlebars helper to do the same:

```<code>var fs = require('fs');
var Handlebars = require('handlebars');
Handlebars.registerHelper('version', function (path) {
    return path + '?v=' + fs.statSync(path).mtime.getTime();
});
</code>```

It shouldn't be hard to do something similar in any other language.

Body:
This is called cache busting and there are a number of tricks you can use for it.

Personally I usually work with Laravel and there I use Mix's own versioning system to version each build. That way the links to the assets point to the latest version. If you're using any Javascript build system you should be able to find a plugin for it to do that.

If all else fails a trick I sometimes use with non-Laravel PHP applications is to get a timestamp for when the file last changed and append it to the file path, as in this example:

<img src="<?=$path?>?v=<?=filemtime($path)?>">

The principle is applicable in any other language too - here's a Handlebars helper to do the same:

var fs = require('fs');
var Handlebars = require('handlebars');
Handlebars.registerHelper('version', function (path) {
    return path + '?v=' + fs.statSync(path).mtime.getTime();
});

It shouldn't be hard to do something similar in any other language.


问:
htaccess, rewrite for specific subdirectory but not others below it
I have a subdirectory /categories/stories/ that I want to rewrite to /books/ but I don't want to rewrite something like /categories/stories/horror. I'm doing the following but it has no effect:

```<code>RewriteCond ${REQUEST_URI} ^/categories/stories[/]?
RewriteCond ${REQUEST_URI} !^/categories/stories/+[/]?
RewriteRule ^(.*) /books/ [R=301,L]
</code>```

The result being if a person goes to, for example, http://bookstore.com/categories/stories they go to http://bookstore.com/books but http://bookstore.com/categories/stories/horror there's not rewrite.

答:
You can just use anchors in your regex pattern:

```<code>RewriteEngine On

RewriteCond %{REQUEST_URI} ^/categories/stories/?$ [NC]
RewriteRule ^ /books/ [R=301,L]
</code>```

Pattern ^/categories/stories/?$ will match /categories/stories/ or /categories/stories but not /categories/stories/anything.

Also make sure to clear your browser cache or use a different browser for testing this change.

Body:
I have a subdirectory /categories/stories/ that I want to rewrite to /books/ but I don't want to rewrite something like /categories/stories/horror. I'm doing the following but it has no effect:

RewriteCond ${REQUEST_URI} ^/categories/stories[/]?
RewriteCond ${REQUEST_URI} !^/categories/stories/+[/]?
RewriteRule ^(.*) /books/ [R=301,L]

The result being if a person goes to, for example, http://bookstore.com/categories/stories they go to http://bookstore.com/books but http://bookstore.com/categories/stories/horror there's not rewrite.

Body:
You can just use anchors in your regex pattern:

RewriteEngine On

RewriteCond %{REQUEST_URI} ^/categories/stories/?$ [NC]
RewriteRule ^ /books/ [R=301,L]

Pattern ^/categories/stories/?$ will match /categories/stories/ or /categories/stories but not /categories/stories/anything.

Also make sure to clear your browser cache or use a different browser for testing this change.


问:
Retrieve available Wifi networks on Ubuntu
I'm starting to learn Ubuntu 9.10. How can I retrieve all available Wifi networks programmatically?  Can someone give an example?</p>

答:
For a better output, sorting from greatest (-43 dBm) to weakest (-87 dBm) signals for each network:

```<code>$ iwlist wlan0 scanning | egrep 'Cell |Encryption|Quality|ESSID' | tr '\n' ' ' | sed 's/Cell/\nCell/g' | sort -k 8 | sed 's/     / /g'
</code>```

Will produce the following output:

```<code>Cell 01 - Address: 20:08:ED:C3:29:F4     Quality=67/70  Signal level=-43 dBm       Encryption key:on     ESSID:"INFINITUM57yt"
Cell 03 - Address: 38:BC:01:94:CA:98     Quality=45/70  Signal level=-65 dBm       Encryption key:on     ESSID:"KATKENAKI"
Cell 15 - Address: A4:B1:E9:57:44:03     Quality=42/70  Signal level=-68 dBm       Encryption key:on     ESSID:"INFINITUM574403"
Cell 07 - Address: 78:D7:52:D2:70:38     Quality=37/70  Signal level=-73 dBm       Encryption key:on     ESSID:"palehouse"
Cell 02 - Address: C8:3A:35:14:5E:F0     Quality=35/70  Signal level=-75 dBm       Encryption key:off     ESSID:"Tenda_145EF0"
Cell 05 - Address: 64:70:02:A8:E8:AD     Quality=35/70  Signal level=-75 dBm       Encryption key:off     ESSID:"ThomasJefferson"
Cell 11 - Address: D0:05:2A:99:3C:92     Quality=35/70  Signal level=-75 dBm       Encryption key:on     ESSID:"INFINITUM4183"
Cell 08 - Address: 9C:97:26:D3:ED:9D     Quality=33/70  Signal level=-77 dBm       Encryption key:on     ESSID:"INFINITUMD3ED9D"
Cell 04 - Address: F8:1A:67:70:71:04     Quality=33/70  Signal level=-77 dBm       Encryption key:on     ESSID:"TP-LINK_707104"
Cell 14 - Address: 64:66:B3:8B:F0:C8     Quality=30/70  Signal level=-80 dBm       Encryption key:on     ESSID:"ola q ace robando el wifi oq ace"
Cell 12 - Address: 9C:2A:70:4B:85:D9     Quality=29/70  Signal level=-81 dBm       Encryption key:off     ESSID:"HP-Print-D9-LaserJet 1025"
Cell 10 - Address: F4:F2:6D:C2:7A:48     Quality=25/70  Signal level=-85 dBm       Encryption key:on     ESSID:"AppGarage"
Cell 13 - Address: 20:25:64:8E:B8:88     Quality=25/70  Signal level=-85 dBm       Encryption key:on     ESSID:"f46f84"
Cell 09 - Address: 60:E3:27:EC:CE:14     Quality=25/70  Signal level=-85 dBm       Encryption key:on     ESSID:"INFINITUM57yt"
Cell 06 - Address: 04:9F:CA:23:A0:00     Quality=23/70  Signal level=-87 dBm       Encryption key:on     ESSID:"Totalplay-F07C"
</code>```

LastEditorDisplayName: Roger Pate

Body:
For a better output, sorting from greatest (-43 dBm) to weakest (-87 dBm) signals for each network:

$ iwlist wlan0 scanning | egrep 'Cell |Encryption|Quality|ESSID' | tr '\n' ' ' | sed 's/Cell/\nCell/g' | sort -k 8 | sed 's/     / /g'

Will produce the following output:

Cell 01 - Address: 20:08:ED:C3:29:F4     Quality=67/70  Signal level=-43 dBm       Encryption key:on     ESSID:"INFINITUM57yt"
Cell 03 - Address: 38:BC:01:94:CA:98     Quality=45/70  Signal level=-65 dBm       Encryption key:on     ESSID:"KATKENAKI"
Cell 15 - Address: A4:B1:E9:57:44:03     Quality=42/70  Signal level=-68 dBm       Encryption key:on     ESSID:"INFINITUM574403"
Cell 07 - Address: 78:D7:52:D2:70:38     Quality=37/70  Signal level=-73 dBm       Encryption key:on     ESSID:"palehouse"
Cell 02 - Address: C8:3A:35:14:5E:F0     Quality=35/70  Signal level=-75 dBm       Encryption key:off     ESSID:"Tenda_145EF0"
Cell 05 - Address: 64:70:02:A8:E8:AD     Quality=35/70  Signal level=-75 dBm       Encryption key:off     ESSID:"ThomasJefferson"
Cell 11 - Address: D0:05:2A:99:3C:92     Quality=35/70  Signal level=-75 dBm       Encryption key:on     ESSID:"INFINITUM4183"
Cell 08 - Address: 9C:97:26:D3:ED:9D     Quality=33/70  Signal level=-77 dBm       Encryption key:on     ESSID:"INFINITUMD3ED9D"
Cell 04 - Address: F8:1A:67:70:71:04     Quality=33/70  Signal level=-77 dBm       Encryption key:on     ESSID:"TP-LINK_707104"
Cell 14 - Address: 64:66:B3:8B:F0:C8     Quality=30/70  Signal level=-80 dBm       Encryption key:on     ESSID:"ola q ace robando el wifi oq ace"
Cell 12 - Address: 9C:2A:70:4B:85:D9     Quality=29/70  Signal level=-81 dBm       Encryption key:off     ESSID:"HP-Print-D9-LaserJet 1025"
Cell 10 - Address: F4:F2:6D:C2:7A:48     Quality=25/70  Signal level=-85 dBm       Encryption key:on     ESSID:"AppGarage"
Cell 13 - Address: 20:25:64:8E:B8:88     Quality=25/70  Signal level=-85 dBm       Encryption key:on     ESSID:"f46f84"
Cell 09 - Address: 60:E3:27:EC:CE:14     Quality=25/70  Signal level=-85 dBm       Encryption key:on     ESSID:"INFINITUM57yt"
Cell 06 - Address: 04:9F:CA:23:A0:00     Quality=23/70  Signal level=-87 dBm       Encryption key:on     ESSID:"Totalplay-F07C"


问:
How to run ftp-server on port 21 on macOs
I have to run ftpserver with node.js and electron, using simple-ftpd on macOs.
It must run on port 21, because i can't update device's hardwares parameters.
Btw all ports < 1024 are locked.

I tried to use pfctl to forward 21 -> 1337, my device can find the ftpserver but can't log or write into it.

```<code>echo “rdr pass on en0 inet proto tcp from any to any port 21 -> 127.0.0.1 port 1337” | sudo pfctl -ef -
</code>```

I dont want to ask for root password after each launch.

i'm using node 8, electron, simple-ftdp

Do you have any suggestions guys ?

答:
You have to be careful with this one, but you can allow your user to run sudo simple-ftpd with no password by adding /etc/sudoers.d/myappconfig with:

```<code>myuser ALL=(ALL) NOPASSWD: /usr/bin/path/to/simpleftp-d
</code>```

If it doesn't work or you don't have the folder /etc/sudoers.d/, you can just append that line to /etc/sudoers.

Body:
I have to run ftpserver with node.js and electron, using simple-ftpd on macOs.
It must run on port 21, because i can't update device's hardwares parameters.
Btw all ports < 1024 are locked.

I tried to use pfctl to forward 21 -> 1337, my device can find the ftpserver but can't log or write into it.

echo “rdr pass on en0 inet proto tcp from any to any port 21 -> 127.0.0.1 port 1337” | sudo pfctl -ef -

I dont want to ask for root password after each launch.

i'm using node 8, electron, simple-ftdp

Do you have any suggestions guys ?

Body:
You have to be careful with this one, but you can allow your user to run sudo simple-ftpd with no password by adding /etc/sudoers.d/myappconfig with:

myuser ALL=(ALL) NOPASSWD: /usr/bin/path/to/simpleftp-d

If it doesn't work or you don't have the folder /etc/sudoers.d/, you can just append that line to /etc/sudoers.


问:
How to make a loading graphic in WPF XAML?
So I have a little WPF XAML that gets the titles of my RSS feed and puts them in a ListBox.

However, it takes about 2 seconds to load.

How can I have put some kind of AJAXy spinning graphic in the ListBox until the data is there?

Here is the code:

```<code><Window x:Class="WpfApplication5.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <StackPanel.Resources>
            <XmlDataProvider x:Key="ExternalColors" Source="http://www.tanguay.info/web/rss" XPath="/"/>
        </StackPanel.Resources>
        <TextBlock Text="RSS Feeds:"/>
        <ListBox Name="lbColor" Height="200" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource ExternalColors}, XPath=//item/title}"/>

        <TextBlock Text="You selected this feed:"/>
        <TextBox
            Text="{Binding ElementName=lbColor, Path=SelectedValue}"
            Background="{Binding ElementName=lbColor, Path=SelectedValue}">
        </TextBox>
    </StackPanel>
</Window>
</code>```

答:
The following videos are from mix08 and walk you through doing exactly what you want.

Part 1

Part 2

(watch in succession if possible. it is in silverlight but will point you in the right direction.)

Have Fun.

OwnerDisplayName: Edward Tanguay

Body:
So I have a little WPF XAML that gets the titles of my RSS feed and puts them in a ListBox.

However, it takes about 2 seconds to load.

How can I have put some kind of AJAXy spinning graphic in the ListBox until the data is there?

Here is the code:

<Window x:Class="WpfApplication5.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <StackPanel.Resources>
            <XmlDataProvider x:Key="ExternalColors" Source="http://www.tanguay.info/web/rss" XPath="/"/>
        </StackPanel.Resources>
        <TextBlock Text="RSS Feeds:"/>
        <ListBox Name="lbColor" Height="200" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource ExternalColors}, XPath=//item/title}"/>

        <TextBlock Text="You selected this feed:"/>
        <TextBox
            Text="{Binding ElementName=lbColor, Path=SelectedValue}"
            Background="{Binding ElementName=lbColor, Path=SelectedValue}">
        </TextBox>
    </StackPanel>
</Window>

OwnerDisplayName: Blounty


问:
how much data to hold in memory when looping through large dataset
I am trying to create a trading simulator to test strategies over long periods of time.

I am using 1 minute data points. So if I were to run a simulation for say 10 years that would be approx 3,740,000 prices (Price class shown below). A simulation could be much longer than 10 years but using this an example.

```<code>     class Price
     {
          DateTime DatePrice
          double Open
          double High
          double Low
          double Close
     }
</code>```

My simulator works however I can't help feeling the way I'm doing it isn't very optimal.

So currently what I do is to grab a years worth of prices from my SQL database so approx 374,400 prices. I do this because I don't want to use too much memory (this might be misguided have no idea).

Now when looping through time the code will also make use of the previous lets say 10 prices. So at 2.30am the code will look back the prices from 2.20am, all the prices previous to this are now redundant. So it seems somewhat wasteful to me if I hold 374,400 prices in memory.

```<code>            time       Close
            00:00      102
            00:01      99
            00:02      100
            ...
            02:20      84
            02:21      88
</code>```

So I have a loop that will loop through from my start date to my end date, checking at each step if I need to download additional prices from the database.

```<code>   List<Price> PriceList = Database.GetPrices(first years worth or prices)

   for(DateTime dtNow = dtStart; dtNow < dtEnd; dtNow = dtNow.AddMinutes(1))
   {
         // run some calculations which doesn't take long

         // then check if PriceList[i] == PriceList.Count - 1
         // if so get more prices from the database and obviously reset i to zero but baring in mind I need to keep the previous 10 prices
   }
</code>```

What is the best solution for this kind of problem? Should I be getting prices from the database on another thread or something?

答:
From a time efficiency perspective, what would be optimal is for you to get back an initial batch of prices, start processing those, then immediately begin to retrieve the rest. The problem with checking for new data during your processing is that you have to delay your program everytime you need new data.

If you really do care about memory, what you need to do is remove prices from the list you have after you are done with them. This will allow the garbage collector to free up the consumed memory. Otherwise with what you have, once your program is finishing and you pulled back the last year of prices you will have retrieved all of the prices and you would be consuming as much memory as if you had gotten all of the prices at once.

I believe you are being premature with your memory concerns. The only time I ever had to worry about memory/the garbage collector in .net was when I had a long running process and one step in that process included downloading PDF's. Even though I retrieved the PDF's as needed, the PDF's in memory would eventually consume GB's of memory after running for a while and throw an exception after consuming whatever the .net memory limit is for lists.

Body:
I am trying to create a trading simulator to test strategies over long periods of time.

I am using 1 minute data points. So if I were to run a simulation for say 10 years that would be approx 3,740,000 prices (Price class shown below). A simulation could be much longer than 10 years but using this an example.

     class Price
     {
          DateTime DatePrice
          double Open
          double High
          double Low
          double Close
     }

My simulator works however I can't help feeling the way I'm doing it isn't very optimal.

So currently what I do is to grab a years worth of prices from my SQL database so approx 374,400 prices. I do this because I don't want to use too much memory (this might be misguided have no idea).

Now when looping through time the code will also make use of the previous lets say 10 prices. So at 2.30am the code will look back the prices from 2.20am, all the prices previous to this are now redundant. So it seems somewhat wasteful to me if I hold 374,400 prices in memory.

            time       Close
            00:00      102
            00:01      99
            00:02      100
            ...
            02:20      84
            02:21      88

So I have a loop that will loop through from my start date to my end date, checking at each step if I need to download additional prices from the database.

   List<Price> PriceList = Database.GetPrices(first years worth or prices)

   for(DateTime dtNow = dtStart; dtNow < dtEnd; dtNow = dtNow.AddMinutes(1))
   {
         // run some calculations which doesn't take long

         // then check if PriceList[i] == PriceList.Count - 1
         // if so get more prices from the database and obviously reset i to zero but baring in mind I need to keep the previous 10 prices
   }

What is the best solution for this kind of problem? Should I be getting prices from the database on another thread or something?


问:
making travis-ci zip my project after successful build and push it to github
I´m currently developing a simple java project stored in a github repository with maven to build it and Travis-ci to build it automatically after pushing changes to the repository. My teacher demands that, after an automatic successful build made by travis-ci, I zip the whole project and store it.
I´ve already accomplished zipping the project with maven. It brings my zip file to the src/main/resources of my project so I can push the ziip file in my github repository. But when travis creates the zip file, it won´t push the zip to my repository in github. Instead, it generates the zip file to /home/travis/build/my-user/...

That´s what it says in the travis terminal:
[INFO] Building zip: /home/travis/build/fabiophillip/calculadoralib/src/main/resources/CalculadoraLib-0.0.1-SNAPSHOT-assembly.zip

How can I make travis-ci push this zip to my github repository instead of this travis folder which I don´t know how to access?

答:
When a Tag is created and pushed the config below will do the following:

Travis will clone the repo (named "api")

Repo is built

Repo is zipped

Zip is uploaded to GitHub as the tagged release download.

I'm using PHP but the steps should work the same.

```<code>dist: trusty
language: php
php: 7.1

env:
 global:
 - REPO=api
 matrix:
  - BUILD_ENV=test
  - BUILD_ENV=qa

install:
- composer install --no-interaction

branches:
  # expected format: v1.0.0
  only:
  - /^v\d+(\.\d+)+$/

before_deploy:
- cd ..
- tar -zcf ${TRAVIS_BUILD_DIR}${REPO}-${BUILD_ENV}-${TRAVIS_TAG}-${TRAVIS_BUILD_NUMBER}.tar.gz ${REPO}

deploy:
  # GitHub - Add zip to release
  - provider: releases
    api_key:
      secure: "YOUR GITHUB API KEY"
    file: ${TRAVIS_BUILD_DIR}${REPO}-${BUILD_ENV}-${TRAVIS_TAG}-${TRAVIS_BUILD_NUMBER}.tar.gz
    skip_cleanup: true
    on:
      tags: true
</code>```

Body:
When a Tag is created and pushed the config below will do the following:

Travis will clone the repo (named "api")

Repo is built

Repo is zipped

Zip is uploaded to GitHub as the tagged release download.

I'm using PHP but the steps should work the same.

dist: trusty
language: php
php: 7.1

env:
 global:
 - REPO=api
 matrix:
  - BUILD_ENV=test
  - BUILD_ENV=qa

install:
- composer install --no-interaction

branches:
  # expected format: v1.0.0
  only:
  - /^v\d+(\.\d+)+$/

before_deploy:
- cd ..
- tar -zcf ${TRAVIS_BUILD_DIR}${REPO}-${BUILD_ENV}-${TRAVIS_TAG}-${TRAVIS_BUILD_NUMBER}.tar.gz ${REPO}

deploy:
  # GitHub - Add zip to release
  - provider: releases
    api_key:
      secure: "YOUR GITHUB API KEY"
    file: ${TRAVIS_BUILD_DIR}${REPO}-${BUILD_ENV}-${TRAVIS_TAG}-${TRAVIS_BUILD_NUMBER}.tar.gz
    skip_cleanup: true
    on:
      tags: true


问:
Apache Toree to connect to a remote spark cluster
Is there a way to connect Apache Toree to a remote spark cluster? I see the common command is

```<code>jupyter toree install --spark_home=/usr/local/bin/apache-spark/
</code>```

How can I go about using spark on a remote server without having to install locally?

答:
This is a possible example with some intuitive details for ANY remote cluster install. For my remote cluster, which is a Cloudera 5.9.2 these are specific steps. (You can also use this example to install with non-Cloudera clusters with some smart edits.)

With OS/X to build CDH version (skip if using a distribution):

Goto https://github.com/Myllyenko/incubator-toree and clone this repo

Download Docker

Setup 'signing' - It's been a some time since I set this up - you'll need to sign the build above. TBD

'new branch git', edit the .travis.xml, README.md, and build.sbt files to change 5.10.x to 5.9.2

Start Docker, cd within the make release dir, build with make release, wait, wait, sign 3 builds

Copy the file ./dist/toree-pip/toree-0.2.0-spark-1.6.0-cdh5.9.2.tar.gz  to your spark-shell machine that can reach your YARN-controlled Spark cluster

Merge, commit, etc your repo to your master repo if this will be mission critical

Spark Machine Installs:

Warning: Some steps may need to be done as root as a last resort

Install pip / anaconda (see other docs)

Install Jupyter sudo pip install jupyter

Install toree sudo pip install toree-0.2.0-spark-1.6.0-cdh5.9.2 or use the apache-toree distribution

Configure Toree to run with Jupyter (example):
Edit & add to ~/.bash_profile

```<code>echo $PATH
PATH=$PATH:$HOME/bin
export PATH
echo $PATH

export CDH_SPARK_HOME=/opt/cloudera/parcels/CDH/lib/spark
export SPARK_HOME=/opt/cloudera/parcels/CDH-5.9.2-1.cdh5.9.2.p0.3/lib/spark
export PYTHONPATH=$PYTHONPATH:$SPARK_HOME/python:$SPARK_HOME/python/lib
export SPARK_CONF_DIR=/etc/spark/conf
export HADOOP_HOME=/opt/cloudera/parcels/CDH/lib/hadoop
PATH=$PATH:$SPARK_HOME/bin
export PATH
echo $PATH

export SPARK_PKGS=$(cat << END | xargs echo | sed 's/ /,/g'
com.databricks:spark-csv_2.10:1.5.0
END
)

export SPARK_JARS=$(cat << END | xargs echo | sed 's/ /,/g'
/home/mymachine/extras/someapp.jar
/home/mymachine/extras/jsoup-1.10.3.jar
END
)

export TOREE_JAR="/usr/local/share/jupyter/kernels/apache_toree_scala/lib/toree-assembly-0.2.0-spark-1.6.0-cdh5.9.2-incubating.jar"

export SPARK_OPTS="--master yarn-client --conf spark.yarn.config.gatewayPath=/opt/cloudera/parcels --conf spark.scheduler.mode=FAIR --conf spark.executor.extraLibraryPath=/opt/cloudera/parcels/CDH-5.9.2-1.cdh5.9.2.p0.3/lib/hadoop/lib/native:/opt/cloudera/parcels/CDH-5.9.2-1.cdh5.9.2.p0.3/lib/hadoop --conf spark.driver.extraLibraryPath=/opt/cloudera/parcels/CDH-5.9.2-1.cdh5.9.2.p0.3/lib/hadoop/lib/native:/opt/cloudera/parcels/CDH-5.9.2-1.cdh5.9.2.p0.3/lib/hadoop --conf spark.yarn.am.extraLibraryPath=/opt/cloudera/parcels/CDH-5.9.2-1.cdh5.9.2.p0.3/lib/hadoop/lib/native:/opt/cloudera/parcels/CDH-5.9.2-1.cdh5.9.2.p0.3/lib/hadoop --conf spark.yarn.historyServer.address=http://yourCDHcluster.net:18088  --conf spark.default.parallelism=20  --conf spark.driver.maxResultSize=1g --conf spark.driver.memory=1g  --conf spark.executor.cores=4 --conf spark.executor.instances=5  --conf spark.executor.memory=1g --packages $SPARK_PKGS --jars $SPARK_JARS"

function jti() {
    jupyter toree install \
    --replace \
    --user \
    --kernel_name="CDH 5.9.2 Toree" \
    --debug \
    --spark_home=${SPARK_HOME} \
    --spark_opts="$SPARK_OPTS" \
    --log-level=0
}
function jn() {
    jupyter notebook --ip=127.0.0.1 --port=8888 --debug --log-level=0
}
</code>```

If you want a different port to hit Toree - now is your chance to edit 8888

Log out of your Toree / spark-shell machine

ssh back to that machine ssh -L 8888:localhost:8888 toreebox.cdhcluster.net (assuming that 8888 is the port in the bash file)

I expect as a user (not root) you can type jti to install Toree into Jupyter (Note: understanding this step may help to install other kernels into Jupyter - sidebar: @jamcom mentioned
the produced file, but this step automatically produces this part. The file is buried in your home dir's tree as a user rather than root.

As user, type jn to start a Jupyter Notebook. Wait a few seconds until the browser url is available and paste that URL into your browser.

You now have Jupyter running and so pick a new CDH 5.9.2 Toree or the version you installed. This launches a new browser window. Since you have some Toree experience, pick something like sc.getConf.getAll.sortWith(_._1 < _._1).foreach(println) in order to get the lazily instantiated spark context going. Be really patient as your jobs is submitted to the cluster and your may have to wait a long time if your cluster is busy or a little while for your job to process in the cluster.

Tips and Tricks:

I ran into an issue on the first run and the subsequent runs never saw that issue. (The issue issue might be fixed in the github)

Sometimes, I have to kill the old 'Apache Toree' app on YARN to start a new Toree.

Sometimes, my VM can has an orphaned JVM. If you get memory errors starting a Jupyter Notebook/ Toree or have unexpectedly disconnected, check your process list with top. And  ... kill the extra JVM (be careful ID-ing your lost process).

Body:
Is there a way to connect Apache Toree to a remote spark cluster? I see the common command is

jupyter toree install --spark_home=/usr/local/bin/apache-spark/

How can I go about using spark on a remote server without having to install locally?

Body:
This is a possible example with some intuitive details for ANY remote cluster install. For my remote cluster, which is a Cloudera 5.9.2 these are specific steps. (You can also use this example to install with non-Cloudera clusters with some smart edits.)

With OS/X to build CDH version (skip if using a distribution):

Goto https://github.com/Myllyenko/incubator-toree and clone this repo

Download Docker

Setup 'signing' - It's been a some time since I set this up - you'll need to sign the build above. TBD

'new branch git', edit the .travis.xml, README.md, and build.sbt files to change 5.10.x to 5.9.2

Start Docker, cd within the make release dir, build with make release, wait, wait, sign 3 builds

Copy the file ./dist/toree-pip/toree-0.2.0-spark-1.6.0-cdh5.9.2.tar.gz  to your spark-shell machine that can reach your YARN-controlled Spark cluster

Merge, commit, etc your repo to your master repo if this will be mission critical

Spark Machine Installs:

Warning: Some steps may need to be done as root as a last resort

Install pip / anaconda (see other docs)

Install Jupyter sudo pip install jupyter

Install toree sudo pip install toree-0.2.0-spark-1.6.0-cdh5.9.2 or use the apache-toree distribution

Configure Toree to run with Jupyter (example):
Edit & add to ~/.bash_profile

echo $PATH
PATH=$PATH:$HOME/bin
export PATH
echo $PATH

export CDH_SPARK_HOME=/opt/cloudera/parcels/CDH/lib/spark
export SPARK_HOME=/opt/cloudera/parcels/CDH-5.9.2-1.cdh5.9.2.p0.3/lib/spark
export PYTHONPATH=$PYTHONPATH:$SPARK_HOME/python:$SPARK_HOME/python/lib
export SPARK_CONF_DIR=/etc/spark/conf
export HADOOP_HOME=/opt/cloudera/parcels/CDH/lib/hadoop
PATH=$PATH:$SPARK_HOME/bin
export PATH
echo $PATH

export SPARK_PKGS=$(cat << END | xargs echo | sed 's/ /,/g'
com.databricks:spark-csv_2.10:1.5.0
END
)

export SPARK_JARS=$(cat << END | xargs echo | sed 's/ /,/g'
/home/mymachine/extras/someapp.jar
/home/mymachine/extras/jsoup-1.10.3.jar
END
)

export TOREE_JAR="/usr/local/share/jupyter/kernels/apache_toree_scala/lib/toree-assembly-0.2.0-spark-1.6.0-cdh5.9.2-incubating.jar"

export SPARK_OPTS="--master yarn-client --conf spark.yarn.config.gatewayPath=/opt/cloudera/parcels --conf spark.scheduler.mode=FAIR --conf spark.executor.extraLibraryPath=/opt/cloudera/parcels/CDH-5.9.2-1.cdh5.9.2.p0.3/lib/hadoop/lib/native:/opt/cloudera/parcels/CDH-5.9.2-1.cdh5.9.2.p0.3/lib/hadoop --conf spark.driver.extraLibraryPath=/opt/cloudera/parcels/CDH-5.9.2-1.cdh5.9.2.p0.3/lib/hadoop/lib/native:/opt/cloudera/parcels/CDH-5.9.2-1.cdh5.9.2.p0.3/lib/hadoop --conf spark.yarn.am.extraLibraryPath=/opt/cloudera/parcels/CDH-5.9.2-1.cdh5.9.2.p0.3/lib/hadoop/lib/native:/opt/cloudera/parcels/CDH-5.9.2-1.cdh5.9.2.p0.3/lib/hadoop --conf spark.yarn.historyServer.address=http://yourCDHcluster.net:18088  --conf spark.default.parallelism=20  --conf spark.driver.maxResultSize=1g --conf spark.driver.memory=1g  --conf spark.executor.cores=4 --conf spark.executor.instances=5  --conf spark.executor.memory=1g --packages $SPARK_PKGS --jars $SPARK_JARS"

function jti() {
    jupyter toree install \
    --replace \
    --user \
    --kernel_name="CDH 5.9.2 Toree" \
    --debug \
    --spark_home=${SPARK_HOME} \
    --spark_opts="$SPARK_OPTS" \
    --log-level=0
}
function jn() {
    jupyter notebook --ip=127.0.0.1 --port=8888 --debug --log-level=0
}

If you want a different port to hit Toree - now is your chance to edit 8888

Log out of your Toree / spark-shell machine

ssh back to that machine ssh -L 8888:localhost:8888 toreebox.cdhcluster.net (assuming that 8888 is the port in the bash file)

I expect as a user (not root) you can type jti to install Toree into Jupyter (Note: understanding this step may help to install other kernels into Jupyter - sidebar: @jamcom mentioned
the produced file, but this step automatically produces this part. The file is buried in your home dir's tree as a user rather than root.

As user, type jn to start a Jupyter Notebook. Wait a few seconds until the browser url is available and paste that URL into your browser.

You now have Jupyter running and so pick a new CDH 5.9.2 Toree or the version you installed. This launches a new browser window. Since you have some Toree experience, pick something like sc.getConf.getAll.sortWith(_._1 < _._1).foreach(println) in order to get the lazily instantiated spark context going. Be really patient as your jobs is submitted to the cluster and your may have to wait a long time if your cluster is busy or a little while for your job to process in the cluster.

Tips and Tricks:

I ran into an issue on the first run and the subsequent runs never saw that issue. (The issue issue might be fixed in the github)

Sometimes, I have to kill the old 'Apache Toree' app on YARN to start a new Toree.

Sometimes, my VM can has an orphaned JVM. If you get memory errors starting a Jupyter Notebook/ Toree or have unexpectedly disconnected, check your process list with top. And  ... kill the extra JVM (be careful ID-ing your lost process).


问:
SQL Server Triggers, Stored Procedures
I dont ever used triggers or stored procedures. Now i want to study how and when i use that.
I have table named Products, when products table filling with row i want to copy ProductID and UnitsInStock and paset into Inventory table. There is one problem in inventory table is column which must fill buy user when row is filling. Would triggers or stored procedures will be useful for this situation?</p>

答: i personally would never use triggers when i'm using code it is fine if all your work is being done in sql. The reason is that it is firstly difficult for someone else to realise that it is a trigger doing work in the back-end. Secoundly if there is an error in your code ... triggers are the last thing you check. And if column names change it is easy to pick up the error in code. Stored procedures are good, but it all depends from organisation to organisation. I have gotten into doing sql in code and like it as there is no back and forth work at looking through hundreds of stored procedures for the relevant one. My views though ...</p>

Title: SQL Server Triggers, Stored Procedures


问:
Trying to change a variable in use to what the user inputs
I have not found an answer that satisfies my needs or is simple enough for me to actually understand as I'm relatively new to python!

I have a variable labelled difficulty which asks the user to input a string to state whether they want easy medium or hard mode. Unfortunately I am unable to successfully have python check the input for the words used and give them what i want, i end up with "easy is not defined" or "medium is not defined" or "hard is not defined." Is there a way for me to get round this problem?  Here is a small section of my code which the problem is enclosed to:

```<code>difficulty=input("What difficulty do you wish to choose, easy,medium or hard?")
   if difficulty==easy:
        print("You have chosen the easy mode, your test will now begin")
        print("")

    elif difficulty==medium:
        print("You have chosen the medium mode, your test will now begin")

    else:
        print("You have chosen the hard mode or tried to be funny, your test
        will now begin")
</code>```

答:
You are trying to get a string from the user (input will return a string) then compare it to another string in this case 'easy' or 'medium'. Here is a link to a google dev article talking about some of the basic things you can do to strings in python.

```<code>difficulty = input("What difficulty do you wish to choose, easy,medium or hard?")
if difficulty == 'easy':
    print("You have chosen the easy mode, your test will now begin")
    print("")

elif difficulty == 'medium':
    print("You have chosen the medium mode, your test will now begin")

else:
    print("You have chosen the hard mode or tried to be funny, your test will now begin")
</code>```

When you put easy or medium in your code you are telling python that they are variables (link to python variable tutorial) not strings. In this case you have not defined the easy variable yet ie: easy = 'some data'. Because you have not defined it python does not know what to do with easy it will throw an error.

Body:
I have not found an answer that satisfies my needs or is simple enough for me to actually understand as I'm relatively new to python!

I have a variable labelled difficulty which asks the user to input a string to state whether they want easy medium or hard mode. Unfortunately I am unable to successfully have python check the input for the words used and give them what i want, i end up with "easy is not defined" or "medium is not defined" or "hard is not defined." Is there a way for me to get round this problem?  Here is a small section of my code which the problem is enclosed to:

difficulty=input("What difficulty do you wish to choose, easy,medium or hard?")
   if difficulty==easy:
        print("You have chosen the easy mode, your test will now begin")
        print("")

    elif difficulty==medium:
        print("You have chosen the medium mode, your test will now begin")

    else:
        print("You have chosen the hard mode or tried to be funny, your test
        will now begin")

Body:
You are trying to get a string from the user (input will return a string) then compare it to another string in this case 'easy' or 'medium'. Here is a link to a google dev article talking about some of the basic things you can do to strings in python.

difficulty = input("What difficulty do you wish to choose, easy,medium or hard?")
if difficulty == 'easy':
    print("You have chosen the easy mode, your test will now begin")
    print("")

elif difficulty == 'medium':
    print("You have chosen the medium mode, your test will now begin")

else:
    print("You have chosen the hard mode or tried to be funny, your test will now begin")

When you put easy or medium in your code you are telling python that they are variables (link to python variable tutorial) not strings. In this case you have not defined the easy variable yet ie: easy = 'some data'. Because you have not defined it python does not know what to do with easy it will throw an error.


问:
Name two portions of a string as variables with Powershell
helpful Stack Overflow community,

I am working with automated report-outs (.txt docs) that contain two pieces of info I need in a larger string. I need to find a way to create variables from each of these and use them to pipe into another command.

Example of Report-Out:

```<code>B072L8FX9H  2017-11-17 14:49:17 -05:00  2017-11-17 14:49:17 -05:00  D1  volenick    amandun                     -   -
</code>```

I need to create two variables, one containing the first bit of text, the file name B072L8FX9H and one variable containing the last bit, the username amandun.

Please note the filename will always be 10 digits, but the username length will vary. Additionally, the spaces at the end prior to the -   - vary. These inconsistencies make me wary of utilizing trim but I am not opposed.

assuming I can get these two variables I believe I can then pipe them into a foreach statement to tag the actual files

Additional examples of Report-Out:

```<code>B075XR6ZR1  2017-11-17 15:19:22 -05:00  2017-11-17 15:19:22 -05:00  D1  volenick    pascalec                        -   -

B01C5AVSBW  2017-11-17 15:21:40 -05:00  2017-11-17 15:21:40 -05:00  D1  volenick    Gunthorp                        -   -

B076FHS4CZ  2017-11-17 15:23:36 -05:00  2017-11-17 15:23:36 -05:00  D1  volenick    amandun                     -   -
</code>```

I havent been able to build a trim command that works with all the inconsistencies. Perhaps there is a better way to extract these variables.

Thanks

EDIT - This is the solution we ended up using:

```<code>#generate individual file to user relationships
$dailyuserSheet = report.txt
$a=@()
$row = ""|Select file, user
$a +=$row
Foreach ($line in(Get-Content $dailyuserSheet)){
If($line -ne ""){
$file = $line.split("`t")[0]
$user = $line.split("`t")[5]
$a += "$file `t $user"
}
}
</code>```

答:
Here's another way, that will split all the fields out.

```<code>$test = @"
B075XR6ZR1  2017-11-17 15:19:22 -05:00  2017-11-17 15:19:22 -05:00  D1  volenick    pascalec                        -   -
B075XR6ZR1  2017-11-17 15:19:22 -05:00  2017-11-17 15:19:22 -05:00  D1  volenick    pascalec                        -   -
B01C5AVSBW  2017-11-17 15:21:40 -05:00  2017-11-17 15:21:40 -05:00  D1  volenick    Gunthorp                        -   -
B076FHS4CZ  2017-11-17 15:23:36 -05:00  2017-11-17 15:23:36 -05:00  D1  volenick    amandun                     -   -
"@

# Depending on how you take your input, splitting the lines can be more straight forward.
# This just splits lines by the -   - at the end of each line, ignoring how
# much whitespace is at the end of the line.
# Get-Content from a file would automatically split the lines.
$lines = $test -split "-\s*-\s*"

foreach($line in $lines)
{
    # split each field of the data based on contiguous whitespace.
    # this will fail if you have whitespace in a name or file, for example.
    $fields = $line -split "\s+"
    Write-Output "$($fields[0]) $($fields[9])"
}
</code>```

With the output:

```<code>B075XR6ZR1 pascalec
B075XR6ZR1 pascalec
B01C5AVSBW Gunthorp
B076FHS4CZ amandun
</code>```

Body:
helpful Stack Overflow community,

I am working with automated report-outs (.txt docs) that contain two pieces of info I need in a larger string. I need to find a way to create variables from each of these and use them to pipe into another command.

Example of Report-Out:

B072L8FX9H  2017-11-17 14:49:17 -05:00  2017-11-17 14:49:17 -05:00  D1  volenick    amandun                     -   -

I need to create two variables, one containing the first bit of text, the file name B072L8FX9H and one variable containing the last bit, the username amandun.

Please note the filename will always be 10 digits, but the username length will vary. Additionally, the spaces at the end prior to the -   - vary. These inconsistencies make me wary of utilizing trim but I am not opposed.

assuming I can get these two variables I believe I can then pipe them into a foreach statement to tag the actual files

Additional examples of Report-Out:

B075XR6ZR1  2017-11-17 15:19:22 -05:00  2017-11-17 15:19:22 -05:00  D1  volenick    pascalec                        -   -

B01C5AVSBW  2017-11-17 15:21:40 -05:00  2017-11-17 15:21:40 -05:00  D1  volenick    Gunthorp                        -   -

B076FHS4CZ  2017-11-17 15:23:36 -05:00  2017-11-17 15:23:36 -05:00  D1  volenick    amandun                     -   -

I havent been able to build a trim command that works with all the inconsistencies. Perhaps there is a better way to extract these variables.

Thanks

EDIT - This is the solution we ended up using:

#generate individual file to user relationships
$dailyuserSheet = report.txt
$a=@()
$row = ""|Select file, user
$a +=$row
Foreach ($line in(Get-Content $dailyuserSheet)){
If($line -ne ""){
$file = $line.split("`t")[0]
$user = $line.split("`t")[5]
$a += "$file `t $user"
}
}

Body:
Here's another way, that will split all the fields out.

$test = @"
B075XR6ZR1  2017-11-17 15:19:22 -05:00  2017-11-17 15:19:22 -05:00  D1  volenick    pascalec                        -   -
B075XR6ZR1  2017-11-17 15:19:22 -05:00  2017-11-17 15:19:22 -05:00  D1  volenick    pascalec                        -   -
B01C5AVSBW  2017-11-17 15:21:40 -05:00  2017-11-17 15:21:40 -05:00  D1  volenick    Gunthorp                        -   -
B076FHS4CZ  2017-11-17 15:23:36 -05:00  2017-11-17 15:23:36 -05:00  D1  volenick    amandun                     -   -
"@

# Depending on how you take your input, splitting the lines can be more straight forward.
# This just splits lines by the -   - at the end of each line, ignoring how
# much whitespace is at the end of the line.
# Get-Content from a file would automatically split the lines.
$lines = $test -split "-\s*-\s*"

foreach($line in $lines)
{
    # split each field of the data based on contiguous whitespace.
    # this will fail if you have whitespace in a name or file, for example.
    $fields = $line -split "\s+"
    Write-Output "$($fields[0]) $($fields[9])"
}

With the output:

B075XR6ZR1 pascalec
B075XR6ZR1 pascalec
B01C5AVSBW Gunthorp
B076FHS4CZ amandun


问:
How to combine two regex using AND operator
I have a dilemma in using regex as I am very new in using this:

I have the URL below:

```<code>var url = https://website.com/something-here/page.html?p=null#confirmation?order=123
</code>```

My expected result is:

```<code>/something-here/page.html #confirmation
</code>```

It could be a space or a comma or simply combine the two(/something-here/page.html#confirmation)

I can do this using two regex below:

```<code>var a= url.match(/som([^#]+).html/)[0];

var b= url.match(/#([^#]+).tion/)[0];

console.log(a,b);
</code>```

But I would like to have it done as a single regex with the same result.

答: Use each your condition in scope "( )" More details answer try find here</p>

Body:
I have a dilemma in using regex as I am very new in using this:

I have the URL below:

var url = https://website.com/something-here/page.html?p=null#confirmation?order=123

My expected result is:

/something-here/page.html #confirmation

It could be a space or a comma or simply combine the two(/something-here/page.html#confirmation)

I can do this using two regex below:

var a= url.match(/som([^#]+).html/)[0];

var b= url.match(/#([^#]+).tion/)[0];

console.log(a,b);

But I would like to have it done as a single regex with the same result.


问:
Ansible - Group Variables with Dynamic Inventory
Im attempting to start using ansible, and my current project is deploying a Graylog cluster.  I operate in AWS and would need to handle dynamic inventory.  I think I am missing the link betweek my playbooks and the dynamic instances getting the variables defined in the group variables.

Here is my directory structure. https://pastebin.com/cuNH4bzX

Here is my tag_Application_graylog file https://pastebin.com/Vw0cbnZq

When I am in the play directory, I am able to connect to instances using that tag.

```<code>ubuntu@ip-10-128-0-86:~/deployments/plays$ ansible -m ping tag_Application_graylog
ec2_justin_graylog01_dev | SUCCESS => {
    "changed": false,
    "failed": false,
    "ping": "pong"
}
ec2_justin_graylog02_dev | SUCCESS => {
    "changed": false,
    "failed": false,
    "ping": "pong"
}
</code>```

When i attempt to run the play, I get the following error.

```<code>TASK [elastic.elasticsearch : os-specific vars] *******************************************************************************************************************************************************************
task path: /home/ubuntu/deployments/roles/elastic.elasticsearch/tasks/main.yml:2
ok: [ec2_justin_graylog01_dev] => {"ansible_facts": {"default_file": "/etc/default/elasticsearch", "es_home": "/usr/share/elasticsearch", "java": "{% if es_java is defined %}{{es_java}}{% else %}openjdk-8-jre-headless{% endif %}"}, "ansible_included_var_files": ["/home/ubuntu/deployments/roles/elastic.elasticsearch/vars/Debian.yml"], "changed": false, "failed": false}
ok: [ec2_justin_graylog02_dev] => {"ansible_facts": {"default_file": "/etc/default/elasticsearch", "es_home": "/usr/share/elasticsearch", "java": "{% if es_java is defined %}{{es_java}}{% else %}openjdk-8-jre-headless{% endif %}"}, "ansible_included_var_files": ["/home/ubuntu/deployments/roles/elastic.elasticsearch/vars/Debian.yml"], "changed": false, "failed": false}

TASK [elastic.elasticsearch : fail] *******************************************************************************************************************************************************************************
task path: /home/ubuntu/deployments/roles/elastic.elasticsearch/tasks/elasticsearch-parameters.yml:3
fatal: [ec2_justin_graylog01_dev]: FAILED! => {"changed": false, "failed": true, "msg": "es_instance_name must be specified and cannot be blank"}
fatal: [ec2_justin_graylog02_dev]: FAILED! => {"changed": false, "failed": true, "msg": "es_instance_name must be specified and cannot be blank"}
    to retry, use: --limit @/home/ubuntu/deployments/plays/graylog.retry

PLAY RECAP ********************************************************************************************************************************************************************************************************
ec2_justin_graylog01_dev   : ok=6    changed=0    unreachable=0    failed=1
ec2_justin_graylog02_dev   : ok=6    changed=0    unreachable=0    failed=1
</code>```

since 'es_instance_name' is defined in my group vars, I am lead to believe they are not being read in.

The command I am using to run the playbook, from within the plays folder.

```<code>ansible-playbook -vv graylog.yml
</code>```

Full output of the command. https://pastebin.com/NxNFVbBG

Contents of graylog.yml https://pastebin.com/Liq8qCDi

Any help would be great.

答:
Found the issue.

https://github.com/ansible/ansible/issues/16878

Basically, group_vars needs to be an adjacent folder to the play.  So I either needded to move my play's up a level, or bring the group var folders down a level.

Based on the posted best practices, I moved my plays up a level.

https://docs.ansible.com/ansible/latest/playbooks_best_practices.html#content-organization

Body:
Im attempting to start using ansible, and my current project is deploying a Graylog cluster.  I operate in AWS and would need to handle dynamic inventory.  I think I am missing the link betweek my playbooks and the dynamic instances getting the variables defined in the group variables.

Here is my directory structure. https://pastebin.com/cuNH4bzX

Here is my tag_Application_graylog file https://pastebin.com/Vw0cbnZq

When I am in the play directory, I am able to connect to instances using that tag.

ubuntu@ip-10-128-0-86:~/deployments/plays$ ansible -m ping tag_Application_graylog
ec2_justin_graylog01_dev | SUCCESS => {
    "changed": false,
    "failed": false,
    "ping": "pong"
}
ec2_justin_graylog02_dev | SUCCESS => {
    "changed": false,
    "failed": false,
    "ping": "pong"
}

When i attempt to run the play, I get the following error.

TASK [elastic.elasticsearch : os-specific vars] *******************************************************************************************************************************************************************
task path: /home/ubuntu/deployments/roles/elastic.elasticsearch/tasks/main.yml:2
ok: [ec2_justin_graylog01_dev] => {"ansible_facts": {"default_file": "/etc/default/elasticsearch", "es_home": "/usr/share/elasticsearch", "java": "{% if es_java is defined %}{{es_java}}{% else %}openjdk-8-jre-headless{% endif %}"}, "ansible_included_var_files": ["/home/ubuntu/deployments/roles/elastic.elasticsearch/vars/Debian.yml"], "changed": false, "failed": false}
ok: [ec2_justin_graylog02_dev] => {"ansible_facts": {"default_file": "/etc/default/elasticsearch", "es_home": "/usr/share/elasticsearch", "java": "{% if es_java is defined %}{{es_java}}{% else %}openjdk-8-jre-headless{% endif %}"}, "ansible_included_var_files": ["/home/ubuntu/deployments/roles/elastic.elasticsearch/vars/Debian.yml"], "changed": false, "failed": false}

TASK [elastic.elasticsearch : fail] *******************************************************************************************************************************************************************************
task path: /home/ubuntu/deployments/roles/elastic.elasticsearch/tasks/elasticsearch-parameters.yml:3
fatal: [ec2_justin_graylog01_dev]: FAILED! => {"changed": false, "failed": true, "msg": "es_instance_name must be specified and cannot be blank"}
fatal: [ec2_justin_graylog02_dev]: FAILED! => {"changed": false, "failed": true, "msg": "es_instance_name must be specified and cannot be blank"}
    to retry, use: --limit @/home/ubuntu/deployments/plays/graylog.retry

PLAY RECAP ********************************************************************************************************************************************************************************************************
ec2_justin_graylog01_dev   : ok=6    changed=0    unreachable=0    failed=1
ec2_justin_graylog02_dev   : ok=6    changed=0    unreachable=0    failed=1

since 'es_instance_name' is defined in my group vars, I am lead to believe they are not being read in.

The command I am using to run the playbook, from within the plays folder.

ansible-playbook -vv graylog.yml

Full output of the command. https://pastebin.com/NxNFVbBG

Contents of graylog.yml https://pastebin.com/Liq8qCDi

Any help would be great.


问:
Explanation of a function that uses toString method and recursion to sum numbers
I am learning JS, and would like to understand this example I have come across:

```<code>function sum(a) {

  let currentSum = a;

  function f(b) {
    currentSum += b;
    return f;
  }

  f.toString = function() {
    return currentSum;
  };

  return f;
}

console.log( sum(1) ); // f 1
console.log( sum(1)(2) ); // f 3
console.log( sum(5)(-1)(2) ); // f 6
console.log( sum(6)(-1)(-2)(-3) ); // f 0
console.log( sum(0)(1)(2)(3)(4)(5) ); // f 15
</code>```

What I don't understand is how is this function returning antyhing with just the call sum(1), when I thought since we return only the function with the first call?
Also, what exactly is this toString method doing here, and how is this giving the f 1, and so on results?
I really hope some can explain this, since I can't understand what is going in this code from the tutorial. Apologise if the question is to noob.

答:
When you log the result of a function, it needs to convert that result to a string. Some browsers do this by calling its .toString() method.

sum() returns a function that adds its argument to the currentSum variable in the closure. That's how the chained function calls accumulate a total. But this function also has a custom .toString() method that returns the sum that was calculated, so this is what gets logged.

We can break down one of the long chains like this:

```<code>console.log(sum(1)(2)(3));
</code>```

is equivalent to:

```<code>temp1 = sum(1); // sets currentSum to 1, returns f
temp2 = temp1(2); // sets currentSum to 3, returns f
temp3 = temp2(3); // sets currentSum to 6, returns f
console.log(temp3); // calls f.toString(), which returns currentSum, so 6 is printed
</code>```

This is a cute trick, but it's not a useful general method for allowing chained calls like this. It depends on the fact that after all the calls are done, the final result will be used by something that requires a string. It's depending on a browser-specific feature of console.log() -- it doesn't work in Firefox.

Body:
I am learning JS, and would like to understand this example I have come across:

function sum(a) {

  let currentSum = a;

  function f(b) {
    currentSum += b;
    return f;
  }

  f.toString = function() {
    return currentSum;
  };

  return f;
}

console.log( sum(1) ); // f 1
console.log( sum(1)(2) ); // f 3
console.log( sum(5)(-1)(2) ); // f 6
console.log( sum(6)(-1)(-2)(-3) ); // f 0
console.log( sum(0)(1)(2)(3)(4)(5) ); // f 15

What I don't understand is how is this function returning antyhing with just the call sum(1), when I thought since we return only the function with the first call?
Also, what exactly is this toString method doing here, and how is this giving the f 1, and so on results?
I really hope some can explain this, since I can't understand what is going in this code from the tutorial. Apologise if the question is to noob.

Body:
When you log the result of a function, it needs to convert that result to a string. Some browsers do this by calling its .toString() method.

sum() returns a function that adds its argument to the currentSum variable in the closure. That's how the chained function calls accumulate a total. But this function also has a custom .toString() method that returns the sum that was calculated, so this is what gets logged.

We can break down one of the long chains like this:

console.log(sum(1)(2)(3));

is equivalent to:

temp1 = sum(1); // sets currentSum to 1, returns f
temp2 = temp1(2); // sets currentSum to 3, returns f
temp3 = temp2(3); // sets currentSum to 6, returns f
console.log(temp3); // calls f.toString(), which returns currentSum, so 6 is printed

This is a cute trick, but it's not a useful general method for allowing chained calls like this. It depends on the fact that after all the calls are done, the final result will be used by something that requires a string. It's depending on a browser-specific feature of console.log() -- it doesn't work in Firefox.