问:
Find and print num of solutions to x1+x2+x3=num
I need to write a recusive function that recive an integer num and returns the number of solutions to the equation :x1 + x2 + x3 = num, where x1,x2,x3 are numbers between 1-10, the method should print all solutions.

For example if num=3 then the method will print 1+1+1 and will return 1.

if num=5 the method will return 6 and will print:

```<code>1 + 1 + 3
1 + 2 + 2
1 + 3 + 1
2 + 1 + 2
2 + 2 + 1
3 + 1 + 1
</code>```

if num<3 or num>30 the method will return 0.

The method should be recursive without using loops. Global variables are not allowed. Lists are also not allowed.

Here my code, it works fine but it also prints duplicates, for num=5 it prints:

```<code>3 + 1 + 1
2 + 2 + 1
2 + 1 + 2
2 + 2 + 1
1 + 3 + 1
1 + 2 + 2
2 + 1 + 2
1 + 2 + 2
1 + 1 + 3
</code>```

Here is my code:

```<code>public static void main(String[] args) {
    System.out.println("num of solutions: "+solutions(5));

}

public static int solutions(int num)
{

    if (num < 3 || num > 30)
        return 0;

    return solutions(num, 1, 1, 1);
}
private static int solutions(int num, int x1, int x2, int x3)
{
    if (x1 < 1 || x1 > 10 || x2 < 1 || x2 > 10||x3 < 1 || x3 > 10)
        return 0;
    if (x1 + x2 + x3 > num)
        return 0;
    if (x1 + x2 + x3 == num)
    {
        System.out.println(x1 + " + " + x2 + " + " + x3);
        return 1;
    }
    return solutions(num, x1 + 1, x2, x3) + solutions(num, x1, x2 + 1, x3) + solutions(num, x1, x2, x3 + 1);

}
</code>```

How do I get the desired output without duplicates?

答:
Well... no collections, no global variables, no duplicates. I hope you are allowed to use StringBuilder?

```<code>public static void main(String[] args) {
    StringBuilder sb = new StringBuilder();

    System.out.println("num of solutions: " + solutions(5, sb));

    System.out.println(sb.toString());
}

public static int solutions(int num, StringBuilder sb) {
    if (num < 3 || num > 30)
        return 0;

    return solutions(num, 1, 1, 1, sb);
}

private static int solutions(int num, int x1, int x2, int x3, StringBuilder sb) {
    if (x1 > 10 || x2 > 10 || x3 > 10) {
        return 0;
    }

    if (x1 + x2 + x3 > num) {
        return 0;
    }

    if (x1 + x2 + x3 == num) {
        String str = x1 + " + " + x2 + " + " + x3;
        if (!sb.toString().contains(str)) {
            sb.append(str).append(System.lineSeparator());
            return 1;
        }
    }

    return solutions(num, x1 + 1, x2, x3, sb)
           + solutions(num, x1, x2 + 1, x3, sb)
           + solutions(num, x1, x2, x3 + 1, sb);
}
</code>```

Result:

```<code>    num of solutions: 6
    3 + 1 + 1
    2 + 2 + 1
    2 + 1 + 2
    1 + 3 + 1
    1 + 2 + 2
    1 + 1 + 3
</code>```

Body:
I need to write a recusive function that recive an integer num and returns the number of solutions to the equation :x1 + x2 + x3 = num, where x1,x2,x3 are numbers between 1-10, the method should print all solutions.

For example if num=3 then the method will print 1+1+1 and will return 1.

if num=5 the method will return 6 and will print:

1 + 1 + 3
1 + 2 + 2
1 + 3 + 1
2 + 1 + 2
2 + 2 + 1
3 + 1 + 1

if num<3 or num>30 the method will return 0.

The method should be recursive without using loops. Global variables are not allowed. Lists are also not allowed.

Here my code, it works fine but it also prints duplicates, for num=5 it prints:

3 + 1 + 1
2 + 2 + 1
2 + 1 + 2
2 + 2 + 1
1 + 3 + 1
1 + 2 + 2
2 + 1 + 2
1 + 2 + 2
1 + 1 + 3

Here is my code:

public static void main(String[] args) {
    System.out.println("num of solutions: "+solutions(5));

}

public static int solutions(int num)
{

    if (num < 3 || num > 30)
        return 0;

    return solutions(num, 1, 1, 1);
}
private static int solutions(int num, int x1, int x2, int x3)
{
    if (x1 < 1 || x1 > 10 || x2 < 1 || x2 > 10||x3 < 1 || x3 > 10)
        return 0;
    if (x1 + x2 + x3 > num)
        return 0;
    if (x1 + x2 + x3 == num)
    {
        System.out.println(x1 + " + " + x2 + " + " + x3);
        return 1;
    }
    return solutions(num, x1 + 1, x2, x3) + solutions(num, x1, x2 + 1, x3) + solutions(num, x1, x2, x3 + 1);

}

How do I get the desired output without duplicates?

Body:
Well... no collections, no global variables, no duplicates. I hope you are allowed to use StringBuilder?

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder();

    System.out.println("num of solutions: " + solutions(5, sb));

    System.out.println(sb.toString());
}

public static int solutions(int num, StringBuilder sb) {
    if (num < 3 || num > 30)
        return 0;

    return solutions(num, 1, 1, 1, sb);
}

private static int solutions(int num, int x1, int x2, int x3, StringBuilder sb) {
    if (x1 > 10 || x2 > 10 || x3 > 10) {
        return 0;
    }

    if (x1 + x2 + x3 > num) {
        return 0;
    }

    if (x1 + x2 + x3 == num) {
        String str = x1 + " + " + x2 + " + " + x3;
        if (!sb.toString().contains(str)) {
            sb.append(str).append(System.lineSeparator());
            return 1;
        }
    }

    return solutions(num, x1 + 1, x2, x3, sb)
           + solutions(num, x1, x2 + 1, x3, sb)
           + solutions(num, x1, x2, x3 + 1, sb);
}

Result:

    num of solutions: 6
    3 + 1 + 1
    2 + 2 + 1
    2 + 1 + 2
    1 + 3 + 1
    1 + 2 + 2
    1 + 1 + 3


来源: stackexchange

问:
Use a String as a conditional in java (Convert String to boolean)
I am new here!

I am doing a school project where I take a .csv file as input and read every line of values and store them into a String[], and then create an ArrayList.

The CSV file has some temperature measurements and I'm required to make filters for the different temperature measurements. What I want to know if there is a way to make the condition of an if statement the value of a string.

Since there are different ways to filter the information (>,<,>=,<=, from int x to int y) I want to create a method that concatenates a string that creates the condition the user is looking for;

Prompts user to choose what data from the array he wants to filter by.

(For instance option 3, which means its the data stored in String[2])

Then asks the user to choose how he wants to filter: >,<,>=,<=, from int x to int y.

Finally asks the remaining value to finish the comparison.

From these prompts we could build:

String a = String[2] + (comparison operator) + comparison value.

For example a = String[2] + " > 20"

Then I want to use the 'a' like this:  if(a){}

Where the console should read this as: - - - - - - -  if(Double.valueOf(String[2]) > 20){}

My IDE is BlueJ which tells me incompatible types: java.lang.String cannot be converted to boolean.
You may wonder why I use a String[] if I'm comparing double values,

Thanks in advance and my apologies if my idea is preposterous or not clear.

答:
You're not "comparing double values", and in fact you aren't comparing anything at all. A string is a string, not a true/false value, hence the incompatible types error. (To clarify, Java sees a string: if("Double.valueOf(String[2]) > 20"){} not if(Double.valueOf(String[2]) > 20){})

