问:
How to write multiple columns in spark dataframe to kafka queue
I know that we can integrate spark with kafka and write the dataframe in format of key and value to kafka queue as shown below

df - dataframe

```<code> df.withColumnRenamed("Column_1", "key")
 .withColumnRenamed("Column_2", "value")
 .write()
 .format("kafka")
 .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
 .save()
</code>```

But how do I write column 3,4,5 and many to kafka queue?
How can I write the entire row to kafka queue in a single go?

Any suggestions are appreciated

答:
Kafka only gets (key, value) formed messages. So you have to aggregate columns to one value (like JSON). here is example

This should work: (Construct the appropriate value_fields)

```<code>import org.apache.spark.sql.functions._

val value_fields = df.columns.filter(_ != "Column_1")

df
.withColumnRenamed("Column_1", "key")
.withColumn("value", to_json(struct(value_fields.map(col(_)):_*)))
.select("key", "value")
.write()
.format("kafka")
.option("kafka.bootstrap.servers", "host1:port1,host2:port2")
.save()
</code>```

Body:
I know that we can integrate spark with kafka and write the dataframe in format of key and value to kafka queue as shown below

df - dataframe

 df.withColumnRenamed("Column_1", "key")
 .withColumnRenamed("Column_2", "value")
 .write()
 .format("kafka")
 .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
 .save()

But how do I write column 3,4,5 and many to kafka queue?
How can I write the entire row to kafka queue in a single go?

Any suggestions are appreciated

Body:
Kafka only gets (key, value) formed messages. So you have to aggregate columns to one value (like JSON). here is example

This should work: (Construct the appropriate value_fields)

import org.apache.spark.sql.functions._

val value_fields = df.columns.filter(_ != "Column_1")

df
.withColumnRenamed("Column_1", "key")
.withColumn("value", to_json(struct(value_fields.map(col(_)):_*)))
.select("key", "value")
.write()
.format("kafka")
.option("kafka.bootstrap.servers", "host1:port1,host2:port2")
.save()


来源: stackexchange

问:
Is it possible to use Android Studio to build a website in flutter
I have some basic knowledge of building android apps using Android Studio with Java language. Now I want to start learning flutter but not really sure about a couple of things. I read that it's possible to build cross-platform mobile apps with flutter and I can use an android studio to build those apps. Using flutter its also possible to build a website and desktop projects.

My confusions are :

1) Can I use Android Studio IDE with flutter to build mobile apps(both Android & IOS), desktop apps and websites?

2) First of all, I thought I just write a single code for both mobile apps and websites but guess I am wrong. So, if codes are different for mobile apps and website then how different are they? I mean is it something totally different or has some similarities. So, if someone can build a mobile app using flutter then they can easily build a website with flutter too?

3) Can flutter web be used instead of PHP for making websites and web services?

答:
1) Yes this is definitely possible. Android studio has a plugin for Flutter and Dart that works beautifully. You can find out how to get it working by following online tutorials step-by-step to get it set up here: https://flutter.dev/docs/get-started/editor.
2) Also as Flutter (a library that uses Dart), & Dart (the language Flutter is used with) are designed to be a hybrid language for mobile development, this means that you write one code base which is then able to be run on Android or IOS. When I was using this technology I was aware that the next step for Flutter & Dart is to add progressive websites to its capabilities so I am not sure if it is available yet so one code base can also work on desktop. 3) Sorry I am not sure about your last question!</p>

ContentLicense: CC BY-SA 4.0


问:
How do you return a dictionary through a function?
I am trying to return a dictionary through a function shown in the code using jupyter notebooks. I am a beginner in Python and not sure how to go about this but I feel the answer is trivial.In my code when i run it, i get {}.

Im not sure if a for loop or if statement is needed.

```<code> def build_book_dict(titles, pages, firsts, lasts, locations):
        if True:
            return dict()
        else:
            None

    titles = ["Harry Potter", "Fear and Lothing in Las Vegas"]
    pages = [200, 350]
    firsts = ["J.K.", "Hunter"]
    lasts = ["Rowling", "Thompson"]
    locations = ["NYC", "Aspen"]
    book_dict = build_book_dict(titles, pages, firsts, lasts, locations)
    print (book_dict)

result should be -->
 {'Fear and Lothing in Las Vegas': {'Publisher': {'Location': 'Aspen'},
 'Author': {'Last': 'Thompson', 'First': 'Hunter'}, 'Pages': 350},
 'Harry Potter': {'Publisher': {'Location': 'NYC'},
 'Author': {'Last': 'Rowling', 'First': 'J.K.'}, 'Pages': 200}}
</code>```

答:
Here is a possible solution:

 Be careful! All the lists must be same size!

```<code>def build_book_dict(titles, pages, firsts, lasts, locations):
    dict = {}
    try:
        for i in range(len(titles)):
            dict[titles[i]] = {'Publisher':{'Location':locations[i]},
                               'Author':{'Last':lasts[i], 'First':firsts[i]}}
        return dict
    except Exception as e:
        print('Invalid length', e)

titles = ["Harry Potter", "Fear and Lothing in Las Vegas"]
pages = [200, 350]
firsts = ["J.K.", "Hunter"]
lasts = ["Rowling", "Thompson"]
locations = ["NYC", "Aspen"]
book_dict = build_book_dict(titles, pages, firsts, lasts, locations)
print (book_dict)
</code>```

Body:
I am trying to return a dictionary through a function shown in the code using jupyter notebooks. I am a beginner in Python and not sure how to go about this but I feel the answer is trivial.In my code when i run it, i get {}.

Im not sure if a for loop or if statement is needed.

 def build_book_dict(titles, pages, firsts, lasts, locations):
        if True:
            return dict()
        else:
            None

    titles = ["Harry Potter", "Fear and Lothing in Las Vegas"]
    pages = [200, 350]
    firsts = ["J.K.", "Hunter"]
    lasts = ["Rowling", "Thompson"]
    locations = ["NYC", "Aspen"]
    book_dict = build_book_dict(titles, pages, firsts, lasts, locations)
    print (book_dict)

result should be -->
 {'Fear and Lothing in Las Vegas': {'Publisher': {'Location': 'Aspen'},
 'Author': {'Last': 'Thompson', 'First': 'Hunter'}, 'Pages': 350},
 'Harry Potter': {'Publisher': {'Location': 'NYC'},
 'Author': {'Last': 'Rowling', 'First': 'J.K.'}, 'Pages': 200}}

Body:
Here is a possible solution:

 Be careful! All the lists must be same size!

def build_book_dict(titles, pages, firsts, lasts, locations):
    dict = {}
    try:
        for i in range(len(titles)):
            dict[titles[i]] = {'Publisher':{'Location':locations[i]},
                               'Author':{'Last':lasts[i], 'First':firsts[i]}}
        return dict
    except Exception as e:
        print('Invalid length', e)

titles = ["Harry Potter", "Fear and Lothing in Las Vegas"]
pages = [200, 350]
firsts = ["J.K.", "Hunter"]
lasts = ["Rowling", "Thompson"]
locations = ["NYC", "Aspen"]
book_dict = build_book_dict(titles, pages, firsts, lasts, locations)
print (book_dict)


问:
ZipEntry returns null When Calling for a Directory Inside an APK File
I'm trying to setup a function where apk files are placed in a specified directory, stored into an array[], then go through a for-each loop, creating a ZipFile instance then create a ZipEntry to call for the lib directory, and read the file names inside to help determine which apks are compatible for androids devices currently connected to PC. This is the code I have so far:

```<code>public File[] apkFileList;
private HashMap<String, File> apkInstallOptions = new HashMap<String, File>();

public void createAPKList() throws ZipException, IOException {
    apkFileList =  new File(".....(many dirs later)/APKDir/APKFiles").listFiles();
    System.out.println(apkFileList[apkFileList.length-1].getName());
    apkInstallOptions = storeAndSortFiles(apkFileList, apkInstallOptions);
}

private HashMap<String, File> storeAndSortFiles(File[] fileList, HashMap<String, File> storageList) throws ZipException, IOException{
    ZipFile apkDetails;
    for(File apk : fileList) {
        apkDetails = new ZipFile(apk);
        ZipEntry libFiles = apkDetails.getEntry("lib/");
        libFiles.isDirectory();
        InputStream inputStream = apkDetails.getInputStream(libFiles);
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        while((line = br.readLine()) != null) {
            System.out.println(line);

        }

    }
    return storageList;
}
</code>```

When I run the code to test out if the mapping to the path looks good, I get the correct name for apk, but when I attempt to call for ZipEntry for the lib directory, it returns Null. I'm not sure what I'm forgetting and what I'm not considering to add in order to read the contents inside. I've seen solutions where the Zip/apk file was extracted and then read, but I only want to read the contents inside the lib directory. Is that possible?

Screenshot of what is seen inside the APK file that a lib file does exist (used 7-Zip to look inside):

答:
Directories do not exist in the zip format. They're artificially shown in desktop tools, but zip libraries only show the actual files that are present, and that excludes directories.

The files present in an APK would thus be for example:

```<code>lib/arm64-v8a/libhello.so
lib/armeabi-v7a/libhello.so
</code>```

But there would be no entries for lib or lib/armeabi-v7a.

You can thus test if a ZipEntry is under the "lib" directory by calling:

```<code>zipEntry.getName().startsWith("lib/");
</code>```

Body:
I'm trying to setup a function where apk files are placed in a specified directory, stored into an array[], then go through a for-each loop, creating a ZipFile instance then create a ZipEntry to call for the lib directory, and read the file names inside to help determine which apks are compatible for androids devices currently connected to PC. This is the code I have so far:

public File[] apkFileList;
private HashMap<String, File> apkInstallOptions = new HashMap<String, File>();

public void createAPKList() throws ZipException, IOException {
    apkFileList =  new File(".....(many dirs later)/APKDir/APKFiles").listFiles();
    System.out.println(apkFileList[apkFileList.length-1].getName());
    apkInstallOptions = storeAndSortFiles(apkFileList, apkInstallOptions);
}

private HashMap<String, File> storeAndSortFiles(File[] fileList, HashMap<String, File> storageList) throws ZipException, IOException{
    ZipFile apkDetails;
    for(File apk : fileList) {
        apkDetails = new ZipFile(apk);
        ZipEntry libFiles = apkDetails.getEntry("lib/");
        libFiles.isDirectory();
        InputStream inputStream = apkDetails.getInputStream(libFiles);
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        while((line = br.readLine()) != null) {
            System.out.println(line);

        }

    }
    return storageList;
}

When I run the code to test out if the mapping to the path looks good, I get the correct name for apk, but when I attempt to call for ZipEntry for the lib directory, it returns Null. I'm not sure what I'm forgetting and what I'm not considering to add in order to read the contents inside. I've seen solutions where the Zip/apk file was extracted and then read, but I only want to read the contents inside the lib directory. Is that possible?

Screenshot of what is seen inside the APK file that a lib file does exist (used 7-Zip to look inside):

Body:
Directories do not exist in the zip format. They're artificially shown in desktop tools, but zip libraries only show the actual files that are present, and that excludes directories.

