问:
Ruby - how to find the NEXT occurrence of a given hour?
I want to return a Ruby Time object (miliseconds) that represents the next X hour from a given DateTime.

Examples for the next 5am

if it currently is 9pm on 3/28, the NEXT 5am would be 3/29 5am

if it currently is 6am on 3/29, the NEXT 5am would be 3/30 5am

Code wise:

```<code># for the below attribute
@object.created_at
=> "2017-03-28 21:00:00"

# given the definition of the next X hour in question
next_hour_to_find = 5 # for 5am

# what's the equation to produce 3/29 5am?
</code>```

I'd like something flexible so that if next_hour_to_find = 14 then the function would be able to find the next 2pm. No worries about time zone, this is all within the scope of the time zone of the @object.created_at.

My current thinking is below, but I feel like there's a cleaner way...

```<code>if @object.created_at.hour > next_hour_to_find
  # the next X hour is always going to occur on the next date
  date = (@object.created_at + 1.days).strftime(...) # get the date out
else
  # the next X hour is always going to occur on the same date
  date = (@object.created_at).strftime(...) # get the date out
end

# now that we have a date in a string, we have to append that string with the next_hour_to_find
# not sure if below works for both single and double digit hours
string = date + next_hour_to_find + ":00:00"

# finish by returning Time object, but this seems suuuuper inefficient since we converted to string and then back again
return Time.parse(string)
</code>```

答:
How about the following?

```<code>def next_hour_from(time, next_hour_to_find)
  hour_on_day_of_time = next_hour_to_find.hours.since( time.beginning_of_day )
  hour_on_day_of_time < time ? 1.day.since(hour_on_day_of_time) : hour_on_day_of_time
end

# e.g.
next_hour_from(@object.created_at, 5) # @object.created_at #=> 2017-03-28 21:00:00
# => 2017-03-29 05:00:00
</code>```

Basically what it does is:

It looks at the time at the beginning of the day of time, and adds next_hour_to_find to it, in hours. Assigns that value to hour_on_day_of_time.

Then checks to see if that hour_on_day_of_time is before or after the given time. If it's after, then the method can just return hour_on_day_of_time. If it's before, it adds 1 day to hour_on_day_of_time and returns that.

Body:
I want to return a Ruby Time object (miliseconds) that represents the next X hour from a given DateTime.

Examples for the next 5am

if it currently is 9pm on 3/28, the NEXT 5am would be 3/29 5am

if it currently is 6am on 3/29, the NEXT 5am would be 3/30 5am

Code wise:

# for the below attribute
@object.created_at
=> "2017-03-28 21:00:00"

# given the definition of the next X hour in question
next_hour_to_find = 5 # for 5am

# what's the equation to produce 3/29 5am?

I'd like something flexible so that if next_hour_to_find = 14 then the function would be able to find the next 2pm. No worries about time zone, this is all within the scope of the time zone of the @object.created_at.

My current thinking is below, but I feel like there's a cleaner way...

if @object.created_at.hour > next_hour_to_find
  # the next X hour is always going to occur on the next date
  date = (@object.created_at + 1.days).strftime(...) # get the date out
else
  # the next X hour is always going to occur on the same date
  date = (@object.created_at).strftime(...) # get the date out
end

# now that we have a date in a string, we have to append that string with the next_hour_to_find
# not sure if below works for both single and double digit hours
string = date + next_hour_to_find + ":00:00"

# finish by returning Time object, but this seems suuuuper inefficient since we converted to string and then back again
return Time.parse(string)

Body:
How about the following?

def next_hour_from(time, next_hour_to_find)
  hour_on_day_of_time = next_hour_to_find.hours.since( time.beginning_of_day )
  hour_on_day_of_time < time ? 1.day.since(hour_on_day_of_time) : hour_on_day_of_time
end

# e.g.
next_hour_from(@object.created_at, 5) # @object.created_at #=> 2017-03-28 21:00:00
# => 2017-03-29 05:00:00

Basically what it does is:

It looks at the time at the beginning of the day of time, and adds next_hour_to_find to it, in hours. Assigns that value to hour_on_day_of_time.

Then checks to see if that hour_on_day_of_time is before or after the given time. If it's after, then the method can just return hour_on_day_of_time. If it's before, it adds 1 day to hour_on_day_of_time and returns that.


来源: stackexchange

问:
How can multi-touch be used in uiautomator?
I haven't found any way to automate multi-touch movements in uiautomator tests

Given it's framework of com.android.uiautomator.* classes, how can I automate multi-touch movements?

答:
You can use pinchOut / pinchIn methods to do Zoom out and Zoom in. Or use Multitouch gestures as JulianHarty pointed out if you want more fine-grained control.</p>
```<code>UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
        device.findObject(uiSelector).pinchOut(percent, steps);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use pinchOut / pinchIn methods to do Zoom out and Zoom in. Or use Multitouch gestures as JulianHarty pointed out if you want more fine-grained control.

UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
        device.findObject(uiSelector).pinchOut(percent, steps);

ContentLicense: CC BY-SA 4.0


问:
Array in Controller laravel
Can anyone help me to fix my code ? i've the concept but dont know how to write them into code in controller

```<code>$temp=DB::table('temporary')->get();

    //dd($temp);
    if($temp['tahun'] < 'current year'){
        $temp['tahun'] = 'current year';
        $temp['nomor'] = 'nomor+1';
        $keluhan->no_laporan = $temp['nomor'];
    } else {
        $temp['nomor']++;
    }
</code>```

Condition :
my table temporary has 2 attribute tahun(value=2017 int) and nomor (value=1 int)
i want to check if my tahun < this current year (real time year, idk the code so i write current year) then my tahun become = this curent year AND my nomor++ (+1 from its value first) how do i wrte them into laravel code ? please kindly help, thank you buddy

答:
DB::table('temporary')->->get() will return a collection. and from your code, it seems you are working with single column, you can use first().

For date can use simple date() function.

```<code>$temp=DB::table('temporary')->first();

//dd($temp);
if($temp->tahun < date("Y")){
    $temp->tahun = date("Y");
    $temp->nomor++;
    $keluhan->no_laporan = $temp->nomor;
} else {
    $temp->nomor++;
}
</code>```

Title: Array in Controller laravel

Body:
Can anyone help me to fix my code ? i've the concept but dont know how to write them into code in controller

$temp=DB::table('temporary')->get();

    //dd($temp);
    if($temp['tahun'] < 'current year'){
        $temp['tahun'] = 'current year';
        $temp['nomor'] = 'nomor+1';
        $keluhan->no_laporan = $temp['nomor'];
    } else {
        $temp['nomor']++;
    }

Condition :
my table temporary has 2 attribute tahun(value=2017 int) and nomor (value=1 int)
i want to check if my tahun < this current year (real time year, idk the code so i write current year) then my tahun become = this curent year AND my nomor++ (+1 from its value first) how do i wrte them into laravel code ? please kindly help, thank you buddy

Body:
DB::table('temporary')->->get() will return a collection. and from your code, it seems you are working with single column, you can use first().

For date can use simple date() function.

$temp=DB::table('temporary')->first();

//dd($temp);
if($temp->tahun < date("Y")){
    $temp->tahun = date("Y");
    $temp->nomor++;
    $keluhan->no_laporan = $temp->nomor;
} else {
    $temp->nomor++;
}


问:
Accessing individual fields in Drupal 8 views templates
I'm having trouble doing something that I think should be relatively simple drupal 8 views.

I have a content type called Countries. I would like to display the 3 latest country nodes on my homepage in a views block. Each country is displayed with the class "views-row" on the container div. I am using views--view--unformatted--countries--block_1.tpl to template the output.

I would like to output something like the following markup:

```<code><a class="view-row-1" href="/link/to/node">
    <img src="source-of-teaser-image.png">
    <h3>Title of node</h3>
</a>

<a class="view-row-2" href="/link/to/node">
    <img src="source-of-teaser-image.png">
    <h3>Title of node</h3>
</a>

<a class="view-row-3" href="/link/to/node">
    <img src="source-of-teaser-image.png">
    <h3>Title of node</h3>
</a>
</code>```

The problem I'm having is accessing individual fields in the template. If I use a view mode, I can access individual fields. If I select "show fields" in the view, I can add a field for "view result counter" and "path", which would allow me to add the "view-row-N" class and link the a tag to the node, but I can't get access to the fields individually. I have the {{row.content}} variable, but any attempt to dig further into the variable (eg row.content.field_name) gives me nothing and calling a {{dump(row.content)}} crashes the website.

I can't output this as a view mode for 2 reasons. I don't have access to the "view result counter" or "path" fields in a view mode and, even if I had these variables, some fields would be nested inside others (The image and title are nested inside the )

I feel this should really be as simple as

```<code><a class="view-row-{{ row.content.view_result_counter }}" href="{{ row.content.path }}">
</code>```

etc but I've tried everything I can think of. Am I completely on the wrong path? Twig and I are not getting along so far...

答:
I have figured a way using kint.

Inside your views-view-unformatted.html.twig use the following code to display your individual fields:

```<code>{% for row in rows %}

{{ row.content['#view'].style_plugin.render_tokens[ loop.index0 ]['{{ YOUR_FIELD_NAME }}'] }}

{% endfor %}
</code>```

Body:
I'm having trouble doing something that I think should be relatively simple drupal 8 views.

I have a content type called Countries. I would like to display the 3 latest country nodes on my homepage in a views block. Each country is displayed with the class "views-row" on the container div. I am using views--view--unformatted--countries--block_1.tpl to template the output.

I would like to output something like the following markup:

Title of node

Title of node

Title of node

The problem I'm having is accessing individual fields in the template. If I use a view mode, I can access individual fields. If I select "show fields" in the view, I can add a field for "view result counter" and "path", which would allow me to add the "view-row-N" class and link the a tag to the node, but I can't get access to the fields individually. I have the {{row.content}} variable, but any attempt to dig further into the variable (eg row.content.field_name) gives me nothing and calling a {{dump(row.content)}} crashes the website.

I can't output this as a view mode for 2 reasons. I don't have access to the "view result counter" or "path" fields in a view mode and, even if I had these variables, some fields would be nested inside others (The image and title are nested inside the )

I feel this should really be as simple as

etc but I've tried everything I can think of. Am I completely on the wrong path? Twig and I are not getting along so far...

Body:
I have figured a way using kint.

Inside your views-view-unformatted.html.twig use the following code to display your individual fields:

{% for row in rows %}

{{ row.content['#view'].style_plugin.render_tokens[ loop.index0 ]['{{ YOUR_FIELD_NAME }}'] }}

{% endfor %}


问:
The simplest way to cut off unnecessary dots in octave/matlab
I have coordinates of dots (x,y) stored in 1206x2 matrix called data. The command plot(data(:,1),data(:,2)) gives that picture:

I've found maximums in my data with findpeaks command:

```<code>[pks,loc,smth] = findpeaks(data(:,2));
</code>```

And then plot them on previous graph:

```<code>plot(mod(:,1),mod(:,2),mod(loc,1),pks,'o')
</code>```

So, the question is: what is the simplest way to cut off maximums which I do not need, I mean the maximums below red line on this picture:

UPD:
The best way I've found by now is to use "MinPeakDistance" parameter.

答:
The easiest way to skip points in a plot is to make them NaN. I am going to assume that you have a variable redline with Y values for all the X values you have such that redline(loc) is going to return the cutoff at the peaks locations. You can ignore peaks beyond the curve as:

```<code>>>pks(pks < redline(loc)) = NaN
>>plot(mod(:,1),mod(:,2),mod(loc,1),pks,'o')
</code>```

Body:
I have coordinates of dots (x,y) stored in 1206x2 matrix called data. The command plot(data(:,1),data(:,2)) gives that picture:

I've found maximums in my data with findpeaks command:

[pks,loc,smth] = findpeaks(data(:,2));

And then plot them on previous graph:

plot(mod(:,1),mod(:,2),mod(loc,1),pks,'o')

So, the question is: what is the simplest way to cut off maximums which I do not need, I mean the maximums below red line on this picture:

UPD:
The best way I've found by now is to use "MinPeakDistance" parameter.

Body:
The easiest way to skip points in a plot is to make them NaN. I am going to assume that you have a variable redline with Y values for all the X values you have such that redline(loc) is going to return the cutoff at the peaks locations. You can ignore peaks beyond the curve as:

>>pks(pks < redline(loc)) = NaN
>>plot(mod(:,1),mod(:,2),mod(loc,1),pks,'o')


问:
How to properly dispose of a WebResponse instance?
Normally, one writes code something like this to download some data using a WebRequest.

```<code>using(WebResponse resp = request.GetResponse())  // WebRequest request...
   using(Stream str = resp.GetResponseStream())
      ; // do something with the stream str