I would probably just use a switch on the comparison operator (make sure it's a string not a char):

```<code>switch(operator) {
    case ">":
        doStuffGreaterThan();
        break;  // Needed or else it will continue into the next cases too
    case "<":
        doStuffLessThan();
        break;
    case ">=":
        doStuffGE();
        break;
    ... etc ...
}
</code>```

Edit: I did a bit of searching and found this, which I haven't seen before but may be useful.

ContentLicense: CC BY-SA 4.0

Body:
You're not "comparing double values", and in fact you aren't comparing anything at all. A string is a string, not a true/false value, hence the incompatible types error. (To clarify, Java sees a string: if("Double.valueOf(String[2]) > 20"){} not if(Double.valueOf(String[2]) > 20){})

I would probably just use a switch on the comparison operator (make sure it's a string not a char):

switch(operator) {
    case ">":
        doStuffGreaterThan();
        break;  // Needed or else it will continue into the next cases too
    case "<":
        doStuffLessThan();
        break;
    case ">=":
        doStuffGE();
        break;
    ... etc ...
}

Edit: I did a bit of searching and found this, which I haven't seen before but may be useful.


问:
Using Unity 2.0 handle exception
When I use Unity 2.0 to handle exception, I got some problem, like below:

```<code>public class TraceBehavior : IInterceptionBehavior
{
    public IEnumerable<Type> GetRequiredInterfaces()
    {
        return Type.EmptyTypes;
    }

    public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
    {
        Console.WriteLine(string.Format("Invoke method:{0}",input.MethodBase.ToString()));
        IMethodReturn result = getNext()(input, getNext);
        if (result.Exception == null)
        {
            Console.WriteLine("Invoke successful!");
        }
        else
        {
            Console.WriteLine(string.Format("Invoke faild, error: {0}", result.Exception.Message));
            result.Exception = null;
        }
        return result;
    }

    public bool WillExecute { get { return true; } }
}
</code>```

I have set result.Exception=null (it's meaning that I have resolved the exception and need not throw again.)

However,it throw a exception to me.

答: That's not how it works. Don't set result.Exception, instead return input.CreateMethodReturn(newReturnValues).</p>

ContentLicense: CC BY-SA 3.0

Title: Using Unity 2.0 handle exception

Body:
When I use Unity 2.0 to handle exception, I got some problem, like below:

public class TraceBehavior : IInterceptionBehavior
{
    public IEnumerable<Type> GetRequiredInterfaces()
    {
        return Type.EmptyTypes;
    }

    public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
    {
        Console.WriteLine(string.Format("Invoke method:{0}",input.MethodBase.ToString()));
        IMethodReturn result = getNext()(input, getNext);
        if (result.Exception == null)
        {
            Console.WriteLine("Invoke successful!");
        }
        else
        {
            Console.WriteLine(string.Format("Invoke faild, error: {0}", result.Exception.Message));
            result.Exception = null;
        }
        return result;
    }

    public bool WillExecute { get { return true; } }
}

I have set result.Exception=null (it's meaning that I have resolved the exception and need not throw again.)

However,it throw a exception to me.


问:
Passing data between Widgets without using Navigator?
I've some struggling with flutter.
I've two widget Details screen so in the first Details, I have a list and I want to send it to the second Screen without using navigator.

So if there is anyone who can help me I will be very thankful.

Details :

```<code> List<String> _instructions = [];

class Details extends StatefulWidget {
  @override
  _DetailsState createState() => new _DetailsState();
}

class _DetailsState extends State<Details> {
              Expanded(
                child: Container(
                  margin: EdgeInsets.all(3),
                  child: OutlineButton(
                    highlightElevation: 21,
                    color: Colors.white,
                    shape: StadiumBorder(),
                    textColor: Colors.lightBlue,
                    child: Text(
                      'ENVOYER',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        fontStyle: FontStyle.normal,
                        color: Colors.lightBlue,
                      ),
                    ),
                    borderSide: BorderSide(
                        color: Colors.lightBlue,
                        style: BorderStyle.solid,
                        width: 1),
                    onPressed: () {

                    },
                  ),
                ),
              ),
}}
</code>```

so what I want is that,when I press the button I will send my list to the next widget without using navigator.

答:
Suppose you have two pages, namely 'page1.dart' and 'page2.dart', both want to access the same list:

Create another dart file 'GlobalVariables.dart', inside this file, create a class gv.

Inside this class gv, create a static list by using:

```<code>static List <String> listAnyList = [];
</code>```

import 'GlobalVariables.dart' in the 2 pages that need to access this list.

Now, in page1.dart and page2.dart,
you can use gv.listAnyList to access the 'Global List'.

Use 'Global Static Variables' if a variable is needed in many dart files, e.g. the 'User ID', then you can simply use gv.strUserID to access it in any pages you want.

Body:
I've some struggling with flutter.
I've two widget Details screen so in the first Details, I have a list and I want to send it to the second Screen without using navigator.

So if there is anyone who can help me I will be very thankful.

Details :

 List<String> _instructions = [];

class Details extends StatefulWidget {
  @override
  _DetailsState createState() => new _DetailsState();
}

class _DetailsState extends State {
              Expanded(
                child: Container(
                  margin: EdgeInsets.all(3),
                  child: OutlineButton(
                    highlightElevation: 21,
                    color: Colors.white,
                    shape: StadiumBorder(),
                    textColor: Colors.lightBlue,
                    child: Text(
                      'ENVOYER',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        fontStyle: FontStyle.normal,
                        color: Colors.lightBlue,
                      ),
                    ),
                    borderSide: BorderSide(
                        color: Colors.lightBlue,
                        style: BorderStyle.solid,
                        width: 1),
                    onPressed: () {

                    },
                  ),
                ),
              ),
}}

so what I want is that,when I press the button I will send my list to the next widget without using navigator.

Body:
Suppose you have two pages, namely 'page1.dart' and 'page2.dart', both want to access the same list:

Create another dart file 'GlobalVariables.dart', inside this file, create a class gv.

Inside this class gv, create a static list by using:

static List <String> listAnyList = [];

import 'GlobalVariables.dart' in the 2 pages that need to access this list.

Now, in page1.dart and page2.dart,
you can use gv.listAnyList to access the 'Global List'.

Use 'Global Static Variables' if a variable is needed in many dart files, e.g. the 'User ID', then you can simply use gv.strUserID to access it in any pages you want.


问:
Comprehension with variable number of arguments?
Can comprehensions be built programmatically to handle variable number of arguments as in Haskell?

For example, how to extend this outer product for dictionaries to more than 2 dictionaries:

```<code>def outer(f,g):
    return lambda d1,d2: {f(k1,k2):g(v1,v2) for k1,v1 in d1.items() for k2,v2 in d2.items()}
</code>```

Given:

```<code>d1 = {'a':1, 'b':2}
d2 = {'a':10, 'b':11, 'c':12}
</code>```

and these helper functions that work with variable args:

```<code>def string_join(*arg):
    return ''.join(tuple(arg))

def arg_sum(*arg):
    return sum(tuple(arg))
</code>```

Then:

```<code>outer(string_join,arg_sum)(d1,d2)
</code>```

{'aa': 11, 'ab': 12, 'ac': 13, 'ba': 12, 'bb': 13, 'bc': 14}

Can the convenient comprehension be extended to variable arg (d1,d2,d3...) or need to use for loops?

答:
The language doesn’t support this directly (since odometer control flow is very different at the bytecode level), but it can be implemented with itertools.product and extensive * unpacking:

```<code>def outer1(f,g,e):
  a,b=zip(*e)
  return f(*a),g(*b)
def outer(f,g):
  return lambda *dd: dict(outer1(f,g,e) for e in itertools.product(*(d.items() for x in dd)))
</code>```

Body:
Can comprehensions be built programmatically to handle variable number of arguments as in Haskell?

For example, how to extend this outer product for dictionaries to more than 2 dictionaries:

def outer(f,g):
    return lambda d1,d2: {f(k1,k2):g(v1,v2) for k1,v1 in d1.items() for k2,v2 in d2.items()}

Given:

d1 = {'a':1, 'b':2}
d2 = {'a':10, 'b':11, 'c':12}

and these helper functions that work with variable args:

def string_join(*arg):
    return ''.join(tuple(arg))

def arg_sum(*arg):
    return sum(tuple(arg))

Then:

outer(string_join,arg_sum)(d1,d2)

{'aa': 11, 'ab': 12, 'ac': 13, 'ba': 12, 'bb': 13, 'bc': 14}

Can the convenient comprehension be extended to variable arg (d1,d2,d3...) or need to use for loops?

Body:
The language doesn’t support this directly (since odometer control flow is very different at the bytecode level), but it can be implemented with itertools.product and extensive * unpacking:

def outer1(f,g,e):
  a,b=zip(*e)
  return f(*a),g(*b)
def outer(f,g):
  return lambda *dd: dict(outer1(f,g,e) for e in itertools.product(*(d.items() for x in dd)))


问:
Vimeo embed on webpage causes an error
I'm trying to troubleshoot a strange bug on one of our pages (https://www.bbg.org/visit/sakura_matsuri_photos).
The bottom of left of the page has the text 'cp_vimeo_code.js Open' and I can't figure out what is generating this.
here is what it looks like

I've noticed that there are other websites that show this error too, for example: https://www.indicia.nl/project/anderson-macgyver/.

I have the following three embeds inside the body tag of a webpage in Expression Engine. Taking them out eliminates the error.

```

Has anyone seen something like this before? I can't find it on Vimeo's site anywhere.
Here is a picture of the error on our page

答: I finally figured where this was coming from, it was some extra code in a Google Tag Manger custom tag!!</p>

Title: Vimeo embed on webpage causes an error

Body:
I'm trying to troubleshoot a strange bug on one of our pages (https://www.bbg.org/visit/sakura_matsuri_photos).
The bottom of left of the page has the text 'cp_vimeo_code.js Open' and I can't figure out what is generating this.
here is what it looks like

I've noticed that there are other websites that show this error too, for example: https://www.indicia.nl/project/anderson-macgyver/.

I have the following three embeds inside the body tag of a webpage in Expression Engine. Taking them out eliminates the error.

Has anyone seen something like this before? I can't find it on Vimeo's site anywhere.
Here is a picture of the error on our page


问:
How to convert my select statement into update statement?
```<code>SELECT quotes.qid, SUM(qitems.net_cost_ext)
FROM quotes, qitems
WHERE quotes.qid = qitems.qid
GROUP BY qitems.qid;

UPDATE quotes, qitems
SET quotes.net_cost_total = SUM(qitems.net_cost_ext)
WHERE quotes.qid = qitems.qid
GROUP BY qitems.qid;
</code>```

The above select statements sums up the net cost for all the products on each quote and displays the sum by quote number.

I added a net_cost_total field to the quotes table. I want to update all the quotes with the net_cost totals from each quote. The query fails, it says the GROUP syntax is bad, I'm not sure how else to go about this.

答:
Try this one:</p>

```<code>UPDATE quotes AS q
        JOIN (SELECT quotes.qid,
                         SUM(qitems.net_cost_ext) AS SUM
                  FROM   quotes,
                         qitems
                  WHERE  quotes.qid = qitems.qid
                  GROUP  BY qitems.qid) AS d
         ON d.qid = q.qid
SET    q.net_cost_total = d.SUM
</code>```

Body:
SELECT quotes.qid, SUM(qitems.net_cost_ext)
FROM quotes, qitems
WHERE quotes.qid = qitems.qid
GROUP BY qitems.qid;

UPDATE quotes, qitems
SET quotes.net_cost_total = SUM(qitems.net_cost_ext)
WHERE quotes.qid = qitems.qid
GROUP BY qitems.qid;

The above select statements sums up the net cost for all the products on each quote and displays the sum by quote number.

I added a net_cost_total field to the quotes table. I want to update all the quotes with the net_cost totals from each quote. The query fails, it says the GROUP syntax is bad, I'm not sure how else to go about this.

Body:
Try this one:

UPDATE quotes AS q
        JOIN (SELECT quotes.qid,
                         SUM(qitems.net_cost_ext) AS SUM
                  FROM   quotes,
                         qitems
                  WHERE  quotes.qid = qitems.qid
                  GROUP  BY qitems.qid) AS d
         ON d.qid = q.qid
SET    q.net_cost_total = d.SUM


问:
Ignoring newlines with regex in xml
This is for a project for a very specific use.

I am trying to find how to find any empty text from the xml and replace it with a message.

```<code>regex = re.compile(r'>\s*</')

replaced = re.sub(regex, ">[!] JSON value does not exist, Check your Json!</", temp)
</code>```

For example filename is blank

```<code>        <file>
            <fileType>Mezza</fileType>
            <fileName></fileName>
            <segments>0000</segments>
        </file>
</code>```

and the output would be:

```<code>         <file>
            <fileType>Mezza</fileType>
            <fileName>[!] value does not exist!</fileName>
            <segments>0000</segments>
        </file>
</code>```

However I am getting for other parts where there is white space and newline I dont want to have this message, both tag names are different there is a new line and they are closing tags how do I implement this in regex?:

```<code></fileName>[!] value does not exist!</file>
</code>```

答:
Maybe, another option here we might be having would be to just find filename, and replace what we desire inside the tag, with likely an expression such as:

```<code>(<fileName>)(.+)?(<\/fileName>)
</code>```

if I understand the problem correctly.

Demo 1

If we have fully empty tags, this expression might likely work:

```<code>(>)()(<\/)
</code>```

Demo 2

If we will be having empty tags and tags with horizontal spaces, then we would be expanding it to:

```<code>(>)(|[^\S\r\n]+)(<\/)
</code>```

Demo 3

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(<fileName>)(.+)?(<\/fileName>)"

test_str = ("        <file>               \n"
    "            <fileType>Mezza</fileType>\n"
    "            <fileName></fileName>\n"
    "            <segments>0000</segments>\n"
    "        </file>")

subst = "\\1[!] value does not exist!\\3"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

Title: Ignoring newlines with regex in xml

Body:
This is for a project for a very specific use.

I am trying to find how to find any empty text from the xml and replace it with a message.

regex = re.compile(r'>\s*</')

replaced = re.sub(regex, ">[!] JSON value does not exist, Check your Json!</", temp)

For example filename is blank

        <file>
            <fileType>Mezza</fileType>
            <fileName></fileName>
            <segments>0000</segments>
        </file>

and the output would be:

         <file>
            <fileType>Mezza</fileType>
            <fileName>[!] value does not exist!</fileName>
            <segments>0000</segments>
        </file>

However I am getting for other parts where there is white space and newline I dont want to have this message, both tag names are different there is a new line and they are closing tags how do I implement this in regex?:

</fileName>[!] value does not exist!</file>

Body:
Maybe, another option here we might be having would be to just find filename, and replace what we desire inside the tag, with likely an expression such as:

(<fileName>)(.+)?(<\/fileName>)

if I understand the problem correctly.

Demo 1

If we have fully empty tags, this expression might likely work:

(>)()(<\/)

Demo 2

If we will be having empty tags and tags with horizontal spaces, then we would be expanding it to:

(>)(|[^\S\r\n]+)(<\/)

Demo 3

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(<fileName>)(.+)?(<\/fileName>)"

test_str = ("        <file>               \n"
    "            <fileType>Mezza</fileType>\n"
    "            <fileName></fileName>\n"
    "            <segments>0000</segments>\n"
    "        </file>")

subst = "\\1[!] value does not exist!\\3"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.


问:
why is my nslookup not always returning an IP?
I wrote an nslookup code but in some cases, it does not print the IP, it prints some domain.

I wrote a DNS packet that the dst IP is 8.8.8.8.
for example the domain "stackoverflow.com" will work but for this one "s.ytimg.com" it wont work and the answer will be "b'ytstatic.l.google.com.'"

```<code># Creates DNS request
fullmsg = IP(dst = DST_IP)/UDP()/DNS(rd = 1,qd = DNSQR(qname = "s.ytimg.com"))
ans = sr1(fullmsg, verbose = 0)
print(ans[DNS].summary())# output: DNS Ans "b'ytstatic.l.google.com.'" expected: "172.217.17.78"
</code>```

I expected that it will print the IP but like I said it does not print IP for every entered domain.

答:
You are getting a CNAME as the answer. You need to further resolve it. I.e.: check if the answer is a valid IP address. If it isn't try to resolve the answer.

https://en.wikipedia.org/wiki/CNAME_record

Body:
I wrote an nslookup code but in some cases, it does not print the IP, it prints some domain.

I wrote a DNS packet that the dst IP is 8.8.8.8.
for example the domain "stackoverflow.com" will work but for this one "s.ytimg.com" it wont work and the answer will be "b'ytstatic.l.google.com.'"

# Creates DNS request
fullmsg = IP(dst = DST_IP)/UDP()/DNS(rd = 1,qd = DNSQR(qname = "s.ytimg.com"))
ans = sr1(fullmsg, verbose = 0)
print(ans[DNS].summary())# output: DNS Ans "b'ytstatic.l.google.com.'" expected: "172.217.17.78"

I expected that it will print the IP but like I said it does not print IP for every entered domain.


问:
OnChange angular is not printing the exact value
I'm trying to retrieve value from a select box on Onchange event:
here is the code I tried :

html:

```<code><select  (change)="onChangeObj($event.target.value)">
    <option value="" hidden>Select</option>
    <option *ngFor="let x of fruits" [ngValue]="x.code"> {{x.name}}</option>
</select>
</code>```

ts:

```<code>onChangeObj(value) {
    console.log(value);
}
</code>```

When I'm printing the value it is printing:
1: AP
2: OR
etc..  how can I print the exact value ('AP', 'OR') without 1: , 2: etc...

example Json :

`Json : { name: "Orange", code: "OR", description: "Orange fruit" }, { name: "Apple", code: "AP", description: "Apple friut" }

when use ($event.target.value).. I'm getting '2: AP' , '1: OR' like that not sure where this numbers are adding.. so now I want only 'OR', 'AP'etc..

答:
Actually your code is correct.
Check your code in action in Stackblitz

Maybe, something is going wrong in your side.

Body:
I'm trying to retrieve value from a select box on Onchange event:
here is the code I tried :

html:

<select  (change)="onChangeObj($event.target.value)">
    <option value="" hidden>Select</option>
    <option *ngFor="let x of fruits" [ngValue]="x.code"> {{x.name}}</option>
</select>

ts:

onChangeObj(value) {
    console.log(value);
}

When I'm printing the value it is printing:
1: AP
2: OR
etc..  how can I print the exact value ('AP', 'OR') without 1: , 2: etc...

example Json :

`Json : { name: "Orange", code: "OR", description: "Orange fruit" }, { name: "Apple", code: "AP", description: "Apple friut" }

when use ($event.target.value).. I'm getting '2: AP' , '1: OR' like that not sure where this numbers are adding.. so now I want only 'OR', 'AP'etc..


问:
How to set already running binary to run at startup
I have a Go program that is supposed to run as a daemon with minimal front-end for the user (just an icon in the system tray.)

The fact that it's written in Go doesn't really matter much, the main issue I have is getting a binary (that is already running) to run at startup on a Mac.

I can set the binary to run at startup like so:

```<code>cp daemon.plist ~/Library/LaunchAgents/daemon.plist
</code>```

(cp the plist into the LaunchAgents directory)

```<code>launchctl load -w ~/Library/LaunchAgents/daemon.plist
</code>```

(then load the plist with launchctl.)

And that works fine.  The only issue is that launchctl load it starts another instance of the binary that is already running.  I want to be able to enable (and disable) running the binary at startup for the binary that is running, without starting another instance of it.

And here's the .plist file if you want to see it:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>daemon</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Applications/Daemon.app/Contents/MacOS/daemon</string>
    </array>
    <key>ProcessType</key>
    <string>Interactive</string>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <false/>
</dict>
</plist>
</code>```

答:
I figured it out.

So first, the binary is running.  It starts out as not enabled to run at startup.  To initialize, you cp the plist to the ~/Library/LaunchAgents/ directory:

```<code>cp daemon.plist ~/Library/LaunchAgents/daemon.plist
</code>```

And the plist looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>daemon</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Applications/Daemon.app/Contents/MacOS/daemon</string>
    </array>
    <key>ProcessType</key>
    <string>Interactive</string>
    <key>RunAtLoad</key>
    <false/>
    <key>KeepAlive</key>
    <false/>
</dict>
</plist>
</code>```

NOTE: The RunAtLoad key is set to false.

Then we load it into launchctl:

```<code>launchctl load -w ~/Library/LaunchAgents/daemon.plist
</code>```

It shouldn't load since RunAtLoad is set to false.

Then, we can enable and disable running at startup like so:

To enable:

Set RunAtLoad to true

cp the plist over

To disable:

Set RunAtLoad to false

cp the plist over

Kind of hacky, but it works.

Body:
I have a Go program that is supposed to run as a daemon with minimal front-end for the user (just an icon in the system tray.)

The fact that it's written in Go doesn't really matter much, the main issue I have is getting a binary (that is already running) to run at startup on a Mac.

I can set the binary to run at startup like so:

cp daemon.plist ~/Library/LaunchAgents/daemon.plist

(cp the plist into the LaunchAgents directory)

launchctl load -w ~/Library/LaunchAgents/daemon.plist

(then load the plist with launchctl.)

And that works fine.  The only issue is that launchctl load it starts another instance of the binary that is already running.  I want to be able to enable (and disable) running the binary at startup for the binary that is running, without starting another instance of it.

And here's the .plist file if you want to see it:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>daemon</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Applications/Daemon.app/Contents/MacOS/daemon</string>
    </array>
    <key>ProcessType</key>
    <string>Interactive</string>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <false/>
</dict>
</plist>

Body:
I figured it out.

So first, the binary is running.  It starts out as not enabled to run at startup.  To initialize, you cp the plist to the ~/Library/LaunchAgents/ directory:

cp daemon.plist ~/Library/LaunchAgents/daemon.plist

And the plist looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>daemon</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Applications/Daemon.app/Contents/MacOS/daemon</string>
    </array>
    <key>ProcessType</key>
    <string>Interactive</string>
    <key>RunAtLoad</key>
    <false/>
    <key>KeepAlive</key>
    <false/>
</dict>
</plist>

NOTE: The RunAtLoad key is set to false.

Then we load it into launchctl:

launchctl load -w ~/Library/LaunchAgents/daemon.plist

It shouldn't load since RunAtLoad is set to false.

Then, we can enable and disable running at startup like so:

To enable:

Set RunAtLoad to true

cp the plist over

To disable:

Set RunAtLoad to false

cp the plist over

Kind of hacky, but it works.


问:
Comparing objects based on the values of multiple fields using Comparator
How can I improve the comparator for objects by several fields? The comparator must sort user by last name or first name if last name doesn't exist. And if there are no last name and first name sort by username. But these users must be at the end of the list.

```<code>public static Comparator<UserConfigurationDto> BY_LASTNAME =  (u1, u2) -> {
        // if users have only username compare them
        if((u1.getLastName().isEmpty() && u1.getFirstName().isEmpty())
                && (u2.getLastName().isEmpty() && u2.getFirstName().isEmpty())){
            return u1.getUsername().compareToIgnoreCase(u2.getUsername());
        }
        //if user doesnt have firstName and LastName drop them at the end
        if(u1.getLastName().isEmpty() && u1.getFirstName().isEmpty()){
            return 1000000 + getWeight(u1.getUsername());
        }
        if(u2.getLastName().isEmpty() && u2.getFirstName().isEmpty()){
            return -1000000 + getWeight(u2.getUsername());
        }
      String s1 = u1.getLastName().isEmpty() ? u1.getFirstName() : u1.getLastName();
      String s2 = u2.getLastName().isEmpty() ? u2.getFirstName() : u2.getLastName();
      return s1.compareToIgnoreCase(s2);
    };
}
private static int getWeight(String s){
    return s.codePoints().sum();
}
</code>```

Does anybody have an idea how to improve this? I try to use Comparator.comparing and Comparator.thenComparing but they produce an incorrect result

答:
I think you can use the Java 8 static comparing function that includes the key comparator to achieve this. String has a handy case insensitive comparator that you can use in a few places as well.</p>

```<code>Comparator.comparing(
                (UserConfigurationDto u) -> u.getLastName().isEmpty()?u.getFirstName():u.getLastName(),
                ((s1, s2) -> {
                    if(s1.isEmpty()) {
                        return 1;
                    } else if(s2.isEmpty()) {
                        return -1;
                    }
                    else {
                        return String.CASE_INSENSITIVE_ORDER.compare(s1, s2);
                    }
                }))
                .thenComparing(UserConfigurationDto::getUsername, String.CASE_INSENSITIVE_ORDER);
</code>```

Body:
How can I improve the comparator for objects by several fields? The comparator must sort user by last name or first name if last name doesn't exist. And if there are no last name and first name sort by username. But these users must be at the end of the list.

public static Comparator<UserConfigurationDto> BY_LASTNAME =  (u1, u2) -> {
        // if users have only username compare them
        if((u1.getLastName().isEmpty() && u1.getFirstName().isEmpty())
                && (u2.getLastName().isEmpty() && u2.getFirstName().isEmpty())){
            return u1.getUsername().compareToIgnoreCase(u2.getUsername());
        }
        //if user doesnt have firstName and LastName drop them at the end
        if(u1.getLastName().isEmpty() && u1.getFirstName().isEmpty()){
            return 1000000 + getWeight(u1.getUsername());
        }
        if(u2.getLastName().isEmpty() && u2.getFirstName().isEmpty()){
            return -1000000 + getWeight(u2.getUsername());
        }
      String s1 = u1.getLastName().isEmpty() ? u1.getFirstName() : u1.getLastName();
      String s2 = u2.getLastName().isEmpty() ? u2.getFirstName() : u2.getLastName();
      return s1.compareToIgnoreCase(s2);
    };
}
private static int getWeight(String s){
    return s.codePoints().sum();
}

Does anybody have an idea how to improve this? I try to use Comparator.comparing and Comparator.thenComparing but they produce an incorrect result

Body:
I think you can use the Java 8 static comparing function that includes the key comparator to achieve this. String has a handy case insensitive comparator that you can use in a few places as well.

Comparator.comparing(
                (UserConfigurationDto u) -> u.getLastName().isEmpty()?u.getFirstName():u.getLastName(),
                ((s1, s2) -> {
                    if(s1.isEmpty()) {
                        return 1;
                    } else if(s2.isEmpty()) {
                        return -1;
                    }
                    else {
                        return String.CASE_INSENSITIVE_ORDER.compare(s1, s2);
                    }
                }))
                .thenComparing(UserConfigurationDto::getUsername, String.CASE_INSENSITIVE_ORDER);


答:
Try:

```<code>UPDATE quotes
INNER JOIN (
    SELECT SUM(qitems.net_cost_ext) AS s
    FROM qitems
    GROUP BY qitems.qid
  ) q USING(qid)
SET net_cost_total = q.s
</code>```

(inspired from the last MySQL comment here)

Title: How to convert my select statement into update statement?

Body:
Try:

UPDATE quotes
INNER JOIN (
    SELECT SUM(qitems.net_cost_ext) AS s
    FROM qitems
    GROUP BY qitems.qid
  ) q USING(qid)
SET net_cost_total = q.s

(inspired from the last MySQL comment here)


问:
Searching a tuple element in a list of lists without changing the data structure
I'd like to search user input in a tuple located in a list of lists.

```<code>data = [[('tick1',12),4],[('tick2', 16),7],...]

if user input: 'tick1'
desired output:[('tick1',12),4]
</code>```

I can do this if I change my list to a dictionary:

```<code>data = [[('tick1',12),4],[('tick2', 16),7]]

data = dict(data)

if not any('tick2' in x for x in data):
    print('not found')
else:
    print('found:', x)

#Output
found: [('tick2', 16), 7]
</code>```

But how can I do this if I want to maintain the list type?

答:
You can use a list comprehension to iterate over the sublists and check for the user input in x[0] which is a tuple

```<code>data = [[('tick1',12),4],[('tick2', 16),7]]

user_input = 'tick1'

output = [x for x in data if user_input in x[0]]
# [[('tick1', 12), 4]]
</code>```

Body:
I'd like to search user input in a tuple located in a list of lists.

data = [[('tick1',12),4],[('tick2', 16),7],...]

if user input: 'tick1'
desired output:[('tick1',12),4]

I can do this if I change my list to a dictionary:

data = [[('tick1',12),4],[('tick2', 16),7]]

data = dict(data)

if not any('tick2' in x for x in data):
    print('not found')
else:
    print('found:', x)

#Output
found: [('tick2', 16), 7]

But how can I do this if I want to maintain the list type?

Body:
You can use a list comprehension to iterate over the sublists and check for the user input in x[0] which is a tuple

data = [[('tick1',12),4],[('tick2', 16),7]]

user_input = 'tick1'

output = [x for x in data if user_input in x[0]]
# [[('tick1', 12), 4]]


问:
How does Spring handle thread safety when a single controller gets many requests?
A single controller in Spring usually has many Request Mappings. Many requests may hit APIs belonging to one controller(means one class) at the same time. Does n't it lead to thread safety issues?
Q1) Is Spring controller inherently thread-safe?

My answer: By default, Spring controller is a Singleton bean. Whether it is inherently thread-safe or not depends upon how Singleton pattern is implemented by Spring. It can be done thread-safe or non-threadsafe. Correct?

Q2) Does Spring provide any annotation or configuration to ensure that handling multiple requests does not run into thread safety issues?
Q3) Is ensuring thread safety the burden of the developer himself?

答:
For your first question about how the Singleton pattern is implemented by Spring
see this link:

How does the singleton Bean serve the concurrent request?

Spring concurrency:
How does Spring bean Handle concurrency

How does Spring MVC handle multiple users


答:
You just iterate over all the elements of the list:

```<code>for (name, num), other in data:
    if name == user_input:
        print("Found it!")
</code>```

Or, if you're into comprehensions:

```<code>if any(True for (name, num), other in data if name == user_input):
# Or: if any(name == user_input for (name, num), other in data):
    print("Found it!")
</code>```

Title: Searching a tuple element in a list of lists without changing the data structure

Body:
You just iterate over all the elements of the list:

for (name, num), other in data:
    if name == user_input:
        print("Found it!")

Or, if you're into comprehensions:

if any(True for (name, num), other in data if name == user_input):
# Or: if any(name == user_input for (name, num), other in data):
    print("Found it!")


问:
Assign negative value to char in Java
I want to assign a negative value to char in Java.
Example: char a='-1'
I tried the below example but an error occurs.

```<code> char[] temp=new char[10];
    for(int i=0;i<10;i++)
    {
        if(condition met)
        temp[i]='-1';
    }
</code>```

答:
You can do this, but char is 16-bit unsigned int so it will result in the char actually being 65535. See this answer for more info.

```<code>char a = (char)-1;
char b = (char)0;
System.out.println((int)a);
System.out.println((int)b);
</code>```

Will result in output of:

```<code>65535
0
</code>```

Title: Assign negative value to char in Java

Body:
I want to assign a negative value to char in Java.
Example: char a='-1'
I tried the below example but an error occurs.

 char[] temp=new char[10];
    for(int i=0;i<10;i++)
    {
        if(condition met)
        temp[i]='-1';
    }

Body:
You can do this, but char is 16-bit unsigned int so it will result in the char actually being 65535. See this answer for more info.

char a = (char)-1;
char b = (char)0;
System.out.println((int)a);
System.out.println((int)b);

Will result in output of:

65535
0


问:
Can't acces a global variable inside a method
I have a problem that when i try to use a global variable inside a method, an error is produced ("local variable 'b' referenced before assignment").
Why is this not the case when the variable is an element of a list?

this works fine:

```<code>a = [1]
def a_add():
    a[0] += 1

a_add()
print(a)
</code>```

but this doesn't:

```<code>b = 1
def b_add():
    b += 1

b_add()
print(b)
</code>```

答:
If anybody wants to take a deep dive into CPython and see the exact reason why this does not work, check out this link to the CPypthon ceval.c sourcecode file. This is the code that executes the python bytecode.
As Vallentin said, python does a LOAD_FAST bytecode instruction for loading b (see below).

```<code>>>> x = 1
>>> def f():
...     x += 1
...
>>> dis.dis(f)
  2           0 LOAD_FAST                0 (x)
              2 LOAD_CONST               1 (1)
              4 INPLACE_ADD
              6 STORE_FAST               0 (x)
              8 LOAD_CONST               0 (None)
             10 RETURN_VALUE
</code>```

In the ceval.c file on line 1228 (as of the 30st of May 2019) the relevant code is as follows:

```<code>case TARGET(LOAD_FAST): {
        PyObject *value = GETLOCAL(oparg);
        if (value == NULL) {
            format_exc_check_arg(tstate, PyExc_UnboundLocalError,
                                 UNBOUNDLOCAL_ERROR_MSG,
                                 PyTuple_GetItem(co->co_varnames, oparg));
            goto error;
</code>```

Body:
I have a problem that when i try to use a global variable inside a method, an error is produced ("local variable 'b' referenced before assignment").
Why is this not the case when the variable is an element of a list?

this works fine:

a = [1]
def a_add():
    a[0] += 1

a_add()
print(a)

but this doesn't:

b = 1
def b_add():
    b += 1

b_add()
print(b)

Body:
If anybody wants to take a deep dive into CPython and see the exact reason why this does not work, check out this link to the CPypthon ceval.c sourcecode file. This is the code that executes the python bytecode.
As Vallentin said, python does a LOAD_FAST bytecode instruction for loading b (see below).

>>> x = 1
>>> def f():
...     x += 1
...
>>> dis.dis(f)
  2           0 LOAD_FAST                0 (x)
              2 LOAD_CONST               1 (1)
              4 INPLACE_ADD
              6 STORE_FAST               0 (x)
              8 LOAD_CONST               0 (None)
             10 RETURN_VALUE

In the ceval.c file on line 1228 (as of the 30st of May 2019) the relevant code is as follows:

case TARGET(LOAD_FAST): {
        PyObject *value = GETLOCAL(oparg);
        if (value == NULL) {
            format_exc_check_arg(tstate, PyExc_UnboundLocalError,
                                 UNBOUNDLOCAL_ERROR_MSG,
                                 PyTuple_GetItem(co->co_varnames, oparg));
            goto error;


问:
Overriding Array.of() in Typescript for a custom 2D array class that extends Array
I'm trying to extend Array and make an Array2D class. I want the constructor to take in any number of arguments, but these arguments should be Arrays of type T. Here is what I have so far:

```<code>class Array2D<T> extends Array<T[]> {
  constructor(...args: T[][]) {
    super(...args)
  }

  static of(...args: T[][]) {
    return new Array2D(...args)
  }
}
</code>```

Typescript is showing this error:

```<code>Types of property 'of' are incompatible.
    Type '<T>(...args: T[][]) => Array2D<T>' is not assignable to type '<T>(...items: T[]) => T[]'.
      Types of parameters 'args' and 'items' are incompatible.
        Type 'T' is not assignable to type 'T[]'.
</code>```

Can someone explain what Tyspecript is complaining about and how to fix this.

答:
Here's another typing workaround.  Let's widen the type of the Array constuctor to something with no known static methods:

```<code>const VanillaArrayConstructor: new <T>(...args: T[]) => Array<T>
    = Array;
</code>```

You can use VanillaArrayConstructor to construct arrays, but the compiler will complain if you try to call .from() or .of() or any other static methods.  And then you can extend that instead of Array:

```<code>class Array2D<T> extends VanillaArrayConstructor<T[]> {
    constructor(...args: T[][]) {
        super(...args)
    }

    static of<T>(...args: T[][]) {
        return new Array2D(...args)
    }
}
</code>```

This makes no difference to the actual behavior of Array2D at runtime, but the typing is now such that the compiler has no expectation that the type of the Array2D constructor extends the type of the Array constructor.

Hope that helps.  Good luck!

Link to code

Body:
I'm trying to extend Array and make an Array2D class. I want the constructor to take in any number of arguments, but these arguments should be Arrays of type T. Here is what I have so far:

class Array2D<T> extends Array<T[]> {
  constructor(...args: T[][]) {
    super(...args)
  }

  static of(...args: T[][]) {
    return new Array2D(...args)
  }
}

Typescript is showing this error:

Types of property 'of' are incompatible.
    Type '<T>(...args: T[][]) => Array2D<T>' is not assignable to type '<T>(...items: T[]) => T[]'.
      Types of parameters 'args' and 'items' are incompatible.
        Type 'T' is not assignable to type 'T[]'.

Can someone explain what Tyspecript is complaining about and how to fix this.

Body:
Here's another typing workaround.  Let's widen the type of the Array constuctor to something with no known static methods:

const VanillaArrayConstructor: new <T>(...args: T[]) => Array<T>
    = Array;

You can use VanillaArrayConstructor to construct arrays, but the compiler will complain if you try to call .from() or .of() or any other static methods.  And then you can extend that instead of Array:

class Array2D<T> extends VanillaArrayConstructor<T[]> {
    constructor(...args: T[][]) {
        super(...args)
    }

    static of<T>(...args: T[][]) {
        return new Array2D(...args)
    }
}

This makes no difference to the actual behavior of Array2D at runtime, but the typing is now such that the compiler has no expectation that the type of the Array2D constructor extends the type of the Array constructor.

Hope that helps.  Good luck!

Link to code


答:
```<code>for tick in data:
    if tick[0][0]==user_input:
        print(tick)
    else:
        pass
</code>```


问:
How do you read a file inside a zip file as text, not bytes?
A simple program for reading a CSV file inside a ZIP archive:

import csv, sys, zipfile

zip_file    = zipfile.ZipFile(sys.argv[1])
items_file  = zip_file.open('items.csv', 'rU')

for row in csv.DictReader(items_file):
    pass
```
<p>works in Python 2.7:</p>
<pre class="lang-none prettyprint-override"><code>$ python2.7 test_zip_file_py3k.py ~/data.zip
$
</code>```

but not in Python 3.2:

$ python3.2 test_zip_file_py3k.py ~/data.zip
Traceback (most recent call last):
    File "test_zip_file_py3k.py", line 8, in <module>
    for row in csv.DictReader(items_file):
    File "/somedir/python3.2/csv.py", line 109, in __next__
    self.fieldnames
    File "/somedir/python3.2/csv.py", line 96, in fieldnames
    self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file
in text mode?)
```

The csv module in Python 3 wants to see a text file, but zipfile.ZipFile.open returns a zipfile.ZipExtFile that is always treated as binary data.

How does one make this work in Python 3?

答:
I just noticed that Lennart's answer didn't work with Python 3.1, but it does work with Python 3.2. They've enhanced zipfile.ZipExtFile in Python 3.2 (see release notes). These changes appear to make zipfile.ZipExtFile work nicely with io.TextWrapper.

Incidentally, it works in Python 3.1, if you uncomment the hacky lines below to monkey-patch zipfile.ZipExtFile, not that I would recommend this sort of hackery. I include it only to illustrate the essence of what was done in Python 3.2 to make things work nicely.

```<code>$ cat test_zip_file_py3k.py
import csv, io, sys, zipfile

zip_file    = zipfile.ZipFile(sys.argv[1])
items_file  = zip_file.open('items.csv', 'rU')
# items_file.readable = lambda: True
# items_file.writable = lambda: False
# items_file.seekable = lambda: False
# items_file.read1 = items_file.read
items_file  = io.TextIOWrapper(items_file)

for idx, row in enumerate(csv.DictReader(items_file)):
    print('Processing row {0} -- row = {1}'.format(idx, row))
</code>```

If I had to support py3k < 3.2, then I would go with the solution in my other answer.

Update for 3.6+

Starting w/3.6, support for mode='U' was removed^1:

Changed in version 3.6: Removed support of mode='U'. Use io.TextIOWrapper for reading compressed text files in universal newlines mode.

Starting w/3.8, a Path object was added which gives us an open() method that we can call like the built-in open() function (passing newline='' in the case of our CSV) and we get back an io.TextIOWrapper object the csv readers accept.  See Yuri's answer, here.

Body:
A simple program for reading a CSV file inside a ZIP archive:

import csv, sys, zipfile

zip_file    = zipfile.ZipFile(sys.argv[1])
items_file  = zip_file.open('items.csv', 'rU')

for row in csv.DictReader(items_file):
    pass

works in Python 2.7:

$ python2.7 test_zip_file_py3k.py ~/data.zip
$

but not in Python 3.2:

$ python3.2 test_zip_file_py3k.py ~/data.zip
Traceback (most recent call last):
    File "test_zip_file_py3k.py", line 8, in <module>
    for row in csv.DictReader(items_file):
    File "/somedir/python3.2/csv.py", line 109, in __next__
    self.fieldnames
    File "/somedir/python3.2/csv.py", line 96, in fieldnames
    self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file
in text mode?)

The csv module in Python 3 wants to see a text file, but zipfile.ZipFile.open returns a zipfile.ZipExtFile that is always treated as binary data.

How does one make this work in Python 3?

Body:
I just noticed that Lennart's answer didn't work with Python 3.1, but it does work with Python 3.2. They've enhanced zipfile.ZipExtFile in Python 3.2 (see release notes). These changes appear to make zipfile.ZipExtFile work nicely with io.TextWrapper.

Incidentally, it works in Python 3.1, if you uncomment the hacky lines below to monkey-patch zipfile.ZipExtFile, not that I would recommend this sort of hackery. I include it only to illustrate the essence of what was done in Python 3.2 to make things work nicely.

$ cat test_zip_file_py3k.py
import csv, io, sys, zipfile

zip_file    = zipfile.ZipFile(sys.argv[1])
items_file  = zip_file.open('items.csv', 'rU')
# items_file.readable = lambda: True
# items_file.writable = lambda: False
# items_file.seekable = lambda: False
# items_file.read1 = items_file.read
items_file  = io.TextIOWrapper(items_file)

for idx, row in enumerate(csv.DictReader(items_file)):
    print('Processing row {0} -- row = {1}'.format(idx, row))

If I had to support py3k < 3.2, then I would go with the solution in my other answer.

Update for 3.6+

Starting w/3.6, support for mode='U' was removed^1:

Changed in version 3.6: Removed support of mode='U'. Use io.TextIOWrapper for reading compressed text files in universal newlines mode.

Starting w/3.8, a Path object was added which gives us an open() method that we can call like the built-in open() function (passing newline='' in the case of our CSV) and we get back an io.TextIOWrapper object the csv readers accept.  See Yuri's answer, here.


问:
java.util.concurrent.ExecutionException: Failed to initialize component
I'm working for a maven web application and I'm struggling with this error and I can't find any solution:

```<code>SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@5b0abc94]
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:831)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:423)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:928)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.startup.Catalina.start(Catalina.java:638)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:350)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:492)
Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@5b0abc94]
at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:441)
at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:139)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:173)
at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:724)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4783)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4918)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
... 21 more
Caused by: java.lang.IllegalArgumentException: java.util.zip.ZipException: error in opening zip file
at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:143)
at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136)
... 33 more
</code>```

It comes from running a index.jsp page that imports multiple other classes:

```<code><%@page import="java.util.ArrayList" %>
<%@page import="java.util.List" %>
<%@page import= "java.net.URL" %>
<%@ page import="models.Chapter" %>
<%@ page import="models.User" %>
<%@ page import="models.Student" %>
<%@ page import="models.Teacher" %>
<%@ page import="models.Enrolment" %>
<%@ page import="dao.UserDAO" %>
<%@ page import="dao.StudentDAO" %>
<%@ page import="dao.TeacherDAO" %>
<%@ page import="dao.ChapterDAO" %>
<%@ page import="dao.Chapter2DAO" %>
<%@ page import="dao.EnrolmentDAO" %>
<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%>
</code>```

From what I found so far, it says that some JAR files could be corrupt so I just deleted them from my lib file. After that I got an error like Java error: Only a type can be imported. XYZ resolves to a package that I also couldn't solve and just sent me back to add all jars in the lib folder in WEB-INF. I tried deleting my repository then maven install again, didn't work. I checked the versions of my jars and everything, I tried lots of things but nothing seem to work so far. Here is my pom.xml for reference:

```<code> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 <java.version>1.8</java.version>
  </properties>

  <dependencies>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>3.8.1</version>
  <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.3.1.Final</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.13</version>
</dependency>

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.4</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>

<dependency>
  <groupId>javax.transaction</groupId>
  <artifactId>jta</artifactId>
  <version>1.1</version>
  </dependency>

<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</code>```

Here is my project structure in Eclipse:

Do you have any idea how I can deal with this issue? I really don't see where problem is.

答:
If you look into the following exception stacktrace which says,

Caused by: java.lang.IllegalArgumentException:
  java.util.zip.ZipException: error in opening zip file

It means, the war file is not proper from a deployment view point. Besides, you have to create war packaging in maven. Apart from that, you have to use maven war plugin. You have to make a complete web project in eclipse also. I will suggest to go through the following tutorials to get an idea.

https://crunchify.com/how-to-create-a-war-file-from-eclipse-using-maven-plugin-apache-maven-war-plugin-usage/

Body:
I'm working for a maven web application and I'm struggling with this error and I can't find any solution:

SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@5b0abc94]
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:831)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:423)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:928)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.startup.Catalina.start(Catalina.java:638)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:350)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:492)
Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@5b0abc94]
at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:441)
at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:139)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:173)
at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:724)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4783)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4918)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
... 21 more
Caused by: java.lang.IllegalArgumentException: java.util.zip.ZipException: error in opening zip file
at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:143)
at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136)
... 33 more