The files present in an APK would thus be for example:

lib/arm64-v8a/libhello.so
lib/armeabi-v7a/libhello.so

But there would be no entries for lib or lib/armeabi-v7a.

You can thus test if a ZipEntry is under the "lib" directory by calling:

zipEntry.getName().startsWith("lib/");


问:
Why does std::array not have an operator T*?
With C arrays, it's been the case that simply naming an array has the same effect as writing &foo[0] for something approaching 50 years.

When converting from C style arrays to std::array<> in a project I'm working on, the vast majority of "error"s that appeared were due to the above property of C arrays.

In all cases, the solution was trivial, just append .data().  However it occurred to me that a carefully crafted operator T* ought to directly solve this issue.

Is there any technical reason this operator could not be created?

答:
Calling data() is a thing you should avoid. It can be useful to have this power for (as in our case migrating code or optimized code processing the guts) however it goes against the safety net std::array provides.

```<code> std::array<int, 2> a{1,2};
 auto* ptr = a.data();
 std::cout << ptr[2]; // boom
</code>```

Things taking away a safety net should be explicit.

Body:
Calling data() is a thing you should avoid. It can be useful to have this power for (as in our case migrating code or optimized code processing the guts) however it goes against the safety net std::array provides.

 std::array<int, 2> a{1,2};
 auto* ptr = a.data();
 std::cout << ptr[2]; // boom

Things taking away a safety net should be explicit.


答:
The dictionary isn't going to automatically assemble itself and know the format you want. Since you are starting with a independent lists you can zip them into groups to easily iterate over them and build your dictionary:

```<code>def build_book_dict(*args):
    d = dict()
    for title, page, first, last, location in zip(*args):
        d[title] = {"Publisher": {"Location":location},
                    "Author": {"last": last, "first":first},
                    "Pages": page}
    return d

titles = ["Harry Potter", "Fear and Lothing in Las Vegas"]
pages = [200, 350]
firsts = ["J.K.", "Hunter"]
lasts = ["Rowling", "Thompson"]
locations = ["NYC", "Aspen"]
book_dict = build_book_dict(titles, pages, firsts, lasts, locations)

from pprint import pprint # pretty print

pprint(book_dict)
</code>```

Result

```<code>{'Fear and Lothing in Las Vegas': {'Author': {'first': 'Hunter',
                                              'last': 'Thompson'},
                                   'Pages': 350,
                                   'Publisher': {'Location': 'Aspen'}},
 'Harry Potter': {'Author': {'first': 'J.K.', 'last': 'Rowling'},
                  'Pages': 200,
                  'Publisher': {'Location': 'NYC'}}}
</code>```

Title: How do you return a dictionary through a function?

Body:
The dictionary isn't going to automatically assemble itself and know the format you want. Since you are starting with a independent lists you can zip them into groups to easily iterate over them and build your dictionary:

def build_book_dict(*args):
    d = dict()
    for title, page, first, last, location in zip(*args):
        d[title] = {"Publisher": {"Location":location},
                    "Author": {"last": last, "first":first},
                    "Pages": page}
    return d

titles = ["Harry Potter", "Fear and Lothing in Las Vegas"]
pages = [200, 350]
firsts = ["J.K.", "Hunter"]
lasts = ["Rowling", "Thompson"]
locations = ["NYC", "Aspen"]
book_dict = build_book_dict(titles, pages, firsts, lasts, locations)

from pprint import pprint # pretty print

pprint(book_dict)

Result

{'Fear and Lothing in Las Vegas': {'Author': {'first': 'Hunter',
                                              'last': 'Thompson'},
                                   'Pages': 350,
                                   'Publisher': {'Location': 'Aspen'}},
 'Harry Potter': {'Author': {'first': 'J.K.', 'last': 'Rowling'},
                  'Pages': 200,
                  'Publisher': {'Location': 'NYC'}}}


问:
How can I customize the positions of legend elements?
I have a figure with several plots and a legend. Is it possible to change the arrangement of the elements in the legend manually? For example, how could you make a two-column legend?</p>

答:
In 2018a, legend has a NumColumns parameter; e.g., if h is an array of handles to lines plotted, and leg_names is a cell array of names for each line:</p>

```<code>hleg = legend(h, leg_names, 'FontSize', fontsize);
set(hleg, 'NumColumns', 2);
set(hleg, 'Location', 'south');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In 2018a, legend has a NumColumns parameter; e.g., if h is an array of handles to lines plotted, and leg_names is a cell array of names for each line:

hleg = legend(h, leg_names, 'FontSize', fontsize);
set(hleg, 'NumColumns', 2);
set(hleg, 'Location', 'south');


问:
How to convert interger to time while the interger is actually time data but no separation
I have data that contains time data but in integer type and have no separation between the integer.
my data like = [91310, 101012, ...]  in fact it's suppose to be ["9:13:10", "10:10:12"]

how to convert that into time format

Body:
This method does not check whether the time is correct, ie hours<24, minutes and secods <60

a = [91310, 101012,94545]
def dd(x):
    n = str(x)
    return f'{n[:-4]}:{n[-4:-2]}:{n[-2:]}'
[dd(i)for i in a]
['9:13:10', '10:10:12', '9:45:45']

or using the regex:

eval(re.sub(r'(\d{1,2})(\d{2})(\d{2})',r"'\1:\2:\3'",str(a)))
 ['9:13:10', '10:10:12', '9:45:45']


问:
Add items dynamically to List<Integer> and convert to Integer[] Array
I have 2 arrays of strings

```<code>  String[] s = {"Light", "Sun", "Sun", "Water"};
  String[] ss = {"on", "off", "on", "off"};
</code>```

which I want to convert to an array of integers to assign pictures from my resource later.
Therefor the strings gets checked by switch statement to assign a specific  integer value:

```<code>  for(int i = 0; i < s.length; i++)
  {
  switch (components[i]) {

            case "Light":
                  if (ss[i]=="on")
                    I.add(1);
                  else
                    I.add(2);
            case "Sun":
                  if (ss[i]=="on")
                    I.add(3);
                  else
                    I.add(4);
            case "Water":
                  if (ss[i]=="on")
                    I.add(5);
                  else
                    I.add(6);
            case "Gravel":
                  if (ss[i]=="on")
                    I.add(7);
                  else
                    I.add(8);
            }
         }
  }
</code>```

Because i cannot add values dynamically to an array, i decided to create an List of Integers first, and convert it to an integer array later:

```<code>  List<Integer> I = new ArrayList<Integer>();
  [...]
  Integer[] arr = I.toArray(new Integer[I.size()]);
</code>```

But Instead of my expected result:

```<code>{"1", "4", "3", "6"}
</code>```

i will get always an sequence of numbers as result:

```<code>{"1", "2", "3", "4"}
</code>```

It seems like I'm doing something wrong with the converting?

Here the complete code:

```<code>  public static Integer[] toImg(String[] s, String[] ss) {

        List<Integer> I = new ArrayList<Integer>();

           for(int i = 0; i < s.length; i++)
  {
  switch (components[i]) {

            case "Light":
                  if (ss[i]=="on")
                    I.add(1);
                  else
                    I.add(2);
            case "Sun":
                  if (ss[i]=="on")
                    I.add(3);
                  else
                    I.add(4);
            case "Water":
                  if (ss[i]=="on")
                    I.add(5);
                  else
                    I.add(6);
            case "Gravel":
                  if (ss[i]=="on")
                    I.add(7);
                  else
                    I.add(8);
            }
         }

        Integer[] arr = I.toArray(new Integer[I.size()]);
        return arr;
  }