</code>```

Now if a WebException is thrown, the WebException has a reference to the WebResponse object, which may or may not have Dispose called (depending on where the exception has happened, or how the response class is implemented) - I don't know.

My question is how one is supposed to deal with this. Is one supposed to be coding very defensively, and dispose of the response in the WebException object (that would be a little weird, as WebException is not IDisposable). Or is one supposed to ignore this, potentially accessing a disposed object or never disposing an IDisposable object?
The example given in the MSDN documentation for WebException.Response is wholly inadequate.

答:
HttpWebRequest internally makes a memory stream off the underlying network stream before throwing WebException, so there is no unmanaged resource associated with the WebResponse returned from WebException.Response.

This makes it unnecessary to call Dispose() on it. In fact, trying to dispose WebException.Response can cause headache and issues because you may have callers of your code that is attempting to read properties associated with it.

However it is a good practice that you should dispose any IDisposable objects you own. If you decide to do so, make sure you don't have code depending on being able to read WebException.Response properties and/or its stream. The best way would be you handle the exception and throw new type of exception so that you don't leak WebException up to the caller when possible.

And also consider moving to HttpClient which replaces HttpWebRequest.

Disclaimer: No warranty implied.

ContentLicense: CC BY-SA 2.5

Body:
Normally, one writes code something like this to download some data using a WebRequest.

using(WebResponse resp = request.GetResponse())  // WebRequest request...
   using(Stream str = resp.GetResponseStream())
      ; // do something with the stream str

Now if a WebException is thrown, the WebException has a reference to the WebResponse object, which may or may not have Dispose called (depending on where the exception has happened, or how the response class is implemented) - I don't know.

My question is how one is supposed to deal with this. Is one supposed to be coding very defensively, and dispose of the response in the WebException object (that would be a little weird, as WebException is not IDisposable). Or is one supposed to ignore this, potentially accessing a disposed object or never disposing an IDisposable object?
The example given in the MSDN documentation for WebException.Response is wholly inadequate.


问:
Could build module 'AFNetworking' in cocoapods
I use the Cocoapods modular project to import private pod,
the O2OIntegrationModules pod can not successfully import AFNetworking in the Pod Project in Workspace, causing the main project to compile failed, but SDWebImage and other libraries can be successful.

Pod version   : 1.2.0

Xcode version : 8.2.1

MacOS version : 10.12

Modular

O2OIntegrationModules dependency O2OIntegrationHelps

O2OIntegrationHelps dependency O2OKit

O2OKit dependcy AFNetworking SDWebImage MJRefresh

I tried to delete all files inside the ModuleCache folder and pod deintegrate, pod clean, pod reinstall, restart Xcode, restart Mac, but has
always failed to compile.

this my error message:

Anyone ever encountered this problem?  help me, please.

答:
I resolved, because the podspec configuration out of the problem, not configured s.homepage s.xxx.target s.platform

```<code>s.platform     = :ios, "8.0"
s.ios.deployment_target = "8.0"
</code>```

Stupid!!!

Body:
I resolved, because the podspec configuration out of the problem, not configured s.homepage s.xxx.target s.platform

s.platform     = :ios, "8.0"
s.ios.deployment_target = "8.0"

Stupid!!!


问:
Error type mismatch, java.lang.String[][] does not match with java.lang.String[]
```<code>Table table;
String N;
String F;
String data;
String[] test = new String[1];
String stringcolumn;

//Here is where I assign all the variables.

void setup() {

  table = loadTable("CVSTEST.csv", "header");
  int rows = table.getRowCount();
  int columns = table.getColumnCount();

  //Get the row count and the table

  for(int column = 0; column <= columns; column++){
    for(int row = 0; row <= rows; row++){

          //For every row in every column, assign data the input for later use

          data = table.getString(rows,columns);
          stringcolumn = Integer.toString(column);
          test = new String[stringcolumn][data];

          //Here is where the error occurs, I try to assign string column and data to the string array of test.

    }
  }
}
</code>```

So I've been stuck on this one for a while. I am making a program that prints out data as you put it in the table, E.G

```<code>Name Score
Tim  513
</code>```

but I keep running into this error. I am saving as a float in order to keep it organised, and so printing it out is easier in the future, and I can use the data in later code, and use it for comparisons later. Cheers.

答:
I don't really understand why you're going through an array. The Table class already contains functions that allow you to access the data from an index. But even if you're trying to do something slightly different, hopefully this helps:

You've got a few problems. First off:

```<code>String[] test = new String[1];
</code>```

This declares your test variable to be a one-dimensional String array, with a length of 1, which doesn't make a ton of sense: why do you need an array if it's only going to store a single value?

If you want to declare it as a two-dimensional String array, you would do this:

```<code>String[][] test;
</code>```

Note that this declares the array, but it doesn't initialize it yet. To initialize it, you probably want to know the size of the 2D array. I'm assuming you want to use the column and row count from the table? If so, you would do this:

```<code>void setup() {

  table = loadTable("CVSTEST.csv", "header");
  int rows = table.getRowCount();
  int columns = table.getColumnCount();

  test = new String[rows][columns];
</code>```

Now your test variable is a two-dimensional array, which you can think of as an array of arrays.

Next, this line makes no sense:

```<code>test = new String[stringcolumn][data];
</code>```

What are you trying to do here? Since this is inside your nested for loop, this is trying to create a new two-dimensional array for each cell in the table. I would guess that what you really want to do is have one two-dimensional array, and you'd populate its indexes inside this nested for loop. Something like this:

```<code>test[row][column] = data;
</code>```

This sets the index at position [row][column] equal to whatever String is in the data variable.

Body:
Table table;
String N;
String F;
String data;
String[] test = new String[1];
String stringcolumn;

//Here is where I assign all the variables.

void setup() {

  table = loadTable("CVSTEST.csv", "header");
  int rows = table.getRowCount();
  int columns = table.getColumnCount();

  //Get the row count and the table

  for(int column = 0; column <= columns; column++){
    for(int row = 0; row <= rows; row++){

          //For every row in every column, assign data the input for later use

          data = table.getString(rows,columns);
          stringcolumn = Integer.toString(column);
          test = new String[stringcolumn][data];

          //Here is where the error occurs, I try to assign string column and data to the string array of test.

    }
  }
}

So I've been stuck on this one for a while. I am making a program that prints out data as you put it in the table, E.G

Name Score
Tim  513

but I keep running into this error. I am saving as a float in order to keep it organised, and so printing it out is easier in the future, and I can use the data in later code, and use it for comparisons later. Cheers.

Body:
I don't really understand why you're going through an array. The Table class already contains functions that allow you to access the data from an index. But even if you're trying to do something slightly different, hopefully this helps:

You've got a few problems. First off:

String[] test = new String[1];

This declares your test variable to be a one-dimensional String array, with a length of 1, which doesn't make a ton of sense: why do you need an array if it's only going to store a single value?

If you want to declare it as a two-dimensional String array, you would do this:

String[][] test;

Note that this declares the array, but it doesn't initialize it yet. To initialize it, you probably want to know the size of the 2D array. I'm assuming you want to use the column and row count from the table? If so, you would do this:

void setup() {

  table = loadTable("CVSTEST.csv", "header");
  int rows = table.getRowCount();
  int columns = table.getColumnCount();

  test = new String[rows][columns];

Now your test variable is a two-dimensional array, which you can think of as an array of arrays.

Next, this line makes no sense:

test = new String[stringcolumn][data];

What are you trying to do here? Since this is inside your nested for loop, this is trying to create a new two-dimensional array for each cell in the table. I would guess that what you really want to do is have one two-dimensional array, and you'd populate its indexes inside this nested for loop. Something like this:

test[row][column] = data;

This sets the index at position [row][column] equal to whatever String is in the data variable.


问:
Python OpenGL - Issues displaying 2d graphics over a 3d scene
My goal is to display a static triangle over a rotated cube using PyOpenGL. However, I had no luck in achieving the result I wanted; instead, I am left with a blank screen. I had tested both the cube and triangle with their corresponding matrix projections on separate files to make sure that the scene itself wasn't the problem. And sure enough, it wasn't.

Triangle Script

Displays a triangle at the bottom left corner of the screen.

```<code>def reshape(width, height):

    glViewport(0, 0, width, height)
    glClearColor(0.0, 0.0, 0.0, 0.0)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(0, width, 0, height, 0, 0.1)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

#--- func for defining triangle
def drawTriangle():

    ### clear color and depth buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()

    ### draw triangle
    glBegin(GL_TRIANGLES)

    glColor3f(0.0, 1.0, 0.0)
    glVertex2f(0, 0)
    glVertex2f(100, 0)
    glVertex2f(0, 100)

    glEnd()
    glutSwapBuffers()

#--- func for main loop
def main():

    window = 0

    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE)
    glutInitWindowSize(640, 480)
    glutInitWindowPosition(200, 200)

    window = glutCreateWindow(b'OpenGL Python Triangle')

    glutReshapeFunc(reshape)
    glutDisplayFunc(drawTriangle)
    glutIdleFunc(drawTriangle)
    glutMainLoop()

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

Cube Script

Displays a cube at the center of the screen.