It comes from running a index.jsp page that imports multiple other classes:

<%@page import="java.util.ArrayList" %>
<%@page import="java.util.List" %>
<%@page import= "java.net.URL" %>
<%@ page import="models.Chapter" %>
<%@ page import="models.User" %>
<%@ page import="models.Student" %>
<%@ page import="models.Teacher" %>
<%@ page import="models.Enrolment" %>
<%@ page import="dao.UserDAO" %>
<%@ page import="dao.StudentDAO" %>
<%@ page import="dao.TeacherDAO" %>
<%@ page import="dao.ChapterDAO" %>
<%@ page import="dao.Chapter2DAO" %>
<%@ page import="dao.EnrolmentDAO" %>
<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%>

From what I found so far, it says that some JAR files could be corrupt so I just deleted them from my lib file. After that I got an error like Java error: Only a type can be imported. XYZ resolves to a package that I also couldn't solve and just sent me back to add all jars in the lib folder in WEB-INF. I tried deleting my repository then maven install again, didn't work. I checked the versions of my jars and everything, I tried lots of things but nothing seem to work so far. Here is my pom.xml for reference:

 <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 <java.version>1.8</java.version>
  </properties>

  <dependencies>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>3.8.1</version>
  <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.3.1.Final</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.13</version>
</dependency>

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.4</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>

