问:
Camera2 API doesn't work on emualtor
I'm trying to work with Camera2 API on emulator but unfortunately i encountered a problem while implementing it.

I'm using the Camera2Basic provided by google from this link and i tried it on real device and it works fine.

Real devices are : Huawei P9 Lite API 24 , Samsung Galaxy S5 API 23.

Genymotion Emulators are : Google Nexus 4,5,6 API 21,22,24 , Samsung Galaxy S6,S7 API 23,25

The problem now is when launching the App on emulator it shows the camera (i'm working with a webcam) but when i click on the button picture normally it shows on a toast that the picture is saved in a certain path. But it doesn't , that means that the picture wasn't taken , it only do that on real devices.

I've noticed while building the project the logcat shows this :

```<code>07-04 07:56:06.252 1694-1694/? E/memtrack: Couldn't load memtrack module (No
such file or directory)
07-04 07:56:06.252 1694-1694/? E/android.os.Debug: failed to load memtrack
module: -2
07-04 07:56:07.360 1709-1709/? E/memtrack: Couldn't load memtrack module (No
such file or directory)
07-04 07:56:07.360 1709-1709/? E/android.os.Debug: failed to load memtrack
module: -2
07-04 07:56:34.492 1723-1723/? E/memtrack: Couldn't load memtrack module (No
such file or directory)
07-04 07:56:34.492 1723-1723/? E/android.os.Debug: failed to load memtrack
module: -2
07-04 07:56:35.220 1816-1816/? E/cutils-trace: Error opening trace file:
Permission denied (13)
07-04 07:56:37.443 1863-1863/? E/memtrack: Couldn't load memtrack module (No
such file or directory)
07-04 07:56:37.444 1863-1863/? E/android.os.Debug: failed to load memtrack
module: -2
07-04 07:56:38.734 1872-1909/com.example.android.camera2basic E/libEGL:
load_driver(/system/lib/egl/libGLES_emulation.so): dlopen failed: library
"/system/lib/egl/libGLES_emulation.so" not found
07-04 07:56:39.621 1872-1909/com.example.android.camera2basic
E/EGL_emulation: tid 1909: eglSurfaceAttrib(1174): error 0x3009
(EGL_BAD_MATCH)
07-04 07:56:40.775 635-727/system_process E/TaskPersister: File error
accessing recents directory (directory doesn't exist?).
07-04 07:56:44.003 1935-1981/com.android.packageinstaller E/libEGL:
load_driver(/system/lib/egl/libGLES_emulation.so): dlopen failed: library
"/system/lib/egl/libGLES_emulation.so" not found
07-04 07:56:44.597 1935-1981/com.android.packageinstaller E/EGL_emulation:
tid 1981: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
</code>```

But when i click on the button picture it shows nothing on the logcat. This is the AndroidManifest.xml file :

```<code><?xml version="1.0" encoding="UTF-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.camera2basic">

<uses-permission android:name="android.permission.CAMERA" />

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application android:allowBackup="true"
    android:label="@string/app_name"
    android:icon="@drawable/ic_launcher"
    android:theme="@style/MaterialTheme">

    <activity android:name=".CameraActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

i saw many questions with the "Couldn't load memtrack module (No
such file or directory)" but i couldn't realy relate to them. Can anyone help ? Thank you in advance.

P.S : to make the Camera2 API work on emulator is a must for my project that's why i'm asking this. Thank you for understanding

答:
Have you tried it in the Android Studio emulator? Does it work there?

This may be a bug specific to the Genymotion emulator, or it could be shared between multiple emulators.

Title: Camera2 API doesn't work on emualtor

Body:
I'm trying to work with Camera2 API on emulator but unfortunately i encountered a problem while implementing it.

I'm using the Camera2Basic provided by google from this link and i tried it on real device and it works fine.

Real devices are : Huawei P9 Lite API 24 , Samsung Galaxy S5 API 23.

Genymotion Emulators are : Google Nexus 4,5,6 API 21,22,24 , Samsung Galaxy S6,S7 API 23,25

The problem now is when launching the App on emulator it shows the camera (i'm working with a webcam) but when i click on the button picture normally it shows on a toast that the picture is saved in a certain path. But it doesn't , that means that the picture wasn't taken , it only do that on real devices.

I've noticed while building the project the logcat shows this :

07-04 07:56:06.252 1694-1694/? E/memtrack: Couldn't load memtrack module (No
such file or directory)
07-04 07:56:06.252 1694-1694/? E/android.os.Debug: failed to load memtrack
module: -2
07-04 07:56:07.360 1709-1709/? E/memtrack: Couldn't load memtrack module (No
such file or directory)
07-04 07:56:07.360 1709-1709/? E/android.os.Debug: failed to load memtrack
module: -2
07-04 07:56:34.492 1723-1723/? E/memtrack: Couldn't load memtrack module (No
such file or directory)
07-04 07:56:34.492 1723-1723/? E/android.os.Debug: failed to load memtrack
module: -2
07-04 07:56:35.220 1816-1816/? E/cutils-trace: Error opening trace file:
Permission denied (13)
07-04 07:56:37.443 1863-1863/? E/memtrack: Couldn't load memtrack module (No
such file or directory)
07-04 07:56:37.444 1863-1863/? E/android.os.Debug: failed to load memtrack
module: -2
07-04 07:56:38.734 1872-1909/com.example.android.camera2basic E/libEGL:
load_driver(/system/lib/egl/libGLES_emulation.so): dlopen failed: library
"/system/lib/egl/libGLES_emulation.so" not found
07-04 07:56:39.621 1872-1909/com.example.android.camera2basic
E/EGL_emulation: tid 1909: eglSurfaceAttrib(1174): error 0x3009
(EGL_BAD_MATCH)
07-04 07:56:40.775 635-727/system_process E/TaskPersister: File error
accessing recents directory (directory doesn't exist?).
07-04 07:56:44.003 1935-1981/com.android.packageinstaller E/libEGL:
load_driver(/system/lib/egl/libGLES_emulation.so): dlopen failed: library
"/system/lib/egl/libGLES_emulation.so" not found
07-04 07:56:44.597 1935-1981/com.android.packageinstaller E/EGL_emulation:
tid 1981: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)

But when i click on the button picture it shows nothing on the logcat. This is the AndroidManifest.xml file :

<?xml version="1.0" encoding="UTF-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.camera2basic">

<uses-permission android:name="android.permission.CAMERA" />

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application android:allowBackup="true"
    android:label="@string/app_name"
    android:icon="@drawable/ic_launcher"
    android:theme="@style/MaterialTheme">

    <activity android:name=".CameraActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

i saw many questions with the "Couldn't load memtrack module (No
such file or directory)" but i couldn't realy relate to them. Can anyone help ? Thank you in advance.

P.S : to make the Camera2 API work on emulator is a must for my project that's why i'm asking this. Thank you for understanding


来源: stackexchange

问:
Merging two dynamic libraries
I use a program called molebox-pro to bundle a dll with an executable that uses that dll. That way when I distribute the executable I don't need to ship the external dll with it, it goes all in one large exe. It's very practical. I wonder though if something exists to bundle two dlls together (one that depends on the presence of the other: they need to be in the same folder or in the path)? I have the C source code for one dll (my-dll) that I compile with gcc, but the other dll on which my-dll depends I don't have its source code. Is this at all possible? Does a tool exist for merging two dlls as it exists for merging an exe with a dll (molebox)?</p>

答: Put one into resource section of another, or elsewhere, and then extract it and load by LoadLibrary.</p>

ContentLicense: CC BY-SA 2.5

Title: Merging two dynamic libraries


问:
How do I make a heatmap in Cartopy
I am mapping latitude, longitude, and then a separate value on cartopy.

How do I make the points colored like a heatmap based the list called klist? I cant find any snippets of code where it will work with cartopy

That list has range of values that I want colored based on the how big the value is.

```<code># Define a Cartopy 'ordinary' lat-lon coordinate reference system.
crs_latlon = ccrs.PlateCarree()

def make_plot(projection_name, projection_crs):

    ax = plt.axes(projection=projection_crs)

# Set display limits to include a set region of latitude * longitude.
# (Note: Cartopy-specific).
    ax.set_extent((-65.0, -62, 44, 45.5), crs=crs_latlon)

# Add coastlines and meridians/parallels (Cartopy-specific).
    ax.coastlines(linewidth=0.2, color='black')
    ax.gridlines(crs=crs_latlon, linestyle='-')

# Mark some particular places with a small circle and a name label...
# Define some test points with latitude and longitude coordinates.
    #city_data = [('Halifax, NS', 44.67, -63.61)]

    plt.plot(lon,lat,marker='x', markersize=1.0, markeredgewidth=2.5,
             markerfacecolor='black',
             transform=crs_latlon)
# Add a title, and display.
    iplt.show("Mission #1: Attenuation Coeffiecient")

def main():
# Demonstrate with two different display projections.
    make_plot('Equidistant Cylindrical', ccrs.PlateCarree())

if __name__ == '__main__':
    main()
</code>```

答:
If you want different coloured points this might help you (based on your code):

```<code>import cartopy.crs as ccrs
import matplotlib.pyplot as plt

def make_plot(projection_name, projection_crs, extent, city_data):
    """
    ?
    """
    fig = plt.figure()
    rect = 0.1, 0.1, 0.8, 0.8
    ax = fig.add_axes(rect, projection=projection_crs)

    # Set display limits to include a set region of latitude * longitude.
    # (Note: Cartopy-specific).
    ax.set_extent(extent, crs=projection_crs)

    # Add coastlines and meridians/parallels (Cartopy-specific).
    ax.coastlines(linewidth=0.2, color='black')
    ax.gridlines(crs=projection_crs, linestyle='-')

    # Mark some particular places with a small circle and a name label...
    for city in city_data:
        ax.plot(city[2], city[1], marker='o',
                markersize=2.0, markeredgewidth=1.0,
                markeredgecolor=city[3], markerfacecolor=city[3],
                linestyle='None', label=city[0], transform=projection_crs)
    # Add a title, legend, and display.
    ax.set_title(''.join(("Mission #1: Attenuation Coeffiecient - ",
                          projection_name)))
    ax.legend()
    fig.show()

def main():
    #extent = (-65.0, -62, 44, 45.5)
    extent = (-90, -40, 30, 60)
    # Define some test points with latitude and longitude coordinates.
    city_data = [('Halifax, NS', 44.67, -63.61, 'black'),
                 ('Neighbour', 45, -63, 'blue'),
                 ('Other_Place', 44.1, -64, 'red')]

    # Demonstrate with two different display projections.
    # Define a Cartopy 'ordinary' lat-lon coordinate reference system.
    crs_latlon = ccrs.PlateCarree()
    make_plot('Equidistant Cylindrical', crs_latlon, extent, city_data)
    crs_ae = ccrs.LambertCylindrical()
    make_plot('Lambert Cylindrical', crs_ae, extent, city_data)

if __name__ == '__main__':
    main()
</code>```

I don't know enough about cartography to understand why the points are in different places in the two projections, but maybe you know what that means and how to correct it.

ContentLicense: CC BY-SA 3.0

Title: How do I make a heatmap in Cartopy

Body:
I am mapping latitude, longitude, and then a separate value on cartopy.

How do I make the points colored like a heatmap based the list called klist? I cant find any snippets of code where it will work with cartopy

That list has range of values that I want colored based on the how big the value is.

# Define a Cartopy 'ordinary' lat-lon coordinate reference system.
crs_latlon = ccrs.PlateCarree()

def make_plot(projection_name, projection_crs):

    ax = plt.axes(projection=projection_crs)

# Set display limits to include a set region of latitude * longitude.
# (Note: Cartopy-specific).
    ax.set_extent((-65.0, -62, 44, 45.5), crs=crs_latlon)

# Add coastlines and meridians/parallels (Cartopy-specific).
    ax.coastlines(linewidth=0.2, color='black')
    ax.gridlines(crs=crs_latlon, linestyle='-')

# Mark some particular places with a small circle and a name label...
# Define some test points with latitude and longitude coordinates.
    #city_data = [('Halifax, NS', 44.67, -63.61)]

    plt.plot(lon,lat,marker='x', markersize=1.0, markeredgewidth=2.5,
             markerfacecolor='black',
             transform=crs_latlon)
# Add a title, and display.
    iplt.show("Mission #1: Attenuation Coeffiecient")

def main():
# Demonstrate with two different display projections.
    make_plot('Equidistant Cylindrical', ccrs.PlateCarree())

if __name__ == '__main__':
    main()

Body:
If you want different coloured points this might help you (based on your code):

import cartopy.crs as ccrs
import matplotlib.pyplot as plt

def make_plot(projection_name, projection_crs, extent, city_data):
    """
    ?
    """
    fig = plt.figure()
    rect = 0.1, 0.1, 0.8, 0.8
    ax = fig.add_axes(rect, projection=projection_crs)

    # Set display limits to include a set region of latitude * longitude.
    # (Note: Cartopy-specific).
    ax.set_extent(extent, crs=projection_crs)

    # Add coastlines and meridians/parallels (Cartopy-specific).
    ax.coastlines(linewidth=0.2, color='black')
    ax.gridlines(crs=projection_crs, linestyle='-')

    # Mark some particular places with a small circle and a name label...
    for city in city_data:
        ax.plot(city[2], city[1], marker='o',
                markersize=2.0, markeredgewidth=1.0,
                markeredgecolor=city[3], markerfacecolor=city[3],
                linestyle='None', label=city[0], transform=projection_crs)
    # Add a title, legend, and display.
    ax.set_title(''.join(("Mission #1: Attenuation Coeffiecient - ",
                          projection_name)))
    ax.legend()
    fig.show()

def main():
    #extent = (-65.0, -62, 44, 45.5)
    extent = (-90, -40, 30, 60)
    # Define some test points with latitude and longitude coordinates.
    city_data = [('Halifax, NS', 44.67, -63.61, 'black'),
                 ('Neighbour', 45, -63, 'blue'),
                 ('Other_Place', 44.1, -64, 'red')]

    # Demonstrate with two different display projections.
    # Define a Cartopy 'ordinary' lat-lon coordinate reference system.
    crs_latlon = ccrs.PlateCarree()
    make_plot('Equidistant Cylindrical', crs_latlon, extent, city_data)
    crs_ae = ccrs.LambertCylindrical()
    make_plot('Lambert Cylindrical', crs_ae, extent, city_data)

if __name__ == '__main__':
    main()

I don't know enough about cartography to understand why the points are in different places in the two projections, but maybe you know what that means and how to correct it.


问:
LIFO Handler in Android
I have a bunch of asynchronous tasks I need to be run, but the task with the highest priority is the one that was added last.

Is there a LIFO (last in first out) stack-like Handler in Android that I can use for this?

If not, my alternative implementation is to have each task pull an item to process from a Stack. But this is causing issues with locking as the stack is populated dynamically. Is there a better approach?

答: Create a Thread.  In the thread, create a LinkedBlockingDeque.  When adding a task, add it to the head of the dequeue.  In the thread, poll() on it (which will remove the head when one exists).  The class itself will handle all locking.</p>

Title: LIFO Handler in Android


问:
how to compare word letters using if statements?
I'm trying to write a program that reads a word and prints if:

it ends with the letter y.

has the same first and last character, ignoring case.

This is what I have so far, but I'm having trouble thinking of a line of code that will check individual letters or compare the first and last letters.

```<code>  if (. . .)
  {
     System.out.println(word + " ends in a y");
  }

  if (. . .)
  {
     System.out.println(word + " starts and ends with the same letter");
  }
</code>```

答:
Consider a word hello in your string.  You can get the word length easily with word.length() this will return 5 for "Hello"

With another method called charAt(int position) you can get the  character at the given position.

System.out.println(String.valueOf(word.charAt(0))); //The result is H
System.out.println(String.valueOf(word.charAt(4))); //The result is o

4 is the length of word minus one so try finding it dynamically for all the word this way:

```<code>String.valueOf((word.length()-1))
</code>```

If you had two string you can compare them with:

```<code>string1.equals(string2)
</code>```

this will return true if they are the same and false if they are not.

Below is the full source code:

```<code>    String word = "Hello";

    //no if is needed for the first one
    println(word + " ends with letter " + word.charAt(word.length()-1) + ".");

   if (String.valueOf(word.charAt(0)).equals(String.valueOf(word.charAt(word.length()-1)))) {
        println(word + " starts and ends with the same letter.");
    }
</code>```

Body:
I'm trying to write a program that reads a word and prints if:

it ends with the letter y.

has the same first and last character, ignoring case.

This is what I have so far, but I'm having trouble thinking of a line of code that will check individual letters or compare the first and last letters.

  if (. . .)
  {
     System.out.println(word + " ends in a y");
  }

  if (. . .)
  {
     System.out.println(word + " starts and ends with the same letter");
  }

Body:
Consider a word hello in your string.  You can get the word length easily with word.length() this will return 5 for "Hello"

With another method called charAt(int position) you can get the  character at the given position.

System.out.println(String.valueOf(word.charAt(0))); //The result is H
System.out.println(String.valueOf(word.charAt(4))); //The result is o

4 is the length of word minus one so try finding it dynamically for all the word this way:

String.valueOf((word.length()-1))

If you had two string you can compare them with:

string1.equals(string2)

this will return true if they are the same and false if they are not.

Below is the full source code:

    String word = "Hello";

    //no if is needed for the first one
    println(word + " ends with letter " + word.charAt(word.length()-1) + ".");

   if (String.valueOf(word.charAt(0)).equals(String.valueOf(word.charAt(word.length()-1)))) {
        println(word + " starts and ends with the same letter.");
    }


问:
Select records when month and day are less than current date
I am using SQL Server Mgmt Studio. I need to create a formula that will only select records when the month and day of a date/time field, LAW_TAEEMASTER.MASTR_ENTRY, is less than or equal to the current month and day. For example, If LAW_TAEEMASTER.MASTR_ENTRY = 8/20/2015 and current date = 7/6/2017, exclude. If LAW_TAEEMASTER.MASTR_ENTRY = 12/21/2014 and current date = 1/15/2017, include. Date formatting is my weakness. Here is what I have tried:

```<code>select LAW_TAEEMASTER.MASTR_ENTRY
    from LAW_TAEEMASTER
    WHERE day(LAW_TAEEMASTER.MASTR_ENTRY) <= DAY(GETDATE()) and MONTH(LAW_TAEEMASTER.MASTR_ENTRY) <= MONTH(getdate())
</code>```

and

```<code>select LAW_TAEEMASTER.MASTR_ENTRY
        from LAW_TAEEMASTER
        WHERE AND DATEPART(DAY,LAW_TAEEMASTER.MASTR_ENTRY) <= DATEPART(DAY,GETDATE()) AND DATEPART(MONTH,LAW_TAEEMASTER.MASTR_ENTRY) <= DATEPART(MONTH,GETDATE())
</code>```

but these just evaluate the month and day separately and as a number, greater than or less than, so it's excluding records. How can I get SQL to recognize these as part of a date and just ignore the year?

答:
Explain the logic and code:
Use CONVERT(varchar(5),<your_date> ,110)). The 110 arguement means USA standard time and have an ouput like mm-dd-yyyy. Then we only take the first five character which is the month and day of the date.

110 = mm-dd-yyyy
  read more about cast and convert here

my sample table:

```<code>MASTER_ENTRY
2017-08-30
2017-07-05
2017-07-04
</code>```

Then I executed this query

```<code>SELECT LAW_TAEEMASTER.MASTR_ENTRY
FROM LAW_TAEEMASTER
WHERE CONVERT(varchar(5),LAW_TAEEMASTER.MASTR_ENTRY ,110) <=  CONVERT(varchar(5),GETDATE() ,110)
</code>```

result:where month and day equal or earlier current month and day

```<code>MASTER_ENTRY
2017-07-05
2017-07-04
</code>```

I hope this helps and welcome to StackOverflow. If you find this answer or any other answer solves your problem please mark it as the solution. This will help the community and fellow programmers who run into the same problem in the future. Thanks.

Body:
I am using SQL Server Mgmt Studio. I need to create a formula that will only select records when the month and day of a date/time field, LAW_TAEEMASTER.MASTR_ENTRY, is less than or equal to the current month and day. For example, If LAW_TAEEMASTER.MASTR_ENTRY = 8/20/2015 and current date = 7/6/2017, exclude. If LAW_TAEEMASTER.MASTR_ENTRY = 12/21/2014 and current date = 1/15/2017, include. Date formatting is my weakness. Here is what I have tried:

select LAW_TAEEMASTER.MASTR_ENTRY
    from LAW_TAEEMASTER
    WHERE day(LAW_TAEEMASTER.MASTR_ENTRY) <= DAY(GETDATE()) and MONTH(LAW_TAEEMASTER.MASTR_ENTRY) <= MONTH(getdate())

and

select LAW_TAEEMASTER.MASTR_ENTRY
        from LAW_TAEEMASTER
        WHERE AND DATEPART(DAY,LAW_TAEEMASTER.MASTR_ENTRY) <= DATEPART(DAY,GETDATE()) AND DATEPART(MONTH,LAW_TAEEMASTER.MASTR_ENTRY) <= DATEPART(MONTH,GETDATE())

but these just evaluate the month and day separately and as a number, greater than or less than, so it's excluding records. How can I get SQL to recognize these as part of a date and just ignore the year?

Body:
Explain the logic and code:
Use CONVERT(varchar(5),<your_date> ,110)). The 110 arguement means USA standard time and have an ouput like mm-dd-yyyy. Then we only take the first five character which is the month and day of the date.

110 = mm-dd-yyyy
  read more about cast and convert here

my sample table:

MASTER_ENTRY
2017-08-30
2017-07-05
2017-07-04

Then I executed this query

SELECT LAW_TAEEMASTER.MASTR_ENTRY
FROM LAW_TAEEMASTER
WHERE CONVERT(varchar(5),LAW_TAEEMASTER.MASTR_ENTRY ,110) <=  CONVERT(varchar(5),GETDATE() ,110)

result:where month and day equal or earlier current month and day

MASTER_ENTRY
2017-07-05
2017-07-04

I hope this helps and welcome to StackOverflow. If you find this answer or any other answer solves your problem please mark it as the solution. This will help the community and fellow programmers who run into the same problem in the future. Thanks.


问:
Replacement for collapseItemsRecursively and expandItemsRecursively in Vaadin 8.1 TreeGrid
Vaadin 8.1 introduced the TreeGrid component. It does not have the collapseItemsRecursively and expandItemsRecursively methods anymore (as available in the now legacy Tree component). Do i miss something or do you need to develop your own implementation? If so, what is a recommended way of doing this?

答:
As I'm sure you've noticed, the TreeGrid is a rather new component, currently being developed and available starting with v8.1.alphaX (current stable version is v8.0.6). As such, it probably has only some basic functionalities for the time being, with the rest to follow sometime in the future, although there are no guarantee. For example this similar feature request for the older TreeTable component has been in open state since 2011.

Either way, even if they're probably not the optimum solutions, there are a couple of work-arounds that you can use to achieve this behavior. I'm shamelessly using as a base sample, a slightly modified version of the code currently available in the vaadin-sampler for TreeGrid.

```<code>public class RecursiveExpansionTreeGrid extends VerticalLayout {

    private Random random = new Random();

    public RecursiveExpansionTreeGrid() {
        // common setup with some dummy data
        TreeGrid<Project> treeGrid = new TreeGrid<>();
        treeGrid.setItems(generateProjectsForYears(2010, 2016), Project::getSubProjects);
        treeGrid.addColumn(Project::getName).setCaption("Project Name").setId("name-column");
        treeGrid.addColumn(Project::getHoursDone).setCaption("Hours Done");
        treeGrid.addColumn(Project::getLastModified).setCaption("Last Modified");
        addComponent(treeGrid);
    }

    // generate some dummy data to display in the tree grid
    private List<Project> generateProjectsForYears(int startYear, int endYear) {
        List<Project> projects = new ArrayList<>();

        for (int year = startYear; year <= endYear; year++) {
            Project yearProject = new Project("Year " + year);

            for (int i = 1; i < 2 + random.nextInt(5); i++) {
                Project customerProject = new Project("Customer Project " + i);
                customerProject.setSubProjects(Arrays.asList(
                        new LeafProject("Implementation", random.nextInt(100), year),
                        new LeafProject("Planning", random.nextInt(10), year),
                        new LeafProject("Prototyping", random.nextInt(20), year)));
                yearProject.addSubProject(customerProject);
            }
            projects.add(yearProject);
        }
        return projects;
    }

    // POJO for easy binding
    public class Project {
        private List<Project> subProjects = new ArrayList<>();
        private String name;

        public Project(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public List<Project> getSubProjects() {
            return subProjects;
        }

        public void setSubProjects(List<Project> subProjects) {
            this.subProjects = subProjects;
        }

        public void addSubProject(Project subProject) {
            subProjects.add(subProject);
        }

        public int getHoursDone() {
            return getSubProjects().stream().map(project -> project.getHoursDone()).reduce(0, Integer::sum);
        }

        public Date getLastModified() {
            return getSubProjects().stream().map(project -> project.getLastModified()).max(Date::compareTo).orElse(null);
        }
    }

    // Second POJO for easy binding
    public class LeafProject extends Project {
        private int hoursDone;
        private Date lastModified;

        public LeafProject(String name, int hoursDone, int year) {
            super(name);
            this.hoursDone = hoursDone;
            lastModified = new Date(year - 1900, random.nextInt(12), random.nextInt(10));
        }

        @Override
        public int getHoursDone() {
            return hoursDone;
        }

        @Override
        public Date getLastModified() {
            return lastModified;
        }
    }
}
</code>```

Next, recursively expanding or collapsing the nodes depends a bit on your scenario, but basically it breaks down to the same thing: making sure each node from the root to the deepest leaf is expanded/collapsed.The simplest way of doing it is to flatten your hierarchy into a list of nodes, and call the appropriate method, expand(List<T> items) or expand(T ... items) (the second delegates to the first and is probably a convenience method eg expand(myItem)).

For simplicity, I've added a flatten method in our Project implementation. If you can't do that for some reason, then create a recursive method that creates a list starting with the selected node and includes all the children, of the children, of the children.... well, you get the idea.

```<code>public Stream<Project> flatten() {
    return Stream.concat(Stream.of(this), getSubProjects().stream().flatMap(Project::flatten));
}
</code>```

Possible scenarios:

Automatically expand the entire hierarchy when expanding the root - add listeners, and expand/collapse the whole flattened hierarchy:

treeGrid.addCollapseListener(event -> {
    if (event.isUserOriginated()) {
        // event is triggered by all collapse calls, so only do it the first time, when the user clicks in the UI
        // and ignore the programmatic calls
        treeGrid.collapse(event.getCollapsedItem().flatten().collect(Collectors.toList()));
    }
});
treeGrid.addExpandListener(event -> {
    if (event.isUserOriginated()) {
        // event is triggered by all expand calls, so only do it the first time, when the user clicks in the UI
        // and ignore the programmatic calls
        treeGrid.expand(event.getExpandedItem().flatten().collect(Collectors.toList()));
    }
});
```

<ol start="2">
<li>Expanding the hierarchy or part of it with a custom action, such as a context menu</li>
</ol>

<pre class="lang-java prettyprint-override"><code>GridContextMenu<Project> contextMenu = new GridContextMenu<>(treeGrid);
contextMenu.addGridBodyContextMenuListener(contextEvent -> {
    contextMenu.removeItems();
    if (contextEvent.getItem() != null) {
        Project project = (Project) contextEvent.getItem();
        // update selection
        treeGrid.select(project);

        // show option for expanding
        contextMenu.addItem("Expand all", VaadinIcons.PLUS, event -> treeGrid.expand((project).flatten().collect(Collectors.toList())));

        // show option for collapsing
        contextMenu.addItem("Collapse all", VaadinIcons.MINUS, event -> treeGrid.collapse((project).flatten().collect(Collectors.toList())));
    }
});
</code>```

In the end, you should be getting this effect:

Body:
As I'm sure you've noticed, the TreeGrid is a rather new component, currently being developed and available starting with v8.1.alphaX (current stable version is v8.0.6). As such, it probably has only some basic functionalities for the time being, with the rest to follow sometime in the future, although there are no guarantee. For example this similar feature request for the older TreeTable component has been in open state since 2011.

Either way, even if they're probably not the optimum solutions, there are a couple of work-arounds that you can use to achieve this behavior. I'm shamelessly using as a base sample, a slightly modified version of the code currently available in the vaadin-sampler for TreeGrid.

public class RecursiveExpansionTreeGrid extends VerticalLayout {

    private Random random = new Random();

    public RecursiveExpansionTreeGrid() {
        // common setup with some dummy data
        TreeGrid<Project> treeGrid = new TreeGrid<>();
        treeGrid.setItems(generateProjectsForYears(2010, 2016), Project::getSubProjects);
        treeGrid.addColumn(Project::getName).setCaption("Project Name").setId("name-column");
        treeGrid.addColumn(Project::getHoursDone).setCaption("Hours Done");
        treeGrid.addColumn(Project::getLastModified).setCaption("Last Modified");
        addComponent(treeGrid);
    }

    // generate some dummy data to display in the tree grid
    private List<Project> generateProjectsForYears(int startYear, int endYear) {
        List<Project> projects = new ArrayList<>();

        for (int year = startYear; year <= endYear; year++) {
            Project yearProject = new Project("Year " + year);

            for (int i = 1; i < 2 + random.nextInt(5); i++) {
                Project customerProject = new Project("Customer Project " + i);
                customerProject.setSubProjects(Arrays.asList(
                        new LeafProject("Implementation", random.nextInt(100), year),
                        new LeafProject("Planning", random.nextInt(10), year),
                        new LeafProject("Prototyping", random.nextInt(20), year)));
                yearProject.addSubProject(customerProject);
            }
            projects.add(yearProject);
        }
        return projects;
    }

    // POJO for easy binding
    public class Project {
        private List<Project> subProjects = new ArrayList<>();
        private String name;

        public Project(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public List<Project> getSubProjects() {
            return subProjects;
        }

        public void setSubProjects(List<Project> subProjects) {
            this.subProjects = subProjects;
        }

        public void addSubProject(Project subProject) {
            subProjects.add(subProject);
        }

        public int getHoursDone() {
            return getSubProjects().stream().map(project -> project.getHoursDone()).reduce(0, Integer::sum);
        }

        public Date getLastModified() {
            return getSubProjects().stream().map(project -> project.getLastModified()).max(Date::compareTo).orElse(null);
        }
    }

    // Second POJO for easy binding
    public class LeafProject extends Project {
        private int hoursDone;
        private Date lastModified;

        public LeafProject(String name, int hoursDone, int year) {
            super(name);
            this.hoursDone = hoursDone;
            lastModified = new Date(year - 1900, random.nextInt(12), random.nextInt(10));
        }

        @Override
        public int getHoursDone() {
            return hoursDone;
        }

        @Override
        public Date getLastModified() {
            return lastModified;
        }
    }
}

Next, recursively expanding or collapsing the nodes depends a bit on your scenario, but basically it breaks down to the same thing: making sure each node from the root to the deepest leaf is expanded/collapsed.The simplest way of doing it is to flatten your hierarchy into a list of nodes, and call the appropriate method, expand(List<T> items) or expand(T ... items) (the second delegates to the first and is probably a convenience method eg expand(myItem)).

For simplicity, I've added a flatten method in our Project implementation. If you can't do that for some reason, then create a recursive method that creates a list starting with the selected node and includes all the children, of the children, of the children.... well, you get the idea.

public Stream<Project> flatten() {
    return Stream.concat(Stream.of(this), getSubProjects().stream().flatMap(Project::flatten));
}

Possible scenarios:

Automatically expand the entire hierarchy when expanding the root - add listeners, and expand/collapse the whole flattened hierarchy:

treeGrid.addCollapseListener(event -> {
    if (event.isUserOriginated()) {
        // event is triggered by all collapse calls, so only do it the first time, when the user clicks in the UI
        // and ignore the programmatic calls
        treeGrid.collapse(event.getCollapsedItem().flatten().collect(Collectors.toList()));
    }
});
treeGrid.addExpandListener(event -> {
    if (event.isUserOriginated()) {
        // event is triggered by all expand calls, so only do it the first time, when the user clicks in the UI
        // and ignore the programmatic calls
        treeGrid.expand(event.getExpandedItem().flatten().collect(Collectors.toList()));
    }
});

Expanding the hierarchy or part of it with a custom action, such as a context menu

GridContextMenu<Project> contextMenu = new GridContextMenu<>(treeGrid);
contextMenu.addGridBodyContextMenuListener(contextEvent -> {
    contextMenu.removeItems();
    if (contextEvent.getItem() != null) {
        Project project = (Project) contextEvent.getItem();
        // update selection
        treeGrid.select(project);

        // show option for expanding
        contextMenu.addItem("Expand all", VaadinIcons.PLUS, event -> treeGrid.expand((project).flatten().collect(Collectors.toList())));

        // show option for collapsing
        contextMenu.addItem("Collapse all", VaadinIcons.MINUS, event -> treeGrid.collapse((project).flatten().collect(Collectors.toList())));
    }
});

In the end, you should be getting this effect:


问:
Inequalities on pandas column
I have a pandas dataframe, and I would like to create a new column based on an existing column and certain inequalities. For example, let

```<code>df=pd.DataFrame({'a':[1,2,3,4,5,6,7],'b':[3,6,4,2,7,7,1]})
</code>```

so df looks like

```<code>    a   b
0   1   3
1   2   6
2   3   4
3   4   2
4   5   7
5   6   7
6   7   1
</code>```

I would like to add a new column, res, that equals 0 if the corresponding value in a is smaller than 2, 1 if the corresponding value in a is at least 2 and smaller than 4, and 2 otherwise. So I would like to get

```<code>    a   b   res
0   1   3   0
1   2   6   1
2   3   4   1
3   4   2   2
4   5   7   2
5   6   7   2
6   7   1   2
</code>```

So far I have been doing this by using apply as follows:

```<code>def f(x):
    if x['a']<2:
        return 0
    elif x['a']>=2 and x['a']<4:
        return 1
    else:
        return 2
df['res']=df.apply(f,axis=1)
</code>```

but I was wondering if there is a more direct way, or some specific pandas method that can enable me to do that.

Title: Inequalities on pandas column

Body:
I have a pandas dataframe, and I would like to create a new column based on an existing column and certain inequalities. For example, let

df=pd.DataFrame({'a':[1,2,3,4,5,6,7],'b':[3,6,4,2,7,7,1]})

so df looks like

    a   b
0   1   3
1   2   6
2   3   4
3   4   2
4   5   7
5   6   7
6   7   1

I would like to add a new column, res, that equals 0 if the corresponding value in a is smaller than 2, 1 if the corresponding value in a is at least 2 and smaller than 4, and 2 otherwise. So I would like to get

    a   b   res
0   1   3   0
1   2   6   1
2   3   4   1
3   4   2   2
4   5   7   2
5   6   7   2
6   7   1   2

So far I have been doing this by using apply as follows:

def f(x):
    if x['a']<2:
        return 0
    elif x['a']>=2 and x['a']<4:
        return 1
    else:
        return 2
df['res']=df.apply(f,axis=1)

but I was wondering if there is a more direct way, or some specific pandas method that can enable me to do that.

Body:
You can use pd.cut:

df['res'] = pd.cut(df.a,[-np.inf,2,4,np.inf],labels=[0,1,2],right=False)

Output:

   a  b res
0  1  3   0
1  2  6   1
2  3  4   1
3  4  2   2
4  5  7   2
5  6  7   2
6  7  1   2


问:
In R dataframe, how to search for previous transaction information
Suppose I have a R data frame. Each row represents a transaction made by someone on a specific date. There are many columns that have more information about the transaction,such as the money he/she spent and the number of commodities he/she bought. It is possible that one person has many transactions so that one person may have several rows. Say that I want to have a column that records how much the customer spent in last transaction. For now, I am using a for loop to look through the entire data frame to check if this customer has a previous transaction. If the customer has a previous transaction, then I add value to the field; if not, I just jump to the next row. It works but I am dealing with a data frame with more than 1.7 million rows so that the for loop is too slow for me.
Do you have any better ideas solving the problem? Appreciate!!!</p>

答:
Assuming you have a data.frame like this

```<code>library(dplyr)
df <- read.table(header = TRUE, text = "
                  CustId  transaction      Spent
                  ID1 1     500
                  ID1 2     706
                  ID1 3     925
                  ID1 4     1195
                  ID1 5    1472
                  ID1 6    1413
                  ID2  1    950
                  ID2 2    1203
                  ID2 3    1486
                  ID2 4    1658")

df%>%group_by(CustId)%>%dplyr::mutate(Last=Spent[transaction==max(transaction)])

  CustId  transaction Spent  Last
   <fctr>       <int> <int> <int>
1     ID1           1   500  1413
2     ID1           2   706  1413
3     ID1           3   925  1413
4     ID1           4  1195  1413
5     ID1           5  1472  1413
6     ID1           6  1413  1413
7     ID2           1   950  1658
8     ID2           2  1203  1658
9     ID2           3  1486  1658
10    ID2           4  1658  1658
</code>```

Body:
Assuming you have a data.frame like this

library(dplyr)
df <- read.table(header = TRUE, text = "
                  CustId  transaction      Spent
                  ID1 1     500
                  ID1 2     706
                  ID1 3     925
                  ID1 4     1195
                  ID1 5    1472
                  ID1 6    1413
                  ID2  1    950
                  ID2 2    1203
                  ID2 3    1486
                  ID2 4    1658")

df%>%group_by(CustId)%>%dplyr::mutate(Last=Spent[transaction==max(transaction)])

  CustId  transaction Spent  Last
   <fctr>       <int> <int> <int>
1     ID1           1   500  1413
2     ID1           2   706  1413
3     ID1           3   925  1413
4     ID1           4  1195  1413
5     ID1           5  1472  1413
6     ID1           6  1413  1413
7     ID2           1   950  1658
8     ID2           2  1203  1658
9     ID2           3  1486  1658
10    ID2           4  1658  1658


问:
Android Device Monitor
When trying to access android device monitor on android studio, and I keep getting the error message

Even though I added the new JDK to my project I still keep getting this.

答:
Here's what you can do:

1) Set your Java Path
JAVA_HOME => C:\Program Files\Java\jdk1.7.0_21
path => C:\Program Files\Java\jdk1.7.0_21\bin

2) Check if your Jre path is correct
To Check:
Go to File > Project Structure > SDK Location:

enter image description here

3) There're 2 exe file in android-studio\bin one for 32-bit (studio.exe) and other for 64-bit (studio64.exe). Make sure you're opening the executable file which matches your Java Version.

If above methods doesn't work, then you can:

4) Try to reinstall JDK and JRE again

5) Try to reinstall the Studio again

Title: Android Device Monitor


问:
Stratified K Fold in Python
I'm trying to perform Stratified K Fold Validation in python, and I read the following in the documentation:

I'm not exactly sure what this means. Could someone explain to me when exactly does cross_val_score use the StratifiedKFold strategy?

答:
When you are performing cross-fold validation, you are splitting up your training set into multiple validation sets. StratifiedKFold ensures that each of your validation sets contains an equal proportion of the labels from your original training set.

For example, let's say you are training a classifier on spam and not spam. Your training set contains 50k samples with 10k spam samples. If you perform 5-fold cross-fold validation, you will split up your training set into 5 validations of size 10k samples each. With stratification, each of your validation sets will be selected in a manner to maintain the 4:1 distribution of not spam to spam.

EDIT: I'm sorry I misunderstood your original question. To expand upon user @unutbu's comments below, you want to confirm that the classifier you are using is a subclass of the base class ClassifierMixin. You can do so using a Method Resolution Order.

Suppose you were using the classifier KNeighborsClassifier:

```<code>>>> from sklearn.neighbors import KNeighborsClassifier
>>> clf = KNeighborsClassifier()
>>> type(clf)
<class 'sklearn.neighbors.classification.KNeighborsClassifier'>
>>> type(clf).mro()
[<class 'sklearn.neighbors.classification.KNeighborsClassifier'>, ..., <class 'sklearn.base.ClassifierMixin'>, <type 'object'>]
</code>```

Notice that the second to last class in the resolution order is ClassifierMixin.

Title: Stratified K Fold in Python

Body:
When you are performing cross-fold validation, you are splitting up your training set into multiple validation sets. StratifiedKFold ensures that each of your validation sets contains an equal proportion of the labels from your original training set.

For example, let's say you are training a classifier on spam and not spam. Your training set contains 50k samples with 10k spam samples. If you perform 5-fold cross-fold validation, you will split up your training set into 5 validations of size 10k samples each. With stratification, each of your validation sets will be selected in a manner to maintain the 4:1 distribution of not spam to spam.

EDIT: I'm sorry I misunderstood your original question. To expand upon user @unutbu's comments below, you want to confirm that the classifier you are using is a subclass of the base class ClassifierMixin. You can do so using a Method Resolution Order.

Suppose you were using the classifier KNeighborsClassifier:

>>> from sklearn.neighbors import KNeighborsClassifier
>>> clf = KNeighborsClassifier()
>>> type(clf)
<class 'sklearn.neighbors.classification.KNeighborsClassifier'>
>>> type(clf).mro()
[<class 'sklearn.neighbors.classification.KNeighborsClassifier'>, ..., <class 'sklearn.base.ClassifierMixin'>, <type 'object'>]

Notice that the second to last class in the resolution order is ClassifierMixin.


问:
PrimeFaces DataTable doesn't update when filtered
I'm new to PrimeFaces and to JSF.

I need to filter a table with "contains" match mode. It works fine when the data is static, but when data changes the view doesn't update, and it still shows the old data. It updates when the user changes the filter. If no filter is applied it works fine.

Have you got any suggestions?

I post the code, inspired from the PrimeFaces 6 showcase. It is a page that displays a two columns table and a button that loads a new data for the table

Thank you, any help will be appreciated

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:c="http://java.sun.com/jsp/jstl/core"
    xmlns:p="http://primefaces.org/ui">
<h:head >
Primefaces Data Table Test
</h:head>
<h:body>
    <h:form>
        <p:dataTable var="car" value="#{dtCar.cars}" widgetVar="carsTable"
            emptyMessage="No cars found with given criteria"
            filteredValue="#{dtCar.filteredCars}">

            <p:column filterBy="#{car.model}" headerText="Model"
                footerText="contains" filterMatchMode="contains">
                <h:outputText value="#{car.model}" />
            </p:column>
            <p:column filterBy="#{car.color}" headerText="Color"
                footerText="contains" filterMatchMode="contains">
                <h:outputText value="#{car.color}" />
            </p:column>

        </p:dataTable>
        <h:commandButton id="myButton" value="Load" action="#{dtCar.loadNewCars()}"/>
    </h:form>

</h:body>
</html>
</code>```

Here is the CarBean.java

```<code>package it.caditech.testtable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean(name = "dtCar")
@ViewScoped
public class CarBean {

  private List<Car> cars;

  private List<Car> filteredCars;

  public CarBean() {
    setCars(new ArrayList<Car>());
    getCars().add(new Car("myModel", "blu"));
    getCars().add(new Car("punto", "blu"));
    getCars().add(new Car("doblo", "grigio"));
    getCars().add(new Car("smart", "blu"));
    getCars().add(new Car("twingo", "rosso"));
    getCars().add(new Car("twingo", "bianco"));
    getCars().add(new Car("doblo", "blu"));
    // add more cars
  }

  // getter setter
  public List<Car> getCars() {
    return cars;
  }

  public void setCars(List<Car> cars) {
    this.cars = cars;
  }

  public List<Car> getFilteredCars() {
    return filteredCars;
  }

  public void setFilteredCars(List<Car> filteredCars) {
    this.filteredCars = filteredCars;
  }

  public String loadNewCars() {
    if (getCars().get(0).getModel().equals("myModel")) {
      getCars().clear();
      getCars().add(new Car("gt", "giallo"));
      getCars().add(new Car("scirocco", "azzurro"));
      getCars().add(new Car("duna", "giallo"));
      getCars().add(new Car("diablo", "griggio"));
      getCars().add(new Car("cayenne", "rosso"));
      getCars().add(new Car("aygo", "azzurro"));
      setFilteredCars(null);
    }
    else {
      getCars().clear();
      getCars().add(new Car("myModel", "blu"));
      getCars().add(new Car("punto", "blu"));
      getCars().add(new Car("doblo", "grigio"));
      getCars().add(new Car("smart", "blu"));
      getCars().add(new Car("twingo", "rosso"));
      getCars().add(new Car("twingo", "bianco"));
      getCars().add(new Car("doblo", "blu"));
      setFilteredCars(null);
    }
    return null;
  }
}
</code>```

And here is the Car.java

```<code>package it.caditech.testtable;
public class Car {
  private String model;

  private String color;

  public Car(String m, String c) {
    model = m;
    color = c;
  }

  public String getModel() {
    return model;
  }

  public void setModel(String model) {
    this.model = model;
  }

  public String getColor() {
    return color;
  }

  public void setColor(String color) {
    this.color = color;
  }
}
</code>```

答: I think you are mixing two different features, filter data and show updated data all the time. For the second case, you have some options to choice. You can listen for some event and then update you data or maybe you can ask all the time for the incoming new data, like jMarcel`s example.</p>

Body:
I'm new to PrimeFaces and to JSF.

I need to filter a table with "contains" match mode. It works fine when the data is static, but when data changes the view doesn't update, and it still shows the old data. It updates when the user changes the filter. If no filter is applied it works fine.

Have you got any suggestions?

I post the code, inspired from the PrimeFaces 6 showcase. It is a page that displays a two columns table and a button that loads a new data for the table

Thank you, any help will be appreciated

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head >
Primefaces Data Table Test
</h:head>
<h:body>
    <h:form>

                <h:outputText value="#{car.model}" />

                <h:outputText value="#{car.color}" />

        <h:commandButton id="myButton" value="Load" action="#{dtCar.loadNewCars()}"/>
    </h:form>

</h:body>

Here is the CarBean.java

package it.caditech.testtable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean(name = "dtCar")
@ViewScoped
public class CarBean {

  private List<Car> cars;

  private List<Car> filteredCars;

  public CarBean() {
    setCars(new ArrayList<Car>());
    getCars().add(new Car("myModel", "blu"));
    getCars().add(new Car("punto", "blu"));
    getCars().add(new Car("doblo", "grigio"));
    getCars().add(new Car("smart", "blu"));
    getCars().add(new Car("twingo", "rosso"));
    getCars().add(new Car("twingo", "bianco"));
    getCars().add(new Car("doblo", "blu"));
    // add more cars
  }

  // getter setter
  public List<Car> getCars() {
    return cars;
  }

  public void setCars(List<Car> cars) {
    this.cars = cars;
  }

  public List<Car> getFilteredCars() {
    return filteredCars;
  }

  public void setFilteredCars(List<Car> filteredCars) {
    this.filteredCars = filteredCars;
  }

  public String loadNewCars() {
    if (getCars().get(0).getModel().equals("myModel")) {
      getCars().clear();
      getCars().add(new Car("gt", "giallo"));
      getCars().add(new Car("scirocco", "azzurro"));
      getCars().add(new Car("duna", "giallo"));
      getCars().add(new Car("diablo", "griggio"));
      getCars().add(new Car("cayenne", "rosso"));
      getCars().add(new Car("aygo", "azzurro"));
      setFilteredCars(null);
    }
    else {
      getCars().clear();
      getCars().add(new Car("myModel", "blu"));
      getCars().add(new Car("punto", "blu"));
      getCars().add(new Car("doblo", "grigio"));
      getCars().add(new Car("smart", "blu"));
      getCars().add(new Car("twingo", "rosso"));
      getCars().add(new Car("twingo", "bianco"));
      getCars().add(new Car("doblo", "blu"));
      setFilteredCars(null);
    }
    return null;
  }
}

And here is the Car.java

package it.caditech.testtable;
public class Car {
  private String model;

  private String color;

  public Car(String m, String c) {
    model = m;
    color = c;
  }

  public String getModel() {
    return model;
  }

  public void setModel(String model) {
    this.model = model;
  }

  public String getColor() {
    return color;
  }

  public void setColor(String color) {
    this.color = color;
  }
}


问:
How to concatenate two github files using a Shell Script command
As part of jenkins I want to concatenate two github files using the Shell script command

```<code>cat https://www.github.com/tree/master/app/file1 >> https://www.github.com/tree/master/app/src/file2
</code>```

I tried the file path urls but I get below error

No such file or directory

I double checked the path to the files and they exist.

I also tried this command in local (I use mac), but gets the same error

答:
Here's a complete, self-contained example showing that your command works fine exactly as posted:

First, we can create two test files:

```<code>$ echo "First file" > file1
$ echo "Second file" > file2
</code>```

And verify that they exist and are readable in the current directory:

```<code>$ ls -l file1 file2
-rw-r--r--  1 myuser  mygroup  11 Jul  5 14:09 file1
-rw-r--r--  1 myuser  mygroup  12 Jul  5 14:09 file2
</code>```

Now we can append file1 to file2 with your command, which completes silently without error

```<code>$ cat file1 >> file2
</code>```

Now we can examine file2 to verify that it worked, which it did:

```<code>$ cat file2
Second file
First file
</code>```

If this is not what you do or it's not working for you, please edit your question and update it with the code that you actually run along with all error messages copy-pasted (not transcribed, paraphrased, translated or edited).

Body:
As part of jenkins I want to concatenate two github files using the Shell script command

cat https://www.github.com/tree/master/app/file1 >> https://www.github.com/tree/master/app/src/file2

I tried the file path urls but I get below error

No such file or directory

I double checked the path to the files and they exist.

I also tried this command in local (I use mac), but gets the same error

Body:
Here's a complete, self-contained example showing that your command works fine exactly as posted:

First, we can create two test files:

$ echo "First file" > file1
$ echo "Second file" > file2

And verify that they exist and are readable in the current directory:

$ ls -l file1 file2
-rw-r--r--  1 myuser  mygroup  11 Jul  5 14:09 file1
-rw-r--r--  1 myuser  mygroup  12 Jul  5 14:09 file2

Now we can append file1 to file2 with your command, which completes silently without error

$ cat file1 >> file2

Now we can examine file2 to verify that it worked, which it did:

$ cat file2
Second file
First file

If this is not what you do or it's not working for you, please edit your question and update it with the code that you actually run along with all error messages copy-pasted (not transcribed, paraphrased, translated or edited).


问:
Typescript throwing error during unit tests that variable undefined even though I have declare var statement at beginning of file
I'm using angular(2) and typescript. I'm using the moment library to convert dates so I have this function inside one of my utility classes:

```<code>static isoStringToDateObj(isoDateString: string): Date {
    // For unit tests and any environment where moment library is not present
    if (!moment) {
        return new Date(isoDateString);
    }
    return moment(isoDateString).toDate();
}
</code>```

This works fine in the browser, but when I try to run my unit tests it throws the error:
ReferenceError: Can't find variable: moment in karma-test-shim.js (line 16240)

The line it is referring to is the if (!moment) line.

Why does it care if the variable does not exist in a statement that
is only checking if the variable exists? It is not referencing any
properties on it.

I have declare var moment: any; at the top of
the file that the function isoStringToDateObj is in, so why is it
saying reference error when the variable is actually declared?

答:
The only proper way to check if global variable does not exist is:

```<code>if (typeof moment === 'undefined') { ... }
</code>```

ReferenceError: Can't find variable: moment

is runtime error, declare var moment: any cheats typing system to be silent about that but can't affect actual moment global in any way.

Body:
I'm using angular(2) and typescript. I'm using the moment library to convert dates so I have this function inside one of my utility classes:

static isoStringToDateObj(isoDateString: string): Date {
    // For unit tests and any environment where moment library is not present
    if (!moment) {
        return new Date(isoDateString);
    }
    return moment(isoDateString).toDate();
}

This works fine in the browser, but when I try to run my unit tests it throws the error:
ReferenceError: Can't find variable: moment in karma-test-shim.js (line 16240)

The line it is referring to is the if (!moment) line.

Why does it care if the variable does not exist in a statement that
is only checking if the variable exists? It is not referencing any
properties on it.

I have declare var moment: any; at the top of
the file that the function isoStringToDateObj is in, so why is it
saying reference error when the variable is actually declared?

Body:
The only proper way to check if global variable does not exist is:

if (typeof moment === 'undefined') { ... }

ReferenceError: Can't find variable: moment

is runtime error, declare var moment: any cheats typing system to be silent about that but can't affect actual moment global in any way.


问:
When you publish an add-in via centralized deployment, can you make it visible by default without having to manualy add it via Insert > My Add-ins?
This is the part in the manifest that controls the taskpaneButton etc etc. I'm pretty sure you can adjust this to make it happen but need some advise.

```<code>        <!-- Form factor. Currently only DesktopFormFactor is supported. -->
    <DesktopFormFactor>
      <!--"This code enables a customizable message to be displayed when the add-in is loaded successfully upon individual install."-->
      <GetStarted>
        <!-- Title of the Getting Started callout. resid points to a ShortString resource -->
        <Title resid="Contoso.GetStarted.Title"/>

        <!-- Description of the Getting Started callout. resid points to a LongString resource -->
        <Description resid="Contoso.GetStarted.Description"/>

        <!-- Point to a url resource which details how the add-in should be used. -->
        <LearnMoreUrl resid="Contoso.GetStarted.LearnMoreUrl"/>
      </GetStarted>
      <!-- PrimaryCommandSurface is the main Office Ribbon. -->
      <ExtensionPoint xsi:type="PrimaryCommandSurface">
        <!-- Use OfficeTab to extend an existing Tab. Use CustomTab to create a new tab. -->
        <OfficeTab id="TabHome">
          <!-- Ensure you provide a unique id for the group. Recommendation for any IDs is to namespace using your company name. -->
          <Group id="Contoso.Group1">
            <!-- Label for your group. resid must point to a ShortString resource. -->
            <Label resid="Contoso.Group1Label" />
            <!-- Icons. Required sizes 16,32,80, optional 20, 24, 40, 48, 64. Strongly recommended to provide all sizes for great UX. -->
            <!-- Use PNG icons. All URLs on the resources section must use HTTPS. -->
            <Icon>
              <bt:Image size="16" resid="Contoso.tpicon_16x16" />
              <bt:Image size="32" resid="Contoso.tpicon_32x32" />
              <bt:Image size="80" resid="Contoso.tpicon_80x80" />
            </Icon>

            <!-- Control. It can be of type "Button" or "Menu". -->
            <Control xsi:type="Button" id="Contoso.TaskpaneButton">
              <Label resid="Contoso.TaskpaneButton.Label" />
              <Supertip>
                <!-- ToolTip title. resid must point to a ShortString resource. -->
                <Title resid="Contoso.TaskpaneButton.Label" />
                <!-- ToolTip description. resid must point to a LongString resource. -->
                <Description resid="Contoso.TaskpaneButton.Tooltip" />
              </Supertip>
              <Icon>
                <bt:Image size="16" resid="Contoso.tpicon_16x16" />
                <bt:Image size="32" resid="Contoso.tpicon_32x32" />
                <bt:Image size="80" resid="Contoso.tpicon_80x80" />
              </Icon>

              <!-- This is what happens when the command is triggered (E.g. click on the Ribbon). Supported actions are ExecuteFunction or ShowTaskpane. -->
              <Action xsi:type="ShowTaskpane">
                <TaskpaneId>ButtonId1</TaskpaneId>
                <!-- Provide a url resource id for the location that will be displayed on the task pane. -->
                <SourceLocation resid="Contoso.Taskpane.Url" />
              </Action>
            </Control>
          </Group>
        </OfficeTab>
      </ExtensionPoint>
    </DesktopFormFactor>
</code>```

This is for an word addin in office 365 and it would be nice to not have to do the insert procedure for everyone. I'm not certain but I think I have seen a similar question, but I ask it anyway.

答: Will the new feature described at Automatically open a task pane with a document serve your needs? There's a sample at: Office OOXML EmbedAddin</p>

Body:
This is the part in the manifest that controls the taskpaneButton etc etc. I'm pretty sure you can adjust this to make it happen but need some advise.

    <DesktopFormFactor>

      <GetStarted>

        <Title resid="Contoso.GetStarted.Title"/>

        <Description resid="Contoso.GetStarted.Description"/>

        <LearnMoreUrl resid="Contoso.GetStarted.LearnMoreUrl"/>
      </GetStarted>

      <ExtensionPoint xsi:type="PrimaryCommandSurface">

        <OfficeTab id="TabHome">

          <Group id="Contoso.Group1">

            <Icon>
              <bt:Image size="16" resid="Contoso.tpicon_16x16" />
              <bt:Image size="32" resid="Contoso.tpicon_32x32" />
              <bt:Image size="80" resid="Contoso.tpicon_80x80" />
            </Icon>

            <Control xsi:type="Button" id="Contoso.TaskpaneButton">

              <Supertip>

                <Title resid="Contoso.TaskpaneButton.Label" />

                <Description resid="Contoso.TaskpaneButton.Tooltip" />
              </Supertip>
              <Icon>
                <bt:Image size="16" resid="Contoso.tpicon_16x16" />
                <bt:Image size="32" resid="Contoso.tpicon_32x32" />
                <bt:Image size="80" resid="Contoso.tpicon_80x80" />
              </Icon>

              <Action xsi:type="ShowTaskpane">
                <TaskpaneId>ButtonId1</TaskpaneId>

                <SourceLocation resid="Contoso.Taskpane.Url" />
              </Action>
            </Control>
          </Group>
        </OfficeTab>
      </ExtensionPoint>
    </DesktopFormFactor>

This is for an word addin in office 365 and it would be nice to not have to do the insert procedure for everyone. I'm not certain but I think I have seen a similar question, but I ask it anyway.


问:
Excel - Comparing Multiple Columns
Hoping someone can assist this Excel newbie...

Trying to figure out how to compare the values in columns B and C starting with B2 and C2 (they are paired together - B3 & C3, B4 & C4 also paired, etc) with the values in columns E and F (E2 and F2 are also paired together). Also need to be able to see if the paired values of B2 and C2 are listed anywhere within paired values in columns E and F.

Hope I'm not making this more confusing than it needs to be... example of data is listed below.

答:
To answer the first part of your question:

```<code>=IF(AND($B2=$E2, $C2=$F2), [return value if true], [return value if false])
</code>```

The second part is a bit trickier.  I would lean toward using a macro to solve this problem since it involves looping.

The logic goes like this:

Does the B2;C2 combination match with E2;F2, E3;F3, E4;F4, ...

Does the B3;C3 combination match with E2;F2, E3;F3, E4;F4, ...

Continue with this loop to end of Bn;Cn combinations

Is this type of solution what you are looking for?

Title: Excel - Comparing Multiple Columns

Body:
To answer the first part of your question:

=IF(AND($B2=$E2, $C2=$F2), [return value if true], [return value if false])

The second part is a bit trickier.  I would lean toward using a macro to solve this problem since it involves looping.

The logic goes like this:

Does the B2;C2 combination match with E2;F2, E3;F3, E4;F4, ...

Does the B3;C3 combination match with E2;F2, E3;F3, E4;F4, ...

Continue with this loop to end of Bn;Cn combinations

Is this type of solution what you are looking for?


问:
How can I set a phase offset for an OscillatorNode in the Web Audio API?
I'm trying to implement Stereo Phase as it is described here:  http://www.image-line.com/support/FLHelp/html/plugins/3x%20OSC.htm

"Stereo Phase (SP) - Allows you to set different phase offset for the left and right channels of the generator. The offset results in the oscillator starting at a different point on the oscillator's shape (for example, start at the highest value of the sine function instead at the zero point). Stereo phase offset adds to the richness and stereo panorama of the sound produced."

I'm trying to achieve this for an OscillatorNode. My only idea is to use createPeriodicWave (https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html#dfn-createPeriodicWave) However, the description of create periodic wave from the specification is above my understanding and I have not found any examples via Google.

Any help in deciphering the description of createPeriodicWave would be helpful as would any other ideas about how to achieve this effect.

Thanks!

答:
```<code>function getTriangleWave(imag, n) {
    for (var i = 1; i < n; i+=2) {
      imag[i] = (8*Math.sin(i*Math.PI/2))/(Math.pow((Math.PI*i), 2));
    }
    return imag;
}
</code>```


问:
Code challenge: finding the divisible in a list
I am playing a code challenge. Simply speaking, the problem is:

Given a list L (max length is of the order of 1000) containing positive integers.
  Find the number of "Lucky Triples", which is L[i] divides L[j], and L[j] divides L[k].

for example, [1,2,3,4,5,6] should give the answer 3 because [1,2,4], [1,2,6],[1,3,6]

My attempt:

Sort the list. (let say there are n elements)

3 For loops: i, j, k (i from 1 to n-2), (j from i+1 to n-1), (k from j+1 to n)

only if L[j] % L[i] == 0, the k for loop will be executed

The algorithm seems to give the correct answer. But the challenge said that my code exceeded the time limit. I tried on my computer for the list [1,2,3,...,2000], count = 40888(I guess it is correct). The time is around 5 second.

Is there any faster way to do that?

This is the code I have written in python.

```<code>def answer(l):
    l.sort()
    cnt = 0
    if len(l) == 2:
        return cnt
    for i in range(len(l)-2):
        for j in range(1,len(l)-1-i):
            if (l[i+j]%l[i] == 0):
                for k in range(1,len(l)-j-i):
                    if (l[i+j+k]%l[i+j] == 0):
                        cnt += 1

    return cnt
</code>```

答:
You can use additional space to help yourself. After you sort the input list you should make a map/dict where the key is each element in the list and  value is a list of elements which are divisible by that in the list so you would have something like this
assume sorted list is list = [1,2,3,4,5,6] your map would be

```<code> 1 -> [2,3,4,5,6]
 2-> [4,6]
 3->[6]
 4->[]
 5->[]
 6->[]
</code>```

now for every key in the map you find what it can divide and then you find what that divides, for example you know that

```<code>1 divides 2 and 2 divides 4 and 6, similarly 1 divides 3 and 3 divides 6
</code>```

the complexity of sorting should be O(nlogn) and that of constructing the list should be better than O(n^2) (but I am not sure about this part) and then I am not sure about the complexity of when you are actually checking for multiples but I think this should be much much faster than a brute force O(n^3)

If someone could help me figure out the time complexity of this I would really appreciate it

EDIT :

You can make the map creation part faster by incrementing by X (and not 1) where X is the number in the list you are currently on since it is sorted.

Body:
I am playing a code challenge. Simply speaking, the problem is:

Given a list L (max length is of the order of 1000) containing positive integers.
  Find the number of "Lucky Triples", which is L[i] divides L[j], and L[j] divides L[k].

for example, [1,2,3,4,5,6] should give the answer 3 because [1,2,4], [1,2,6],[1,3,6]

My attempt:

Sort the list. (let say there are n elements)

3 For loops: i, j, k (i from 1 to n-2), (j from i+1 to n-1), (k from j+1 to n)

only if L[j] % L[i] == 0, the k for loop will be executed

The algorithm seems to give the correct answer. But the challenge said that my code exceeded the time limit. I tried on my computer for the list [1,2,3,...,2000], count = 40888(I guess it is correct). The time is around 5 second.

Is there any faster way to do that?

This is the code I have written in python.

def answer(l):
    l.sort()
    cnt = 0
    if len(l) == 2:
        return cnt
    for i in range(len(l)-2):
        for j in range(1,len(l)-1-i):
            if (l[i+j]%l[i] == 0):
                for k in range(1,len(l)-j-i):
                    if (l[i+j+k]%l[i+j] == 0):
                        cnt += 1

    return cnt

Body:
You can use additional space to help yourself. After you sort the input list you should make a map/dict where the key is each element in the list and  value is a list of elements which are divisible by that in the list so you would have something like this
assume sorted list is list = [1,2,3,4,5,6] your map would be

 1 -> [2,3,4,5,6]
 2-> [4,6]
 3->[6]
 4->[]
 5->[]
 6->[]

now for every key in the map you find what it can divide and then you find what that divides, for example you know that

1 divides 2 and 2 divides 4 and 6, similarly 1 divides 3 and 3 divides 6

the complexity of sorting should be O(nlogn) and that of constructing the list should be better than O(n^2) (but I am not sure about this part) and then I am not sure about the complexity of when you are actually checking for multiples but I think this should be much much faster than a brute force O(n^3)

If someone could help me figure out the time complexity of this I would really appreciate it

EDIT :

You can make the map creation part faster by incrementing by X (and not 1) where X is the number in the list you are currently on since it is sorted.


问:
Count number of ways to climb a ladder with a twist
I am aware of this question.

Question:

A ladder has n steps. One can climb the ladder using any combination of steps of 1 or steps of 2. How many possible ways are there for one to climb the ladder?

However, how will this number change if some of the stairs are broken?

PS: This is not homework.

答: If the number of steps is large, then it should be insignificant if some steps are broken.</p>


问:
Using JSON files to initialize static class
I have a class thats acts as a properties/configurations class. In addition to this, I also have a JSON file which contains the properties.

Right now, in my main class, I am instantiating a property object and then using the gson's fromJson method to read in the JSON file into this object. I am then passing this to my other classes so that they will be able to access the properties.

I want to refactor my design so that this property class will have static variables and methods, so that I don't have to instantiate it in order to access the properties.

I am wondering if this is possible using gson, or if this design is a good idea.

Thank you!

答: You can use a static block in the property class, right? Initialize the fields there like you're doing now. Make them final to avoid race conditions.


问:
What capabilities does systemd daemon require to create cgroups?
In my project I need sometimes to be able to create new control groups as an unprivileged user. I decided to write a systemd daemon for this.

I use libcgroup in the daemon code for cgroup manipulation.

When I try to create a cgroup (cgroup_create_cgroup), I receive a libcgroup error ECGROUPNOTALLOWED (Cgroup, operation not allowed). How to allow my daemon to create new cgroups?

systemd .service file:

```<code>[Service]
...
CapabilityBoundingSet=CAP_SYS_ADMIN
PrivateTmp=yes
PrivateDevices=yes
PrivateNetwork=yes
ProtectSystem=yes
ProtectHome=yes
ProtectControlGroups=no
ProtectKernelTunables=no
RestrictRealtime=no
User=root
Group=root
</code>```

答: Well, I don't really know which of those protections was odd but just removing them all did the trick.</p>

Body:
In my project I need sometimes to be able to create new control groups as an unprivileged user. I decided to write a systemd daemon for this.

I use libcgroup in the daemon code for cgroup manipulation.

When I try to create a cgroup (cgroup_create_cgroup), I receive a libcgroup error ECGROUPNOTALLOWED (Cgroup, operation not allowed). How to allow my daemon to create new cgroups?

systemd .service file:

[Service]
...
CapabilityBoundingSet=CAP_SYS_ADMIN
PrivateTmp=yes
PrivateDevices=yes
PrivateNetwork=yes
ProtectSystem=yes
ProtectHome=yes
ProtectControlGroups=no
ProtectKernelTunables=no
RestrictRealtime=no
User=root
Group=root


问:
Same code different syntax(ilm_client.h vs ilm_control_platform.h)
I would like to know that in the following code is (*layerSetOpacity) is some sort of function pointer. I could not find the reference anywhere in the whole repository!

The following code found in ilm_client.h is understandable as ilm_layerSetOpacity pertains to function

```<code>ilmErrorTypes ilm_layerSetOpacity(t_ilm_layer layerId, t_ilm_float opacity);
</code>```

But this code found in ilm_control_platform.h is confusing as what does bracket with pointer represent - function pointer?

```<code> ilmErrorTypes (*layerSetOpacity)(t_ilm_layer layerId,
               t_ilm_float opacity);
</code>```

I am not asking for code specifics only the syntax.

答:
Let's dissect: - ilmErrorTypes (*layerSetOpacity)(t_ilm_layer layerId, t_ilm_float opacity):-

layerSetOpacity is a pointer to a function that takes 2 params as input

The inparams to the function  are of type t_ilm_layer and t_ilm_float

The function returns a adata type ilmErrorTypes

The fact that you can't find anything in your code base that matches the symbol layerSetOpacity means the function pointer is declared in the header but never invoked using this function pointer but quite possibly invoked using ilm_layerSetOpacity

A simpler analogy would be:-

```<code>int a = 10;
int *p1; //Uninitialized pointer
int *p2 = &a; //pointer pointing to a
</code>```

In your case a is ilm_layerSetOpacity and p1 is layerSetOpacity and p2 does not exist

HTH!

Body:
I would like to know that in the following code is (*layerSetOpacity) is some sort of function pointer. I could not find the reference anywhere in the whole repository!

The following code found in ilm_client.h is understandable as ilm_layerSetOpacity pertains to function

ilmErrorTypes ilm_layerSetOpacity(t_ilm_layer layerId, t_ilm_float opacity);

But this code found in ilm_control_platform.h is confusing as what does bracket with pointer represent - function pointer?

 ilmErrorTypes (*layerSetOpacity)(t_ilm_layer layerId,
               t_ilm_float opacity);

I am not asking for code specifics only the syntax.

Body:
Let's dissect: - ilmErrorTypes (*layerSetOpacity)(t_ilm_layer layerId, t_ilm_float opacity):-

layerSetOpacity is a pointer to a function that takes 2 params as input

The inparams to the function  are of type t_ilm_layer and t_ilm_float

The function returns a adata type ilmErrorTypes

The fact that you can't find anything in your code base that matches the symbol layerSetOpacity means the function pointer is declared in the header but never invoked using this function pointer but quite possibly invoked using ilm_layerSetOpacity

A simpler analogy would be:-

int a = 10;
int *p1; //Uninitialized pointer
int *p2 = &a; //pointer pointing to a

In your case a is ilm_layerSetOpacity and p1 is layerSetOpacity and p2 does not exist

HTH!


问:
How do I pull project properties in Google Scripts?
I'm currently working on a google script that emails designated users when a project is marked as complete in the associated spreadsheet. The first function triggers when the spreadsheet is edited, and checks column 5 and moves the row if it matches accordingly. The first If statement checks column 5 to see if it matches "Completed" and moves it to the "COMPLETED" sheet if it does. I'm able to have it email a desired user successfully, but I'm also trying to include the first column of the selected row in the email.

This lead me to trying to use project properties as global variables aren't possible in Google Scripts. However, when trying to pull a test property, it breaks the script.

Does anybody know how I might correct my code to be able to push column A to a project property in one function and pull it in a separate function?

The original idea for using project properties was taken from the following thread: How to define global variable in Google Apps Script

Thank you!

```<code>function onEditTrigger(event) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = event.source.getActiveSheet();
  var r = event.source.getActiveRange()

  // Below sends a completed project from the IN PROGRESS sheet to the COMPLETED sheet
  if(s.getName() == "IN PROGRESS" && r.getColumn() == 5 && r.getValue() == "Completed") {
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName("COMPLETED");
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    s.getRange(row, 1, 1, numColumns).moveTo(target);
    s.deleteRow(row);
    // Send an email when a project is marked complete
    sendEmail();
  }
    // Below sends a completed project from the COMPLETED sheet to the IN PROGRESS sheet
   if(s.getName() == "COMPLETED" && r.getColumn() == 5 && (r.getValue() == "In Development" || r.getValue() == "On Hold" || r.getValue() == "Delayed")) {
    var row2 = r.getRow();
    var numColumns2 = s.getLastColumn();
    var targetSheet2 = ss.getSheetByName("IN PROGRESS");
    var target2 = targetSheet2.getRange(targetSheet2.getLastRow() + 1, 1);
    s.getRange(row2, 1, 1, numColumns2).moveTo(target2);
    s.deleteRow(row2);
  }
}
// Code that establishes desired emails, subject
function sendEmail() {
  var project = PropertiesService.getScriptProperties().getProperty('project');
  var subject = "Learning Solutions project has been completed: " + project;
  var emailAddress = "test@email.com";
  MailApp.sendEmail(emailAddress,subject,"This is a test"
    );
}
</code>```

Screenshot of the current setup for Project Properties

答:
Global variables are supported by Google Apps Script, see this simple example of Code.gs:

```<code>var myGlobalVar = 'This is global var value';

function myFunction()
{
  Logger.log(myGlobalVar);
}
</code>```

Run function myFunction then select View - Logs from script editor menu and you will see

[17-07-06 00:12:58:691 EEST] This is global var value

Body:
I'm currently working on a google script that emails designated users when a project is marked as complete in the associated spreadsheet. The first function triggers when the spreadsheet is edited, and checks column 5 and moves the row if it matches accordingly. The first If statement checks column 5 to see if it matches "Completed" and moves it to the "COMPLETED" sheet if it does. I'm able to have it email a desired user successfully, but I'm also trying to include the first column of the selected row in the email.

This lead me to trying to use project properties as global variables aren't possible in Google Scripts. However, when trying to pull a test property, it breaks the script.

Does anybody know how I might correct my code to be able to push column A to a project property in one function and pull it in a separate function?

The original idea for using project properties was taken from the following thread: How to define global variable in Google Apps Script

Thank you!

function onEditTrigger(event) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = event.source.getActiveSheet();
  var r = event.source.getActiveRange()

  // Below sends a completed project from the IN PROGRESS sheet to the COMPLETED sheet
  if(s.getName() == "IN PROGRESS" && r.getColumn() == 5 && r.getValue() == "Completed") {
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName("COMPLETED");
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    s.getRange(row, 1, 1, numColumns).moveTo(target);
    s.deleteRow(row);
    // Send an email when a project is marked complete
    sendEmail();
  }
    // Below sends a completed project from the COMPLETED sheet to the IN PROGRESS sheet
   if(s.getName() == "COMPLETED" && r.getColumn() == 5 && (r.getValue() == "In Development" || r.getValue() == "On Hold" || r.getValue() == "Delayed")) {
    var row2 = r.getRow();
    var numColumns2 = s.getLastColumn();
    var targetSheet2 = ss.getSheetByName("IN PROGRESS");
    var target2 = targetSheet2.getRange(targetSheet2.getLastRow() + 1, 1);
    s.getRange(row2, 1, 1, numColumns2).moveTo(target2);
    s.deleteRow(row2);
  }
}
// Code that establishes desired emails, subject
function sendEmail() {
  var project = PropertiesService.getScriptProperties().getProperty('project');
  var subject = "Learning Solutions project has been completed: " + project;
  var emailAddress = "test@email.com";
  MailApp.sendEmail(emailAddress,subject,"This is a test"
    );
}

Screenshot of the current setup for Project Properties

Body:
Global variables are supported by Google Apps Script, see this simple example of Code.gs:

var myGlobalVar = 'This is global var value';

function myFunction()
{
  Logger.log(myGlobalVar);
}

Run function myFunction then select View - Logs from script editor menu and you will see

[17-07-06 00:12:58:691 EEST] This is global var value


问:
Preprocessor output on Qt Creator
I am compiling C code in Qt Creator and I need to look at the preprocessor output.

I added the -E flag to the make, but I don't see the *.i files:

```<code>mingw32-make.exe -e -w in \qt\qt-build-desktop
</code>```

Please help.

答:
I could get Qt Creator to generate preprocessed files using one (or more) of the following options in the .pro file:

```<code>QMAKE_CFLAGS_DEBUG += -E

QMAKE_CFLAGS_RELEASE += -E

QMAKE_CXXFLAGS_DEBUG += -E

QMAKE_CXXFLAGS_RELEASE += -E
</code>```

However, one bit of ugliness is that instead of putting the output into .i files it put them into the .o files (which the linker didn't much like...).  Since this is presumably a 'one-off' situation for troubleshooting, I didn't look into how to clean that that up.

You may need to rerun 'qmake' before you rebuild, and you'll almost certainly need to run a "Clean Project" build before trying to generate the preprocessed output.

Title: Preprocessor output on Qt Creator

Body:
I am compiling C code in Qt Creator and I need to look at the preprocessor output.

I added the -E flag to the make, but I don't see the *.i files:

mingw32-make.exe -e -w in \qt\qt-build-desktop

Please help.

Body:
I could get Qt Creator to generate preprocessed files using one (or more) of the following options in the .pro file:

QMAKE_CFLAGS_DEBUG += -E

QMAKE_CFLAGS_RELEASE += -E

QMAKE_CXXFLAGS_DEBUG += -E

QMAKE_CXXFLAGS_RELEASE += -E

However, one bit of ugliness is that instead of putting the output into .i files it put them into the .o files (which the linker didn't much like...).  Since this is presumably a 'one-off' situation for troubleshooting, I didn't look into how to clean that that up.

You may need to rerun 'qmake' before you rebuild, and you'll almost certainly need to run a "Clean Project" build before trying to generate the preprocessed output.


问:
PHP MySQL Query Where x = $variable from function
Why is this not working:

```<code>function listOrderComments ($factnr){
global $connection;

//$factnr = 123; //or $factnr = "123"; (Both work)

$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);
</code>```

When I echo $factnr I get "123" back.

When I uncommented //$factnr = 123; my function is working.

Looked everywhere for a solution. check the type $factnr is (string).

答:
You can go with:</p>

```<code>$query = "SELECT * FROM orderstatus WHERE factuurnummer = ". $factnr;
</code>```

Body:
Why is this not working:

function listOrderComments ($factnr){
global $connection;

//$factnr = 123; //or $factnr = "123"; (Both work)

$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);

When I echo $factnr I get "123" back.

When I uncommented //$factnr = 123; my function is working.

Looked everywhere for a solution. check the type $factnr is (string).

Body:
You can go with:

$query = "SELECT * FROM orderstatus WHERE factuurnummer = ". $factnr;


问:
NodeJS Identify once
I want variable identify once so;

├── project_folder

|   ├── app.js //main file

|   └── router/index.js

app.js

```<code>const express = require('express');
const app = express();
const path = require('path');
const router = require('./router/index');
const mysql = require('mysql');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use('/',router);

app.listen( 8000, function(){
    console.log( 'Server listening on * 8000' );
});
</code>```

index.js

```<code>//other codes
const connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'wordpress'
});