```<code>def reshape(width, height):

        glClearColor(0.0, 0.0, 0.0, 0.0)
        glClearDepth(1.0)
        glDepthMask(GL_TRUE)
        glDepthFunc(GL_LESS)
        glEnable(GL_DEPTH_TEST)
        glShadeModel(GL_SMOOTH)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45.0, float(width)/float(height), 0.1, 100.0)
        glMatrixMode(GL_MODELVIEW)

#--- func for defining cube
def drawCube():

        ### clear color and depth buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        ### set position and rotation
        glLoadIdentity()
        glTranslatef(0.0,0.0,-6.0)
        glRotatef(30,1.0,0.0,0.0)
        glRotatef(0,0.0,1.0,0.0)
        glRotatef(30,0.0,0.0,1.0)

        ### draw cube
        glBegin(GL_QUADS)

        #/* Long list of vertices

        glEnd()
        glutSwapBuffers()

#--- func for main loop
def main():

        window = 0

        glutInit(sys.argv)
        glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
        glutInitWindowSize(640,480)
        glutInitWindowPosition(200,200)

        window = glutCreateWindow(b'OpenGL Python Cube')

        glutReshapeFunc(reshape)
        glutDisplayFunc(drawCube)
        glutIdleFunc(drawCube)
        glutMainLoop()

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

I believe the problem might be occurring with the depth test but I was unsuccessful in providing any results that proved the idea right. Instead, it might be with organizing the matrix projections. I ordered it so that the 3d scene would render first and then the 2d scene would overlay it.

HUD Script

```<code>#--- 3D projection function
def render3d():

        global width, height

        ### clear buffers
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glViewport(0, 0, width, height)

        ### projection mode
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45.0, float(width)/float(height), 0.1, 100.0)

        ### modelview mode
        glMatrixMode(GL_MODELVIEW)

        ### setup 3d shader
        glDepthFunc(GL_LESS)
        glEnable(GL_DEPTH_TEST)
        glShadeModel(GL_SMOOTH)

#--- 2D projection function
def render2d():

        global width, height

        ### projection mode
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluOrtho2D(0.0, width, height, 0.0)

        ### modelview mode
        glMatrixMode(GL_MODELVIEW)

        ### setup 2d shader
        glDisable(GL_DEPTH_TEST)

#--- reshape function
def reshape(new_width, new_height):

        global width, height

        ### apply new window size
        width = new_width
        height = new_height

#--- 3D cube function
def scene3d():

        ### setup polygon location & orientation
        glTranslatef(0.0, 0.0, -6.0)
        glRotatef(30, 1.0, 0.0, 0.0)
        glRotatef(0, 1.0, 1.0, 0.0)
        glRotatef(30, 0.0, 0.0, 1.0)

        ### draw cube
        glBegin(GL_QUADS)

        glColor3f(0.0,1.0,0.0)
        glVertex3f( 1.0, 1.0,-1.0)
        glVertex3f(-1.0, 1.0,-1.0)
        glVertex3f(-1.0, 1.0, 1.0)
        glVertex3f( 1.0, 1.0, 1.0)

        glColor3f(1.0,0.0,0.0)
        glVertex3f( 1.0,-1.0, 1.0)
        glVertex3f(-1.0,-1.0, 1.0)
        glVertex3f(-1.0,-1.0,-1.0)
        glVertex3f( 1.0,-1.0,-1.0)

        glColor3f(0.0,1.0,1.0)
        glVertex3f( 1.0, 1.0, 1.0)
        glVertex3f(-1.0, 1.0, 1.0)
        glVertex3f(-1.0,-1.0, 1.0)
        glVertex3f( 1.0,-1.0, 1.0)

        glColor3f(1.0,1.0,0.0)
        glVertex3f( 1.0,-1.0,-1.0)
        glVertex3f(-1.0,-1.0,-1.0)
        glVertex3f(-1.0, 1.0,-1.0)
        glVertex3f( 1.0, 1.0,-1.0)

        glColor3f(0.0,0.0,1.0)
        glVertex3f(-1.0, 1.0, 1.0)
        glVertex3f(-1.0, 1.0,-1.0)
        glVertex3f(-1.0,-1.0,-1.0)
        glVertex3f(-1.0,-1.0, 1.0)

        glColor3f(1.0,0.0,1.0)
        glVertex3f( 1.0, 1.0,-1.0)
        glVertex3f( 1.0, 1.0, 1.0)
        glVertex3f( 1.0,-1.0, 1.0)
        glVertex3f( 1.0,-1.0,-1.0)

        glEnd()

#--- 2D triangle function
def scene2d():

        ### draw triangle
        glBegin(GL_TRIANGLES)

        glColor3f(0.0, 1.0, 0.0)
        glVertex2f(0, 0)
        glVertex2f(100, 0)
        glVertex2f(0, 100)

        glEnd()

#--- draw function
def draw():

        ### 3D scene
        render3d()
        scene3d()

        ### 2D scene
        glPushMatrix()

        render2d()
        scene2d()

        glPopMatrix()

        ### swap buffers
        glutSwapBuffers()

#--- main loop function
def main():

        window = 0

        glutInit(sys.argv)
        glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
        glutInitWindowSize(640,480)
        glutInitWindowPosition(200,200)

        window = glutCreateWindow(b'OpenGL Python HUD')

        glutReshapeFunc(reshape)
        glutDisplayFunc(draw)
        glutIdleFunc(draw)
        glutMainLoop()

#--- only run if this is the main module
if __name__ == "__main__":
        main()
</code>```

To explain, I defined two matrix projection functions: one for the 3d scene (render3d) and the other for the 2d scene (render2d). The next function (reshape) is to obtain the current window size so that I can input it into the proportions for the matrix projections. The following function (scene3d) creates the cube and sets it at the center of the scene while (scene2d) creates the triangle and sets it at the bottom left corner of the scene. The (draw) function puts everything in order in which the 3d scene is rendered first and then the 2d scene [which I nested under a push and pop matrix]. Finally, the main function creates the window and starts the loop.

Feedback would be greatly appreciated. Thank you and have a nice day!

答:
Inside draw() consider this for a second:

```<code>def draw():
    render3d()
    scene3d()

    glPushMatrix()
    render2d()
    scene2d()
    glPopMatrix()
</code>```

Noticing anything missing?

There should be a glPushMatrix() and glPopMatrix() around the other part as well:

```<code>def draw():
    glPushMatrix()
    render3d()
    scene3d()
    glPopMatrix()

    glPushMatrix()
    render2d()
    scene2d()
    glPopMatrix()