<dependency>
  <groupId>javax.transaction</groupId>
  <artifactId>jta</artifactId>
  <version>1.1</version>
  </dependency>

<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>

Here is my project structure in Eclipse:

Do you have any idea how I can deal with this issue? I really don't see where problem is.


问:
How to make a repeating CanvasGradient
Is there any way to make a CanvasGradient that repeats?

I assume not, because I don't see any options on CanvasRenderingContext2D.createLinearGradient or createRadialGradient or any properties on CanvasGradient that would apply

But I'm really surprised this feature would be missing given that CSS3 supports repeating-linear-gradient and repeating-radial-gradient background styles.

I have figured out a workaround for repeating linear gradients using CanvasRenderingContext2D.createPattern (see my answer below) but not a way to make a repeating radial gradient.

答:
For a linear gradient it's possible to create a pattern from the unit rectangle of the gradient:

var tile = document.createElement('canvas')
tile.width = tile.height = 10
var tileCtx = tile.getContext('2d')
var gradient = tileCtx.createLinearGradient(0, 0, tile.width, tile.height)
gradient.addColorStop(0, 'red')
gradient.addColorStop(0.25, 'red')
gradient.addColorStop(0.25, 'blue')
gradient.addColorStop(0.5, 'blue')
gradient.addColorStop(0.5, 'red')
gradient.addColorStop(0.75, 'red')
gradient.addColorStop(0.75, 'blue')
gradient.addColorStop(1, 'blue')
tileCtx.fillStyle = gradient
tileCtx.fillRect(0, 0, 10, 10)