</code>```

答:
The first and foremost problem with your code is that you are looking over the components array and there is no such field defined in your method but instead according to your problem statement it should be

```<code>switch (s[i])
</code>```

And then there is also problem with your switch statement as they end without the break statement making them run for all cases whether or not it is the case.
You can better understand by my implementation of your code which looks like

```<code>import java.io.*;
import java.util.*;
class Test
{
public static void main(String args[])throws IOException
{

   List<Integer> I = new ArrayList<Integer>();
    String[] s = {"Light", "Sun", "Sun", "Water"};
    String[] ss = {"on", "off", "on", "off"};
    for(int i = 0; i < s.length; i++) {
        switch (s[i]) {
            case "Light":
            if (ss[i]=="on")
            I.add(1);
            else
            I.add(2);
            case "Sun":
            if (ss[i]=="on")
            I.add(3);
            else
            I.add(4);
            case "Water":
            if (ss[i]=="on")
            I.add(5);
            else
            I.add(6);
            case "Gravel":
            if (ss[i]=="on")
            I.add(7);
            else
            I.add(8);
            }
            System.out.println(I+" at i="+i);
        }
    Integer[] arr = I.toArray(new Integer[I.size()]);
    System.out.println(I);
}
}
</code>```

So here is the code you have written and when I run it I get the output

```<code>[1, 3, 5, 7] at i=0
[1, 3, 5, 7, 4, 6, 8] at i=1
[1, 3, 5, 7, 4, 6, 8, 3, 5, 7] at i=2
[1, 3, 5, 7, 4, 6, 8, 3, 5, 7, 6, 8] at i=3
[1, 3, 5, 7, 4, 6, 8, 3, 5, 7, 6, 8]
</code>```

So you can see that always all case are run and based on the value of ss[] the output arrives.
So you can correct the code as

```<code>import java.io.*;
import java.util.*;
class Test
{
public static void main(String args[])throws IOException
{

   List<Integer> I = new ArrayList<Integer>();
    String[] s = {"Light", "Sun", "Sun", "Water"};
    String[] ss = {"on", "off", "on", "off"};
    for(int i = 0; i < s.length; i++) {
        switch (s[i]) {
            case "Light":
            if (ss[i]=="on")
            I.add(1);
            else
            I.add(2);
            break;
            case "Sun":
            if (ss[i]=="on")
            I.add(3);
            else
            I.add(4);
            break;
            case "Water":
            if (ss[i]=="on")
            I.add(5);
            else
            I.add(6);
            break;
            case "Gravel":
            if (ss[i]=="on")
            I.add(7);
            else
            I.add(8);
            break;
            }
            System.out.println(I+" at i="+i);
        }
    Integer[] arr = I.toArray(new Integer[I.size()]);
    System.out.println(I);
}
}
</code>```

And the output would be

```<code>[1] at i=0
[1, 4] at i=1
[1, 4, 3] at i=2
[1, 4, 3, 6] at i=3
[1, 4, 3, 6]
</code>```

Which is the required answer.
Hope I have made myself clear.

Body:
I have 2 arrays of strings

  String[] s = {"Light", "Sun", "Sun", "Water"};
  String[] ss = {"on", "off", "on", "off"};

which I want to convert to an array of integers to assign pictures from my resource later.
Therefor the strings gets checked by switch statement to assign a specific  integer value:

  for(int i = 0; i < s.length; i++)
  {
  switch (components[i]) {

            case "Light":
                  if (ss[i]=="on")
                    I.add(1);
                  else
                    I.add(2);
            case "Sun":
                  if (ss[i]=="on")
                    I.add(3);
                  else
                    I.add(4);
            case "Water":
                  if (ss[i]=="on")
                    I.add(5);
                  else
                    I.add(6);
            case "Gravel":
                  if (ss[i]=="on")
                    I.add(7);
                  else
                    I.add(8);
            }
         }
  }

Because i cannot add values dynamically to an array, i decided to create an List of Integers first, and convert it to an integer array later:

  List<Integer> I = new ArrayList<Integer>();
  [...]
  Integer[] arr = I.toArray(new Integer[I.size()]);

But Instead of my expected result:

{"1", "4", "3", "6"}

i will get always an sequence of numbers as result:

{"1", "2", "3", "4"}

It seems like I'm doing something wrong with the converting?

Here the complete code:

  public static Integer[] toImg(String[] s, String[] ss) {

        List<Integer> I = new ArrayList<Integer>();

           for(int i = 0; i < s.length; i++)
  {
  switch (components[i]) {

            case "Light":
                  if (ss[i]=="on")
                    I.add(1);
                  else
                    I.add(2);
            case "Sun":
                  if (ss[i]=="on")
                    I.add(3);
                  else
                    I.add(4);
            case "Water":
                  if (ss[i]=="on")
                    I.add(5);
                  else
                    I.add(6);
            case "Gravel":
                  if (ss[i]=="on")
                    I.add(7);
                  else
                    I.add(8);
            }
         }

        Integer[] arr = I.toArray(new Integer[I.size()]);
        return arr;
  }

Body:
The first and foremost problem with your code is that you are looking over the components array and there is no such field defined in your method but instead according to your problem statement it should be

switch (s[i])

And then there is also problem with your switch statement as they end without the break statement making them run for all cases whether or not it is the case.
You can better understand by my implementation of your code which looks like

import java.io.*;
import java.util.*;
class Test
{
public static void main(String args[])throws IOException
{

   List<Integer> I = new ArrayList<Integer>();
    String[] s = {"Light", "Sun", "Sun", "Water"};
    String[] ss = {"on", "off", "on", "off"};
    for(int i = 0; i < s.length; i++) {
        switch (s[i]) {
            case "Light":
            if (ss[i]=="on")
            I.add(1);
            else
            I.add(2);
            case "Sun":
            if (ss[i]=="on")
            I.add(3);
            else
            I.add(4);
            case "Water":
            if (ss[i]=="on")
            I.add(5);
            else
            I.add(6);
            case "Gravel":
            if (ss[i]=="on")
            I.add(7);
            else
            I.add(8);
            }
            System.out.println(I+" at i="+i);
        }
    Integer[] arr = I.toArray(new Integer[I.size()]);
    System.out.println(I);
}
}

So here is the code you have written and when I run it I get the output

[1, 3, 5, 7] at i=0
[1, 3, 5, 7, 4, 6, 8] at i=1
[1, 3, 5, 7, 4, 6, 8, 3, 5, 7] at i=2
[1, 3, 5, 7, 4, 6, 8, 3, 5, 7, 6, 8] at i=3
[1, 3, 5, 7, 4, 6, 8, 3, 5, 7, 6, 8]

So you can see that always all case are run and based on the value of ss[] the output arrives.
So you can correct the code as

import java.io.*;
import java.util.*;
class Test
{
public static void main(String args[])throws IOException
{

   List<Integer> I = new ArrayList<Integer>();
    String[] s = {"Light", "Sun", "Sun", "Water"};
    String[] ss = {"on", "off", "on", "off"};
    for(int i = 0; i < s.length; i++) {
        switch (s[i]) {
            case "Light":
            if (ss[i]=="on")
            I.add(1);
            else
            I.add(2);
            break;
            case "Sun":
            if (ss[i]=="on")
            I.add(3);
            else
            I.add(4);
            break;
            case "Water":
            if (ss[i]=="on")
            I.add(5);
            else
            I.add(6);
            break;
            case "Gravel":
            if (ss[i]=="on")
            I.add(7);
            else
            I.add(8);
            break;
            }
            System.out.println(I+" at i="+i);
        }
    Integer[] arr = I.toArray(new Integer[I.size()]);
    System.out.println(I);
}
}

And the output would be

[1] at i=0
[1, 4] at i=1
[1, 4, 3] at i=2
[1, 4, 3, 6] at i=3
[1, 4, 3, 6]

Which is the required answer.
Hope I have made myself clear.


问:
Asynchronous socket send on Linux
When send on an asynchronous socket returns EAGAIN, does that mean :
that the current call has just been successfully queued or that nothing was done because the system is still processing a previous send ?

Thank you in advance.

答:
Nothing was done.

If something is done, the return value tells you how many characters were sent. As you get the return value -1 and errno=EAGAIN, nothing was sent.

Title: Asynchronous socket send on Linux


问:
Java force Object::toString
This is mentioned in one of the comments on this question:
Force invocation of base class method
Wondering if there as a way to force the Object.toString instead of MyClass.toString. Just want it for debugging logs (want to see if a library is creating multiple objects or re-using the same one). e.g. Something like

```<code>myObject.Object::toString()
</code>```

Can this be done easily? We are using java8

答: No, it can't be done easily. But there's no need. If you want the hex number the default toString() method prints, call System.identityHashCode().

Title: Java force Object::toString

Body:
This is mentioned in one of the comments on this question:
Force invocation of base class method
Wondering if there as a way to force the Object.toString instead of MyClass.toString. Just want it for debugging logs (want to see if a library is creating multiple objects or re-using the same one). e.g. Something like

myObject.Object::toString()

Can this be done easily? We are using java8


问:
Decoding unnamed JSON array swift 4 with structure
I have been trying to decode an array for an app where I have to decode JSON.

I just can't decode it with my actual structure and others which I tried before.

Here are my latest structures:

```<code>struct peticion: Decodable{
    let datos_conexion: datos_conexion
    let estado_lanzamiento: estado_lanzamiento
    let usuario: usuario
}

struct datos_conexion: Decodable {
    let conexion: datosConexion
}

struct datosConexion: Decodable{
    let datos_conexion: String
}

struct estado_lanzamiento: Decodable{
    let tiempo_restante: String
    let etapa_actual: String
}