</code>```

The reason you're seeing a black screen is because within scene3d() you're calling glTranslatef(). So everything within milliseconds of starting the application gets translated off-screen.

Adding the missing glPushMatrix() and glPopMatrix() and you should see this:

Body:
My goal is to display a static triangle over a rotated cube using PyOpenGL. However, I had no luck in achieving the result I wanted; instead, I am left with a blank screen. I had tested both the cube and triangle with their corresponding matrix projections on separate files to make sure that the scene itself wasn't the problem. And sure enough, it wasn't.

Triangle Script

Displays a triangle at the bottom left corner of the screen.

def reshape(width, height):

    glViewport(0, 0, width, height)
    glClearColor(0.0, 0.0, 0.0, 0.0)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(0, width, 0, height, 0, 0.1)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

#--- func for defining triangle
def drawTriangle():

    ### clear color and depth buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()

    ### draw triangle
    glBegin(GL_TRIANGLES)

    glColor3f(0.0, 1.0, 0.0)
    glVertex2f(0, 0)
    glVertex2f(100, 0)
    glVertex2f(0, 100)

    glEnd()
    glutSwapBuffers()

#--- func for main loop
def main():

    window = 0

    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE)
    glutInitWindowSize(640, 480)
    glutInitWindowPosition(200, 200)

    window = glutCreateWindow(b'OpenGL Python Triangle')

    glutReshapeFunc(reshape)
    glutDisplayFunc(drawTriangle)
    glutIdleFunc(drawTriangle)
    glutMainLoop()

if __name__ == '__main__':
    main()

Cube Script

Displays a cube at the center of the screen.

def reshape(width, height):

        glClearColor(0.0, 0.0, 0.0, 0.0)
        glClearDepth(1.0)
        glDepthMask(GL_TRUE)
        glDepthFunc(GL_LESS)
        glEnable(GL_DEPTH_TEST)
        glShadeModel(GL_SMOOTH)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45.0, float(width)/float(height), 0.1, 100.0)
        glMatrixMode(GL_MODELVIEW)

#--- func for defining cube
def drawCube():

        ### clear color and depth buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        ### set position and rotation
        glLoadIdentity()
        glTranslatef(0.0,0.0,-6.0)
        glRotatef(30,1.0,0.0,0.0)
        glRotatef(0,0.0,1.0,0.0)
        glRotatef(30,0.0,0.0,1.0)

        ### draw cube
        glBegin(GL_QUADS)

        #/* Long list of vertices

        glEnd()
        glutSwapBuffers()

#--- func for main loop
def main():

        window = 0

        glutInit(sys.argv)
        glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
        glutInitWindowSize(640,480)
        glutInitWindowPosition(200,200)

        window = glutCreateWindow(b'OpenGL Python Cube')

        glutReshapeFunc(reshape)
        glutDisplayFunc(drawCube)
        glutIdleFunc(drawCube)
        glutMainLoop()

if __name__ == "__main__":
        main()

I believe the problem might be occurring with the depth test but I was unsuccessful in providing any results that proved the idea right. Instead, it might be with organizing the matrix projections. I ordered it so that the 3d scene would render first and then the 2d scene would overlay it.

HUD Script

#--- 3D projection function
def render3d():

        global width, height

        ### clear buffers
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glViewport(0, 0, width, height)

        ### projection mode
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45.0, float(width)/float(height), 0.1, 100.0)

        ### modelview mode
        glMatrixMode(GL_MODELVIEW)

        ### setup 3d shader
        glDepthFunc(GL_LESS)
        glEnable(GL_DEPTH_TEST)
        glShadeModel(GL_SMOOTH)

#--- 2D projection function
def render2d():

        global width, height

        ### projection mode
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluOrtho2D(0.0, width, height, 0.0)

        ### modelview mode
        glMatrixMode(GL_MODELVIEW)

        ### setup 2d shader
        glDisable(GL_DEPTH_TEST)

#--- reshape function
def reshape(new_width, new_height):

        global width, height

        ### apply new window size
        width = new_width
        height = new_height

#--- 3D cube function
def scene3d():

        ### setup polygon location & orientation
        glTranslatef(0.0, 0.0, -6.0)
        glRotatef(30, 1.0, 0.0, 0.0)
        glRotatef(0, 1.0, 1.0, 0.0)
        glRotatef(30, 0.0, 0.0, 1.0)

        ### draw cube
        glBegin(GL_QUADS)

        glColor3f(0.0,1.0,0.0)
        glVertex3f( 1.0, 1.0,-1.0)
        glVertex3f(-1.0, 1.0,-1.0)
        glVertex3f(-1.0, 1.0, 1.0)
        glVertex3f( 1.0, 1.0, 1.0)

        glColor3f(1.0,0.0,0.0)
        glVertex3f( 1.0,-1.0, 1.0)
        glVertex3f(-1.0,-1.0, 1.0)
        glVertex3f(-1.0,-1.0,-1.0)
        glVertex3f( 1.0,-1.0,-1.0)

        glColor3f(0.0,1.0,1.0)
        glVertex3f( 1.0, 1.0, 1.0)
        glVertex3f(-1.0, 1.0, 1.0)
        glVertex3f(-1.0,-1.0, 1.0)
        glVertex3f( 1.0,-1.0, 1.0)

        glColor3f(1.0,1.0,0.0)
        glVertex3f( 1.0,-1.0,-1.0)
        glVertex3f(-1.0,-1.0,-1.0)
        glVertex3f(-1.0, 1.0,-1.0)
        glVertex3f( 1.0, 1.0,-1.0)

        glColor3f(0.0,0.0,1.0)
        glVertex3f(-1.0, 1.0, 1.0)
        glVertex3f(-1.0, 1.0,-1.0)
        glVertex3f(-1.0,-1.0,-1.0)
        glVertex3f(-1.0,-1.0, 1.0)

        glColor3f(1.0,0.0,1.0)
        glVertex3f( 1.0, 1.0,-1.0)
        glVertex3f( 1.0, 1.0, 1.0)
        glVertex3f( 1.0,-1.0, 1.0)
        glVertex3f( 1.0,-1.0,-1.0)

        glEnd()

#--- 2D triangle function
def scene2d():

        ### draw triangle
        glBegin(GL_TRIANGLES)

        glColor3f(0.0, 1.0, 0.0)
        glVertex2f(0, 0)
        glVertex2f(100, 0)
        glVertex2f(0, 100)

        glEnd()

#--- draw function
def draw():

        ### 3D scene
        render3d()
        scene3d()

        ### 2D scene
        glPushMatrix()

        render2d()
        scene2d()

        glPopMatrix()

        ### swap buffers
        glutSwapBuffers()

#--- main loop function
def main():

        window = 0

        glutInit(sys.argv)
        glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
        glutInitWindowSize(640,480)
        glutInitWindowPosition(200,200)

        window = glutCreateWindow(b'OpenGL Python HUD')

        glutReshapeFunc(reshape)
        glutDisplayFunc(draw)
        glutIdleFunc(draw)
        glutMainLoop()

#--- only run if this is the main module
if __name__ == "__main__":
        main()

To explain, I defined two matrix projection functions: one for the 3d scene (render3d) and the other for the 2d scene (render2d). The next function (reshape) is to obtain the current window size so that I can input it into the proportions for the matrix projections. The following function (scene3d) creates the cube and sets it at the center of the scene while (scene2d) creates the triangle and sets it at the bottom left corner of the scene. The (draw) function puts everything in order in which the 3d scene is rendered first and then the 2d scene [which I nested under a push and pop matrix]. Finally, the main function creates the window and starts the loop.

Feedback would be greatly appreciated. Thank you and have a nice day!

Body:
Inside draw() consider this for a second:

def draw():
    render3d()
    scene3d()

    glPushMatrix()
    render2d()
    scene2d()
    glPopMatrix()

Noticing anything missing?

There should be a glPushMatrix() and glPopMatrix() around the other part as well:

def draw():
    glPushMatrix()
    render3d()
    scene3d()
    glPopMatrix()

    glPushMatrix()
    render2d()
    scene2d()
    glPopMatrix()

The reason you're seeing a black screen is because within scene3d() you're calling glTranslatef(). So everything within milliseconds of starting the application gets translated off-screen.

Adding the missing glPushMatrix() and glPopMatrix() and you should see this:


问:
How to do a nested if else statement in ReactJS JSX?
I wanted to know if its possible to do nested if else if in ReactJS JSX?

I have tried various different ways and I am unable to get it to work.

I am looking for

```<code>if (x) {
  loading screen
} else {
  if (y) {
    possible title if we need it
  }
  main
}
</code>```

I have tried this but I can not get it to render.  I have tried various ways.  It always breaks once I add the nested if.

```<code>{
  this.state.loadingPage ? (
    <div>loading page</div>
  ) : (
    <div>
      this.otherCondition && <div>title</div>
      <div>body</div>
    </div>
  );
}
</code>```

Update

I ended up choosing the solution to move this to renderContent and call the function.  Both of the answers did work though.  I think I may use the inline solution if it is for a simple render and renderContent for more complicated cases.

Thank you

答:
Instead of nesting ternary operators as it is often suggested or creating a separate function that will not be reused anywhere else, you can simply call an inline expression:</p>

```<code><div className="some-container">
{
   (() => {
       if (conditionOne)
          return <span>One</span>
       if (conditionTwo)
          return <span>Two</span>
       else (conditionOne)
          return <span>Three</span>
   })()
}
</div>
</code>```

Body:
I wanted to know if its possible to do nested if else if in ReactJS JSX?

I have tried various different ways and I am unable to get it to work.

I am looking for

if (x) {
  loading screen
} else {
  if (y) {
    possible title if we need it
  }
  main
}

I have tried this but I can not get it to render.  I have tried various ways.  It always breaks once I add the nested if.

{
  this.state.loadingPage ? (

loading page

  ) : (

      this.otherCondition &&
title

body

  );
}

Update

I ended up choosing the solution to move this to renderContent and call the function.  Both of the answers did work though.  I think I may use the inline solution if it is for a simple render and renderContent for more complicated cases.

Thank you

Body:
Instead of nesting ternary operators as it is often suggested or creating a separate function that will not be reused anywhere else, you can simply call an inline expression:

<div className="some-container">
{
   (() => {
       if (conditionOne)
          return <span>One</span>
       if (conditionTwo)
          return <span>Two</span>
       else (conditionOne)
          return <span>Three</span>
   })()
}
</div>


问:
Is there any difference between $.trim and trim?
I have this simple example below which uses trim. As per the title of the question, is there any difference between them?. As you can see below they have the same output. If the answer is "No", which one is much better to use?

Currently I use .trim() because it's my first time seeing $.trim().

var SampleTrim = '     TRIM         ';

console.log(SampleTrim.trim());
console.log($.trim(SampleTrim));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

答:
String.prototype.trim is not available below IE9, otherwise they are the same.

The recommended String.prototype.trim polyfill on MDN is exactly the same as that used in jQuery source.

In most cases, the native implementation would be faster to use. This JSPerf by Sumit Gulati suggests that too.

Realistically, the difference in performance would be quite negligible and I wouldn't base my decision on performance. However, it would be better to use the native implementation so that there's no dependency on jQuery. The large websites have dropped support for IE8 and I think it's safe to follow suit (:


问:
How do I get the data model in ios 9?
I'm trying to run this project in ios 9.3 on an iphone 4s. It's a snapchat clone on github.

https://github.com/Kesoyuh/simple-snapchat

This code gives me an error in ios 9.3, but works on the simulator (ios 10).

```<code>func getContext() -> NSManagedObjectContext {
        var context: NSManagedObjectContext?

        if #available(iOS 10.0, *) {
            context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        } else {
            // iOS 9.0 and below - however you were previously handling it
            guard let modelURL = Bundle.main.url(forResource: "Model", withExtension:"momd") else {
                fatalError("Error loading model from bundle")
            }
            guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
                fatalError("Error initializing mom from: \(modelURL)")
            }
            let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
            context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
            let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            let docURL = urls[urls.endIndex-1]
            let storeURL = docURL.appendingPathComponent("Model.sqlite")
            do {
                try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
            } catch {
                fatalError("Error migrating store: \(error)")
            }

        }
        return context!
    }
</code>```

The problem is where it says "iOS 9.0 and below" where it says Bundle.main.url it's returning that error there:  "Error loading model from bundle".  I have never messed with any of this model / bundle stuff and was wondering if anyone could help with this?  I really want it to work on my iphone so i can see/use the camera part because that doesn't work on the simulator. Thanks in advance!

答:
If you want to run your code on iPhone 4s then you need to set iOS deployment target accordingly that are supported by iPhone 4s, Currently you set iOS deployment target 9.3 that are not supported by iPhone 4s. Set your Project iOS Deployment target as 8.0,

Steps:- Click on Project -> Info -> iOS Deployment target.

Hope this will help you.

Title: How do I get the data model in ios 9?

Body:
I'm trying to run this project in ios 9.3 on an iphone 4s. It's a snapchat clone on github.

https://github.com/Kesoyuh/simple-snapchat

This code gives me an error in ios 9.3, but works on the simulator (ios 10).

func getContext() -> NSManagedObjectContext {
        var context: NSManagedObjectContext?

        if #available(iOS 10.0, *) {
            context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        } else {
            // iOS 9.0 and below - however you were previously handling it
            guard let modelURL = Bundle.main.url(forResource: "Model", withExtension:"momd") else {
                fatalError("Error loading model from bundle")
            }
            guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
                fatalError("Error initializing mom from: \(modelURL)")
            }
            let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
            context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
            let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            let docURL = urls[urls.endIndex-1]
            let storeURL = docURL.appendingPathComponent("Model.sqlite")
            do {
                try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
            } catch {
                fatalError("Error migrating store: \(error)")
            }

        }
        return context!
    }

The problem is where it says "iOS 9.0 and below" where it says Bundle.main.url it's returning that error there:  "Error loading model from bundle".  I have never messed with any of this model / bundle stuff and was wondering if anyone could help with this?  I really want it to work on my iphone so i can see/use the camera part because that doesn't work on the simulator. Thanks in advance!


问:
how to sort numerical arraylist in ascending order
I have an ArrayList which I have sorted using Collections.sort.
But the outcome looks like down below. How do I get it to be ascending order?

[0, 1, 11, 12, 12, 13, 13, 14, 14, 16, 16, 16, 17, 17, 17, 18, 18, 19, 2, 2, 20, 20, 20, 21, 21, 22, 4, 7, 7, 7, 8, 9, 9, 9, 9, 9]

答:
Looks like your ArrayList contains strings instead of numbers. You can sort it in numerical order by passing a custom Comparator to the sort() method.

In java 8, you can use Comparator.comparingInt() to do the actual comparision, in combination with the Integer.parseInt() method to perform the conversion from string to int:

```<code>ArrayList<String> list = new ArrayList<>();
// ... add values

list.sort(Comparator.comparingInt(Integer::parseInt));
</code>```

Body:
Looks like your ArrayList contains strings instead of numbers. You can sort it in numerical order by passing a custom Comparator to the sort() method.

In java 8, you can use Comparator.comparingInt() to do the actual comparision, in combination with the Integer.parseInt() method to perform the conversion from string to int:

ArrayList<String> list = new ArrayList<>();
// ... add values

list.sort(Comparator.comparingInt(Integer::parseInt));


问:
geom_raster() normal distrubution
I have been trying to understand geom_raster(). As a simple example I wanted to visualize something like normal distribution as a raster. I used the following code.

```<code>v1 <- rnorm(n=50)
v2 <- rnorm(n=50)
v3 <- rnorm(n=50)
vs <- tibble(v1,v2,v3)
ggplot(vs, aes(v1, v2)) +
 geom_raster(aes(fill = v3))