var canvas = document.createElement('canvas')
canvas.width = canvas.height = 200
canvas.style.width = canvas.style.height = '200px'
document.body.appendChild(canvas)
var context = canvas.getContext('2d')
context.fillStyle = context.createPattern(tile, 'repeat')
context.fillRect(0, 0, 200, 200)
```

However, I don't know of a way to make a repeating radial gradient.

Title: How to make a repeating CanvasGradient

Body:
For a linear gradient it's possible to create a pattern from the unit rectangle of the gradient:

var tile = document.createElement('canvas')
tile.width = tile.height = 10
var tileCtx = tile.getContext('2d')
var gradient = tileCtx.createLinearGradient(0, 0, tile.width, tile.height)
gradient.addColorStop(0, 'red')
gradient.addColorStop(0.25, 'red')
gradient.addColorStop(0.25, 'blue')
gradient.addColorStop(0.5, 'blue')
gradient.addColorStop(0.5, 'red')
gradient.addColorStop(0.75, 'red')
gradient.addColorStop(0.75, 'blue')
gradient.addColorStop(1, 'blue')
tileCtx.fillStyle = gradient
tileCtx.fillRect(0, 0, 10, 10)

var canvas = document.createElement('canvas')
canvas.width = canvas.height = 200
canvas.style.width = canvas.style.height = '200px'
document.body.appendChild(canvas)
var context = canvas.getContext('2d')
context.fillStyle = context.createPattern(tile, 'repeat')
context.fillRect(0, 0, 200, 200)

However, I don't know of a way to make a repeating radial gradient.


问:
Vuetify v-data-table v-if issue
Alright, so I have a v-data-table with one column that conditionally shows either a checkmark icon or an x icon :

```<code><v-data-table :headers="headers" :items="items" item-key="id">
    <template v-slot:headers="props">
        <tr>
            <th v-for="header in props.headers" :key="header.text">{{ header.text }}</th>
        </tr>
    </template>
    <template v-slot:items="props">
        <tr>
            <td>{{ props.item.id }}</td>
            <td>{{ props.item.name }}</td>
            <td>
                <v-icon v-if="props.item.status === 1" color="light-green">fas fa-check</v-icon>
                <v-icon v-if="props.item.status === 0" color="red">fas fa-times</v-icon>
            </td>
        </tr>
    </template>