struct usuario: Decodable {
    let Id: Int
    let Nombre: String
    let Password: String
    let Imagen: String
    let Puesto: String
    let Departamento: String
}
</code>```

JSON full example from Request

```<code>[
    {
        "datos_conexion": {
            "conexion": "2019-05-27 17:05:45"
        }
    },
    {
        "estado_lanzamiento": {
            "tiempo_restante": 240,
            "etapa_actual": "Configuracion"
        }
    },
    {
        "usuario": [
            {
                "Id": "4",
                "Nombre": "This is the Name",
                "Email": "email@gmail.com",
                "Password": "1234",
                "Imagen": "default.jpg",
                "Puesto": "",
                "Departamento": "Etapa Final"
            }
        ]
    }
]
</code>```

decoding code

```<code>URLSession.shared.dataTask(with: url2) { (data, resp, err) in
    guard let data = data else{return}
    let dataAsString = String(data: data, encoding: .utf8)
//      print(dataAsString)
    do {
        let JSONDATA = try JSONDecoder().decode([peticion].self, from: data)
//     print(data)
    } catch let jsonErr {
        print("cant decode", jsonErr)
    }
</code>```

Errors trying to do this:

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode dictionary but found an Array instead.", underlyingError: nil))

答:
```<code>import Foundation

// MARK: - WelcomeElement
struct WelcomeElement: Codable {
    let datosConexion: DatosConexion?
    let estadoLanzamiento: EstadoLanzamiento?
    let usuario: [Usuario]?

    enum CodingKeys: String, CodingKey {
        case datosConexion = "datos_conexion"
        case estadoLanzamiento = "estado_lanzamiento"
        case usuario
    }
}

// MARK: - DatosConexion
struct DatosConexion: Codable {
    let conexion: String
}

// MARK: - EstadoLanzamiento
struct EstadoLanzamiento: Codable {
    let tiempoRestante: Int
    let etapaActual: String

    enum CodingKeys: String, CodingKey {
        case tiempoRestante = "tiempo_restante"
        case etapaActual = "etapa_actual"
    }
}

// MARK: - Usuario
struct Usuario: Codable {
    let id, nombre, email, password: String
    let imagen, puesto, departamento: String

    enum CodingKeys: String, CodingKey {
        case id = "Id"
        case nombre = "Nombre"
        case email = "Email"
        case password = "Password"
        case imagen = "Imagen"
        case puesto = "Puesto"
        case departamento = "Departamento"
    }
}

typealias Welcome = [WelcomeElement]
</code>```

Body:
I have been trying to decode an array for an app where I have to decode JSON.

I just can't decode it with my actual structure and others which I tried before.

Here are my latest structures:

struct peticion: Decodable{
    let datos_conexion: datos_conexion
    let estado_lanzamiento: estado_lanzamiento
    let usuario: usuario
}

struct datos_conexion: Decodable {
    let conexion: datosConexion
}

struct datosConexion: Decodable{
    let datos_conexion: String
}

struct estado_lanzamiento: Decodable{
    let tiempo_restante: String
    let etapa_actual: String
}

struct usuario: Decodable {
    let Id: Int
    let Nombre: String
    let Password: String
    let Imagen: String
    let Puesto: String
    let Departamento: String
}

JSON full example from Request

[
    {
        "datos_conexion": {
            "conexion": "2019-05-27 17:05:45"
        }
    },
    {
        "estado_lanzamiento": {
            "tiempo_restante": 240,
            "etapa_actual": "Configuracion"
        }
    },
    {
        "usuario": [
            {
                "Id": "4",
                "Nombre": "This is the Name",
                "Email": "email@gmail.com",
                "Password": "1234",
                "Imagen": "default.jpg",
                "Puesto": "",
                "Departamento": "Etapa Final"
            }
        ]
    }
]

decoding code

URLSession.shared.dataTask(with: url2) { (data, resp, err) in
    guard let data = data else{return}
    let dataAsString = String(data: data, encoding: .utf8)
//      print(dataAsString)
    do {
        let JSONDATA = try JSONDecoder().decode([peticion].self, from: data)
//     print(data)
    } catch let jsonErr {
        print("cant decode", jsonErr)
    }

Errors trying to do this:

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode dictionary but found an Array instead.", underlyingError: nil))


答:
No, In java it's impossible as far as I know.
However, there are some workarounds:

Workaround 1:

```<code>class MyObject {
   public String toString() {
       return super.toString() + <whatever_of_my_object>;
   }
}
</code>```

Workaround 2:

```<code>class MyObject {

      public String toIdentityString() { // this is your custom function you can call it foo
           return super.toString();
      }
}
</code>```

And then use toIdentityString to print id of the object

Title: Java force Object::toString

Body:
No, In java it's impossible as far as I know.
However, there are some workarounds:

Workaround 1:

class MyObject {
   public String toString() {
       return super.toString() + <whatever_of_my_object>;
   }
}

Workaround 2:

class MyObject {

      public String toIdentityString() { // this is your custom function you can call it foo
           return super.toString();
      }
}

And then use toIdentityString to print id of the object


问:
How to combine 3 or more CompletionStages?
If have 2 CompletionStages, I can combine them with thenCombine method:

CompletionStage aCompletionStage = getA();
CompletionStage bCompletionStage = getB();
CompletionStage<Combined> combinedCompletionStage =
    aCompletionStage.thenCombine(bCompletionStage, (aData, bData) -> combine(aData, bData));
```
<p>If I have 3 or more CompletionStages, I can make a chain of <code>thenCombine</code> methods, but I have to use temporary objects to pass results. For example, here is a solution using <code>Pair</code> and <code>Triple</code> from the <code>org.apache.commons.lang3.tuple</code> package:</p>
<pre class="lang-java prettyprint-override"><code>CompletionStage<A> aCompletionStage = getA();
CompletionStage<B> bCompletionStage = getB();
CompletionStage<C> cCompletionStage = getC();
CompletionStage<D> dCompletionStage = getD();

CompletionStage<Combined> combinedDataCompletionStage =
        aCompletionStage.thenCombine(bCompletionStage, (Pair::of))
                .thenCombine(cCompletionStage, (ab, c) ->
                        Triple.of(ab.getLeft(), ab.getRight(), c))
                .thenCombine(dCompletionStage, (abc, d) ->
                        combine(abc.getLeft(), abc.getMiddle(), abc.getRight(), d));
</code>```

Is there a better way to combine results from multiple CompletionStages?

答:
I had a similar problem but had more than 3 completablefutures so building up on Holger's answer I made a small generic utility. </p>

```<code>public static <T, R> CompletableFuture<R> allOf(List<CompletableFuture<T>> args, Function<List<T>, R> combiner) {
    final Queue<CompletableFuture<T>> queue = new LinkedList<>();
    for (CompletableFuture<T> arg : args) {
        queue.add(arg);
    }
    return aggregator(queue, new ArrayList<>(), combiner);
}

private static <T, R> CompletableFuture<R> aggregator(Queue<CompletableFuture<T>> queue, List<T> arg,
        Function<List<T>, R> combiner) {
    if (queue.size() == 2)
        return queue.poll().thenCombine(queue.poll(), (c, d) -> {
            arg.add(c);
            arg.add(d);
            return combiner.apply(arg);
        });
    return queue.poll().thenCompose(data -> {
        arg.add(data);
        return aggregator(queue, arg, combiner);
    });
}
</code>```

Body:
If have 2 CompletionStages, I can combine them with thenCombine method:

CompletionStage aCompletionStage = getA();
CompletionStage bCompletionStage = getB();
CompletionStage<Combined> combinedCompletionStage =
    aCompletionStage.thenCombine(bCompletionStage, (aData, bData) -> combine(aData, bData));

If I have 3 or more CompletionStages, I can make a chain of thenCombine methods, but I have to use temporary objects to pass results. For example, here is a solution using Pair and Triple from the org.apache.commons.lang3.tuple package:

CompletionStage aCompletionStage = getA();
CompletionStage bCompletionStage = getB();
CompletionStage<C> cCompletionStage = getC();
CompletionStage<D> dCompletionStage = getD();

CompletionStage<Combined> combinedDataCompletionStage =
        aCompletionStage.thenCombine(bCompletionStage, (Pair::of))
                .thenCombine(cCompletionStage, (ab, c) ->
                        Triple.of(ab.getLeft(), ab.getRight(), c))
                .thenCombine(dCompletionStage, (abc, d) ->
                        combine(abc.getLeft(), abc.getMiddle(), abc.getRight(), d));

Is there a better way to combine results from multiple CompletionStages?

Body:
I had a similar problem but had more than 3 completablefutures so building up on Holger's answer I made a small generic utility.

public static <T, R> CompletableFuture<R> allOf(List<CompletableFuture<T>> args, Function<List<T>, R> combiner) {
    final Queue<CompletableFuture<T>> queue = new LinkedList<>();
    for (CompletableFuture<T> arg : args) {
        queue.add(arg);
    }
    return aggregator(queue, new ArrayList<>(), combiner);
}

private static <T, R> CompletableFuture<R> aggregator(Queue<CompletableFuture<T>> queue, List<T> arg,
        Function<List<T>, R> combiner) {
    if (queue.size() == 2)
        return queue.poll().thenCombine(queue.poll(), (c, d) -> {
            arg.add(c);
            arg.add(d);
            return combiner.apply(arg);
        });
    return queue.poll().thenCompose(data -> {
        arg.add(data);
        return aggregator(queue, arg, combiner);
    });
}


问:
How to configure Zurb Foundation in a VueJS TypeScript project?
I am trying to incorporate Zurb Foundation v6.5.3 into a TypeScript based VueJS project created w/ @Vue/CLI. The jQuery type definitions are included project. In the following component Foundation is initialized with the $(document).foundation() command.

```<code><template>
  <div>
    <p>TEST</p>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import $ from 'jquery';

@Component({
  components: {},
  mounted: () => {
    $(document).foundation();
  },
})
export default class Layout extends Vue { }
</script>
</code>```

However, the following message is displayed when compiling the project which prevents it from running.

Property 'foundation' does not exist on type 'JQuery'.

Version: typescript 3.4.5, tslint 5.16.0

Has anyone experienced this problem or found the proper way to incorporate Foundation into a VueJS TypeScript project?

答:
It turns out that you need to add

```<code>import 'foundation-sites';
</code>```

after

```<code>import $ from 'jquery';
</code>```

and it will load all the Foundation modules. Alternatively, individual modules can be initialized.

If this is done in App.vue then all child components will have Foundation initialized.

Body:
I am trying to incorporate Zurb Foundation v6.5.3 into a TypeScript based VueJS project created w/ @Vue/CLI. The jQuery type definitions are included project. In the following component Foundation is initialized with the $(document).foundation() command.

<template>

TEST

</template>

However, the following message is displayed when compiling the project which prevents it from running.

Property 'foundation' does not exist on type 'JQuery'.

Version: typescript 3.4.5, tslint 5.16.0

Has anyone experienced this problem or found the proper way to incorporate Foundation into a VueJS TypeScript project?

Body:
It turns out that you need to add

import 'foundation-sites';

after

import $ from 'jquery';

and it will load all the Foundation modules. Alternatively, individual modules can be initialized.

If this is done in App.vue then all child components will have Foundation initialized.


问:
Eclipse's Package explorer background color follows windows theme. I want to change the color without changing windows' theme. Possible?
Maybe a way to alter the colors locally (as in application dependant)?

A background color of eclipse is white, the same white of windows' active window background color. If I change the color on the theme, eclipse changes to the color.

I want to change this software's color without changing the whole theme (because then every program gets weird colors). Is this possible? I thought that maybe there was a way to apply different windows themes to different programs, or something.

I'm using windows XP, classic windows theme.

答:
Knowing the way the workbench is built, I'm sure your request is not possible on the Eclipse side. You can do this for the editors, because they are StyledText widgets, and you are exposed some preferences to customize these.
The other views are various widgets, some are Trees, some are Text, some are composed from various other widgets. All of them are created with the default constructor which just uses the Windows theme.</p>


问:
Move generated 0's to the beginning of the array
I would like to put all the seed [i] values to the right, causing the zeros to be left.
However, if the seed [i] = 0 I want this 0 to be on the right. For example, the value 1056 can be possible because if I chose that seed[i] to be 0.

// Download Function
function download(fileName, text) {
    let element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', fileName);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
}
function genBatch (seed) {
    let result = new Array(4);
    for (var i = 0; i < 4; i++) {
        result[i] = seed[i] || "0";
    }
    return result.join("");
}

// Generate File
document.getElementById("generate").addEventListener("click", function(){

    let batch = document.getElementById("batchNumber").value;
    /* /header2 */
    let text =  genBatch(batch) + "  ";

    let fileName = document.getElementById("fileName").value + ".txt";

    download(fileName, text);
}, false);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <body>
    <div class="container">
          <label for="batchNumber" class="font-weight-bold">Batch Number:</label>
          <input id="batchNumber" type="number" maxlength="4" size="4"/>
          <label for="fileName" class="font-weight-bold">File Name:</label>
          <input id="fileName" type="text"/>
    </div>
    <button id="generate" type="button" class="btn btn-light font-weight-bold mx-auto">Generate File</button>
    <script src="js/app.js"></script>
  </body>
</html></code>```

答:
I think you are just looking for the padStart method.

String.prototype.padStart() MDN

const getAsString = (num, minLen) => {
  return (num||'').toString().padStart( minLen||4, '0');
};

console.log(getAsString());
console.log(getAsString(1));
console.log(getAsString(333));
console.log(getAsString(1234));```

Body:
I would like to put all the seed [i] values to the right, causing the zeros to be left.
However, if the seed [i] = 0 I want this 0 to be on the right. For example, the value 1056 can be possible because if I chose that seed[i] to be 0.

// Download Function
function download(fileName, text) {
    let element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', fileName);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
}
function genBatch (seed) {
    let result = new Array(4);
    for (var i = 0; i < 4; i++) {
        result[i] = seed[i] || "0";
    }
    return result.join("");
}

// Generate File
document.getElementById("generate").addEventListener("click", function(){

    let batch = document.getElementById("batchNumber").value;
    /* /header2 */
    let text =  genBatch(batch) + "  ";

    let fileName = document.getElementById("fileName").value + ".txt";

    download(fileName, text);
}, false);

<!DOCTYPE html>

          Batch Number:
          <input id="batchNumber" type="number" maxlength="4" size="4"/>
          File Name:
          <input id="fileName" type="text"/>

    <button id="generate" type="button" class="btn btn-light font-weight-bold mx-auto">Generate File</button>


问:
Android Glide: How to download and cache bitmaps?
I am using Glide to download and cache images on Android. Everything works well except the fact that I don't want to load the bitmaps directly into the ImageView, I don't want to have the fade animation, neither image placeholders.

All I want is to create a global method which will help me to download the image all over the application.

```<code>public class MyApp extends Application {

   public static void downloadImage(String url, final OnImageLoadedCallback callback) {

     // And how to implement the listener ?

     RequestListener<String, Bitmap> requestListener = new RequestListener<String, Bitmap() {
        @Override
        public boolean onException(Exception exc, String string, Target<Bitmap> target, boolean isFirstResource) {

           callback.onDone(null);

           return false;
        }

        @Override
        public boolean onResourceReady(Bitmap bitmap, String string, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) {

            callback.onDone(bitmap);

            return false;
        }
     };

      Glide.with(context)
           .load(url)
           .asBitmap()
           .dontAnimate()
           .diskCacheStrategy(DiskCacheStrategy.SOURCE)
           .listener(requestListener);
   }

}
</code>```

The problem is that I don't know how to implement the listener. RequestListener isn't called at all.

答:
It is now even simpler on Glide 4.9.0.</p>

```<code>Glide.with(this)
    .downloadOnly()
    .load(url)
</code>```

Body:
I am using Glide to download and cache images on Android. Everything works well except the fact that I don't want to load the bitmaps directly into the ImageView, I don't want to have the fade animation, neither image placeholders.

All I want is to create a global method which will help me to download the image all over the application.

public class MyApp extends Application {

   public static void downloadImage(String url, final OnImageLoadedCallback callback) {

     // And how to implement the listener ?

     RequestListener<String, Bitmap> requestListener = new RequestListener<String, Bitmap() {
        @Override
        public boolean onException(Exception exc, String string, Target<Bitmap> target, boolean isFirstResource) {

           callback.onDone(null);

           return false;
        }

        @Override
        public boolean onResourceReady(Bitmap bitmap, String string, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) {

            callback.onDone(bitmap);

            return false;
        }
     };

      Glide.with(context)
           .load(url)
           .asBitmap()
           .dontAnimate()
           .diskCacheStrategy(DiskCacheStrategy.SOURCE)
           .listener(requestListener);
   }

}

The problem is that I don't know how to implement the listener. RequestListener isn't called at all.

Body:
It is now even simpler on Glide 4.9.0.

Glide.with(this)
    .downloadOnly()
    .load(url)


问:
Why the li tag not getting the value of loop variable?
I am trying to loop through the object that is coming from app.js. I am using each loop in PUG/JADE, so that I can use its value to print some values. But the li is not getting the value of loop variable

 Note :  I am getting 'post.title' and 'post.body' below 4 times because, it's coming from the mongo database and I did exactly 4 entries in the database. Plus this also means that object is correctly coming to the index page, but li is not getting the value of loop variable.

 Output I am getting

```<code> . = post.title
 . = post.body
 . = post.title
 . = post.body
 . = post.title
 . = post.body
 . = post.title
 . = post.body
</code>```

 What I want

```<code> Title of the post
 body of the post

 Title of another post
 Body of another post

 and so on....
</code>```

 My Code

---- index.pug ----

```<code>block content
    ul
    each post in posts
        li = post.title
        li = post.body
</code>```

---- app.js ----

```<code>let Post = require('./models/post');

app.get('/', function(req, res){
   Post.find({}, function(err, posts){

   if(err){
       console.log(err);
   } else {
      res.render('index', {
        title:'Posts',
        posts: posts
     });
   }
 });
});
</code>```

 What Else I tried

I made a constant array just above the loop to check and iterated through that array. But it gave me the same result as

```<code>. = name
. = name
. = name
</code>```

don't know why. The code for that is below.

```<code>block content
     - const names = ["Sami", "Abeer", "Hassaan"];
     ul.list-group
         each name in names
            li = name
</code>```

答:
Remove the space between li =, so you get li= name. The space indicates that the equal sign should be content of the tag.

Full example of your index.pug:

```<code>block content
    ul
    each post in posts
        li= post.title
        li= post.body
</code>```

Body:
I am trying to loop through the object that is coming from app.js. I am using each loop in PUG/JADE, so that I can use its value to print some values. But the li is not getting the value of loop variable

 Note :  I am getting 'post.title' and 'post.body' below 4 times because, it's coming from the mongo database and I did exactly 4 entries in the database. Plus this also means that object is correctly coming to the index page, but li is not getting the value of loop variable.

 Output I am getting

 . = post.title
 . = post.body
 . = post.title
 . = post.body
 . = post.title
 . = post.body
 . = post.title
 . = post.body

 What I want

 Title of the post
 body of the post

 Title of another post
 Body of another post

 and so on....

 My Code

---- index.pug ----

block content
    ul
    each post in posts
        li = post.title
        li = post.body

---- app.js ----

let Post = require('./models/post');

app.get('/', function(req, res){
   Post.find({}, function(err, posts){

   if(err){
       console.log(err);
   } else {
      res.render('index', {
        title:'Posts',
        posts: posts
     });
   }
 });
});

 What Else I tried

I made a constant array just above the loop to check and iterated through that array. But it gave me the same result as

. = name
. = name
. = name

don't know why. The code for that is below.

block content
     - const names = ["Sami", "Abeer", "Hassaan"];
     ul.list-group
         each name in names
            li = name

Body:
Remove the space between li =, so you get li= name. The space indicates that the equal sign should be content of the tag.

Full example of your index.pug:

block content
    ul
    each post in posts
        li= post.title
        li= post.body


问:
Oauth2 Authentication handle code programmatically
I implemented the OAuth2 authentication using Apache OLTU libraries.
It works but I handle manually the request token from RedirectURL.

step:

request = OAuthClientRequest.authorizationProvider(OAuthProviderType.GOOGLE)//authorizationProvider(OAuthProviderType.GOOGLE)
                .setState(OAuth.OAUTH_STATE)
                .setResponseType(OAuth.OAUTH_CODE)
                .setRedirectURI("http://localhost:8080")
                .setClientId(clientId)
                .setScope("https://www.googleapis.com/auth/drive")
                .buildQueryMessage();

Step:

OAuthClientRequest oAuthClientRequest = OAuthClientRequest.tokenProvider(OAuthProviderType.GOOGLE)
                .setGrantType(GrantType.AUTHORIZATION_CODE)
                .setClientId(clientId)
                .setClientSecret(clientSecret)
                .setRedirectURI("http://localhost:8080")
                .setCode(requestCode).buildBodyMessage();

Between the two-step, I need to handle automatically the extraction of the code.
How can I implement in code this step?

I'm wont it not in a servlet, but in a Portlet.

答:
Question "How can I implement in code this step?"

Requirement "I'm wont it not in a servlet, but in a Portlet."

Answer:

(1) For your reference I add the source code into your source code (using Apache OLTU libraries) to "handle automatically the extraction of the OAuth authorization code."

```<code>// 1. Step
OAuthClientRequest request = OAuthClientRequest.authorizationProvider(OAuthProviderType.GOOGLE)//authorizationProvider(OAuthProviderType.GOOGLE) .setState(OAuth.OAUTH_STATE) .setResponseType(OAuth.OAUTH_CODE) .setRedirectURI("http://localhost:8080") .setClientId(clientId) .setScope("https://www.googleapis.com/auth/drive") .buildQueryMessage();

// Create the response wrapper
OAuthAuthzResponse oar = null;
oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);