</code>```

I ended up with the following:

I was expected something like the following image

答:
geom_raster is for when you have one value for each rectangle. I think you're looking for something like geom_bin2d, but you'll need more data, and you likely won't get any data for areas far from the modes:

ggplot(data.frame(v1 = rnorm(10000),
                  v2 = rnorm(10000)),
       aes(x = v1, y = v2)) +
    geom_bin2d()
```

<p><img src="https://i.imgur.com/XGON0JW.png" alt=""></p>

<p>If the sharpness of the corners bothers, you, <code>geom_hex</code> is a nice alternative that leaves isolated points looking less pixellated and more like points. <code>geom_density_2d</code> is a common accompaniment to add contour lines.</p>

<p>To use <code>geom_raster</code>, you'd need something more like</p>

<pre class="lang-r prettyprint-override"><code>df <- expand.grid(v1 = seq(-2, 2, .1), v2 = seq(-2, 2, .1))
df$v3 <- dnorm(df$v1) * dnorm(df$v2)

ggplot(df, aes(v1, v2, fill = v3)) + geom_raster()
</code>```

geom_contour can be used as an accompaniment to show contour lines. It requires a z aesthetic instead of fill, but otherwise works like geom_raster.

Title: geom_raster() normal distrubution

Body:
I have been trying to understand geom_raster(). As a simple example I wanted to visualize something like normal distribution as a raster. I used the following code.

v1 <- rnorm(n=50)
v2 <- rnorm(n=50)
v3 <- rnorm(n=50)
vs <- tibble(v1,v2,v3)
ggplot(vs, aes(v1, v2)) +
 geom_raster(aes(fill = v3))

I ended up with the following:

I was expected something like the following image

Body:
geom_raster is for when you have one value for each rectangle. I think you're looking for something like geom_bin2d, but you'll need more data, and you likely won't get any data for areas far from the modes:

ggplot(data.frame(v1 = rnorm(10000),
                  v2 = rnorm(10000)),
       aes(x = v1, y = v2)) +
    geom_bin2d()

If the sharpness of the corners bothers, you, geom_hex is a nice alternative that leaves isolated points looking less pixellated and more like points. geom_density_2d is a common accompaniment to add contour lines.

To use geom_raster, you'd need something more like

df <- expand.grid(v1 = seq(-2, 2, .1), v2 = seq(-2, 2, .1))
df$v3 <- dnorm(df$v1) * dnorm(df$v2)

ggplot(df, aes(v1, v2, fill = v3)) + geom_raster()

geom_contour can be used as an accompaniment to show contour lines. It requires a z aesthetic instead of fill, but otherwise works like geom_raster.


问:
Set default appearance for a UIView subclass without overriding initialize() in Swift 3.1
I have a subclass of UITextView, which needs to have a specific default appearance. So far, I've been able to achieve this by overriding the initialize() class function, which has been deprecated in Swift 3.1.

```<code>public class CustomTextView : UITextView {
    override public class func initialize() {
        self.appearance().backgroundColor = .green
    }
}
</code>```

Is there a way to achieve the same thing pure Swift?

答:
I'm working around the loss of the class method initialize by using a construct like this:

```<code>class CustomTextView : UITextView {
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame:frame, textContainer: textContainer)
        CustomTextView.doInitialize
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
        CustomTextView.doInitialize
    }
    static let doInitialize : Void = {
        CustomTextView.appearance().backgroundColor = .green
    }()
}
</code>```

This construct has the advantage that doInitialize will be initialized only once, so the code connected with it will run only once (in this case we'll configure the appearance proxy only once); and it is early enough to affect even the first instance created (that is, every CustomTextView you ever make will in fact be green).

Body:
I have a subclass of UITextView, which needs to have a specific default appearance. So far, I've been able to achieve this by overriding the initialize() class function, which has been deprecated in Swift 3.1.

public class CustomTextView : UITextView {
    override public class func initialize() {
        self.appearance().backgroundColor = .green
    }
}

Is there a way to achieve the same thing pure Swift?

Body:
I'm working around the loss of the class method initialize by using a construct like this:

class CustomTextView : UITextView {
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame:frame, textContainer: textContainer)
        CustomTextView.doInitialize
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
        CustomTextView.doInitialize
    }
    static let doInitialize : Void = {
        CustomTextView.appearance().backgroundColor = .green
    }()
}

This construct has the advantage that doInitialize will be initialized only once, so the code connected with it will run only once (in this case we'll configure the appearance proxy only once); and it is early enough to affect even the first instance created (that is, every CustomTextView you ever make will in fact be green).


答:
jQuery's trim() function was available long before JavaScript's native trim() function was added, which is available in browsers above IE9 and the like.

Use the native trim function for future projects.

Title: Is there any difference between $.trim and trim?

Body:
I have this simple example below which uses trim. As per the title of the question, is there any difference between them?. As you can see below they have the same output. If the answer is "No", which one is much better to use?

Currently I use .trim() because it's my first time seeing $.trim().

var SampleTrim = '     TRIM         ';

console.log(SampleTrim.trim());
console.log($.trim(SampleTrim));


答:
As I know, SimpleTrim.trim() is a native way to trim a string that modern brower support.

And $.trim(SimpleTrim) is another way that jQuery help user in the past to trim string, when browser does not support native trim.


问:
How to use functions more than once in a Custom Class
is there anyway to implement the

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {}
</code>```

twice? I am trying to create a conversion app that has several view controllers in which all have similar UITextFields. I followed a great tutorial on www.globalnerdy.com that shows how to create a custom class that will limit characters and only allow certain characters within a given text field. After the code is complete, you can modify the properties within the Attributes Inspector vs. within the View Controller. Below is the MaxLengthTextField custom class that I created.

```<code>class MaxLengthTextField: UITextField, UITextFieldDelegate {

private var characterLimit: Int?

required init?(coder aDecoder: NSCoder) {

    super.init(coder: aDecoder)

    delegate = self

}

@IBInspectable var maxLength: Int {

    get {

        guard let length = characterLimit else {

            return Int.max

        }

        return length

    }

    set {

        characterLimit = newValue

    }

}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    guard string.characters.count > 0 else {

        return true

    }

    let currentText = textField.text ?? ""

    let prospectiveText = (currentText as NSString).replacingCharacters(in: range, with: string)

    return allowedIntoTextField(text: prospectiveText)

}

func allowedIntoTextField(text: String) -> Bool {

    return text.characters.count <= maxLength

}

}
</code>```

Here is the AllowedCharacters custom class, the sub-class of MaxLengthTextField.

```<code>class AllowedCharsTextField: MaxLengthTextField {

@IBInspectable var allowedChars: String = ""

required init?(coder aDecoder: NSCoder) {

    super.init(coder: aDecoder)

    delegate = self

    autocorrectionType = .no

}

override func allowedIntoTextField(text: String) -> Bool {

    return super.allowedIntoTextField(text: text) && text.containsOnlyCharactersIn(matchCharacters: allowedChars)

}

}

private extension String {

// Returns true if the string contains only characters found in mainCharacters.
func containsOnlyCharactersIn(matchCharacters: String) -> Bool {

    let disallowedCharacterSet = CharacterSet(charactersIn: matchCharacters).inverted

    return self.rangeOfCharacter(from: disallowedCharacterSet) == nil

}
}
</code>```

The problem that I am having is limiting the decimal "." in my code. I have tried implementing the func textField(_ textField: UITextField, shouldChangeCharactersIn... function twice by using the code that I found here on Stack Overflow (which works) for limiting decimals but since the specific text field is already a custom class that limits characters, I am unable to make the text field a delegate of the view controller and limit the "dots" at the same time.

Any guidance, references, and straight up help will be greatly appreciated!

答:
In your code, methods are uniquely identified by their signature - or the combination of the method name plus the parameters (the type of parameters) that it takes. So, you cannot have the exact same method twice in your code. That will lead to compiler errors.

Rather than implementing the textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {} method twice, what you should do is look at the passed in textField parameter to identify which text field sent the delegate method in the first place.

Make your view controller the UITextFieldDelegate and then in your view controller have outlets for your different text fields. So, if your text fields are text1 and text2, your delegate method would look something like this:

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == text1 {
        // Handle text1 code
    } else if textField == text2 {
        // Handle text2 code
    }
}
</code>```

Hope the above makes sense to you but if not, feel free to ask for clarifications :)

Body:
is there anyway to implement the

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {}

twice? I am trying to create a conversion app that has several view controllers in which all have similar UITextFields. I followed a great tutorial on www.globalnerdy.com that shows how to create a custom class that will limit characters and only allow certain characters within a given text field. After the code is complete, you can modify the properties within the Attributes Inspector vs. within the View Controller. Below is the MaxLengthTextField custom class that I created.

class MaxLengthTextField: UITextField, UITextFieldDelegate {

private var characterLimit: Int?

required init?(coder aDecoder: NSCoder) {

    super.init(coder: aDecoder)

    delegate = self

}

@IBInspectable var maxLength: Int {

    get {

        guard let length = characterLimit else {

            return Int.max

        }

        return length

    }

    set {

        characterLimit = newValue

    }

}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    guard string.characters.count > 0 else {

        return true

    }

    let currentText = textField.text ?? ""

    let prospectiveText = (currentText as NSString).replacingCharacters(in: range, with: string)

    return allowedIntoTextField(text: prospectiveText)

}

func allowedIntoTextField(text: String) -> Bool {

    return text.characters.count <= maxLength

}

}

Here is the AllowedCharacters custom class, the sub-class of MaxLengthTextField.

class AllowedCharsTextField: MaxLengthTextField {

@IBInspectable var allowedChars: String = ""

required init?(coder aDecoder: NSCoder) {

    super.init(coder: aDecoder)

    delegate = self

    autocorrectionType = .no

}

override func allowedIntoTextField(text: String) -> Bool {

    return super.allowedIntoTextField(text: text) && text.containsOnlyCharactersIn(matchCharacters: allowedChars)

}

}

private extension String {

// Returns true if the string contains only characters found in mainCharacters.
func containsOnlyCharactersIn(matchCharacters: String) -> Bool {

    let disallowedCharacterSet = CharacterSet(charactersIn: matchCharacters).inverted

    return self.rangeOfCharacter(from: disallowedCharacterSet) == nil

}
}

The problem that I am having is limiting the decimal "." in my code. I have tried implementing the func textField(_ textField: UITextField, shouldChangeCharactersIn... function twice by using the code that I found here on Stack Overflow (which works) for limiting decimals but since the specific text field is already a custom class that limits characters, I am unable to make the text field a delegate of the view controller and limit the "dots" at the same time.

Any guidance, references, and straight up help will be greatly appreciated!

Body:
In your code, methods are uniquely identified by their signature - or the combination of the method name plus the parameters (the type of parameters) that it takes. So, you cannot have the exact same method twice in your code. That will lead to compiler errors.

Rather than implementing the textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {} method twice, what you should do is look at the passed in textField parameter to identify which text field sent the delegate method in the first place.

Make your view controller the UITextFieldDelegate and then in your view controller have outlets for your different text fields. So, if your text fields are text1 and text2, your delegate method would look something like this:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == text1 {
        // Handle text1 code
    } else if textField == text2 {
        // Handle text2 code
    }
}

Hope the above makes sense to you but if not, feel free to ask for clarifications :)


问:
React Native TextInput not updating state
Well this is an embarrassing question, but I can't get this TextInput to take values I type into it.

It just deletes it as fast as I can type it - and I'm pretty sure logging this.state.code shows an empty variable.

Is it the keyboard type messing with me? Do I need to do a  .toString()?

constructor() {
    super()
    this.state = {
        code: '12'
    }
}

<TextInput
    onChangedText={(text) => this.setState({code: text})}
    value={this.state.code}
    keyboardType='numeric'
    style={styles.input}
    placeholder='Code'
    maxLength={4}
/>```