</v-data-table>
</code>```

The issue is: While paginating the data in this table, rows where v-if evaluate differently stay rendered, as in they don't go away, and more icons are actually appended rather than replacing what's there.

So say on Page 1, the third row has a status of 0, so it renders an x, then on Page 2, the third row has a status of 1, but instead of showing checkmark, it shows x checkmark. Then I switch back to Page 1, and it shows x checkmark still... then when I go back to Page 2, it shows x checkmark checkmark, and so on as many times as I switch back and forth.

Has anyone else encountered this issue?

I've tried instead using v-show, but this one also acts weirdly - it only renders the result of the first page, and doesn't change when switching pages. I guess also considered a bug.

答: Oh bother. In the project there's a utility that converts FA icons into SVG, and by doing so it overrides the default behavior of v-data-table. Switched to Material icons, works fine.</p>

Title: Vuetify v-data-table v-if issue

Body:
Alright, so I have a v-data-table with one column that conditionally shows either a checkmark icon or an x icon :

<v-data-table :headers="headers" :items="items" item-key="id">
    <template v-slot:headers="props">

            {{ header.text }}

    </template>
    <template v-slot:items="props">

            {{ props.item.id }}
            {{ props.item.name }}

                <v-icon v-if="props.item.status === 1" color="light-green">fas fa-check</v-icon>
                <v-icon v-if="props.item.status === 0" color="red">fas fa-times</v-icon>

    </template>
</v-data-table>

The issue is: While paginating the data in this table, rows where v-if evaluate differently stay rendered, as in they don't go away, and more icons are actually appended rather than replacing what's there.

So say on Page 1, the third row has a status of 0, so it renders an x, then on Page 2, the third row has a status of 1, but instead of showing checkmark, it shows x checkmark. Then I switch back to Page 1, and it shows x checkmark still... then when I go back to Page 2, it shows x checkmark checkmark, and so on as many times as I switch back and forth.

Has anyone else encountered this issue?

I've tried instead using v-show, but this one also acts weirdly - it only renders the result of the first page, and doesn't change when switching pages. I guess also considered a bug.


问:
How to fix "ModuleNotFoundError" in Jupiter-notebook?
Well, I am trying to write a starvation DHCP attack code through the following code.

I have tried pip install scapy and also pip install --pre but they do not work. I am running the program on windows. The problem is with from scapy.all import * line:

```<code>import sys
import os
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
</code>```

...

Here is the error:

ModuleNotFoundError: No module named 'scapy'

What should I do?

答:
This error means that you have not successfully installed scapy in a place that python is expecting it. I expect that you have not installed scapy successfully at all, based on installation methods you have tried.

I would recommend following the Windows specific scapy documentation found here: https://scapy.readthedocs.io/en/latest/installation.html#windows

pip install is not supported for scapy on Windows.

See the relevant section below:

You need the following software in order to install Scapy on Windows:

Python: Python 2.7.X or 3.4+. After installation, add the Python
  installation directory and its Scripts subdirectory to your PATH.
  Depending on your Python version, the defaults would be C:\Python27
  and C:\Python27\Scripts respectively.

Npcap: the latest version.
  Default values are recommended. Scapy will also work with Winpcap.

Scapy: latest development version from the Git repository. Unzip the
  archive, open a command prompt in that directory and run python
  setup.py install. Just download the files and run the setup program.
  Choosing the default installation options should be safe. (In the case
  of Npcap, Scapy will work with 802.11 option enabled. You might want
  to make sure that this is ticked when installing).

After all packages are installed, open a command prompt (cmd.exe) and
  run Scapy by typing scapy. If you have set the PATH correctly, this
  will find a little batch file in your C:\Python27\Scripts directory
  and instruct the Python interpreter to load Scapy.

Body:
Well, I am trying to write a starvation DHCP attack code through the following code.

I have tried pip install scapy and also pip install --pre but they do not work. I am running the program on windows. The problem is with from scapy.all import * line:

import sys
import os
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *

...

Here is the error:

ModuleNotFoundError: No module named 'scapy'

What should I do?


问:
How fix "Refused to load script" error on Android cordova app
I'm getting a refused to load script error when I run my cordova app on the Android platform

I've uninstalled and reinstalled cordova-plugin-whitelist. I've added <access origin="*" /> to my config.xml. The whole works.

This is the error message

```<code>Refused to load the script 'file://www.radiojar.com/wrappers/api-plugins/v1/player.js?1.65.1t' because it violates the following Content Security Policy directive:
"script-src 'self' 'unsafe-inline' http://www.radiojar.com/wrappers/api-plugins/v1/player.js http://www.radiojar.com/wrappers/api-plugins/v1/jplayer/jplayer.js http://now-dot-playing-dot-radiojarcom.appspot.com/api/stations/u31u2awpxbwtv/now_playing/".
Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
</code>```

Here is my config.xml

```<code><?xml version='1.0' encoding='utf-8'?>
<widget android-versionCode="2" id="org.christsheart" version="1.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>Christs Heart</name>
    <description>
        Christ's Heart app.
    </description>
    <author email="info@christsheart.org" href="https://christsheart.org">
        Christ's Heart
    </author>
    <preference name="ShowSplashScreenSpinner" value="false" />
    <content src="index.html" />
    <access origin="*" />
    <allow-navigation href="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <access origin="*" />
        <allow-navigation href="*" />
        <allow-intent href="market:*" />
        <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application">
            <application android:usesCleartextTraffic="true" />
        </edit-config>
        <icon density="ldpi" src="res/android/ldpi.png" />
        .....
    </platform>
    <platform name="ios">
        <allow-intent href="itms-apps:*" />
        ....
    </platform>
    <plugin name="cordova-plugin-whitelist" spec="1.3.3" />
    <plugin name="cordova-plugin-splashscreen" spec="~5.0.2" />
    <plugin name="cordova-plugin-dialogs" spec="~2.0.1" />
    <plugin name="cordova-plugin-network-information" spec="~2.0.1" />
    <plugin name="cordova-plugin-inappbrowser" spec="~3.0.0" />
    <engine name="android" spec="^8.0.0" />
    <engine name="ios" spec="^5.0.0" />
    <engine name="browser" spec="^6.0.0" />