// Get Authorization Code
String requestCode = oar.getCode();

// 2. Step
OAuthClientRequest oAuthClientRequest = OAuthClientRequest.tokenProvider(OAuthProviderType.GOOGLE) .setGrantType(GrantType.AUTHORIZATION_CODE) .setClientId(clientId) .setClientSecret(clientSecret) .setRedirectURI("http://localhost:8080") .setCode(requestCode).buildBodyMessage();

</code>```

(2) More details can be referred to the following sample code

"demos/client-demo/src/main/java/org/apache/oltu/oauth2/client/demo/controller/RedirectController.java"

from Apache Oltu OAuth 2.0 Client and Provider at GitHub repository, which is a fork of Apache Oltu with Pull Request #10 for two new commits "Add provider demo and README".

The provider demo application ("demos/provider-demo" from Apache Oltu OAuth 2.0 Client and Provider at GitHub repository) allows you to run a standalone OAuth 2.0 server to test and debug your OAuth2 authentication client (implemented by you in a Portlet).

Body:
Question "How can I implement in code this step?"

Requirement "I'm wont it not in a servlet, but in a Portlet."

Answer:

(1) For your reference I add the source code into your source code (using Apache OLTU libraries) to "handle automatically the extraction of the OAuth authorization code."

// 1. Step
OAuthClientRequest request = OAuthClientRequest.authorizationProvider(OAuthProviderType.GOOGLE)//authorizationProvider(OAuthProviderType.GOOGLE) .setState(OAuth.OAUTH_STATE) .setResponseType(OAuth.OAUTH_CODE) .setRedirectURI("http://localhost:8080") .setClientId(clientId) .setScope("https://www.googleapis.com/auth/drive") .buildQueryMessage();

// Create the response wrapper
OAuthAuthzResponse oar = null;
oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);

// Get Authorization Code
String requestCode = oar.getCode();

// 2. Step
OAuthClientRequest oAuthClientRequest = OAuthClientRequest.tokenProvider(OAuthProviderType.GOOGLE) .setGrantType(GrantType.AUTHORIZATION_CODE) .setClientId(clientId) .setClientSecret(clientSecret) .setRedirectURI("http://localhost:8080") .setCode(requestCode).buildBodyMessage();

(2) More details can be referred to the following sample code

"demos/client-demo/src/main/java/org/apache/oltu/oauth2/client/demo/controller/RedirectController.java"

from Apache Oltu OAuth 2.0 Client and Provider at GitHub repository, which is a fork of Apache Oltu with Pull Request #10 for two new commits "Add provider demo and README".

The provider demo application ("demos/provider-demo" from Apache Oltu OAuth 2.0 Client and Provider at GitHub repository) allows you to run a standalone OAuth 2.0 server to test and debug your OAuth2 authentication client (implemented by you in a Portlet).


问:
"&optional" in (prettify-symbols-mode &optional ARG)
using Emacs Lisp:

Upon invoking describe-function to review prettify-symbols-mode

```<code>(prettify-symbols-mode &optional ARG)
</code>```

What does &optional mean? is & is a 'logand'?

答:
&optional in an argument list mean that the arguments that follow are not required.  If the caller provides them then they'll be assigned to the respective variables.  If not, then the variables will be nil.

See also https://www.gnu.org/software/emacs/manual/html_node/elisp/Argument-List.html

The '&' in front of 'optional' makes it possible for the defun to recognize '&optional' as a keyword and not an argument itself.

Body:
using Emacs Lisp:

Upon invoking describe-function to review prettify-symbols-mode

(prettify-symbols-mode &optional ARG)

What does &optional mean? is & is a 'logand'?


问:
Raising events in C# from classes
Basically I am attempting to write a generic interprocess communication implementation between C# and the Android platform (using Java).

Creating the socket stack is simple enough but what I am wondering is what would be a good pattern to passing in delegates into my TcpServer class and raising the required events.

The idea so far is.

```<code>while (connected) {
    //Compile all the required data and so forth
        switch (currentState)
        {
               case CurrentServerState.EventReceived:
                    //Raise my event...
               break;
               case CurrentServerState.ObjectReceived:
               break;

        }
}
</code>```

So would the correct implementation simply expose an array of delegates and use reflection to match event names or something along those lines? What are my options? Also how do I make sure that any raised events are raised in the UI thread given that this is all occurring from a thread created for the server?

答:
If you don't need to pass any custom arguments to the event handler you can use the default EventHandler delegate which uses the base EventArgs.

Declare the events you want to make available like this:

```<code>public event EventHandler EventReceived;
public event EventHandler ObjectReceived;
</code>```

Declare a protected method for each event to handle raising the event for you. This is really just a convenience to keep from repeating this each time you need it. You could do this inline.

Your events will be null if there are no attached event handlers. The method handles checking for this before firing the event.

```<code>protected void RaiseEventReceived(EventArgs e)
{
    if (EventReceived != null)
        EventReceived(this, e);
}
</code>```

Then call the method when you want to raise the event. The method will handle checking to see if anyone is listening for the event.

```<code>public void SomeOtherMethod()
{
    while (IsConnected)
    {
        switch (CurrentState)
        {
            case CurrentServerState.EventReceived:
                RaiseEventReceived(EventArgs.Empty);
                break;

            case CurrentServerState.ObjectReceived:
                RaiseObjectReceived(EventArgs.Empty);
                break;
        }
    }
}
</code>```

You can declare your own class to pass custom arguments to the event handlers by deriving from EventArgs such as the following. By convention your class should be named *something*EventArgs.

```<code>public class EventReceivedEventArgs : EventArgs
{
    // Declare properties to hold additional event info here
}
</code>```

Then you would need to declare a custom delegate that takes your new event args parameter:

```<code>public delegate void EventReceivedEventHandler(object sender, EventReceivedEventArgs e);
</code>```

Update your event declarations to use your new delegate type instead of EventHandler:

```<code>public event EventReceivedEventHandler EventReceived;
</code>```

And finally, when raising the event you of course would want to create a new instance of your custom event arguments class and intitialize your custom properties.

Clients can attach multiple handlers to your events using the normal syntax and they will always be called on the correct thread.

Title: Raising events in C# from classes

Body:
Basically I am attempting to write a generic interprocess communication implementation between C# and the Android platform (using Java).

Creating the socket stack is simple enough but what I am wondering is what would be a good pattern to passing in delegates into my TcpServer class and raising the required events.

The idea so far is.

while (connected) {
    //Compile all the required data and so forth
        switch (currentState)
        {
               case CurrentServerState.EventReceived:
                    //Raise my event...
               break;
               case CurrentServerState.ObjectReceived:
               break;

        }
}

So would the correct implementation simply expose an array of delegates and use reflection to match event names or something along those lines? What are my options? Also how do I make sure that any raised events are raised in the UI thread given that this is all occurring from a thread created for the server?

Body:
If you don't need to pass any custom arguments to the event handler you can use the default EventHandler delegate which uses the base EventArgs.

Declare the events you want to make available like this:

public event EventHandler EventReceived;
public event EventHandler ObjectReceived;

Declare a protected method for each event to handle raising the event for you. This is really just a convenience to keep from repeating this each time you need it. You could do this inline.

Your events will be null if there are no attached event handlers. The method handles checking for this before firing the event.

protected void RaiseEventReceived(EventArgs e)
{
    if (EventReceived != null)
        EventReceived(this, e);
}

Then call the method when you want to raise the event. The method will handle checking to see if anyone is listening for the event.

public void SomeOtherMethod()
{
    while (IsConnected)
    {
        switch (CurrentState)
        {
            case CurrentServerState.EventReceived:
                RaiseEventReceived(EventArgs.Empty);
                break;

            case CurrentServerState.ObjectReceived:
                RaiseObjectReceived(EventArgs.Empty);
                break;
        }
    }
}

You can declare your own class to pass custom arguments to the event handlers by deriving from EventArgs such as the following. By convention your class should be named *something*EventArgs.

public class EventReceivedEventArgs : EventArgs
{
    // Declare properties to hold additional event info here
}

Then you would need to declare a custom delegate that takes your new event args parameter:

public delegate void EventReceivedEventHandler(object sender, EventReceivedEventArgs e);

Update your event declarations to use your new delegate type instead of EventHandler:

public event EventReceivedEventHandler EventReceived;

And finally, when raising the event you of course would want to create a new instance of your custom event arguments class and intitialize your custom properties.

Clients can attach multiple handlers to your events using the normal syntax and they will always be called on the correct thread.


问:
Matplotlib iterate to combine legend handles and labels
If I have the following plotting routine that plots a scatter plot and corresponding linear regression and combines the legend handles:

```<code>import pandas as pd
from scipy.stats import linregress
import numpy as np
import matplotlib.pyplot as plt