答: The correct prop is onChangeText. Not onChangedText


问:
Find out flash players connection URL
I have this page which has a flash player trying to connect to a rtmp URL. It's the source of a live radio.

How can I find out this URL the player is trying to connect to?

I wasn't able to get much out of web inspector.

答:
I did another google search and found several results. The useful one was on superuser.

I looked under the hood (webpage source) and saw *.m3u8 links. I downloaded this file and it was openable in text editor. Though I couldn't play this on VLC/Quicktime/Chrome. I simply googled the m3u8 file namae and came across this page: fmscan.org/main.php?qth=Bangalore&l=77.5833333&b=12.9833333&csave=2

The RTMP live stream url opens directly in VLC and plays well! :)

Title: Find out flash players connection URL


问:
Laravel 5 Class 'form' not found
I have added "illuminate/html": "5.*" to composer.json and ran "composer update".

```<code>  - Installing illuminate/html (v5.0.0)
    Loading from cache
</code>```

I ran this command in the root of the website. I modified the composer.json file in /root/.composer... and in the root of the project and neither have made a difference.

This downloaded the class and it seemed to install. I have added the following to file config/app.php.

```<code>    'Illuminate\Html\HtmlServiceProvider',

    'Form'      => 'Illuminate\Html\FormFacade',
    'Html'      => 'Illuminate\Html\HtmlFacade',
</code>```

I think I have an idea what is wrong, but I don’t know how to fix it. My install is in '/var/www/website'. I have checked the file path and the Html folder does not exist.

```<code>"/var/www/website/vendor/laravel/framework/src/Illuminate/Html"
</code>```

I was able to find the class files, but in a different directory.

```<code>"/var/www/website/vendor/illuminate/html"
</code>```

I manually copied the files over to the main Laravel illuminate/html folder, but this hasn't worked either.

答:
In Laravel Version - 4, HTML and Form existed, but not now.

Why:

The only reason is they have collected some user requirements and they want it more lightweight and so they removed it as in the sense that a user can add it manually.

What to do to add HTML & Forms in Laravel 5.2 or 5.3:

For 5.2:

Go to the Laravel Collective site and installation processes have demonstrated their.

Like for 5.2: on the command line, run the command

```<code>composer require "laravelcollective/html":"^5.2.0"
</code>```

Then, in the provider array which is in config/app.php. Add this line at last using a comma(,):

```<code>Collective\Html\HtmlServiceProvider::class,
</code>```

For using HTML and FORM text we need to alias them in the aliases array of config/app.php. Add the two lines at the last

```<code>'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
</code>```

And for 5.3:

Just run the command

```<code>composer require "laravelcollective/html":"^5.3.0"
</code>```

And the rest of the procedure is like 5.2.

Then you can use Laravel Form and other HTML links in your projects. For this, follow this documentation:

5.2: https://laravelcollective.com/docs/5.2/html

5.3:  https://laravelcollective.com/docs/5.3/html

Demo Code:

To open a form, open and close a tag:

```<code>{!! Form::open(['url' => 'foo/bar']) !!}

{!! Form::close() !!}
</code>```

And for creating label and input text with a Bootstrap form-control class and other use:

```<code>{!! Form::label('title', 'Post Title') !!}
{!! Form::text('title', null, array('class' => 'form-control')) !!}
</code>```

And for more, use the documentation, https://laravelcollective.com/.

Title: Laravel 5 Class 'form' not found

Body:
I have added "illuminate/html": "5.*" to composer.json and ran "composer update".

  - Installing illuminate/html (v5.0.0)
    Loading from cache

I ran this command in the root of the website. I modified the composer.json file in /root/.composer... and in the root of the project and neither have made a difference.

This downloaded the class and it seemed to install. I have added the following to file config/app.php.

    'Illuminate\Html\HtmlServiceProvider',

    'Form'      => 'Illuminate\Html\FormFacade',
    'Html'      => 'Illuminate\Html\HtmlFacade',

I think I have an idea what is wrong, but I don’t know how to fix it. My install is in '/var/www/website'. I have checked the file path and the Html folder does not exist.

"/var/www/website/vendor/laravel/framework/src/Illuminate/Html"

I was able to find the class files, but in a different directory.

"/var/www/website/vendor/illuminate/html"

I manually copied the files over to the main Laravel illuminate/html folder, but this hasn't worked either.

Body:
In Laravel Version - 4, HTML and Form existed, but not now.

Why:

The only reason is they have collected some user requirements and they want it more lightweight and so they removed it as in the sense that a user can add it manually.

What to do to add HTML & Forms in Laravel 5.2 or 5.3:

For 5.2:

Go to the Laravel Collective site and installation processes have demonstrated their.

Like for 5.2: on the command line, run the command

composer require "laravelcollective/html":"^5.2.0"

Then, in the provider array which is in config/app.php. Add this line at last using a comma(,):

Collective\Html\HtmlServiceProvider::class,

For using HTML and FORM text we need to alias them in the aliases array of config/app.php. Add the two lines at the last

'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,

And for 5.3:

Just run the command

composer require "laravelcollective/html":"^5.3.0"

And the rest of the procedure is like 5.2.

Then you can use Laravel Form and other HTML links in your projects. For this, follow this documentation:

5.2: https://laravelcollective.com/docs/5.2/html

5.3:  https://laravelcollective.com/docs/5.3/html

Demo Code:

To open a form, open and close a tag:

{!! Form::open(['url' => 'foo/bar']) !!}

{!! Form::close() !!}

And for creating label and input text with a Bootstrap form-control class and other use:

{!! Form::label('title', 'Post Title') !!}
{!! Form::text('title', null, array('class' => 'form-control')) !!}

And for more, use the documentation, https://laravelcollective.com/.


问:
ssh google compute engine instance from ubuntu
I am not able to access the google compute engine instance using ssh or gcutil ssh. I have tried adding my local machine keys into metadata and shh keys of the specific instance. How to achieve access using a shh-client?

this is the link to the guides i followed.

Google Compute Engine - troubleshooting SSH "Connection refused"

https://cloud.google.com/compute/docs/instances/connecting-to-instance#standardssh

答:
the official way is google compute ssh [instance-name]

If this isn't what you did to get the error, let me know and I'll try.


问:
VBA looping and pasting to new worksheet
HI,
i have data of this structure :

User   |  Channels

1      | 12391  | 123123 | 122121

2      | 91283 | 1239871| 12731| 1231982|128317

3|

4| 1231

5| 19881|19288

how can i use vba to tranpose this data set into a new sheet such that the result is:

User | Channel

1      | 12391

1 | 123123

1 | 122121

2      | 91283

2| 1239871

2| 12731

2| 1231982

答:
For example:</p>

```<code>Dim cn As Object
Dim rs As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim s As String
Dim i As Integer, j As Integer

''This is not the best way to refer to the workbook
''you want, but it is very convenient for notes
''It is probably best to use the name of the workbook.

strFile = ActiveWorkbook.FullName

''Note that if HDR=No, F1,F2 etc are used for column names,
''if HDR=Yes, the names in the first row of the range
''can be used.
''This is the Jet 4 connection string, you can get more
''here : http://www.connectionstrings.com/excel

strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
    & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"

''Late binding, so no reference is needed

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

cn.Open strCon

''This example list the fields by name (HDR=Yes)
''and only the first two columns have names (User, Channels)
''so F3,F4 etc are automatically assigned to the unnamed columns

''It would not be difficult to select everything from the relevant
''sheet and loop through that to build the Union query.
strSQL = "SELECT [User], Channels " _
       & "FROM [Sheet1$] " _
       & "WHERE Channels Is Not Null " _
       & "UNION ALL " _
       & "SELECT [User], F3 " _
       & "FROM [Sheet1$] " _
       & "WHERE F3 Is Not Null "
''And so on

rs.Open strSQL, cn, 3, 3

''Pick a suitable empty worksheet for the results

 Worksheets("Sheet3").Cells(2, 1).CopyFromRecordset rs

 ''Tidy up
 rs.Close
 Set rs = Nothing
 cn.Close
 Set cn = Nothing
</code>```

Body:
For example:

Dim cn As Object
Dim rs As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim s As String
Dim i As Integer, j As Integer

''This is not the best way to refer to the workbook
''you want, but it is very convenient for notes
''It is probably best to use the name of the workbook.

strFile = ActiveWorkbook.FullName

''Note that if HDR=No, F1,F2 etc are used for column names,
''if HDR=Yes, the names in the first row of the range
''can be used.
''This is the Jet 4 connection string, you can get more
''here : http://www.connectionstrings.com/excel

strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
    & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"

''Late binding, so no reference is needed

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

cn.Open strCon

''This example list the fields by name (HDR=Yes)
''and only the first two columns have names (User, Channels)
''so F3,F4 etc are automatically assigned to the unnamed columns

''It would not be difficult to select everything from the relevant
''sheet and loop through that to build the Union query.
strSQL = "SELECT [User], Channels " _
       & "FROM [Sheet1$] " _
       & "WHERE Channels Is Not Null " _
       & "UNION ALL " _
       & "SELECT [User], F3 " _
       & "FROM [Sheet1$] " _
       & "WHERE F3 Is Not Null "
''And so on

rs.Open strSQL, cn, 3, 3

''Pick a suitable empty worksheet for the results

 Worksheets("Sheet3").Cells(2, 1).CopyFromRecordset rs

 ''Tidy up
 rs.Close
 Set rs = Nothing
 cn.Close
 Set cn = Nothing


问:
Visual Studio 2015 Team Explorer error write access denied comes and goes
I have a school group project on TFS and working with VS 2015. I can connect to Team Explorer and sync up with the solution just fine. However when I start working on my local version I get the 'Save As' pop up box when I attempt to save code I'm working on just recently. That save as pop up shouldn't happen. I can also see the file inside the pop up, but I'll attempt to go ahead and save it, but when I do I get this error message, "The process cannot access the file '' because it is being used by another process" or I will see this error message 'An error occurred. Detailed message:  for writing: Access is denied."

I also get the Access is denied error on Team Explorer when I attempt to undo changes on that particular file.

The crazy thing is that this isn't a consistent issue, after a minute or so I can save the file just fine and move on.

Any help would be appreciated on this annoyance?

Note: I have tried going into the file explorer path of the file and remove it (and allow team explorer to pull it back down from server) but once i get into that last folder, File Explorer closes...

答: Please checkout the deleted local branch first and try to sync again in your local git repository.