</widget>
</code>```

答:
I believe it is because you are missing some permissions, try</p>

```<code> script-src 'self' 'unsafe-inline' 'unsafe-eval' *;
</code>```

Body:
I'm getting a refused to load script error when I run my cordova app on the Android platform

I've uninstalled and reinstalled cordova-plugin-whitelist. I've added <access origin="*" /> to my config.xml. The whole works.

This is the error message

Refused to load the script 'file://www.radiojar.com/wrappers/api-plugins/v1/player.js?1.65.1t' because it violates the following Content Security Policy directive:
"script-src 'self' 'unsafe-inline' http://www.radiojar.com/wrappers/api-plugins/v1/player.js http://www.radiojar.com/wrappers/api-plugins/v1/jplayer/jplayer.js http://now-dot-playing-dot-radiojarcom.appspot.com/api/stations/u31u2awpxbwtv/now_playing/".
Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

Here is my config.xml

<?xml version='1.0' encoding='utf-8'?>
<widget android-versionCode="2" id="org.christsheart" version="1.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>Christs Heart</name>
    <description>
        Christ's Heart app.
    </description>
    <author email="info@christsheart.org" href="https://christsheart.org">
        Christ's Heart
    </author>
    <preference name="ShowSplashScreenSpinner" value="false" />
    <content src="index.html" />
    <access origin="*" />
    <allow-navigation href="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <access origin="*" />
        <allow-navigation href="*" />
        <allow-intent href="market:*" />
        <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application">
            <application android:usesCleartextTraffic="true" />
        </edit-config>
        <icon density="ldpi" src="res/android/ldpi.png" />
        .....
    </platform>
    <platform name="ios">
        <allow-intent href="itms-apps:*" />
        ....
    </platform>
    <plugin name="cordova-plugin-whitelist" spec="1.3.3" />
    <plugin name="cordova-plugin-splashscreen" spec="~5.0.2" />
    <plugin name="cordova-plugin-dialogs" spec="~2.0.1" />
    <plugin name="cordova-plugin-network-information" spec="~2.0.1" />
    <plugin name="cordova-plugin-inappbrowser" spec="~3.0.0" />
    <engine name="android" spec="^8.0.0" />
    <engine name="ios" spec="^5.0.0" />
    <engine name="browser" spec="^6.0.0" />
</widget>

Body:
I believe it is because you are missing some permissions, try

 script-src 'self' 'unsafe-inline' 'unsafe-eval' *;


问:
How to set custom launcher as default launcher into ANDROID AOSP source code
I am creating a custom launcher in my embedded android development board.How to set custom launcher as default launcher into ANDROID AOSP source code.

Please help me.

Thanks.**

答:
I think a simple solution could be to remove any other launchers from the system, I've listed a couple of ways you could achieve this below.

        A simple way to achieve your goal would be to remove any other launchers from your AOSP source and Android should load up whatever launcher you added. Information on removing apps from AOSP

        If you already have the system deployed you can delete the original launcher(s), I've added some sample adb commands which should get you where you want to be(You might have to change the name of the launcher depending on what launcher you're trying to remove)

```<code>adb root
adb remount
adb shell "rm -r /system/app/Launcher3"
</code>```

Body:
I think a simple solution could be to remove any other launchers from the system, I've listed a couple of ways you could achieve this below.

        A simple way to achieve your goal would be to remove any other launchers from your AOSP source and Android should load up whatever launcher you added. Information on removing apps from AOSP

        If you already have the system deployed you can delete the original launcher(s), I've added some sample adb commands which should get you where you want to be(You might have to change the name of the launcher depending on what launcher you're trying to remove)

adb root
adb remount
adb shell "rm -r /system/app/Launcher3"


问:
Unable to download csv file using URL from Digikey
I'm currently attempting to create a batch script to download this csv file from digikey(http://www.digikey.com/product-search/download.csv?lang=en&site=ca&pv7=2&KeyWords=SZMMBZ5V6ALT1G&rohs=1&pageSize=500). If the URL is manually inputted in a browser, a download will happen. Is there a way to make a batch script download and save this csv to a file?

I have already attempted wget and curl where nothing gets returned. I have also attempted using selenium in python but the page opens with a 403 error.

```<code>curl  -o yes.csv "http://www.digikey.com/product-search/download.csv?lang=en&site=ca&pv7=2&KeyWords=SZMMBZ5V6ALT1G&rohs=1&pageSize=500"
SET AGENT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"
Wget -U %AGENT% -O yes.csv "http://www.digikey.com/product-search/download.csv?lang=en&site=ca&pv7=2&KeyWords=SZMMBZ5V6ALT1G&rohs=1&pageSize=500"
</code>```

答:
Maybe it ok with vbs ?</p>

```<code>@echo off

call:download "http://www.digikey.com/product-search/download.csv?lang=en&site=ca&pv7=2&KeyWords=SZMMBZ5V6ALT1G&rohs=1&pageSize=500" "%~dp0thing.csv"

exit