#data and Regression
x = np.arange(0,5,1)
y = np.arange(0,10,2)
df = pd.DataFrame(data = {'x':x,'y':y})
s, intcpt, r, p, serr = linregress(df.x, df.y)
xHat = np.linspace(0,5,100)

# do the plotting
fig,ax = plt.subplots()
df.plot(x='x',y='y',ax=ax,label='series1',ls=' ',marker='x',c='blue')
ls_handle, = ax.plot(xHat, s*xHat + intcpt, linestyle='-', marker=None, c='blue')
handle2merge = [ls_handle]
handles, labels = ax.get_legend_handles_labels()
handle_combined = zip(handles, handle2merge)
ax.legend(handle_combined, labels)
</code>```

Which returns the where the marker and line handles are merged looking like:

Now I want to plot another dataset in a similar fashion:

```<code>#get current axis handles and labels
handle_start, label_start = ax.get_legend_handles_labels()

#second dataset and regression
x1 = np.arange(0,5,1)
y1 = np.arange(0,2.5,0.5)
df1 = pd.DataFrame(data = {'x':x1,'y':y1})
s1, intcpt1, r1, p1, serr1 = linregress(df1.x, df1.y)
xHat1 = np.linspace(0,5,100)

#plot second data set on same figure
marker_handle2, = ax.plot(df1.x, df1.y, marker = 'x', zorder=10,c='k', linestyle=' ')
line_handle2, = ax.plot(xHat, s1*xHat1 + intcpt1, linestyle='--', marker=None, c='k')
new_line_handles = [line_handle2]
new_marker_handles= [marker_handle2]

ax.legend(handle_start + zip(new_marker_handles,new_line_handles), label_start + ['series2'])
</code>```

This returns a plot where the handles for series1 legend handle only contains the marker.

Why is len(handle_start)=1 when I constructed the handle with handle_combined = zip(handles, handle2merge)?

答:
I have poked around the code a little. What you are doing is passing a list of tuples to ax.legend, which apparently draws each Artist in each tuple as one entry in the legend. I have actually not come across this behaviour before; it could be a bug, or unintended use of ax.legend.

Nevertheless, I think that in this case, since you know what your lines should look like beforehand, instead of going the roundabout way with zip and stuff, you could just pass a custom Line2D to legend directly:

```<code>import numpy as np

from scipy.stats import linregress

from matplotlib import pyplot as plt
from matplotlib import lines

x1 = np.arange(0, 5, 1)
y1 = np.arange(0, 10, 2)
x2 = np.arange(0, 5, 1)
y2 = np.arange(0, 2.5, 0.5)

m1, c1, r1, p1, serr1 = linregress(x1, y1)
m2, c2, r2, p2, serr2 = linregress(x2, y2)

x_pred = np.linspace(0,5,100)

fig, ax = plt.subplots()

first_line, = ax.plot(x_pred, x_pred * m1 + c1, ls='-', c='blue')
first_scatter = ax.scatter(x1, y1, marker='x', c='blue')

second_line, = ax.plot(x_pred, x_pred * m2 + c2, ls='--', c='black')
second_scatter = ax.scatter(x2, y2, marker='x', c='black')

ax.legend([lines.Line2D([0], [0], marker='x', ls='-', c='blue'),
           lines.Line2D([0], [0], marker='x', ls='--', c='black')],
          ['series_1', 'series_2'])
</code>```

I cleaned up your code a little, but feel free to take only the last line and the necessary import.

Body:
If I have the following plotting routine that plots a scatter plot and corresponding linear regression and combines the legend handles:

import pandas as pd
from scipy.stats import linregress
import numpy as np
import matplotlib.pyplot as plt

#data and Regression
x = np.arange(0,5,1)
y = np.arange(0,10,2)
df = pd.DataFrame(data = {'x':x,'y':y})
s, intcpt, r, p, serr = linregress(df.x, df.y)
xHat = np.linspace(0,5,100)

# do the plotting
fig,ax = plt.subplots()
df.plot(x='x',y='y',ax=ax,label='series1',ls=' ',marker='x',c='blue')
ls_handle, = ax.plot(xHat, s*xHat + intcpt, linestyle='-', marker=None, c='blue')
handle2merge = [ls_handle]
handles, labels = ax.get_legend_handles_labels()
handle_combined = zip(handles, handle2merge)
ax.legend(handle_combined, labels)

Which returns the where the marker and line handles are merged looking like:

Now I want to plot another dataset in a similar fashion:

#get current axis handles and labels
handle_start, label_start = ax.get_legend_handles_labels()

#second dataset and regression
x1 = np.arange(0,5,1)
y1 = np.arange(0,2.5,0.5)
df1 = pd.DataFrame(data = {'x':x1,'y':y1})
s1, intcpt1, r1, p1, serr1 = linregress(df1.x, df1.y)
xHat1 = np.linspace(0,5,100)

#plot second data set on same figure
marker_handle2, = ax.plot(df1.x, df1.y, marker = 'x', zorder=10,c='k', linestyle=' ')
line_handle2, = ax.plot(xHat, s1*xHat1 + intcpt1, linestyle='--', marker=None, c='k')
new_line_handles = [line_handle2]
new_marker_handles= [marker_handle2]

ax.legend(handle_start + zip(new_marker_handles,new_line_handles), label_start + ['series2'])

This returns a plot where the handles for series1 legend handle only contains the marker.

Why is len(handle_start)=1 when I constructed the handle with handle_combined = zip(handles, handle2merge)?

Body:
I have poked around the code a little. What you are doing is passing a list of tuples to ax.legend, which apparently draws each Artist in each tuple as one entry in the legend. I have actually not come across this behaviour before; it could be a bug, or unintended use of ax.legend.

Nevertheless, I think that in this case, since you know what your lines should look like beforehand, instead of going the roundabout way with zip and stuff, you could just pass a custom Line2D to legend directly:

import numpy as np

from scipy.stats import linregress

from matplotlib import pyplot as plt
from matplotlib import lines

x1 = np.arange(0, 5, 1)
y1 = np.arange(0, 10, 2)
x2 = np.arange(0, 5, 1)
y2 = np.arange(0, 2.5, 0.5)

m1, c1, r1, p1, serr1 = linregress(x1, y1)
m2, c2, r2, p2, serr2 = linregress(x2, y2)

x_pred = np.linspace(0,5,100)

fig, ax = plt.subplots()

first_line, = ax.plot(x_pred, x_pred * m1 + c1, ls='-', c='blue')
first_scatter = ax.scatter(x1, y1, marker='x', c='blue')

second_line, = ax.plot(x_pred, x_pred * m2 + c2, ls='--', c='black')
second_scatter = ax.scatter(x2, y2, marker='x', c='black')

ax.legend([lines.Line2D([0], [0], marker='x', ls='-', c='blue'),
           lines.Line2D([0], [0], marker='x', ls='--', c='black')],
          ['series_1', 'series_2'])

I cleaned up your code a little, but feel free to take only the last line and the necessary import.


问:
Why do I get an error in a simple cast of String to Integer in an List<String>
I want to cast a List<String> to an Array Integer[]. I made this function:

```<code>public static Integer[] castToArrayInteger(List<String> cadenas) {
    Integer[] enteros = new Integer[cadenas.size()];
    for(int iteracion = 0; iteracion < cadenas.size(); iteracion++) {
        enteros[iteracion] = Integer.valueOf(cadenas.get(iteracion));
    }
    return enteros;
}
</code>```

Then I made a Test:

```<code>@Test
public void castToArrayInteger() {
    List<String> cadenas = new ArrayList<>();
    Integer[] enteros = new Integer[3];
    int i = 0;
    while(i < 3) {
        cadenas.add(String.valueOf(i));
        enteros[i] = i;
        i++;
    }
    Assert.assertArrayEquals(enteros, ArregloUtils.castToArrayInteger(cadenas)) ;
}
</code>```

It works like a charm. But when I use the  function in an web application, it fails.

The debug tool mark the line :

```<code>Integer.valueOf(cadenas.get(iteracion));
</code>```

The error is

Integer is not compatible with the declared Type String.
```