问:
Algol: correct syntax leads to problems in compilation?
Here is a relatively simple code for "Evaluation of pi using the Mid-ordinate Rule on a quadrant of circle with radius 2 units."

main.alg

```<code>BEGIN
REAL x, y, sumy, pi;
INT n := lowerlimit, p := 1, lowerlimit := 10, upperlimit := 100, interval := 10;

FOR n BY interval TO upperlimit DO
    sumy := 0.0;

    FOR p BY 2 TO n+n-1 DO
        x := p/n;
        y := sqrt(4.0 - x**2);
        sumy := sumy + y;
    OD
    pi := sumy * (2.0 / n);
    print((n,pi))
OD
END
</code>```

I'm getting the following errors:

```<code>a68g: syntax error: 1: possibly a missing or erroneous separator nearby.
sh-4.3$ a68g main.alg
13                sumy := sumy + y;
                              1
a68g: warning: 1: skipped superfluous semi-symbol.
15            pi := sumy * (2.0 / n);
          1
a68g: syntax error: 1: possibly a missing or erroneous separator nearby.
</code>```

Try it live here.

What am I doing wrong? How to correct it?

答:
The short answer:
The following code has your specific problem fixed...

The thing to remember is that a ";" is a "statement separator"... so all "compound statement" should have each statement separated by a ";".. eg consider:

```<code>statement; statement; statement # is a valid program #
statement; statement statement; # is not valid #

(statement; statement; statement) # is a valid program #
(statement; statement; statement;) # is not valid #
(statement; statement; statement); # is not valid #
</code>```

The moral is... separate all statements with a ";" and dont put a ";" after the last statement.  (eg before an END, FI, DO, ")"  or ESAC)

```<code>BEGIN
REAL x, y, sumy, pi;
INT n := lowerlimit, p := 1, lowerlimit := 10, upperlimit := 100, interval := 10;

FOR n BY interval TO upperlimit DO
    sumy := 0.0;

    FOR p BY 2 TO n+n-1 DO
        x := p/n;
        y := sqrt(4.0 - x**2);
        sumy := sumy + y
    OD;
    pi := sumy * (2.0 / n);
    print((n,pi))
OD
END
</code>```

It is interesting to note that you can often use a "," instead of a ";", this tells the compiler you dont care what order the statements are run.  It is called a GOMMA.  (A contraction of go on and comma)

e.g. The GOMMA should be used sparingly as the compiler is not required to warn you about side effects... for example (in theory)

```<code>#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #

INT x:=0;
(x+:=1, x+:=2); # allow the compiler the choice of threading #
PAR(x+:=10, x+:=20); # force statements into different threads #
printf(($"Answer="gl$,x))
</code>```

What is the Answer? ... it could be 33, but it might also be 21 or 12 etc. depending on your compiler.

In this case the +:= operation is so small and fast that the answer will probably be 33.

The long answer:
The location of the statement separators in languages cause caused grief through the years.  For example consider the following FORTRAN code with a missing comma:

```<code>DO 999 I=1 1000
  PRINT *,I
999 CONTINUE
</code>```

This bug was found and corrected before the launch of Project Mercury.  Urban myth has it that the  Mariner Program had a similar bug causing it to crash.

Note that it is often useful to have "Fake" statements, this is used to fulfill syntax/semantic requirements.  Python as various examples, eg: "None", "NoneType" and "pass".  Algol68 has "VOID", "SKIP" and "~"

To demonstrate the usage of SKIP (or "~").

```<code>BEGIN
REAL x, y, sumy, pi;
INT n := lowerlimit, p := 1, lowerlimit := 10, upperlimit := 100, interval := 10;

FOR n BY interval TO upperlimit DO
    sumy := 0.0;

    FOR p BY 2 TO n+n-1 DO
        x := p/n;
        y := sqrt(4.0 - x**2);
        sumy := sumy + y; SKIP # insert a "fake statement after the ";" #
    OD; # the ";" is still needed #
    pi := sumy * (2.0 / n);
    print((n,pi))
OD
END
</code>```

SKIP is often used to permit code to be cleanly commented out:

```<code>statement1;
statement2;
SKIP COMMENT
statement3;
statement4 # eg. no ";" on the last statement #
END COMMENT
</code>```

Without the SKIP the program would not compile.

In the case of Algol68, there is a weird case Yoneda's ambiguity.  This ambiguity has haunted numerous programming languages ever since, including Ada and python, and maybe even C...