connection.connect(function(err){
    if(err)
        console.log(err);
});
//other codes
</code>```

error : mysql is not defined

I don't want identify mysql and other variables again.

How can I solve?

Thank you for your helping.

SOLVED

Create a settings.js
Define settings in file

EXAMPLE

```<code>const testSettings = "test Settings...";

module.exports = {
    test:testSettings
}
</code>```

In a file you want
require('./settings');

Using: settings.test

答:
You need to import the modules that are required:

index.js

```<code>const mysql = require('mysql');

const connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'wordpress'
});

connection.connect(function(err) {
    if (err) {
        console.log(err);
    }
});
</code>```

Title: NodeJS Identify once

Body:
I want variable identify once so;

├── project_folder

|   ├── app.js //main file

|   └── router/index.js

app.js

const express = require('express');
const app = express();
const path = require('path');
const router = require('./router/index');
const mysql = require('mysql');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use('/',router);

app.listen( 8000, function(){
    console.log( 'Server listening on * 8000' );
});

index.js

//other codes
const connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'wordpress'
});

connection.connect(function(err){
    if(err)
        console.log(err);
});
//other codes

error : mysql is not defined

I don't want identify mysql and other variables again.

How can I solve?

Thank you for your helping.

SOLVED

Create a settings.js
Define settings in file

EXAMPLE

const testSettings = "test Settings...";

module.exports = {
    test:testSettings
}

In a file you want
require('./settings');

Using: settings.test

Body:
You need to import the modules that are required:

index.js

const mysql = require('mysql');

const connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'wordpress'
});

connection.connect(function(err) {
    if (err) {
        console.log(err);
    }
});


问:
Strange behavior with switch statement using dynamic numbers as case
I'm getting very weird behavior from a switch statement that I am using inside of a while loop in PHP.

So I rewrote some code earlier that I had written in if-else if statements, I decided to (pardon the pun) switch to a switch statement.

This code in particular is inside of a while loop, it looks like this:

```<code><?
    $ret  = $db->query("SELECT * from teammates WHERE `current_team`='$lineID';");
    $loop = 1;
    while($row = $ret->fetchArray(SQLITE3_ASSOC)) {
        switch($loop) {
            case 5:
                echo "</div>";
                $loop = 1;
                break;
            case 1:
                echo "<div class='row'>";
                break;
            default:
                $loop++;
        }
        echo "<div class='col-lg-3'>";
        echo "  <img src='somesite.com/somepicture.png"></img>;
        echo "</div>";
        $loop++;
    }