<p>This is the line where I Implemented the function, getRubros:</p>

```List<CatalogoDto> rubros =  this.catalogoService.buscar(
                ArregloUtils.castToArrayInteger(this.getProductor().getRubrosId()));
```

<p>The method <code>getRubrosId()</code> get the data in a <code>List<String></code></p>

<p>I would like to know why do I have this issue.</p>

<p>Environment:<br>
Java 1.8<br>
Wildfly 16<br>
Red Hat CodeReadyStudio.</p>

<p>I expected for this input:</p>

```List<String> data = new ArrayList<String>();
data.add("1");
data.add("2");
data.add("3");

Integer output = [1,2,3];
```

答:
Just to be clear the part where you convert valid String to int entries using Integer.valueOf (as in your test for example) is not the actual problem. You are trying to convert String entries that cannot be converted to strings as your error message indicated:

Integer is not compatible with the declared Type String.

You can confirm that the problem is not in the conversion process itself but what you're trying to convert by running this code below:

```<code>    List<String> sData = new java.util.ArrayList<String>();
    sData.add("1"); sData.add("2"); sData.add("3");

    Integer[] iData = new Integer[sData.size()];
    for (int i = 0; i < sData.size(); i++) {
        iData[i] = Integer.valueOf(sData.get(i));
        System.out.println(iData[i]);
    }
</code>```

I would recommend inspecting the entries you are converting at runtime using some debugging technique like breakpoints or simple logging. This should solve your problem.

Body:
I want to cast a List<String> to an Array Integer[]. I made this function:

public static Integer[] castToArrayInteger(List<String> cadenas) {
    Integer[] enteros = new Integer[cadenas.size()];
    for(int iteracion = 0; iteracion < cadenas.size(); iteracion++) {
        enteros[iteracion] = Integer.valueOf(cadenas.get(iteracion));
    }
    return enteros;
}

Then I made a Test:

@Test
public void castToArrayInteger() {
    List<String> cadenas = new ArrayList<>();
    Integer[] enteros = new Integer[3];
    int i = 0;
    while(i < 3) {
        cadenas.add(String.valueOf(i));
        enteros[i] = i;
        i++;
    }
    Assert.assertArrayEquals(enteros, ArregloUtils.castToArrayInteger(cadenas)) ;
}

It works like a charm. But when I use the  function in an web application, it fails.

The debug tool mark the line :

Integer.valueOf(cadenas.get(iteracion));

The error is

Integer is not compatible with the declared Type String.

This is the line where I Implemented the function, getRubros:

List<CatalogoDto> rubros =  this.catalogoService.buscar(
                ArregloUtils.castToArrayInteger(this.getProductor().getRubrosId()));

The method getRubrosId() get the data in a List<String>

I would like to know why do I have this issue.

Environment:

Java 1.8

Wildfly 16

Red Hat CodeReadyStudio.

I expected for this input:

List<String> data = new ArrayList<String>();
data.add("1");
data.add("2");
data.add("3");

Integer output = [1,2,3];

Body:
Just to be clear the part where you convert valid String to int entries using Integer.valueOf (as in your test for example) is not the actual problem. You are trying to convert String entries that cannot be converted to strings as your error message indicated:

Integer is not compatible with the declared Type String.

You can confirm that the problem is not in the conversion process itself but what you're trying to convert by running this code below:

    List<String> sData = new java.util.ArrayList<String>();
    sData.add("1"); sData.add("2"); sData.add("3");

    Integer[] iData = new Integer[sData.size()];
    for (int i = 0; i < sData.size(); i++) {
        iData[i] = Integer.valueOf(sData.get(i));
        System.out.println(iData[i]);
    }

I would recommend inspecting the entries you are converting at runtime using some debugging technique like breakpoints or simple logging. This should solve your problem.


问:
Alternative to the use of the 'withColumn' function in Spark Scala
I am reviewing the code of a development and I need to avoid or use a different way of adding columns with the use of the 'withColumn' function in a dataframe; but I have the following doubts:

Using nested 'withColumn', create new tables (as the code below)? using 6 'withColumn', create 6 new in memory tables?

newDataframe = table
.withColumn("name", col("consolidate").cast(DecimalType(17,2)))
.withColumn("name", col("consolidate").cast(DecimalType(17,2)))
```

<ol start="2">
<li><p>If the use of many 'withColumn' increases memory usage and lowers performance (if true), how can I avoid using 'withColumn' when adding columns in a dataframe and get the same result?</p></li>
<li><p>Is there a way that consumes less memory and is faster to run without using 'withColumn', but getting the same result ?, that is, a dataframe with 6 columns added</p></li>
</ol>

<p>I don't know how to do this.</p>

<p>The code to optimize is like this:</p>

```def myMethod(table: DataFrame): DataFrame = {
    newDataframe = table
      .withColumn("name", col("consolidate").cast(DecimalType(17,2)))
      .withColumn("id_value", col("east").cast(DecimalType(17,2)))
      .withColumn("x_value", col("daily").cast(DecimalType(17,2)))
      .withColumn("amount", col("paid").cast(DecimalType(17,2)))
      .withColumn("client", col("lima").cast(DecimalType(17,2)))
      .withColumn("capital", col("econo").cast(DecimalType(17,2)))
    newDataframe
  }
```

答:
There is a misconception here : Spark does not create the 6 intermediary datasets in memory. In fact your function won't trigger any change in memory as Spark transformations (such as withColumn) are evaluated lazily only when a action is called (such as .count() or .show()).

When the action is called Spark will optimize your transformations and do them all at once, so there is no problem with calling 6 times .withColumn in term of memory.

Body:
I am reviewing the code of a development and I need to avoid or use a different way of adding columns with the use of the 'withColumn' function in a dataframe; but I have the following doubts:

Using nested 'withColumn', create new tables (as the code below)? using 6 'withColumn', create 6 new in memory tables?

newDataframe = table
.withColumn("name", col("consolidate").cast(DecimalType(17,2)))
.withColumn("name", col("consolidate").cast(DecimalType(17,2)))

If the use of many 'withColumn' increases memory usage and lowers performance (if true), how can I avoid using 'withColumn' when adding columns in a dataframe and get the same result?

Is there a way that consumes less memory and is faster to run without using 'withColumn', but getting the same result ?, that is, a dataframe with 6 columns added

I don't know how to do this.

The code to optimize is like this:

def myMethod(table: DataFrame): DataFrame = {
    newDataframe = table
      .withColumn("name", col("consolidate").cast(DecimalType(17,2)))
      .withColumn("id_value", col("east").cast(DecimalType(17,2)))
      .withColumn("x_value", col("daily").cast(DecimalType(17,2)))
      .withColumn("amount", col("paid").cast(DecimalType(17,2)))
      .withColumn("client", col("lima").cast(DecimalType(17,2)))
      .withColumn("capital", col("econo").cast(DecimalType(17,2)))
    newDataframe
  }


问:
PHP Doc generic type declaration
I'm working on a library which uses the phpDocumentor specification on determining the type system using reflection. However, I couldn't find any information about generic type declarations.

Is there any way a generic type declaration should be specified?

For example: is there any specification (in-progress) which specifies anything like:

```<code>/**
 * @template <T extends Base>
 */
class Collection {

    /**
     * @return Iterator<T>
     */
    function get_iterator();

}
</code>```

Note that the code above is just an example to illustrate what I mean by generic type declarations. I do not want this achieve anything to do with collections and iterators.

答:
You might want to check out the psalm project.

https://psalm.dev/docs/

https://github.com/vimeo/psalm

It supports generics in the documentation, as well as so much more. It's also used by Symfony's DB ORM, doctrine.

It supports Emacs, Phpstorm/Intellij, vim, and visual studio

Title: PHP Doc generic type declaration

Body:
I'm working on a library which uses the phpDocumentor specification on determining the type system using reflection. However, I couldn't find any information about generic type declarations.

Is there any way a generic type declaration should be specified?

For example: is there any specification (in-progress) which specifies anything like:

/**
 * @template <T extends Base>
 */
class Collection {

    /**
     * @return Iterator<T>
     */
    function get_iterator();

}

Note that the code above is just an example to illustrate what I mean by generic type declarations. I do not want this achieve anything to do with collections and iterators.


问:
How to delete additional days added by pandas resample?
I have a pandas df with tick data, with index as datetime64[ns] I want to resample this data into 5 minute intervals like this: price_5min = price.price.resample('5T').ohlc().between_time('09:00:00, '16:20:00')

It works, however it adds weekends and holidays to the new timeseries, which I need to remove. I'm not following US (or any other standard holiday calendar). I just want to remove days not in the original price df.

Index is not unique, many cases of same timestamp. Pandas version 0.20.1

What I have tried:

1) dropna(): I have rows with NANs that I need to ffill, so this will not work.

2) price.index.difference(price_5min.index): Gives me all the tick dates, not the day dates.

3) price.index.date.difference(price_5min.index.date): Does not work as index.date is a numpy.ndarray

4) price != price_5min: Error: Can only compare identically-labeled DataFrame objects

5) price.index != price_4min.index: Error: Lengths must match to compare

Suggested logic to solve my problem:

a) Somehow compare the day dates in the two dataframes and delete based on this, but how?

b) Remove days with no variance, but how?

c) The obvious that I have not thought of (most likely..)

df price looks like this:

```<code>                     price  quantity
time
2016-06-15 16:19:20  29.85     429.6
2016-06-15 16:19:20  29.85      65.6
2016-06-15 16:19:20  29.85    1351.4
2016-06-15 16:19:30  29.70     729.4
2016-06-15 16:19:30  29.70     287.0
2016-06-15 16:19:30  29.70     219.4
2016-06-15 16:19:49  29.70      47.4
2016-06-15 16:19:52  29.70      11.8
2016-06-16 09:01:42  29.05     350.0
2016-06-16 09:01:42  29.10     189.4
2016-06-16 09:01:45  29.05      33.6
2016-06-16 09:01:54  29.05      33.6
...
</code>```

答:
Fast solution:
</p>

```<code>price_5min=price.groupby(price.index.Date).resample('5T').ohlc()
price_5min.index = price_5min.index.droplevel(0)
</code>```

Body:
I have a pandas df with tick data, with index as datetime64[ns] I want to resample this data into 5 minute intervals like this: price_5min = price.price.resample('5T').ohlc().between_time('09:00:00, '16:20:00')

It works, however it adds weekends and holidays to the new timeseries, which I need to remove. I'm not following US (or any other standard holiday calendar). I just want to remove days not in the original price df.

Index is not unique, many cases of same timestamp. Pandas version 0.20.1

What I have tried:

1) dropna(): I have rows with NANs that I need to ffill, so this will not work.

2) price.index.difference(price_5min.index): Gives me all the tick dates, not the day dates.

3) price.index.date.difference(price_5min.index.date): Does not work as index.date is a numpy.ndarray

4) price != price_5min: Error: Can only compare identically-labeled DataFrame objects

5) price.index != price_4min.index: Error: Lengths must match to compare

Suggested logic to solve my problem:

a) Somehow compare the day dates in the two dataframes and delete based on this, but how?

b) Remove days with no variance, but how?

c) The obvious that I have not thought of (most likely..)

df price looks like this:

                     price  quantity
time
2016-06-15 16:19:20  29.85     429.6
2016-06-15 16:19:20  29.85      65.6
2016-06-15 16:19:20  29.85    1351.4
2016-06-15 16:19:30  29.70     729.4
2016-06-15 16:19:30  29.70     287.0
2016-06-15 16:19:30  29.70     219.4
2016-06-15 16:19:49  29.70      47.4
2016-06-15 16:19:52  29.70      11.8
2016-06-16 09:01:42  29.05     350.0
2016-06-16 09:01:42  29.10     189.4
2016-06-16 09:01:45  29.05      33.6
2016-06-16 09:01:54  29.05      33.6
...

Body:
Fast solution:

price_5min=price.groupby(price.index.Date).resample('5T').ohlc()
price_5min.index = price_5min.index.droplevel(0)


问:
Clob Data filed replacement issue in Oracle
my Input string

```<code>Employee[10|||Aryan|||CA|||USA|||URBAN|||IT
ENGINEER+++20|||Arjun|||FA|||USA|||RULER|||DEVELOPER]
</code>```

My output should be

```<code>[
 {Employee Name : Aryan,Employee ID:10,Emploee Role:IT ENGINEER}
   ,
 {Employee Name : Arjun,Employee ID:20,Emploee Role:DEVELOPER}
]
</code>```

I tried multiple scenarios which are not working as expected

答:
The below is written assuming you are running a oracle version pre 12c which adds support for JSON.

This is not something you are going to be able to do with a simple replace.

It will need to be a function / procedure.  To give you some idea see below anonymous block this will just output the string, you will need to adapt it to update your field if that is what you need.

I added a third row to your input string as first, last, and lines in the middle all need to be handled differently so needed three records to fully test.

Note CHR(13) = Carriage return, CHR(10) = Line Feed, CHR(9) = tab.  These are just try and match your formatting and can be excluded if the exact formatting is not necessary.

```<code>declare