:download
(echo src = "%~1"
echo Set v1 = CreateObject ("MSXML2.XMLHTTP"^)
echo Set v2  = CreateObject ("ADODB.Stream"^)
echo v1.open "GET", src, false
echo v1.send (^)
echo v2.open
echo v2.Type = 1
echo v2.Write v1.ResponseBody
echo v2.SaveToFile "%~2") >"%~dpn0.vbs"
cscript "%~dpn0.vbs"
del "%~dpn0.vbs" >nul
goto:eof
</code>```

Body:
I'm currently attempting to create a batch script to download this csv file from digikey(http://www.digikey.com/product-search/download.csv?lang=en&site=ca&pv7=2&KeyWords=SZMMBZ5V6ALT1G&rohs=1&pageSize=500). If the URL is manually inputted in a browser, a download will happen. Is there a way to make a batch script download and save this csv to a file?

I have already attempted wget and curl where nothing gets returned. I have also attempted using selenium in python but the page opens with a 403 error.

curl  -o yes.csv "http://www.digikey.com/product-search/download.csv?lang=en&site=ca&pv7=2&KeyWords=SZMMBZ5V6ALT1G&rohs=1&pageSize=500"
SET AGENT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"
Wget -U %AGENT% -O yes.csv "http://www.digikey.com/product-search/download.csv?lang=en&site=ca&pv7=2&KeyWords=SZMMBZ5V6ALT1G&rohs=1&pageSize=500"

Body:
Maybe it ok with vbs ?

@echo off

call:download "http://www.digikey.com/product-search/download.csv?lang=en&site=ca&pv7=2&KeyWords=SZMMBZ5V6ALT1G&rohs=1&pageSize=500" "%~dp0thing.csv"

exit

:download
(echo src = "%~1"
echo Set v1 = CreateObject ("MSXML2.XMLHTTP"^)
echo Set v2  = CreateObject ("ADODB.Stream"^)
echo v1.open "GET", src, false
echo v1.send (^)
echo v2.open
echo v2.Type = 1
echo v2.Write v1.ResponseBody
echo v2.SaveToFile "%~2") >"%~dpn0.vbs"
cscript "%~dpn0.vbs"
del "%~dpn0.vbs" >nul
goto:eof


问:
Get list of custom attributes for current action/controller in ASP.NET MVC
Checking out the sample code from http://lukesampson.com/post/471548689/entering-and-exiting-https-with-asp-net-mvc written for ASP.NET MVC2, I noticed they can check if a custom attribute is applied to the current action or controller by accessing filterContext.ActionDescriptor and filterContext.ActionDescriptor.ControllerDescriptor respectively:

```<code>public class ExitHttpsIfNotRequiredAttribute : FilterAttribute, IAuthorizationFilter {
    public void OnAuthorization(AuthorizationContext filterContext) {
        // snip

        // abort if a [RequireHttps] attribute is applied to controller or action
        if(filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0) return;
        if(filterContext.ActionDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0) return;

        // snip
    }
}
</code>```

What would be the ASP.NET MVC 1 method of checking the action and controller for a custom attribute? In ASP.NET MVC 1 there is no filterContext.ActionDescriptor that I can tell.

答:
I'm using MVC5 and had to use the following to check from within a class that inherits from ActionFilterAttribute and implements IAuthenticationFilter.

```<code>If filterContext.ActionDescriptor.GetCustomAttributes(GetType(RequireHttpsAttribute), True).Any() OrElse filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(GetType(RequireHttpsAttribute), True).Any() Then
' .. the given attribute is present ..
End If
</code>```

I couldn't get Ruben's solution to work for me but it was probably because I messed up in the conversion from C# to VB.

Body:
Checking out the sample code from http://lukesampson.com/post/471548689/entering-and-exiting-https-with-asp-net-mvc written for ASP.NET MVC2, I noticed they can check if a custom attribute is applied to the current action or controller by accessing filterContext.ActionDescriptor and filterContext.ActionDescriptor.ControllerDescriptor respectively:

public class ExitHttpsIfNotRequiredAttribute : FilterAttribute, IAuthorizationFilter {
    public void OnAuthorization(AuthorizationContext filterContext) {
        // snip

        // abort if a [RequireHttps] attribute is applied to controller or action
        if(filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0) return;
        if(filterContext.ActionDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0) return;

        // snip
    }
}

What would be the ASP.NET MVC 1 method of checking the action and controller for a custom attribute? In ASP.NET MVC 1 there is no filterContext.ActionDescriptor that I can tell.

Body:
I'm using MVC5 and had to use the following to check from within a class that inherits from ActionFilterAttribute and implements IAuthenticationFilter.

If filterContext.ActionDescriptor.GetCustomAttributes(GetType(RequireHttpsAttribute), True).Any() OrElse filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(GetType(RequireHttpsAttribute), True).Any() Then
' .. the given attribute is present ..
End If

I couldn't get Ruben's solution to work for me but it was probably because I messed up in the conversion from C# to VB.


问:
How can I reach the values of an array that is inside an object that is part of an array of objects?
In my componentWillMount, I have a function that calls for a 'shopping cart' field inside the current user's doc.

This shopping cart field is an array of objects, and each object has a field that contains an array of image URLs.

My problem is that I declare my desired variable 'shoppingCart' in my component's state and then in the componentWillMount, I assign this value the returned array of objects (shopping cart objects).

When I test to see if I can acquire the first link of the array inside one of the objects, the program complains that the field is undefined and proceeds to crash. I noticed that depending on how I declare my state variable I can acquire more or less information from these objects.

For Example:

If I declare my state variable like this:

```<code>this.state={
shoppingCart:"",
}
</code>```

Then I can only get to the object in shoppingCart[n],

But if I declare my state like this:

```<code>this.state={
shoppingCart:[{}],
}
</code>```

I can go into the field of the object of my choosing for example:

```<code>shoppingCart[n].name;
</code>```

But when it comes to trying to get one of the values of an array inside the object for example:

```<code>shoppingCart[n].url[n]
</code>```

This isn't possible.

Do I have to declare the state variable a certain way?

```<code>export const getCartItems = (props) => {

return (dispatch, getState, { getFirebase, getFirestore }) => {
       const firebase = getFirebase();
       const firestore = getFirestore();
        const storage = firebase.storage();

    return
    firestore.collection('users').doc(props.auth.uid).get().then((user)=>{
        return user.data().shoppingCart;
        })

    }

}

constructor(props) {
        super(props)

        this.state = {
             shoppingCart: [{}],
        }

     }

    componentWillMount() {

        if (this.props.auth.uid) {
        this.props.getCartItems(this.props).then((shoppingCart) => {
            this.setState({
                shoppingCart,
            })
        })

    }
}
</code>```

答:
When you declare your initial state to be { shoppingCart: [{}] }, you are saying to load one shopping cart with no fields. If you try to access url of an empty object you will get undefined. If you try to access the nth element of undefined, you will get a runtime error.

After you call the promise, there is a bit of time before your response is loaded into state. In that time, your initial state needs to protect against cases where you are accessing fields of undefined as described above.

Two viable options are either

```<code>this.state = { shoppingCart: [] };
</code>```

or

```<code>this.state = { shoppingCart: [ { url: [] } ] };
</code>```

Lastly, another solution involves having no default state, but having a conditional reference every time you reference state.

Body:
In my componentWillMount, I have a function that calls for a 'shopping cart' field inside the current user's doc.

This shopping cart field is an array of objects, and each object has a field that contains an array of image URLs.

My problem is that I declare my desired variable 'shoppingCart' in my component's state and then in the componentWillMount, I assign this value the returned array of objects (shopping cart objects).

When I test to see if I can acquire the first link of the array inside one of the objects, the program complains that the field is undefined and proceeds to crash. I noticed that depending on how I declare my state variable I can acquire more or less information from these objects.

For Example:

If I declare my state variable like this:

this.state={
shoppingCart:"",
}

Then I can only get to the object in shoppingCart[n],

But if I declare my state like this:

this.state={
shoppingCart:[{}],
}

I can go into the field of the object of my choosing for example:

shoppingCart[n].name;

But when it comes to trying to get one of the values of an array inside the object for example:

shoppingCart[n].url[n]

This isn't possible.

Do I have to declare the state variable a certain way?

export const getCartItems = (props) => {

return (dispatch, getState, { getFirebase, getFirestore }) => {
       const firebase = getFirebase();
       const firestore = getFirestore();
        const storage = firebase.storage();

    return
    firestore.collection('users').doc(props.auth.uid).get().then((user)=>{
        return user.data().shoppingCart;
        })

    }

}

constructor(props) {
        super(props)

        this.state = {
             shoppingCart: [{}],
        }

     }

    componentWillMount() {

        if (this.props.auth.uid) {
        this.props.getCartItems(this.props).then((shoppingCart) => {
            this.setState({
                shoppingCart,
            })
        })

    }
}

Body:
When you declare your initial state to be { shoppingCart: [{}] }, you are saying to load one shopping cart with no fields. If you try to access url of an empty object you will get undefined. If you try to access the nth element of undefined, you will get a runtime error.

After you call the promise, there is a bit of time before your response is loaded into state. In that time, your initial state needs to protect against cases where you are accessing fields of undefined as described above.

Two viable options are either

this.state = { shoppingCart: [] };

or

this.state = { shoppingCart: [ { url: [] } ] };

Lastly, another solution involves having no default state, but having a conditional reference every time you reference state.


问:
In Java, can you modify a List while iterating through it?
I understand that in Java a Collection<E> should not be modified while iterating through it, such as removing or adding elements. But what about changing the elements in a List? For example, what if we have

```<code>List<String> letters = new ArrayList<String>();
letters.add("A");
letters.add("B");
letters.add("C");
int i = 0;

for (String letter : letters) {
    letters.set(i, "D");
    i++;
}
</code>```

So, I'm not talking about modifying the object stored at an element; I'm talking about changing what the object is. The size of the List is not being changed, but the object at the index is changing, so technically the List is being modified. My boss claims this code is fine (and it does appear to work), but I still don't think it is correct. Would a different way of doing it, maybe using the set(E e) method of a ListIterator, be better?

答:
Java 8's stream() interface provides a great way to update a list in place.

To safely update items in the list, use map():

List<String> letters = new ArrayList<>();

// add stuff to list

letters = letters.stream().map(x -> "D").collect(Collectors.toList());

```

<p>To safely remove items in place, use <code>filter()</code>:</p>

<pre class="lang-java prettyprint-override"><code>
letters.stream().filter(x -> !x.equals("A")).collect(Collectors.toList());
</code>```

Body:
I understand that in Java a Collection<E> should not be modified while iterating through it, such as removing or adding elements. But what about changing the elements in a List? For example, what if we have

List<String> letters = new ArrayList<String>();
letters.add("A");
letters.add("B");
letters.add("C");
int i = 0;

for (String letter : letters) {
    letters.set(i, "D");
    i++;
}

So, I'm not talking about modifying the object stored at an element; I'm talking about changing what the object is. The size of the List is not being changed, but the object at the index is changing, so technically the List is being modified. My boss claims this code is fine (and it does appear to work), but I still don't think it is correct. Would a different way of doing it, maybe using the set(E e) method of a ListIterator, be better?

Body:
Java 8's stream() interface provides a great way to update a list in place.

To safely update items in the list, use map():

List<String> letters = new ArrayList<>();

// add stuff to list

letters = letters.stream().map(x -> "D").collect(Collectors.toList());

To safely remove items in place, use filter():

letters.stream().filter(x -> !x.equals("A")).collect(Collectors.toList());


问:
How to automatically post a tweet on twitter
I am working on a site where users can submit data. Is it possible to set up an automated system such that a tweet goes out every time a new data set is received?</p>

答: A good place to start is the Twitter API.</p>