?>
</code>```

Now, this code works, BUT, I am experiencing some weird behavior, and I would really like to know why it happens.

This code takes some images, puts 4 of them in a row, then starts a new row until all the images are displayed. Giving me basically a page with 4 columns of images.

As you can see in my code, there is 2 parts where it increments the $loop variable. The weird behavior happens when I remove either of these increments.

Here is some images of the behavior (I'd be happy to include any other information needed)

With BOTH increments:

Missing the 2nd increment:

Missing the switch increment:

答:
You are counting by two's. You increment $loop twice in the same loop.

Try a simplified version...

```<code><?php
$loop = 1;

do {

    echo "$loop ";

    switch($loop) {
        case 5:
            echo "CLOSE>";
            $loop = 1;
            break;
        case 1:
            echo "<OPEN";
            break;
        default:
            $loop++;
    }

    $loop++;

} while ($loop < 50);

die('eof');
</code>```

<OPEN2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 eof

I'd say refactor it.  Try using a modulus function instead. Think it will look better. Also $loop = 0; is how I like to start counting things when possible.

Take a look at the following:

```<code>$i = 0;
echo '<div class="row">';
do {
    $i++;
    echo '<div class="col-lg-3"><img src="somesite.com/somepicture.png" /></div>';
    if ($i % 5 === 0) {
        echo '</div>' . PHP_EOL . PHP_EOL; //close row - new line for readability here
        echo '<div class="row">';
    }
} while ($i < 50);
</code>```

You would want to add a closing row div or prevent echoing it out if no more columns are to follow. The modulus % operator is a great way to do things like shade alternate rows, create grids like this, or code the "fizz-buzz" scenario that often is asked in interviews. Please comment if you are still unclear about anything.

Or, specifically as you provided it:

```<code><?php
$ret  = $db->query("SELECT * from teammates WHERE `current_team`='$lineID';");
$loop = 0;
echo "<div class='row'>";
while($row = $ret->fetchArray(SQLITE3_ASSOC)) {
    $loop++;
    if ($loop % 5 === 0) {
            echo "</div>";
            echo "<div class='row'>"; //***
    }
    echo "<div class='col-lg-3'>";
    echo "  <img src='somesite.com/somepicture.png'/>";
    echo "</div>";
}
echo "</div>";
?>
</code>```

Body:
I'm getting very weird behavior from a switch statement that I am using inside of a while loop in PHP.

So I rewrote some code earlier that I had written in if-else if statements, I decided to (pardon the pun) switch to a switch statement.

This code in particular is inside of a while loop, it looks like this:

<?
    $ret  = $db->query("SELECT * from teammates WHERE `current_team`='$lineID';");
    $loop = 1;
    while($row = $ret->fetchArray(SQLITE3_ASSOC)) {
        switch($loop) {
            case 5:
                echo "
";
                $loop = 1;
                break;
            case 1:
                echo "
";
                break;
            default:
                $loop++;
        }
        echo "
";
        echo "  ;
        echo "
";
        $loop++;
    }
?>

Now, this code works, BUT, I am experiencing some weird behavior, and I would really like to know why it happens.

This code takes some images, puts 4 of them in a row, then starts a new row until all the images are displayed. Giving me basically a page with 4 columns of images.

As you can see in my code, there is 2 parts where it increments the $loop variable. The weird behavior happens when I remove either of these increments.

Here is some images of the behavior (I'd be happy to include any other information needed)

With BOTH increments:

Missing the 2nd increment:

Missing the switch increment:

Body:
You are counting by two's. You increment $loop twice in the same loop.

Try a simplified version...

<?php
$loop = 1;

do {

    echo "$loop ";

    switch($loop) {
        case 5:
            echo "CLOSE>";
            $loop = 1;
            break;
        case 1:
            echo "<OPEN";
            break;
        default:
            $loop++;
    }

    $loop++;

} while ($loop < 50);

die('eof');

<OPEN2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 eof

I'd say refactor it.  Try using a modulus function instead. Think it will look better. Also $loop = 0; is how I like to start counting things when possible.

Take a look at the following:

$i = 0;
echo '<div class="row">';
do {
    $i++;
    echo '<div class="col-lg-3"><img src="somesite.com/somepicture.png" /></div>';
    if ($i % 5 === 0) {
        echo '</div>' . PHP_EOL . PHP_EOL; //close row - new line for readability here
        echo '<div class="row">';
    }
} while ($i < 50);

You would want to add a closing row div or prevent echoing it out if no more columns are to follow. The modulus % operator is a great way to do things like shade alternate rows, create grids like this, or code the "fizz-buzz" scenario that often is asked in interviews. Please comment if you are still unclear about anything.

Or, specifically as you provided it:

<?php
$ret  = $db->query("SELECT * from teammates WHERE `current_team`='$lineID';");
$loop = 0;
echo "<div class='row'>";
while($row = $ret->fetchArray(SQLITE3_ASSOC)) {
    $loop++;
    if ($loop % 5 === 0) {
            echo "</div>";
            echo "<div class='row'>"; //***
    }
    echo "<div class='col-lg-3'>";
    echo "  <img src='somesite.com/somepicture.png'/>";
    echo "</div>";
}
echo "</div>";
?>


问:
How does OLE DB Source storage records in memory? (SSIS)
I have a OLE DB Source in my Sql Server Integration Service package. And then, I also have a Script component connected to the Source.

The OLE DB Source access data from a SQL query that gets 500.000 records. I want to know if when the package starts running the application begins to storage all the records in memory (500.000) or if the package storage records in cicle's like 5.000 records...

How does it work? Can I configure this?

答:
Your package could attempt to buffer all 500.000 rows into memory if you have asynchronous/blocking components (Sort/Aggregate) because data can't flow beyond that point until every row has been sent from the source and has reached that component. Only then can SSIS determine the maximum value for column X or that all the rows have been sorted by key Y.

If your machine runs out of memory, then you will have a event recorded for buffers spilled to disk (approximate name). That means that your high performance in memory ETL engine has now begun writing the data to disk. Performance is going to suffer mightily at this point because as all that data gets written to disk so that you can get through that blocking component, guess what? That written data has to get read back from disk now that whatever calculation had to happen has happened. And if you happened to do something like Sort my data in the data flow followed by aggregate data, you just paid for doubly poor performance.

That said, if you're using just the synchronous components, there are mechanisms built into the data flow to detect back pressure. Thus, your target destination can't keep up with the source flow it will signal that component to send fewer records until it can catch up. Pretty clever stuff but nothing you as a developer can really influence beyond not adding asynchronous components unless the solution requires it.