v_input clob default 'Employee[10|||Aryan|||CA|||USA|||URBAN|||IT ENGINEER+++20|||Arjun|||FA|||USA|||RULER|||DEVELOPER+++30|||BOB|||FA|||USA|||RULER|||DEVELOPER]';
v_line  varchar2(32000) default null;
v_output clob default null;
v_exit boolean default false;

begin

loop -- loop until we have no more employees to process
  if instr(v_input, '+++') > 0 then -- not the last line
    if v_output is null then -- first line
      v_line  := substr(v_input, instr(v_input, 'Employee[') + 9, instr(v_input, '+++') -10); -- get a single employee row (first line)
    else
      v_line  := substr(v_input, 1, instr(v_input, '+++') -1); -- get a single employee row (not fist line)
    end if;
    v_input := substr(v_input, instr(v_input, '+++') + 3); -- trim off the stuff we have already processed.
  else
    v_line := substr(v_input, 1, length(v_line) - 2); -- get a single employee row (last line)
    v_exit := true;
  end if;
  if v_output is null then -- first line
    v_output := '['||chr(13)||chr(10)||chr(9)||'{'; -- start string
  else
    v_output := v_output || chr(9) || '{'; -- add the opening brace
  end if;
  v_output := v_output ||'Employee Name : ' || substr(v_line, instr(v_line, '|||', 1, 1) + 3, instr(v_line, '|||', 1, 2)-6) || ','; -- add name
  v_output := v_output ||'Employee ID:' || substr(v_line, 1, 2) || ','; -- add ID
  v_output := v_output ||'Employee Role:' || substr(v_line, instr(v_line, '|||', 1, 5) + 3) || '}'; -- add role
  if v_exit then -- we are on last line so close it all out and exit loop
    v_output := v_output || chr(13) || chr(10) || ']';
    exit;
  else
    v_output := v_output || CHR(13) || CHR(10) || CHR(9) || CHR(9) || ',' || chr(13) || chr(10); -- not last line so format ready to start new line
  end if;
end loop;
dbms_output.put_line(v_output);
end;
/
</code>```

The output from this is

```<code>[
    {Employee Name : Aryan,Employee ID:10,Employee Role:IT ENGINEER}
        ,
    {Employee Name : Arjun,Employee ID:20,Employee Role:DEVELOPER}
        ,
    {Employee Name : BOB,Employee ID:30,Employee Role:DEVELOPER}
]
</code>```

Body:
my Input string

Employee[10|||Aryan|||CA|||USA|||URBAN|||IT
ENGINEER+++20|||Arjun|||FA|||USA|||RULER|||DEVELOPER]

My output should be

[
 {Employee Name : Aryan,Employee ID:10,Emploee Role:IT ENGINEER}
   ,
 {Employee Name : Arjun,Employee ID:20,Emploee Role:DEVELOPER}
]

I tried multiple scenarios which are not working as expected

Body:
The below is written assuming you are running a oracle version pre 12c which adds support for JSON.

This is not something you are going to be able to do with a simple replace.

It will need to be a function / procedure.  To give you some idea see below anonymous block this will just output the string, you will need to adapt it to update your field if that is what you need.

I added a third row to your input string as first, last, and lines in the middle all need to be handled differently so needed three records to fully test.

Note CHR(13) = Carriage return, CHR(10) = Line Feed, CHR(9) = tab.  These are just try and match your formatting and can be excluded if the exact formatting is not necessary.

declare

v_input clob default 'Employee[10|||Aryan|||CA|||USA|||URBAN|||IT ENGINEER+++20|||Arjun|||FA|||USA|||RULER|||DEVELOPER+++30|||BOB|||FA|||USA|||RULER|||DEVELOPER]';
v_line  varchar2(32000) default null;
v_output clob default null;
v_exit boolean default false;

begin

loop -- loop until we have no more employees to process
  if instr(v_input, '+++') > 0 then -- not the last line
    if v_output is null then -- first line
      v_line  := substr(v_input, instr(v_input, 'Employee[') + 9, instr(v_input, '+++') -10); -- get a single employee row (first line)
    else
      v_line  := substr(v_input, 1, instr(v_input, '+++') -1); -- get a single employee row (not fist line)
    end if;
    v_input := substr(v_input, instr(v_input, '+++') + 3); -- trim off the stuff we have already processed.
  else
    v_line := substr(v_input, 1, length(v_line) - 2); -- get a single employee row (last line)
    v_exit := true;
  end if;
  if v_output is null then -- first line
    v_output := '['||chr(13)||chr(10)||chr(9)||'{'; -- start string
  else
    v_output := v_output || chr(9) || '{'; -- add the opening brace
  end if;
  v_output := v_output ||'Employee Name : ' || substr(v_line, instr(v_line, '|||', 1, 1) + 3, instr(v_line, '|||', 1, 2)-6) || ','; -- add name
  v_output := v_output ||'Employee ID:' || substr(v_line, 1, 2) || ','; -- add ID
  v_output := v_output ||'Employee Role:' || substr(v_line, instr(v_line, '|||', 1, 5) + 3) || '}'; -- add role
  if v_exit then -- we are on last line so close it all out and exit loop
    v_output := v_output || chr(13) || chr(10) || ']';
    exit;
  else
    v_output := v_output || CHR(13) || CHR(10) || CHR(9) || CHR(9) || ',' || chr(13) || chr(10); -- not last line so format ready to start new line
  end if;
end loop;
dbms_output.put_line(v_output);
end;
/

The output from this is

[
    {Employee Name : Aryan,Employee ID:10,Employee Role:IT ENGINEER}
        ,
    {Employee Name : Arjun,Employee ID:20,Employee Role:DEVELOPER}
        ,
    {Employee Name : BOB,Employee ID:30,Employee Role:DEVELOPER}
]


问:
React Native Could not open URL No Activity found to handle Intent
I'm working with React Native and Square Point of Sale. I'm using Web API for Android.
Also I have installed Square Point of Sale.
This is my code:

```<code>componentDidMount() {
    let url ="intent:#Intent;action=com.squareup.pos.action.CHARGE;package=com.squareup;S.browser_fallback_url=https://my.website.com/index.html;S.com.squareup.pos.WEB_CALLBACK_URI=https://my.website.com/index.html;S.com.squareup.pos.CLIENT_ID=sq0ids-yOurCLieNtId;S.com.squareup.pos.API_VERSION=v2.0;i.com.squareup.pos.TOTAL_AMOUNT=100;S.com.squareup.pos.CURRENCY_CODE=USD;S.com.squareup.pos.TENDER_TYPES=com.squareup.pos.TENDER_CARD,com.squareup.pos.TENDER_CARD_ON_FILE,com.squareup.pos.TENDER_CASH,com.squareup.pos.TENDER_OTHER;end";

    Linking.openURL(url).catch(err => console.error("An error occurred", err));
}
</code>```

This is my error message:

```<code>Could not open URL 'intent:#Intent; ... end': No Activity found to handle Intent { act=android.intent.action.VIEW dat=intent: flg=0x10000000 }
</code>```

What I'm doing wrong?

答:
I tried building using the web API but found that the flow wasn't great. The user doesn't always make it back to the app; sometimes they get stuck on the website.

I built react-native-square-pos to make things easier for the next developer.  It uses Native Modules to communicate with the Android / iOS Square PoS APIs.. so you don't have to write Java or Objective-C.

Body:
I'm working with React Native and Square Point of Sale. I'm using Web API for Android.
Also I have installed Square Point of Sale.
This is my code:

componentDidMount() {
    let url ="intent:#Intent;action=com.squareup.pos.action.CHARGE;package=com.squareup;S.browser_fallback_url=https://my.website.com/index.html;S.com.squareup.pos.WEB_CALLBACK_URI=https://my.website.com/index.html;S.com.squareup.pos.CLIENT_ID=sq0ids-yOurCLieNtId;S.com.squareup.pos.API_VERSION=v2.0;i.com.squareup.pos.TOTAL_AMOUNT=100;S.com.squareup.pos.CURRENCY_CODE=USD;S.com.squareup.pos.TENDER_TYPES=com.squareup.pos.TENDER_CARD,com.squareup.pos.TENDER_CARD_ON_FILE,com.squareup.pos.TENDER_CASH,com.squareup.pos.TENDER_OTHER;end";

    Linking.openURL(url).catch(err => console.error("An error occurred", err));
}

This is my error message:

Could not open URL 'intent:#Intent; ... end': No Activity found to handle Intent { act=android.intent.action.VIEW dat=intent: flg=0x10000000 }

What I'm doing wrong?