To find out more go to your university library and read: "A History of ALGOL 68" - by C. H. Lindsey - [Includes a candid reflection of the language design process "Revision by mail", language feature struggles "The Bend" and included/excluded ambiguities (eg Yoneda's ambiguity and incestuous unions)]

In python they tries to side step the "Separator" by making it optional and hiding it with indentation... but the comma ambiguity remained.. eg. spot the syntax/semantic error, and run time error in the following...

```<code>print [i for i in ()]
print [i for i in (1)]
print [i for i in (1,2)]
print [i for i in (1,2,3)]
ab="ab etc etc etc"
print "first 2 only: %c,%c"%ab[0:2]
</code>```

C also suffers a little from "where do I put a semicolon and comma"... the logic is that the ";" need never follow a "}", eg always ";}" but never "};"...  It turns out that sometimes you do need ";};"

Then C completely throws a spanner in the works for commas with never ",)" but sometimes "),".

1968's Algol68 does produce an error message for this class of ambiguities.  The moral to the story might be: if your compiler does not pick up this kind of ambiguity at compile time, then (just maybe) you should pick another language.

BTW: You can find some sample Algol68 Programs here...  And next is your code with the sharp edges removed.

```<code>INT lower limit = 10, upper limit = 100, interval = 10;

PROC circle = (REAL x)REAL: sqrt(4 - x**2);

FOR n FROM lower limit BY interval TO upper limit DO
    REAL sum y := 0;

    FOR p FROM 1 BY 2 TO 2*n DO
        REAL x = p/n;
        REAL y = circle(x);
        sum y +:= y
    OD;
    REAL pi := sum y * 2 / n;
    printf(($g(0)": "g(-real width,real width-2)l$,n,pi))
OD
</code>```

Compare the code changes to see if you can figure out the effect and what hints they provide... :-)

Or... here is how a standard numerical quadrature program might be coded for sharing.  Note the use of passing functions as arguments, in particular there is a concept called Currying here circle(2,) ... where the comma is significant!

```<code>INT lower limit = 10, upper limit = 100, interval = 10;

PROC circle = (REAL radius, x)REAL: sqrt(radius**2 - x**2);

PROC mid point integrate = (PROC(REAL)REAL f, REAL lwb, upb, INT num steps)REAL: (
  REAL dx := (upb - lwb ) / num steps;
  REAL x := lwb + dx/2;
  REAL sum y := 0;

  FOR p TO num steps DO
      REAL y = f(x);
      sum y +:= y;
      x +:= dx
  OD;
  sum y * dx
);

FOR num steps FROM lower limit BY interval TO upper limit DO
  REAL pi := mid point integrate(circle(2,),0,2,num steps);
  printf(($g(0)": "g(-real width,real width-2)l$,num steps,pi))
OD
</code>```

Body:
Here is a relatively simple code for "Evaluation of pi using the Mid-ordinate Rule on a quadrant of circle with radius 2 units."

main.alg

BEGIN
REAL x, y, sumy, pi;
INT n := lowerlimit, p := 1, lowerlimit := 10, upperlimit := 100, interval := 10;

FOR n BY interval TO upperlimit DO
    sumy := 0.0;

    FOR p BY 2 TO n+n-1 DO
        x := p/n;
        y := sqrt(4.0 - x**2);
        sumy := sumy + y;
    OD
    pi := sumy * (2.0 / n);
    print((n,pi))
OD
END

I'm getting the following errors:

a68g: syntax error: 1: possibly a missing or erroneous separator nearby.
sh-4.3$ a68g main.alg
13                sumy := sumy + y;
                              1
a68g: warning: 1: skipped superfluous semi-symbol.
15            pi := sumy * (2.0 / n);
          1
a68g: syntax error: 1: possibly a missing or erroneous separator nearby.

Try it live here.

What am I doing wrong? How to correct it?

Body:
The short answer:
The following code has your specific problem fixed...

The thing to remember is that a ";" is a "statement separator"... so all "compound statement" should have each statement separated by a ";".. eg consider:

statement; statement; statement # is a valid program #
statement; statement statement; # is not valid #

(statement; statement; statement) # is a valid program #
(statement; statement; statement;) # is not valid #
(statement; statement; statement); # is not valid #

The moral is... separate all statements with a ";" and dont put a ";" after the last statement.  (eg before an END, FI, DO, ")"  or ESAC)

BEGIN
REAL x, y, sumy, pi;
INT n := lowerlimit, p := 1, lowerlimit := 10, upperlimit := 100, interval := 10;

FOR n BY interval TO upperlimit DO
    sumy := 0.0;

    FOR p BY 2 TO n+n-1 DO
        x := p/n;
        y := sqrt(4.0 - x**2);
        sumy := sumy + y
    OD;
    pi := sumy * (2.0 / n);
    print((n,pi))
OD
END

It is interesting to note that you can often use a "," instead of a ";", this tells the compiler you dont care what order the statements are run.  It is called a GOMMA.  (A contraction of go on and comma)

e.g. The GOMMA should be used sparingly as the compiler is not required to warn you about side effects... for example (in theory)

#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #

INT x:=0;
(x+:=1, x+:=2); # allow the compiler the choice of threading #
PAR(x+:=10, x+:=20); # force statements into different threads #
printf(($"Answer="gl$,x))

What is the Answer? ... it could be 33, but it might also be 21 or 12 etc. depending on your compiler.

In this case the +:= operation is so small and fast that the answer will probably be 33.

The long answer:
The location of the statement separators in languages cause caused grief through the years.  For example consider the following FORTRAN code with a missing comma:

DO 999 I=1 1000
  PRINT *,I
999 CONTINUE

This bug was found and corrected before the launch of Project Mercury.  Urban myth has it that the  Mariner Program had a similar bug causing it to crash.

Note that it is often useful to have "Fake" statements, this is used to fulfill syntax/semantic requirements.  Python as various examples, eg: "None", "NoneType" and "pass".  Algol68 has "VOID", "SKIP" and "~"

To demonstrate the usage of SKIP (or "~").

BEGIN
REAL x, y, sumy, pi;
INT n := lowerlimit, p := 1, lowerlimit := 10, upperlimit := 100, interval := 10;

FOR n BY interval TO upperlimit DO
    sumy := 0.0;

    FOR p BY 2 TO n+n-1 DO
        x := p/n;
        y := sqrt(4.0 - x**2);
        sumy := sumy + y; SKIP # insert a "fake statement after the ";" #
    OD; # the ";" is still needed #
    pi := sumy * (2.0 / n);
    print((n,pi))
OD
END

SKIP is often used to permit code to be cleanly commented out:

statement1;
statement2;
SKIP COMMENT
statement3;
statement4 # eg. no ";" on the last statement #
END COMMENT

Without the SKIP the program would not compile.

In the case of Algol68, there is a weird case Yoneda's ambiguity.  This ambiguity has haunted numerous programming languages ever since, including Ada and python, and maybe even C...

To find out more go to your university library and read: "A History of ALGOL 68" - by C. H. Lindsey - [Includes a candid reflection of the language design process "Revision by mail", language feature struggles "The Bend" and included/excluded ambiguities (eg Yoneda's ambiguity and incestuous unions)]

In python they tries to side step the "Separator" by making it optional and hiding it with indentation... but the comma ambiguity remained.. eg. spot the syntax/semantic error, and run time error in the following...

print [i for i in ()]
print [i for i in (1)]
print [i for i in (1,2)]
print [i for i in (1,2,3)]
ab="ab etc etc etc"
print "first 2 only: %c,%c"%ab[0:2]

C also suffers a little from "where do I put a semicolon and comma"... the logic is that the ";" need never follow a "}", eg always ";}" but never "};"...  It turns out that sometimes you do need ";};"

Then C completely throws a spanner in the works for commas with never ",)" but sometimes "),".

1968's Algol68 does produce an error message for this class of ambiguities.  The moral to the story might be: if your compiler does not pick up this kind of ambiguity at compile time, then (just maybe) you should pick another language.

BTW: You can find some sample Algol68 Programs here...  And next is your code with the sharp edges removed.

INT lower limit = 10, upper limit = 100, interval = 10;

PROC circle = (REAL x)REAL: sqrt(4 - x**2);

FOR n FROM lower limit BY interval TO upper limit DO
    REAL sum y := 0;

    FOR p FROM 1 BY 2 TO 2*n DO
        REAL x = p/n;
        REAL y = circle(x);
        sum y +:= y
    OD;
    REAL pi := sum y * 2 / n;
    printf(($g(0)": "g(-real width,real width-2)l$,n,pi))
OD

Compare the code changes to see if you can figure out the effect and what hints they provide... :-)

Or... here is how a standard numerical quadrature program might be coded for sharing.  Note the use of passing functions as arguments, in particular there is a concept called Currying here circle(2,) ... where the comma is significant!

INT lower limit = 10, upper limit = 100, interval = 10;

PROC circle = (REAL radius, x)REAL: sqrt(radius**2 - x**2);

PROC mid point integrate = (PROC(REAL)REAL f, REAL lwb, upb, INT num steps)REAL: (
  REAL dx := (upb - lwb ) / num steps;
  REAL x := lwb + dx/2;
  REAL sum y := 0;

  FOR p TO num steps DO
      REAL y = f(x);
      sum y +:= y;
      x +:= dx
  OD;
  sum y * dx
);

FOR num steps FROM lower limit BY interval TO upper limit DO
  REAL pi := mid point integrate(circle(2,),0,2,num steps);
  printf(($g(0)": "g(-real width,real width-2)l$,num steps,pi))
OD


问:
Avoid zombie processes by regularly calling `join()`
I'm writing a program in Python that runs forever and randomly receives requests
that have to be processed in parallel. Each request can take dozens of minutes
to process and puts some burden on the CPU, so asyncio is not an option. For
each request I start a new worker process.

The problem is, that if I don't call join() on a worker after it's finished,
it turns into a zombie process.

My current solution is to regularly iterate over all worker processes and call
join() on them if they are finished. Is there a more elegant way than using a
timeout on multiprocessing.Queue.get()? Maybe an event driven approach? Or is using a timeout totally fine in this case?
Please see the following code for my
current solution.

```<code>#!/usr/bin/env python3

import multiprocessing as mp
import queue
import random
import time
from typing import List

def main():
    q = mp.Queue()
    p_produce = mp.Process(target=produce, args=(q,))
    p_receive = mp.Process(target=receive, args=(q,))

    p_produce.start()
    p_receive.start()

    p_receive.join()
    p_produce.join()

def produce(q: mp.Queue):
    for i in range(10):
        print(f"put({i})")
        q.put(str(i))
        time.sleep(random.uniform(2.0, 3.0))
    q.put("EOF")

def receive(q: mp.Queue):
    workers = []  # type: List[mp.Process]
    while True:
        to_join = [w for w in workers if not w.is_alive()]
        for p_worker in to_join:
            print(f"Join {p_worker.name}")
            p_worker.join()
            workers.remove(p_worker)

        try:
            request = q.get(block=True, timeout=1)  # Is there a better way?
        except queue.Empty:
            continue

        if request == "EOF":
            break

        p_worker = mp.Process(target=worker, args=(request,), name=request)
        p_worker.start()
        workers.append(p_worker)

    for p_worker in workers:
        print(f"Join {p_worker.name}")
        p_worker.join()

def worker(name: str):
    print(f"Working on {name}")
    time.sleep(random.uniform(2.0, 3.0))

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

答: Well, one solution would be using a workqueue like python rq or selery. Essentially you would spawn n workers (seperate processes) which would look at a queue for tasks to execute and then on your main program you would just push tasks in the queue and check for the results periodically.</p>

Body:
I'm writing a program in Python that runs forever and randomly receives requests
that have to be processed in parallel. Each request can take dozens of minutes
to process and puts some burden on the CPU, so asyncio is not an option. For
each request I start a new worker process.

The problem is, that if I don't call join() on a worker after it's finished,
it turns into a zombie process.

My current solution is to regularly iterate over all worker processes and call
join() on them if they are finished. Is there a more elegant way than using a
timeout on multiprocessing.Queue.get()? Maybe an event driven approach? Or is using a timeout totally fine in this case?
Please see the following code for my
current solution.

#!/usr/bin/env python3

import multiprocessing as mp
import queue
import random
import time
from typing import List

def main():
    q = mp.Queue()
    p_produce = mp.Process(target=produce, args=(q,))
    p_receive = mp.Process(target=receive, args=(q,))

    p_produce.start()
    p_receive.start()

    p_receive.join()
    p_produce.join()

def produce(q: mp.Queue):
    for i in range(10):
        print(f"put({i})")
        q.put(str(i))
        time.sleep(random.uniform(2.0, 3.0))
    q.put("EOF")

def receive(q: mp.Queue):
    workers = []  # type: List[mp.Process]
    while True:
        to_join = [w for w in workers if not w.is_alive()]
        for p_worker in to_join:
            print(f"Join {p_worker.name}")
            p_worker.join()
            workers.remove(p_worker)

        try:
            request = q.get(block=True, timeout=1)  # Is there a better way?
        except queue.Empty:
            continue

        if request == "EOF":
            break

        p_worker = mp.Process(target=worker, args=(request,), name=request)
        p_worker.start()
        workers.append(p_worker)

    for p_worker in workers:
        print(f"Join {p_worker.name}")
        p_worker.join()

def worker(name: str):
    print(f"Working on {name}")
    time.sleep(random.uniform(2.0, 3.0))

if __name__ == "__main__":
    main()


问:
How many threads does curl_multi_exec use?
I'm using curl_multi_exec in php to check the status of a number of URLs. I want to benchmark this so that, for a given system, I know how many handlers I can check synchronously before curl starts queuing. Does anyone have any experience on how to gauge capacity?

Thanks,

Adam

答:
You can see from PHP source code that it uses select() and non-blocking reads.
So only one process is used.

Note that select() will fail, if you give it a file descriptor with fd >= FD_SETSIZE. The FD_SETSIZE limit is defined when compiling PHP. The default seems to be 256. It would be better to use poll() in the PHP implementation.

About correct curl_multi_exec() usage:

curl_multi_exec() should be followed by curl_multi_select(). That will wait for available data, instead of checking them in a busy loop.
The example in the PHP manual is good.


问:
Android copy/paste from clipboard manager
Is it possible to send past command so that it pastes text into currently focused edit text.
Scenario:

Background service listening for notification (done)

When notification is received text needs to be copied to clipboard (done)

Paste text to any currently focused field, if not possible just discard paste command.

I know how to copy text with ClipboardManager, but I don't know how to paste it.

答:
If you just want to "copy and paste" some code into your app, you can use the following.

#Copy

```<code>String textToCopy = etCodeWindow.getText().toString();

ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(null, textToCopy);
if (clipboard == null) return;
clipboard.setPrimaryClip(clip);
</code>```

#Paste

Get the text to paste

```<code>ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard == null) return;
ClipData clip = clipboard.getPrimaryClip();
if (clip == null) return;
ClipData.Item item = clip.getItemAt(0);
if (item == null) return;
CharSequence textToPaste = item.getText();
if (textToPaste == null) return;
</code>```

or

```<code>ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
try {
    CharSequence textToPaste = clipboard.getPrimaryClip().getItemAt(0).getText();
} catch (Exception e) {
    return;
}
</code>```

or the same in Kotlin:

```<code>val clipboard = (getSystemService(Context.CLIPBOARD_SERVICE)) as? ClipboardManager
val textToPaste = clipboard?.primaryClip?.getItemAt(0)?.text ?: return false
</code>```

Inserting it at the cursor position

If there is a selection then the selection will be replaced with the paste text.

```<code>int start = Math.max(myEditText.getSelectionStart(), 0);
int end = Math.max(myEditText.getSelectionEnd(), 0);
myEditText.getText().replace(Math.min(start, end), Math.max(start, end),
            textToPaste, 0, textToPaste.length());
</code>```

#Notes

This answer assumes that you are no longer supporting pre-API 11. If you are then see the edit history.

Import android.content.ClipboardManager and android.content.ClipData.

I used to just get the paste text in a one liner until I discovered that ClipData was giving a NPE crash sometimes. Now I would either use a try/catch block or check more carefully for nulls.

Body:
If you just want to "copy and paste" some code into your app, you can use the following.

#Copy

String textToCopy = etCodeWindow.getText().toString();

ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(null, textToCopy);
if (clipboard == null) return;
clipboard.setPrimaryClip(clip);

#Paste

Get the text to paste

ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard == null) return;
ClipData clip = clipboard.getPrimaryClip();
if (clip == null) return;
ClipData.Item item = clip.getItemAt(0);
if (item == null) return;
CharSequence textToPaste = item.getText();
if (textToPaste == null) return;

or

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
try {
    CharSequence textToPaste = clipboard.getPrimaryClip().getItemAt(0).getText();
} catch (Exception e) {
    return;
}

or the same in Kotlin:

val clipboard = (getSystemService(Context.CLIPBOARD_SERVICE)) as? ClipboardManager
val textToPaste = clipboard?.primaryClip?.getItemAt(0)?.text ?: return false

Inserting it at the cursor position

If there is a selection then the selection will be replaced with the paste text.

int start = Math.max(myEditText.getSelectionStart(), 0);
int end = Math.max(myEditText.getSelectionEnd(), 0);
myEditText.getText().replace(Math.min(start, end), Math.max(start, end),
            textToPaste, 0, textToPaste.length());

#Notes

This answer assumes that you are no longer supporting pre-API 11. If you are then see the edit history.

Import android.content.ClipboardManager and android.content.ClipData.

I used to just get the paste text in a one liner until I discovered that ClipData was giving a NPE crash sometimes. Now I would either use a try/catch block or check more carefully for nulls.