问:
Handle exception in EJB
I have an EJB which performs some DB operation and then call another EJB after JNDI lookup which performs more DB operation. This 2nd EJB call can throw some exceptions i.e. PersistenceException (I looked in the code that this exception marks the transaction as rollbackonly). Is there any way I can avoid rollback of the transaction? Below is the code summarizing the problem. Thank in advance. </p>

```<code>public class Test {

    ejbMthod1() {
        // This method run under transaction
        // Do some DB operation like update\delete
        if(somecondition) {
            try {
                // JNDI lookup for ejb2
                ejbMethod2();
            }
            catch(Exception ex){
                // Will catching the exception here save the Transaction from rollback ?
                // Is there any way I can avoid this rollback just by handling proper exceptions ?
            }
        }
    }
}

class Test2 {
    ejbMethod2() {
        // Run under same transaction as caller
        // do some DB operation which can throw many exception i.e. PersistenceException.
    }
}
</code>```

答:
The method that throws the exception must be annotated like:

```<code>@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
</code>```

There are much more to know about in this subject. I strongly recommend to read this great article.

Title: Handle exception in EJB

Body:
I have an EJB which performs some DB operation and then call another EJB after JNDI lookup which performs more DB operation. This 2nd EJB call can throw some exceptions i.e. PersistenceException (I looked in the code that this exception marks the transaction as rollbackonly). Is there any way I can avoid rollback of the transaction? Below is the code summarizing the problem. Thank in advance.

public class Test {

    ejbMthod1() {
        // This method run under transaction
        // Do some DB operation like update\delete
        if(somecondition) {
            try {
                // JNDI lookup for ejb2
                ejbMethod2();
            }
            catch(Exception ex){
                // Will catching the exception here save the Transaction from rollback ?
                // Is there any way I can avoid this rollback just by handling proper exceptions ?
            }
        }
    }
}

class Test2 {
    ejbMethod2() {
        // Run under same transaction as caller
        // do some DB operation which can throw many exception i.e. PersistenceException.
    }
}

Body:
The method that throws the exception must be annotated like:

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)

There are much more to know about in this subject. I strongly recommend to read this great article.


来源: stackexchange

问:
Log all warnings with futile.logger
Trying to log all errors and warnings with futile.logger.

Somewhat satisfied with this for dealing with errors:

```<code>library(futile.logger)
options(error = function() { flog.error(geterrmessage()) ; traceback() ; stop() })
log("a")
# Error in log("a") : argument non numérique pour une fonction mathématique
# ERROR [2016-12-01 21:12:07] Error in log("a") : argument non numérique pour une fonction mathématique
#
# No traceback available
# Erreur pendant l'emballage (wrapup) :
</code>```

There is redundancy, but I can easily separate between stderr, stdout and log file, so it's not a problem. It's certainly not pretty, there is an additional "wrapup" error message somehow caused by the final stop() that I don't understand, so I'm open to suggestions.

I cannot find a similar solution for warnings. What I tried:

```<code>options(warn = 1L)
options(warning.expression = expression(flog.warn(last.warning)))
log(- 1)
# [1] NaN
</code>```

But to no avail.

Follow-up question: Are there best practices that I am unknowingly ignoring?

答:
How about:</p>

```<code>options(warning.expression =
        quote({
            if(exists("last.warning",baseenv()) && !is.null(last.warning)){
                txt = paste0(names(last.warning),collapse=" ")
                try(suppressWarnings(flog.warn(txt)))
                cat("Warning message:\n",txt,'\n',sep = "")
            }
        }))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Log all warnings with futile.logger

Body:
Trying to log all errors and warnings with futile.logger.

Somewhat satisfied with this for dealing with errors:

library(futile.logger)
options(error = function() { flog.error(geterrmessage()) ; traceback() ; stop() })
log("a")
# Error in log("a") : argument non numérique pour une fonction mathématique
# ERROR [2016-12-01 21:12:07] Error in log("a") : argument non numérique pour une fonction mathématique
#
# No traceback available
# Erreur pendant l'emballage (wrapup) :

There is redundancy, but I can easily separate between stderr, stdout and log file, so it's not a problem. It's certainly not pretty, there is an additional "wrapup" error message somehow caused by the final stop() that I don't understand, so I'm open to suggestions.

I cannot find a similar solution for warnings. What I tried:

options(warn = 1L)
options(warning.expression = expression(flog.warn(last.warning)))
log(- 1)
# [1] NaN

But to no avail.

Follow-up question: Are there best practices that I am unknowingly ignoring?

Body:
How about:

options(warning.expression =
        quote({
            if(exists("last.warning",baseenv()) && !is.null(last.warning)){
                txt = paste0(names(last.warning),collapse=" ")
                try(suppressWarnings(flog.warn(txt)))
                cat("Warning message:\n",txt,'\n',sep = "")
            }
        }))


问:
'setAutoTickStep' : is not a member of 'QCPAxis' with QCustomPlot 2.00-beta
I'm using Qt5.6.1 and QCustomPlot 2.00-beta. And I set a new widget called "widget". But when I code

```<code>ui->widget->xAxis->setAutoTickStep(false);
</code>```

it says

error: C2039: 'setAutoTickStep' : is not a member of 'QCPAxis'

how to solve it?

答:
You will need to create an object of type QCustomPlot, do a customPlot->addGraph(), and then access its settings like customPlot->xAxis->QCPAxisTicker(...).

It appears you are trying to access a member of an object of type QWidget, which knows nothing about custom plots, until overridden.  Neither the old nor the new method will work on an object of QWidget.  You should use a new method of QCPAxis instead; perhaps

ui->customPlot->xAxis->ticker()->setTickCount(0);

If your problem is that you are trying to create a plot in QtCreator, you can create a QWidget in it, and then right-click on it, and do a "Promote to ...".  Make sure the QCustomPlot headers are already in your project first, and then specify the one which defines QCustomPlot when promoting.  When you say, "rename it as widget and remote it to a QCustomPlot", did you mean "promote it to"?

Body:
I'm using Qt5.6.1 and QCustomPlot 2.00-beta. And I set a new widget called "widget". But when I code

ui->widget->xAxis->setAutoTickStep(false);

it says

error: C2039: 'setAutoTickStep' : is not a member of 'QCPAxis'

how to solve it?


问:
Initialized empty numpy array is not really empty (contains zeros)
In order to store many 3D points coordinates tuples in a numpy.ndarray I initialize an empty numpy array before entering a loop for each of some features.

To do so, I currently do this before entering the loop:

```<code>import numpy as np
pointsarrray = np.empty((1,3))
</code>```

but this results in an array which is all but empty:

```<code>array([[  5.30498948e-315,   0.00000000e+000,   7.81250000e-003]])
</code>```

When filling pointsarray in my loop after, I do this:

```<code>pointsarray = np.vstack((pointsarray, [np.array(myPoint)]))
</code>```

(it also works with np.append)

and I finally need to delete the first line of the array after exiting the loop because this first line always contains the values from the initialization step!

It's not a big deal but I wonder if there is a cleaner way to achieve a really empty array, I mean; with nothing inside it (it shows 1 row yet, I can not figure out why) but at the right dimensions?

答:
Maybe it's the name that is confusing you but numpy.emptys documentation explains what is happening:

Return a new array of given shape and type, without initializing entries.

So it just doesn't initialize the entries (sometimes they are random sometimes they are zero) but empty refers only to the value of the entries not to the shape of the array.

However it's really bad for performance to create an array by appending or stacking. Just collect them in a list and create the array afterwards:

```<code>pointsarray = [np.array(myPoint)]

# ...

pointsarray = np.array(pointsarray)  # or np.stack(pointsarray, axis=...) whatever you need.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In order to store many 3D points coordinates tuples in a numpy.ndarray I initialize an empty numpy array before entering a loop for each of some features.

To do so, I currently do this before entering the loop:

import numpy as np
pointsarrray = np.empty((1,3))

but this results in an array which is all but empty:

array([[  5.30498948e-315,   0.00000000e+000,   7.81250000e-003]])

When filling pointsarray in my loop after, I do this:

pointsarray = np.vstack((pointsarray, [np.array(myPoint)]))

(it also works with np.append)

and I finally need to delete the first line of the array after exiting the loop because this first line always contains the values from the initialization step!

It's not a big deal but I wonder if there is a cleaner way to achieve a really empty array, I mean; with nothing inside it (it shows 1 row yet, I can not figure out why) but at the right dimensions?

Body:
Maybe it's the name that is confusing you but numpy.emptys documentation explains what is happening:

Return a new array of given shape and type, without initializing entries.

So it just doesn't initialize the entries (sometimes they are random sometimes they are zero) but empty refers only to the value of the entries not to the shape of the array.

However it's really bad for performance to create an array by appending or stacking. Just collect them in a list and create the array afterwards:

pointsarray = [np.array(myPoint)]

# ...

pointsarray = np.array(pointsarray)  # or np.stack(pointsarray, axis=...) whatever you need.


问:
How to draw a "speech bubble" on an iPhone?
I'm trying to get a "speech bubble" effect similar to the one in Mac OS X when you right click on something in the dock.  Here's what I have now:

I need to get the "triangle" part of the lower portion.  Is there any way I can draw something like that and get a border around it?  This will be for an iPhone app.

Thanks in advance!

EDIT:  Many thanks to Brad Larson, here's what it looks like now:

答:
I would probably make the whole image (including the triangle) in Photoshop, and then display it on the screen at the appropriate time using the:</p>

```<code>CGRect myRect = CGRectMake(10.0f, 0.0f, 300.0f, 420.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myRect];
[myImage setImage:[UIImage imageNamed:@"ThisIsMyImageName.png"]];
myImage.opaque = YES;
[self.view addSubview:myImage];
[myImage release];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I would probably make the whole image (including the triangle) in Photoshop, and then display it on the screen at the appropriate time using the:

CGRect myRect = CGRectMake(10.0f, 0.0f, 300.0f, 420.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myRect];
[myImage setImage:[UIImage imageNamed:@"ThisIsMyImageName.png"]];
myImage.opaque = YES;
[self.view addSubview:myImage];
[myImage release];


问:
How to use the NOAA API to query past weather data for a given set of coordinates
I am trying to retrieve past NOAA data using latitudinal and longitudinal coordinates. I am interested both in historical time series and annual summaries for variables such as temperature, wind speed, cloud fraction, and precipitation.

EX: 2008-02-20 13:00 in (25.033972, 121.564493)

I hope to automate a process that achieves this for 900,000+ locations. Any ideas? Ideally this script would be written in R or Python.

答:
NOAA is now on its second version of the NOAA web API.  APIs are useful because you can essentially query a web service, using requests and a python dict of arguments that describe what you want.  @Cravden has made a nice class that will get you started on GitHub. NOAA has nice documentation describing what you can get and how (you need to give them and email to get an access token). Other climate data aggregators also do this kind of thing.

Something as simple as this might get you started:

```<code>import requests

def get_noaa_data(url, data_type, header):

    r = requests.get(url, data_type, headers=header)
    print(r)

if __name__ == '__main__':

    token = 'gotowebsitetorequesttoken'
    creds = dict(token=token)
    dtype = 'dataset'
    url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/'

    get_noaa_data(url, dtype, creds)
</code>```

If you are going for thousands of places, you might consider downloading gridded data, making a shapefile of the points, then extracting raster values to an attribute table as done here.

Body:
NOAA is now on its second version of the NOAA web API.  APIs are useful because you can essentially query a web service, using requests and a python dict of arguments that describe what you want.  @Cravden has made a nice class that will get you started on GitHub. NOAA has nice documentation describing what you can get and how (you need to give them and email to get an access token). Other climate data aggregators also do this kind of thing.

Something as simple as this might get you started:

import requests

def get_noaa_data(url, data_type, header):

    r = requests.get(url, data_type, headers=header)
    print(r)

if __name__ == '__main__':

    token = 'gotowebsitetorequesttoken'
    creds = dict(token=token)
    dtype = 'dataset'
    url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/'

    get_noaa_data(url, dtype, creds)

If you are going for thousands of places, you might consider downloading gridded data, making a shapefile of the points, then extracting raster values to an attribute table as done here.


问:
Why does M2Eclipse execute the maven-compiler-plugin
This is not currently an error, i just want to know how it works that m2e executes the maven-compiler-plugin.

I cannot find any lifecycleMappingMetadata in the pom.xml of the plugin.

Is it possible that the magic takes place in
workspace\.metadata\.plugins\org.eclipse.m2e.core\>projectname>.lifecyclemapping?

I cannot really read the file, it seems to be binary.

答:
It depends what you do in Eclipse:

If you run a Maven target via a Maven launch configuration from Eclipse, then maven-compiler-plugin gets executed as if you'd run Maven from cmd line (well, mostly).

Otherwise, no maven-compiler-plugin is executed; Eclipse runs its own compiler, and ignores the plugin. Please note however that if you configure parameters for the JVM, in pom.xml (in the config section of the plugin), those parameters might be taken in consideration by certain Eclipse plugins (m2e-apt comes to mind, but there might be others)

I don't understand your statement about lifecycleMappingMetadata; did you expect to find it in pom.xml? If so, then in my experience, maven-compiler-plugin is excepted from it (i.e. you don't need to add explicit lifecycle mapping).


问:
Symfony2.8 Error Using $this when not in object context using doctrine
I am tryin to call a function from my controller and return the $todolist to my controller. But i get this error, when i leave this function inside the controller it works fine, but i don't want it to be in the controller.

This is my controller

```<code>namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use AppBundle\Entity\Todo;
use AppBundle\Model\TodoModel;

class TodoController extends Controller
{
    /**
    * @Route("/", name="homepage")
    */
    public function ShowList()
    {
        $todolist = TodoModel::getTodolist();

        $html = $this->container->get('templating')->render(
            'todolist/todolist.html.twig',
            array('todolist' => $todolist)
        );

        return new response($html);
    }
}
</code>```

This is my model

```<code>namespace AppBundle\Model;

use AppBundle\Entity\Todo;

class TodoModel
{

     public function getTodolist()
     {
       $repository = $this->getDoctrine()
           ->getRepository('AppBundle:Todo');
       $todolist = $repository->findAll();
       return $todolist;
    }

}
</code>```

答:
You need to inject doctrine into model, and define model as service. And better to use repository.

Using repositories

Body:
I am tryin to call a function from my controller and return the $todolist to my controller. But i get this error, when i leave this function inside the controller it works fine, but i don't want it to be in the controller.

This is my controller

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use AppBundle\Entity\Todo;
use AppBundle\Model\TodoModel;

class TodoController extends Controller
{
    /**
    * @Route("/", name="homepage")
    */
    public function ShowList()
    {
        $todolist = TodoModel::getTodolist();

        $html = $this->container->get('templating')->render(
            'todolist/todolist.html.twig',
            array('todolist' => $todolist)
        );

        return new response($html);
    }
}

This is my model

namespace AppBundle\Model;

use AppBundle\Entity\Todo;

class TodoModel
{

     public function getTodolist()
     {
       $repository = $this->getDoctrine()
           ->getRepository('AppBundle:Todo');
       $todolist = $repository->findAll();
       return $todolist;
    }

}


问:
Erratic behaviour when mixing pandas, datetime and numpy timedelta (bug?)
I have noticed by chance that some operations (a > b) on datetime that should give the same (well-defined) results actually give different results (some correct, some wrong, some just throwing an error) depending on whether I do them on a pandas dataframe or in numpy. I try to give a small example below. For brevity, I use dateutile.parser.parse function, but I think that the issue comes up in the interplay between datetime, pandas and numpy packages, in particular when using pandas' DatetimeIndex.

First I try to create a df out of np.timedelta64, and that I can't compare to a single np.timedelta64; it's a clean error, which I think is ok:

```<code>import numpy as np
import pandas as pd
from dateutil.parser import parse
a1 = np.array([np.datetime64(parse('20200101')),np.datetime64(parse('20150101'))]).reshape((1,-1))
a2 = np.array([np.datetime64(parse('20100101')),np.datetime64(parse('20180101'))]).reshape((-1,1))
df1 = pd.DataFrame(a1-a2)
df1 > np.timedelta64(1000,'D')
</code>```

With the above df1 is:

```<code>    0                       1
0   3652 days 00:00:00  1826 days 00:00:00
1   730 days 00:00:00   -1096 days +00:00:00
</code>```

and the second command throws an error "TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''". So far, so good.

However, if I write:

```<code>a3 = pd.DatetimeIndex(a1.flatten()).values.reshape((1,-1))
df2 = pd.DataFrame(a3 - a2)
</code>```

then the result looks similar: df2 =

```<code>    0           1
0   3652 days   1826 days
1   730 days    -1096 days
</code>```

But in this case, df2 > np.timedelta64(1000,'D') not only does not throw an error, but it gives a wrong answer:

```<code>    0       1
0   True    True
1   True    False
</code>```

On the other hand, if instead of doing pd.DataFrame(a3-a2) > np.timedelta64(1000,'D'), we do pd.DataFrame(a3-a2 > np.timedelta64(1000,'D')), we get the good answer:

```<code>    0       1
0   True    True
1   False   False
</code>```

Given the situation, I imagine there must be a bug somewhere, although I am not quite sure where. Maybe I am just misunderstanding some notations, but the behavior is a bit puzzling anyway. Some issue may come from the fact that, with the above definitions, some dtypes (e.g. df1) are in microseconds, some other (e.g. df2) are in nanoseconds; however, I expect these should be treated correctly, since the output is correctly transformed to days...

For reference, I am using Python 3.5, numpy version 1.12.1, pandas version 0.18.0, and python-dateutil version 2.5.1.

EDIT: After further testing, and taking into account Paul's answer below:

The error has apparently been solved with Pandas version 0.19.2. Paul's code snippet below, as well as the code above concerning df2, have been tested by Paul to correctly work under Linux, Python3.5, Pandas 0.19.2, and I have also checked them under both Linux and windows, both Python2.7 and Python3.5, Pandas 0.20.2.

In 0.18.2, Paul's code snippet below gives the same (wrong) answer as df2 above.

However, in my tests, also in 0.20.2, the first code above (df1 on this question) gives a wrong answer, giving all False. This is probably due to the fact that pandas stores the dates as microseconds (because Paul's explicit cast solves the issue), while numpy as nanoseconds, so there is a silent factor of 1000. Still, I would think that this should be taken care of automatically...

答:
This behavior is apparently not consistent, as I am not able to recreate your problem on the latest version of pandas, but it does seem that the main difference between the two situations is that df1 is storing np.dtype('timedelta64[us]') objects and df2 is storing np.dtype('timedelta64[ns]') objects.

I'm not sure why you think that df1 > np.timedelta64(1000, 'D') should fail - my intuition would be that it does not have any type-casting problems. That said, it seems that, as of at least version 0.19.2, if you always make sure to cast your dataframes to np.timedelta64[ns], you won't have this problem:

```<code>import pandas as pd
import numpy as np
from datetime import datetime

a1 = np.array([np.datetime64(datetime(2020, 1, 1)),
               np.datetime64(datetime(2015, 1, 1))]).reshape((1,-1))
a2 = np.array([np.datetime64(datetime(2010,1,1)),
               np.datetime64(datetime(2018,1,1))]).reshape((-1,1))

df1 = pd.DataFrame(a1 - a2).astype(np.dtype('timedelta64[ns]'))
kiloday = np.timedelta64(1000, 'D')

df1 > kiloday
#        0      1
# 0   True   True
# 1  False  False
</code>```

Body:
I have noticed by chance that some operations (a > b) on datetime that should give the same (well-defined) results actually give different results (some correct, some wrong, some just throwing an error) depending on whether I do them on a pandas dataframe or in numpy. I try to give a small example below. For brevity, I use dateutile.parser.parse function, but I think that the issue comes up in the interplay between datetime, pandas and numpy packages, in particular when using pandas' DatetimeIndex.

First I try to create a df out of np.timedelta64, and that I can't compare to a single np.timedelta64; it's a clean error, which I think is ok:

import numpy as np
import pandas as pd
from dateutil.parser import parse
a1 = np.array([np.datetime64(parse('20200101')),np.datetime64(parse('20150101'))]).reshape((1,-1))
a2 = np.array([np.datetime64(parse('20100101')),np.datetime64(parse('20180101'))]).reshape((-1,1))
df1 = pd.DataFrame(a1-a2)
df1 > np.timedelta64(1000,'D')

With the above df1 is:

    0                       1
0   3652 days 00:00:00  1826 days 00:00:00
1   730 days 00:00:00   -1096 days +00:00:00

and the second command throws an error "TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''". So far, so good.

However, if I write:

a3 = pd.DatetimeIndex(a1.flatten()).values.reshape((1,-1))
df2 = pd.DataFrame(a3 - a2)

then the result looks similar: df2 =

    0           1
0   3652 days   1826 days
1   730 days    -1096 days

But in this case, df2 > np.timedelta64(1000,'D') not only does not throw an error, but it gives a wrong answer:

    0       1
0   True    True
1   True    False

On the other hand, if instead of doing pd.DataFrame(a3-a2) > np.timedelta64(1000,'D'), we do pd.DataFrame(a3-a2 > np.timedelta64(1000,'D')), we get the good answer:

    0       1
0   True    True
1   False   False

Given the situation, I imagine there must be a bug somewhere, although I am not quite sure where. Maybe I am just misunderstanding some notations, but the behavior is a bit puzzling anyway. Some issue may come from the fact that, with the above definitions, some dtypes (e.g. df1) are in microseconds, some other (e.g. df2) are in nanoseconds; however, I expect these should be treated correctly, since the output is correctly transformed to days...

For reference, I am using Python 3.5, numpy version 1.12.1, pandas version 0.18.0, and python-dateutil version 2.5.1.

EDIT: After further testing, and taking into account Paul's answer below:

The error has apparently been solved with Pandas version 0.19.2. Paul's code snippet below, as well as the code above concerning df2, have been tested by Paul to correctly work under Linux, Python3.5, Pandas 0.19.2, and I have also checked them under both Linux and windows, both Python2.7 and Python3.5, Pandas 0.20.2.

In 0.18.2, Paul's code snippet below gives the same (wrong) answer as df2 above.

However, in my tests, also in 0.20.2, the first code above (df1 on this question) gives a wrong answer, giving all False. This is probably due to the fact that pandas stores the dates as microseconds (because Paul's explicit cast solves the issue), while numpy as nanoseconds, so there is a silent factor of 1000. Still, I would think that this should be taken care of automatically...

Body:
This behavior is apparently not consistent, as I am not able to recreate your problem on the latest version of pandas, but it does seem that the main difference between the two situations is that df1 is storing np.dtype('timedelta64[us]') objects and df2 is storing np.dtype('timedelta64[ns]') objects.

I'm not sure why you think that df1 > np.timedelta64(1000, 'D') should fail - my intuition would be that it does not have any type-casting problems. That said, it seems that, as of at least version 0.19.2, if you always make sure to cast your dataframes to np.timedelta64[ns], you won't have this problem:

import pandas as pd
import numpy as np
from datetime import datetime

a1 = np.array([np.datetime64(datetime(2020, 1, 1)),
               np.datetime64(datetime(2015, 1, 1))]).reshape((1,-1))
a2 = np.array([np.datetime64(datetime(2010,1,1)),
               np.datetime64(datetime(2018,1,1))]).reshape((-1,1))

df1 = pd.DataFrame(a1 - a2).astype(np.dtype('timedelta64[ns]'))
kiloday = np.timedelta64(1000, 'D')

df1 > kiloday
#        0      1
# 0   True   True
# 1  False  False


问:
Faster reading of time series from netCDF?
I have some large netCDF files that contain 6 hourly data for the earth at 0.5 degree resolution.

There are 360 latitude points, 720 longitude points, and 1420 time points per year. I have both yearly files (12 GB ea) and one file with 110 years of data (1.3 TB) stored as netCDF-4 (here is an example of the 1901 data, 1901.nc, its use policy, and the original, public files that I started with).

From what I understood, it should be faster to read from one netCDF file rather than looping over the set of files separated by year and variable originally provided.

I want to extract a time series for each grid point, e.g. 10 or 30 years from a specific latitude and longitude. However, I am finding this to be very slow. As an example, it takes me 0.01 seconds to read in 10 values over time from a point location although I can read in a global slice of 10000 values from a single time point in 0.002 second (the order of the dimensions is lat, lon, time):

```<code>## a time series of 10 points from one location:
library(ncdf4)
met.nc <- nc_open("1901.nc")
system.time(a <- ncvar_get(met.nc, "lwdown", start = c(100,100,1),
                                             count = c(1,1,10)))
   user  system elapsed
  0.001   0.000   0.090

## close down session

## a global slice of 10k points from one time
library(ncdf4)
system.time(met.nc <- nc_open("1901.nc"))
system.time(a <- ncvar_get(met.nc, "lwdown", start = c(100,100,1),
                                             count = c(100,100,1)))
   user  system elapsed
  0.002   0.000   0.002
</code>```

I suspect that these files have been written to optimize reading of spatial layers because a) the order of variables is lat, lon, time, b) that would be the logical order for the climate models that generated these files and c) because global extents are the most common visualization.

I have attempted to reorder variables so that time comes first:

```<code>ncpdq -a time,lon,lat 1901.nc 1901_time.nc
</code>```

(ncpdq is from the NCO (netCDF operators) software)

```<code>> library(ncdf4)

## first with the original data set:
> system.time(met.nc <- nc_open("test/1901.nc"))
   user  system elapsed
  0.024   0.045  22.334
> system.time(a <- ncvar_get(met.nc, "lwdown", start = c(100,100,1), count = c(1, 1, 1000))
+ )
   user  system elapsed
  0.005   0.027  14.958

## now with the rearranged dimensions:
> system.time(met_time.nc <- nc_open("test/1901_time.nc"))
   user  system elapsed
  0.025   0.041  16.704
> system.time(a <- ncvar_get(met_time.nc, "lwdown", start = c(100,100,1), count = c(1, 1, 1000)))
   user  system elapsed
  0.001   0.019   9.660
</code>```

How can I optimize reading time series at a point rather than layers of large areas at one time point? For example, would it be faster if the files were written differently, such as time, lat, lon? Is there an "easy" way to transform the order of dimensions in a netCDF-4 file?

Update

(benchmarks requested by @mdsumner)

```<code>library(rbenchmark)
library(ncdf4)
nc <- nc_open("1901.nc")
benchmark(timeseries = ncvar_get(nc, "lwdown",
                                 start = c(1, 1, 50),
                                 count = c(10, 10, 100)),
          spacechunk = ncvar_get(nc, "lwdown",
                                  start = c(1, 1, 50),
                                  count = c(100, 100, 1)),
          replications = 1000)

        test replications elapsed relative user.self sys.self user.child
2 spacechunk         1000   0.909    1.000     0.843    0.066          0
1 timeseries         1000   2.211    2.432     1.103    1.105          0
  sys.child
2         0
1         0
</code>```

Update 2:

I have started developing a solution here. The bits and pieces are in a set of scripts in github.com/ebimodeling/model-drivers/tree/master/met/cruncep

The scripts still need some work and organization - not all of the scripts are useful. But the reads are lightning quick. Not exactly comparable to the above results, but at the end of the day, I can read a 100 year, six-hourly time series from a 1.3TB file (0.5 degree resolution in 2.5s) instantly:

```<code>system.time(ts <- ncvar_get(met.nc, "lwdown", start = c(50, 1, 1), count = c(160000, 1, 1)))
   user  system elapsed
  0.004   0.000   0.004
</code>```

(note: The order of dimensions have changed, as described here: How can I specify dimension order when using ncdf4::ncvar_get?)

答:
Not sure if you have considered cdo to extract the point ?

```<code>cdo remapnn,lon=x/lat=y in.nc point.nc
</code>```

Sometimes CDO runs out of memory, if this happens, you might need to loop over the yearly files, and then cat the separate point files with

```<code>cdo mergetime point_${yyyy}.nc point_series.nc
</code>```

Body:
I have some large netCDF files that contain 6 hourly data for the earth at 0.5 degree resolution.

There are 360 latitude points, 720 longitude points, and 1420 time points per year. I have both yearly files (12 GB ea) and one file with 110 years of data (1.3 TB) stored as netCDF-4 (here is an example of the 1901 data, 1901.nc, its use policy, and the original, public files that I started with).

From what I understood, it should be faster to read from one netCDF file rather than looping over the set of files separated by year and variable originally provided.

I want to extract a time series for each grid point, e.g. 10 or 30 years from a specific latitude and longitude. However, I am finding this to be very slow. As an example, it takes me 0.01 seconds to read in 10 values over time from a point location although I can read in a global slice of 10000 values from a single time point in 0.002 second (the order of the dimensions is lat, lon, time):

## a time series of 10 points from one location:
library(ncdf4)
met.nc <- nc_open("1901.nc")
system.time(a <- ncvar_get(met.nc, "lwdown", start = c(100,100,1),
                                             count = c(1,1,10)))
   user  system elapsed
  0.001   0.000   0.090

## close down session

## a global slice of 10k points from one time
library(ncdf4)
system.time(met.nc <- nc_open("1901.nc"))
system.time(a <- ncvar_get(met.nc, "lwdown", start = c(100,100,1),
                                             count = c(100,100,1)))
   user  system elapsed
  0.002   0.000   0.002

I suspect that these files have been written to optimize reading of spatial layers because a) the order of variables is lat, lon, time, b) that would be the logical order for the climate models that generated these files and c) because global extents are the most common visualization.

I have attempted to reorder variables so that time comes first:

ncpdq -a time,lon,lat 1901.nc 1901_time.nc

(ncpdq is from the NCO (netCDF operators) software)

> library(ncdf4)

## first with the original data set:
> system.time(met.nc <- nc_open("test/1901.nc"))
   user  system elapsed
  0.024   0.045  22.334
> system.time(a <- ncvar_get(met.nc, "lwdown", start = c(100,100,1), count = c(1, 1, 1000))
+ )
   user  system elapsed
  0.005   0.027  14.958

## now with the rearranged dimensions:
> system.time(met_time.nc <- nc_open("test/1901_time.nc"))
   user  system elapsed
  0.025   0.041  16.704
> system.time(a <- ncvar_get(met_time.nc, "lwdown", start = c(100,100,1), count = c(1, 1, 1000)))
   user  system elapsed
  0.001   0.019   9.660

How can I optimize reading time series at a point rather than layers of large areas at one time point? For example, would it be faster if the files were written differently, such as time, lat, lon? Is there an "easy" way to transform the order of dimensions in a netCDF-4 file?

Update

(benchmarks requested by @mdsumner)

library(rbenchmark)
library(ncdf4)
nc <- nc_open("1901.nc")
benchmark(timeseries = ncvar_get(nc, "lwdown",
                                 start = c(1, 1, 50),
                                 count = c(10, 10, 100)),
          spacechunk = ncvar_get(nc, "lwdown",
                                  start = c(1, 1, 50),
                                  count = c(100, 100, 1)),
          replications = 1000)

        test replications elapsed relative user.self sys.self user.child
2 spacechunk         1000   0.909    1.000     0.843    0.066          0
1 timeseries         1000   2.211    2.432     1.103    1.105          0
  sys.child
2         0
1         0

Update 2:

I have started developing a solution here. The bits and pieces are in a set of scripts in github.com/ebimodeling/model-drivers/tree/master/met/cruncep

The scripts still need some work and organization - not all of the scripts are useful. But the reads are lightning quick. Not exactly comparable to the above results, but at the end of the day, I can read a 100 year, six-hourly time series from a 1.3TB file (0.5 degree resolution in 2.5s) instantly:

system.time(ts <- ncvar_get(met.nc, "lwdown", start = c(50, 1, 1), count = c(160000, 1, 1)))
   user  system elapsed
  0.004   0.000   0.004

(note: The order of dimensions have changed, as described here: How can I specify dimension order when using ncdf4::ncvar_get?)

Body:
Not sure if you have considered cdo to extract the point ?

cdo remapnn,lon=x/lat=y in.nc point.nc

Sometimes CDO runs out of memory, if this happens, you might need to loop over the yearly files, and then cat the separate point files with

cdo mergetime point_${yyyy}.nc point_series.nc


问:
Sending email via Node.js using nodemailer is not working
I've set up a basic NodeJS server (using the nodemailer module) locally (http://localhost:8080) just so that I can test whether the server can actually send out emails.

If I understand the SMTP option correctly (please correct me if I'm wrong), I can either try to send out an email from my server to someone's email account directly, or I can send the email, still using Node.js, but via an actual email account (in this case my personal Gmail account), i.e using SMTP. This option requires me to login into that acount remotely via NodeJS.

So in the server below I'm actually trying to use NodeJs to send an email from my personal email account to my personal email account.

Here's my simple server :

```<code>var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport("SMTP", {
    service: 'Gmail',
    auth: {
        user: '*my personal Gmail address*',
        pass: '*my personal Gmail password*'
    }
});

var http = require('http');
var httpServer = http.createServer(function (request, response)
{
    transporter.sendMail({
       from: '*my personal Gmail address*',
       to: '*my personal Gmail address*',
       subject: 'hello world!',
       text: 'hello world!'
    });
}).listen(8080);
</code>```

However, it's not working. I got an email by Google saying :

Google Account: sign-in attempt blocked
  If this was you
  You can switch to an app made by Google such as Gmail to access your account (recommended) or change
  your settings at https://www.google.com/settings/security/lesssecureapps so that your account is no
  longer protected by modern security standards.

I couldn't find a solution for the above problem on the nodemailer GitHub page. Does anyone have a solution/suggestion ?

Thanks! :-)

答:
i just set my domain to: smtp.gmail.com and it works. I am using a VPS Vultr.

the code:

```<code>const nodemailer = require('nodemailer');
const ejs = require('ejs');
const fs = require('fs');

let transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: {
        user: 'xxx@gmail.com',
        pass: 'xxx'
    }
});

let mailOptions = {
    from: '"xxx" <xxx@gmail.com>',
    to: 'yyy@gmail.com',
    subject: 'Teste Templete ✔',
    html: ejs.render( fs.readFileSync('e-mail.ejs', 'utf-8') , {mensagem: 'olá, funciona'})
};

transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    console.log('Message %s sent: %s', info.messageId, info.response);
});
</code>```

my ejs template (e-mail.ejs):

```<code><html>
    <body>
        <span>Esse é um templete teste</span>
        <p> gerando com o EJS - <%=mensagem%> </p>
    </body>
</html>
</code>```

Make sure:

install ejs: npm install ejs --save

install nodemailer: npm install nodemailer --save

ping to smtp.gmail.com works: ping smtp.gmail.com

change xxx@gmail.com to your gmail email

change yyy@gmail.com to the    email that you want to send a email

Enable less secure apps

Disable Captcha temporarily

have a nice day ;)

Body:
I've set up a basic NodeJS server (using the nodemailer module) locally (http://localhost:8080) just so that I can test whether the server can actually send out emails.

If I understand the SMTP option correctly (please correct me if I'm wrong), I can either try to send out an email from my server to someone's email account directly, or I can send the email, still using Node.js, but via an actual email account (in this case my personal Gmail account), i.e using SMTP. This option requires me to login into that acount remotely via NodeJS.

So in the server below I'm actually trying to use NodeJs to send an email from my personal email account to my personal email account.

Here's my simple server :

var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport("SMTP", {
    service: 'Gmail',
    auth: {
        user: '*my personal Gmail address*',
        pass: '*my personal Gmail password*'
    }
});

var http = require('http');
var httpServer = http.createServer(function (request, response)
{
    transporter.sendMail({
       from: '*my personal Gmail address*',
       to: '*my personal Gmail address*',
       subject: 'hello world!',
       text: 'hello world!'
    });
}).listen(8080);

However, it's not working. I got an email by Google saying :

Google Account: sign-in attempt blocked
  If this was you
  You can switch to an app made by Google such as Gmail to access your account (recommended) or change
  your settings at https://www.google.com/settings/security/lesssecureapps so that your account is no
  longer protected by modern security standards.

I couldn't find a solution for the above problem on the nodemailer GitHub page. Does anyone have a solution/suggestion ?

Thanks! :-)

Body:
i just set my domain to: smtp.gmail.com and it works. I am using a VPS Vultr.

the code:

const nodemailer = require('nodemailer');
const ejs = require('ejs');
const fs = require('fs');

let transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: {
        user: 'xxx@gmail.com',
        pass: 'xxx'
    }
});

let mailOptions = {
    from: '"xxx" <xxx@gmail.com>',
    to: 'yyy@gmail.com',
    subject: 'Teste Templete ✔',
    html: ejs.render( fs.readFileSync('e-mail.ejs', 'utf-8') , {mensagem: 'olá, funciona'})
};

transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    console.log('Message %s sent: %s', info.messageId, info.response);
});

my ejs template (e-mail.ejs):

<html>
    <body>
        <span>Esse é um templete teste</span>
        <p> gerando com o EJS - <%=mensagem%> </p>
    </body>
</html>

Make sure:

install ejs: npm install ejs --save

install nodemailer: npm install nodemailer --save

ping to smtp.gmail.com works: ping smtp.gmail.com

change xxx@gmail.com to your gmail email

change yyy@gmail.com to the    email that you want to send a email

Enable less secure apps

Disable Captcha temporarily

have a nice day ;)


问:
Min-height on class doesn't work
I'm creating a website, but have a little problem, that I don't know how to solve.

```<code> <div id="middle">
        <div id="clock">Here shows JS clock</div><br>
        <div class="element">
            <img  height="80px" src="SOURCE"/><h1 style="float:left" >TITLE TEXT</h1><div class="clearboth"></div>
             TITLE TEXT
        </div>
        <div class="clearboth"></div>
        <div class="element">
            <img  height="80px" src="SOURCE"/><h1 style="float:left">TITLE TEXT</h1><div class="clearboth"></div>
            <p>SOME TEXT</p>
        </div>
</code>```

And CSS

```<code>    .element{
        background-color:#fff;
        min-heigth:100px;
    }
    #middle{
        font-family:'Roboto', monospace;
        padding-left:5px;
        padding-right:5px;
        min-height:1000px;
        width:1000px;
        background-color:#ffffff;
        margin:auto;
    }
    #middle > h1,h2,h3{
        font-family: 'VT323', monospace;
        font-size:34px;
        margin-left:20px;
    }
.clearboth{
    clear:both;
}

    #middle  p{
        text-indent: 40px;
        font-size:18px;
    }
</code>```

But it min-height doesn't work - next element starts right after previous one.

答:
It seems to me that what you want is to have space between  your elements, assuming that the code you write is corrected ("height" instead of "heigth" and the div#middle is closed), try adding to your element some margin at bottom.

```<code>.element {
    background-color: #fff;
    min-height: 100px;
    margin-bottom: 30px; /* Add this line to separate each element for 30px */
}
</code>```

If you don't need the margin on the last element just add a new selector to target the last .element in your code.

```<code>.element:last-of-type {
    margin-botton: 0;
}
</code>```

Title: Min-height on class doesn't work

Body:
I'm creating a website, but have a little problem, that I don't know how to solve.

Here shows JS clock

TITLE TEXT

             TITLE TEXT

TITLE TEXT

SOME TEXT

And CSS

    .element{
        background-color:#fff;
        min-heigth:100px;
    }
    #middle{
        font-family:'Roboto', monospace;
        padding-left:5px;
        padding-right:5px;
        min-height:1000px;
        width:1000px;
        background-color:#ffffff;
        margin:auto;
    }
    #middle > h1,h2,h3{
        font-family: 'VT323', monospace;
        font-size:34px;
        margin-left:20px;
    }
.clearboth{
    clear:both;
}

    #middle  p{
        text-indent: 40px;
        font-size:18px;
    }

But it min-height doesn't work - next element starts right after previous one.

Body:
It seems to me that what you want is to have space between  your elements, assuming that the code you write is corrected ("height" instead of "heigth" and the div#middle is closed), try adding to your element some margin at bottom.

.element {
    background-color: #fff;
    min-height: 100px;
    margin-bottom: 30px; /* Add this line to separate each element for 30px */
}

If you don't need the margin on the last element just add a new selector to target the last .element in your code.

.element:last-of-type {
    margin-botton: 0;
}


问:
html section jump with  more than once?
I have a simple

```<code><a name="top"></a>
</code>```

and another link:

```<code><a href="#top">Back to Top of Page</a>
</code>```

it works but after the first time the url turns to:

```<code>www.site.com/#top
</code>```

and it doesn't work after a user uses it one time.
How can I make it so it will work multiple times?

答: I've seen this before. Can you test in different browsers and see if behavior is consistent? Try restarting browser, also.</p>

Title: html section jump with <a name="something"> more than once?

Body:
I have a simple

and another link:

Back to Top of Page

it works but after the first time the url turns to:

www.site.com/#top

and it doesn't work after a user uses it one time.
How can I make it so it will work multiple times?


问:
Javascript change Typeof
I am new in JavaScript.

My code allows me to list the elements of a JSON document as well as their types, and concatenate all its in a string donnees_types.

The problem is that the typeof in JavaScript returns only number for a number and string for a string. I want to return double instead of number and varchar instead of string in order to get:

temperature double, humidite double, built varchar, fire varchar

I know I can replace in my string using replace, but is there any other method to change the typeof?

 var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

var keys = Object.keys(event);

donnees_types = "";

for(var i= 0; i < keys.length -1; i++)
donnees_types +=  keys[i] + " " +  typeof(event[keys[i]]) + ", ";

var donnees_t = donnees_types.substring(0, donnees_types.length - 2);
console.log(donnees_t);
 ```

答:
Look below - but be aware of some artifacts of isNaN (see documentation)

 var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

var keys = Object.keys(event);

donnees_types = "";

for(var i= 0; i < keys.length -1; i++)
donnees_types +=  keys[i] + " " +  (isNaN(event[keys[i]])?'varchar':'double') + ", ";

var donnees_t = donnees_types.substring(0, donnees_types.length - 2);
console.log(donnees_t);

 ```

Title: Javascript change Typeof


问:
How to get data fields from existing form library to the new list in SharePoint
I have an InfoPath form template in SharePoint and that is for some Project setup form. In that I had a simple text field name "PO Number" that was being used in some other form library to receive project details including
PO Number.

As per the requirement now one Project can have more than one "PO Number" so I changed the form design and code to make it functional following this link:

Submitting Data from InfoPath to a SharePoint List
And I created a list MyPONumbers in SharePoint to save all the PO Numbers for different Projects.And it works fine when I enter a new record in Project setup form, it saves PONumber for that Project in MyPONumbers list.

But Initially MyPONumbers list is empty and I want to get all the (Past) PONumbers for different Projects already existing in my Project setup Library as those projects are still active.

Is there any automatic process or way to get the past(existing) form data field  in the newly created list.

Please advise. Thank you.

答: You could create a Workflow for the old form Library? To do this make it start on change then go ahead and create another column in that old library (not the form) and create a grid view so you can edit that new column and change it(you can change 1 field then grab the bottom right of that field and drag to all of the old rows) or copy another columns data then past it into that new column and this will create the change event and trigger the WF you create to Create List Item in your new List. Worked for me one time I had this issue.</p>


问:
How do i remove dash(-) in R?
I'm very new to r. How should I make r read dash(-) or skip it and calculate average of No. of plant(last column).</p>

```<code>Genotype Rep    No. of plant
184  1   8
7    1   7
98   1   -
101  2   7
X    2   8
62   2   -
24   3   3
30   3   4
78   3   8
119  3   8
</code>```

答:
There are several options.

You can use gsub to convert it to an NA. For example gsub('-', NA, dat$'No. of plant', fixed=TRUE). (Use backticks instead of quotes). Then convert the data to numeric using as.numeric()

You can also specify the NA values when importing your data.

Below is an example:

```<code>dat=data.frame(Genotype=c(184, 7, 98, 101, 'X'),
           Rep=c(1,1,1,2,2),
           No=c(8,7,'-',7,8))

dat$No <- gsub('-',NA,dat$No,fixed=TRUE)
dat$No <- as.numeric(dat$No)
</code>```

Title: How do i remove dash(-) in R?

Body:
I'm very new to r. How should I make r read dash(-) or skip it and calculate average of No. of plant(last column).

Genotype Rep    No. of plant
184  1   8
7    1   7
98   1   -
101  2   7
X    2   8
62   2   -
24   3   3
30   3   4
78   3   8
119  3   8

Body:
There are several options.

You can use gsub to convert it to an NA. For example gsub('-', NA, dat$'No. of plant', fixed=TRUE). (Use backticks instead of quotes). Then convert the data to numeric using as.numeric()

You can also specify the NA values when importing your data.

Below is an example:

dat=data.frame(Genotype=c(184, 7, 98, 101, 'X'),
           Rep=c(1,1,1,2,2),
           No=c(8,7,'-',7,8))

dat$No <- gsub('-',NA,dat$No,fixed=TRUE)
dat$No <- as.numeric(dat$No)


问:
PHP function returns same values
I have defined a PHP function that works absolutely fine but I am facing a problem. I am trying to call GenerateIDNumber function multiple times on same page with different values but its returning the same value of first time defined variables, is there any way to close/end the function and recall it with new values.

Here is my code

```<code><?php
/* GenerateID Number */
function GenerateIDNumber($tablenames, $columnnames)
{
    global $conn;
    global $highest_id;

    $sql    = "SELECT MAX(" . $columnnames . ") as max FROM " . $tablenames;
    $rs     = mysqli_query($conn, $sql);
    $result = mysqli_fetch_row($rs);
    if ($result[0] >= 1) {
        $highest_id = $result[0] + 1;
    } else {
        $highest_id = 1;
    }
}
/* GenerateID Number */

$highest_id    = null;
$mytable_name  = "tblleasesalespayment";
$mycolumn_name = "PaymentID";
GenerateIDNumber($mytable_name, $mycolumn_name);
$printNumber     = $highest_id;
$SaleIDGenerator = "CRV-";
$SetNumberCust   = $SaleIDGenerator . $_SESSION['ACTBRANCHID'] . date('y') . sprintf("%08s", $printNumber);

$Code1 = $SetNumberCust;

$highest_id    = null;
$mytable_name  = "tblrepossess_vehicles";
$mycolumn_name = "rp_id";
new GenerateIDNumber($mytable_name, $mycolumn_name);
$printNumber   = $highest_id;
$SetNumberCust = "REP-" . $_SESSION['ACTBRANCHID'] . date('y') . sprintf("%08s", $printNumber);
$Code2         = $SetNumberCust;
?>
</code>```

答:
Check if this servers your request</p>

```<code>/* GenerateID Number */
function GenerateIDNumber($tablenames, $columnnames)
{
    global $conn;

    $sql    = "SELECT MAX(" . $columnnames . ") as max FROM " . $tablenames;
    $rs     = mysqli_query($conn, $sql);
    $result = mysqli_fetch_row($rs);
    if ($result[0] >= 1) {
        $highest_id = $result[0] + 1;
    } else {
        $highest_id = 1;
    }
    return $highest_id ;
}

 $highest_id    = null;
$mytable_name  = "tblleasesalespayment";
$mycolumn_name = "PaymentID";
$highest_id = GenerateIDNumber($mytable_name, $mycolumn_name);
$printNumber     = $highest_id;
$SaleIDGenerator = "CRV-";
$SetNumberCust   = $SaleIDGenerator . $_SESSION['ACTBRANCHID'] . date('y') . sprintf("%08s", $printNumber);

echo $Code1 = $SetNumberCust. " As Code1 value <br />";

$highest_id    = null;
$mytable_name  = "tblrepossess_vehicles";
$mycolumn_name = "rp_id";
$highest_id = GenerateIDNumber($mytable_name, $mycolumn_name);
$printNumber   = $highest_id;
$SetNumberCust = "REP-" . $_SESSION['ACTBRANCHID'] . date('y') . sprintf("%08s", $printNumber);
echo $Code2 = $SetNumberCust. " As Code2 value <br />";
</code>```

Title: PHP function returns same values

Body:
I have defined a PHP function that works absolutely fine but I am facing a problem. I am trying to call GenerateIDNumber function multiple times on same page with different values but its returning the same value of first time defined variables, is there any way to close/end the function and recall it with new values.

Here is my code

<?php
/* GenerateID Number */
function GenerateIDNumber($tablenames, $columnnames)
{
    global $conn;
    global $highest_id;

    $sql    = "SELECT MAX(" . $columnnames . ") as max FROM " . $tablenames;
    $rs     = mysqli_query($conn, $sql);
    $result = mysqli_fetch_row($rs);
    if ($result[0] >= 1) {
        $highest_id = $result[0] + 1;
    } else {
        $highest_id = 1;
    }
}
/* GenerateID Number */

$highest_id    = null;
$mytable_name  = "tblleasesalespayment";
$mycolumn_name = "PaymentID";
GenerateIDNumber($mytable_name, $mycolumn_name);
$printNumber     = $highest_id;
$SaleIDGenerator = "CRV-";
$SetNumberCust   = $SaleIDGenerator . $_SESSION['ACTBRANCHID'] . date('y') . sprintf("%08s", $printNumber);

$Code1 = $SetNumberCust;

$highest_id    = null;
$mytable_name  = "tblrepossess_vehicles";
$mycolumn_name = "rp_id";
new GenerateIDNumber($mytable_name, $mycolumn_name);
$printNumber   = $highest_id;
$SetNumberCust = "REP-" . $_SESSION['ACTBRANCHID'] . date('y') . sprintf("%08s", $printNumber);
$Code2         = $SetNumberCust;
?>

Body:
Check if this servers your request

/* GenerateID Number */
function GenerateIDNumber($tablenames, $columnnames)
{
    global $conn;

    $sql    = "SELECT MAX(" . $columnnames . ") as max FROM " . $tablenames;
    $rs     = mysqli_query($conn, $sql);
    $result = mysqli_fetch_row($rs);
    if ($result[0] >= 1) {
        $highest_id = $result[0] + 1;
    } else {
        $highest_id = 1;
    }
    return $highest_id ;
}

 $highest_id    = null;
$mytable_name  = "tblleasesalespayment";
$mycolumn_name = "PaymentID";
$highest_id = GenerateIDNumber($mytable_name, $mycolumn_name);
$printNumber     = $highest_id;
$SaleIDGenerator = "CRV-";
$SetNumberCust   = $SaleIDGenerator . $_SESSION['ACTBRANCHID'] . date('y') . sprintf("%08s", $printNumber);

echo $Code1 = $SetNumberCust. " As Code1 value <br />";

$highest_id    = null;
$mytable_name  = "tblrepossess_vehicles";
$mycolumn_name = "rp_id";
$highest_id = GenerateIDNumber($mytable_name, $mycolumn_name);
$printNumber   = $highest_id;
$SetNumberCust = "REP-" . $_SESSION['ACTBRANCHID'] . date('y') . sprintf("%08s", $printNumber);
echo $Code2 = $SetNumberCust. " As Code2 value <br />";


问:
How does app engine flexible environment works?
How does app engine flexible environment works? It creates one BIG instance, by increase memory and CPU capacity, or creates several small instances?

How I can implement one BIG instance, which will increase memory and CPU only, without creating new instances?

答:
Look at the resource settings to increase your host size.
 https://cloud.google.com/appengine/docs/flexible/nodejs/configuring-your-app-with-app-yaml#resource-settings</p>


问:
Can AD Distribution Group be used for authorizing users?
All the users I want to let into the admin section of my app are in a distribution group but not a security group.  Can I use a distribution group in the Usre.IsInRole() method and in the Authorize(Role="Domain\DistribGroup")] ?</p>

答: No you can't. Distribution groups play no part in security at all. They are used solely for email distribution via Outlook or Exchange etc.</p>


问:
Indexing arrays with enums in C#
I have a lot of fixed-size collections of numbers where each entry can be accessed with a constant. Naturally this seems to point to arrays and enums:

```<code>enum StatType {
    Foo = 0,
    Bar
    // ...
}

float[] stats = new float[...];
stats[StatType.Foo] = 1.23f;
</code>```

The problem with this is of course that you cannot use an enum to index an array without a cast (though the compiled IL is using plain ints). So you have to write this all over the place:

```<code>stats[(int)StatType.foo] = 1.23f;
</code>```

I have tried to find ways to use the same easy syntax without casting but haven't found a perfect solution yet. Using a dictionary seems to be out of the question since I found it to be around 320 times slower than an array. I also tried to write a generic class for an array with enums as index:

```<code>public sealed class EnumArray<T>
{
    private T[] array;
    public EnumArray(int size)
    {
        array = new T[size];
    }
    // slow!
    public T this[Enum idx]
    {
        get { return array[(int)(object)idx]; }
        set { array[(int)(object)idx] = value; }
    }
}
</code>```

or even a variant with a second generic parameter specifying the enum. This comes quite close to what I want but the problem is that you cannot just cast an unspecific enum (be it from a generic parameter or the boxed type Enum) to int. Instead you have to first box it with a cast to object and then cast it back. This works, but is quite slow. I found that the generated IL for the indexer looks something like this:

```<code>.method public hidebysig specialname instance !T get_Item(!E idx) cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldfld !0[] EnumArray`2<!T, !E>::array
    L_0006: ldarg.1
    L_0007: box !E
    L_000c: unbox.any int32
    L_0011: ldelem.any !T
    L_0016: ret
}
</code>```

As you can see there are unnecessary box and unbox instructions there. If you strip them from the binary the code works just fine and is just a tad slower than pure array access.

Is there any way to easily overcome this problem? Or maybe even better ways?
I think it would also be possible to tag such indexer methods with a custom attribute and strip those two instructions post-compile. What would be a suitable library for that? Maybe Mono.Cecil?

Of course there's always the possibility to drop enums and use constants like this:

```<code>static class StatType {
    public const int Foo = 0;
    public const int Bar = 1;
    public const int End = 2;
}
</code>```

which may be the fastest way since you can directly access the array.

答:
If you have a lot of fixed-size collections, then it would probably be easier to wrap up your properties in an object than a float[]:

```<code>public class Stats
{
    public float Foo = 1.23F;
    public float Bar = 3.14159F;
}
</code>```

Passing an object around will give you the type safety, concise code, and constant-time access that you want.

And if you really need to use an array, its easy enough to add a ToArray() method which maps the properties of your object to a float[].

Title: Indexing arrays with enums in C#

Body:
I have a lot of fixed-size collections of numbers where each entry can be accessed with a constant. Naturally this seems to point to arrays and enums:

enum StatType {
    Foo = 0,
    Bar
    // ...
}

float[] stats = new float[...];
stats[StatType.Foo] = 1.23f;

The problem with this is of course that you cannot use an enum to index an array without a cast (though the compiled IL is using plain ints). So you have to write this all over the place:

stats[(int)StatType.foo] = 1.23f;

I have tried to find ways to use the same easy syntax without casting but haven't found a perfect solution yet. Using a dictionary seems to be out of the question since I found it to be around 320 times slower than an array. I also tried to write a generic class for an array with enums as index:

public sealed class EnumArray<T>
{
    private T[] array;
    public EnumArray(int size)
    {
        array = new T[size];
    }
    // slow!
    public T this[Enum idx]
    {
        get { return array[(int)(object)idx]; }
        set { array[(int)(object)idx] = value; }
    }
}

or even a variant with a second generic parameter specifying the enum. This comes quite close to what I want but the problem is that you cannot just cast an unspecific enum (be it from a generic parameter or the boxed type Enum) to int. Instead you have to first box it with a cast to object and then cast it back. This works, but is quite slow. I found that the generated IL for the indexer looks something like this:

.method public hidebysig specialname instance !T get_Item(!E idx) cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldfld !0[] EnumArray`2<!T, !E>::array
    L_0006: ldarg.1
    L_0007: box !E
    L_000c: unbox.any int32
    L_0011: ldelem.any !T
    L_0016: ret
}

As you can see there are unnecessary box and unbox instructions there. If you strip them from the binary the code works just fine and is just a tad slower than pure array access.

Is there any way to easily overcome this problem? Or maybe even better ways?
I think it would also be possible to tag such indexer methods with a custom attribute and strip those two instructions post-compile. What would be a suitable library for that? Maybe Mono.Cecil?

Of course there's always the possibility to drop enums and use constants like this:

static class StatType {
    public const int Foo = 0;
    public const int Bar = 1;
    public const int End = 2;
}

which may be the fastest way since you can directly access the array.

Body:
If you have a lot of fixed-size collections, then it would probably be easier to wrap up your properties in an object than a float[]:

public class Stats
{
    public float Foo = 1.23F;
    public float Bar = 3.14159F;
}

Passing an object around will give you the type safety, concise code, and constant-time access that you want.

And if you really need to use an array, its easy enough to add a ToArray() method which maps the properties of your object to a float[].

OwnerDisplayName: Princess


问:
CSV File Processing - SAS
I am pretty new to SAS programming and trying to find the most efficient way to my current ongoing initiative. Basically, I need to modify the existing .csv file stored on the SAS server and save it in my folder on the same server.

Modification required:

keep .csv as format

use "|" instead of "," as delimiter

have the following output name: filename_YYYYMMDDhhmmss.csv

keep only 4 variables from the original file

rename some of the variables we keep

Here is the script I am currently using, but there are a few issues with it:

```<code> PROC IMPORT OUT = libname.original_file (drop=var0)
              FILE = "/.../file_on_server.csv"
              DBMS = CSV
              REPLACE;
 RUN;

%PUT date_human = %SYSFUNC(PUTN(%sysevalf(%SYSFUNC(TODAY())-1), datetime20.));

proc export data = libname.original_file ( rename= ( var1=VAR11 var2=VAR22 Type=VAR33 ))
        outfile = '/.../filename_&date_human..csv' label dbms=csv replace;
        delimiter='|';
run;
</code>```

I also have an issue with the variable called "Type" when renaming it as it looks like there is a conflict with some of the system key words. Date format is not good either, and I was not able to find the exact format on the SAS forums, unfortunately.

Any advice on how to make this script more efficient is greatly appreciated.

答:
I wouldn't bother with trying to actually read the data into a SAS dataset. Just process it and write it back out.  If the input structure is consistent then it is pretty simple.  Just read everything as character strings and output the columns that you want to keep.

Let's assume that the data has 12 columns and the last one of the four that want to keep is the 10th column.  So you only need to read in 10 of them.

First setup your input and output filenames in macro variables to make it easier to edit. You can use your logic for generating the filename for the new file.

```<code>%let infile=/.../file_on_server.csv;
%let outfile=/.../filename_&date_human..csv;
</code>```

Then use a simple DATA _NULL_ step to read the data as character strings and write it back out.  You can even change the relative order of the four columns if you want.  So this program will copy the 2nd, 5th, 4th and 10th columns and change the column headers to NewName1, NewName2, NewName3 and NewName4.

```<code>data _null_;
  infile "&infile" dsd dlm=',' truncover;
  file "&outfile" dsd dlm='|';
  length var1-var10 $200 ;
  input var1-var10;
  if _n_=1 then do;
     var2='NewName1';
     var5='NewName2';
     var4='NewName3';
     var10='NewName4';
  end;
  put var2 var5 var4 var10 ;
run;
</code>```

If some of the data for the four columns you want to keep are longer than 200 characters then just update the LENGTH statement.

So let's try a little experiment. First let's make a dummy CSV file.

```<code>filename example temp;
data _null_;
  file example ;
  input;
  put _infile_;
cards4;
a,b,c,d,e,f,g,h,i,j,k,l,m
1,2,3,4,5,6,7,8,9,10,11,12,13
o,p,q,r,s,t,u,v,w,x,y,z
;;;;
</code>```

Now let's try running it.  I will modify the INFILE and FILE statements to read from my temp file and write the result to the log.

```<code>  infile example /* "&infile" */ dsd dlm=',' truncover;
  file log /* "&outfile" */ dsd dlm='|';
</code>```

Here are the resulting rows written.

```<code>NewName1|NewName2|NewName3|NewName4
2|5|4|10
p|s|r|x
</code>```

Title: CSV File Processing - SAS

Body:
I am pretty new to SAS programming and trying to find the most efficient way to my current ongoing initiative. Basically, I need to modify the existing .csv file stored on the SAS server and save it in my folder on the same server.

Modification required:

keep .csv as format

use "|" instead of "," as delimiter

have the following output name: filename_YYYYMMDDhhmmss.csv

keep only 4 variables from the original file

rename some of the variables we keep

Here is the script I am currently using, but there are a few issues with it:

 PROC IMPORT OUT = libname.original_file (drop=var0)
              FILE = "/.../file_on_server.csv"
              DBMS = CSV
              REPLACE;
 RUN;

%PUT date_human = %SYSFUNC(PUTN(%sysevalf(%SYSFUNC(TODAY())-1), datetime20.));

proc export data = libname.original_file ( rename= ( var1=VAR11 var2=VAR22 Type=VAR33 ))
        outfile = '/.../filename_&date_human..csv' label dbms=csv replace;
        delimiter='|';
run;

I also have an issue with the variable called "Type" when renaming it as it looks like there is a conflict with some of the system key words. Date format is not good either, and I was not able to find the exact format on the SAS forums, unfortunately.

Any advice on how to make this script more efficient is greatly appreciated.

Body:
I wouldn't bother with trying to actually read the data into a SAS dataset. Just process it and write it back out.  If the input structure is consistent then it is pretty simple.  Just read everything as character strings and output the columns that you want to keep.

Let's assume that the data has 12 columns and the last one of the four that want to keep is the 10th column.  So you only need to read in 10 of them.

First setup your input and output filenames in macro variables to make it easier to edit. You can use your logic for generating the filename for the new file.

%let infile=/.../file_on_server.csv;
%let outfile=/.../filename_&date_human..csv;

Then use a simple DATA _NULL_ step to read the data as character strings and write it back out.  You can even change the relative order of the four columns if you want.  So this program will copy the 2nd, 5th, 4th and 10th columns and change the column headers to NewName1, NewName2, NewName3 and NewName4.

data _null_;
  infile "&infile" dsd dlm=',' truncover;
  file "&outfile" dsd dlm='|';
  length var1-var10 $200 ;
  input var1-var10;
  if _n_=1 then do;
     var2='NewName1';
     var5='NewName2';
     var4='NewName3';
     var10='NewName4';
  end;
  put var2 var5 var4 var10 ;
run;

If some of the data for the four columns you want to keep are longer than 200 characters then just update the LENGTH statement.

So let's try a little experiment. First let's make a dummy CSV file.

filename example temp;
data _null_;
  file example ;
  input;
  put _infile_;
cards4;
a,b,c,d,e,f,g,h,i,j,k,l,m
1,2,3,4,5,6,7,8,9,10,11,12,13
o,p,q,r,s,t,u,v,w,x,y,z
;;;;

Now let's try running it.  I will modify the INFILE and FILE statements to read from my temp file and write the result to the log.

  infile example /* "&infile" */ dsd dlm=',' truncover;
  file log /* "&outfile" */ dsd dlm='|';

Here are the resulting rows written.

NewName1|NewName2|NewName3|NewName4
2|5|4|10
p|s|r|x


问:
How can I put a database under git (version control)?
I'm doing a web app, and I need to make a branch for some major changes, the thing is, these changes require changes to the database schema, so I'd like to put the entire database under git as well.

How do I do that? is there a specific folder that I can keep under a git repository? How do I know which one? How can I be sure that I'm putting the right folder?

I need to be sure, because these changes are not backward compatible; I can't afford to screw up.

The database in my case is PostgreSQL

Edit:

Someone suggested taking backups and putting the backup file under version control instead of the database. To be honest, I find that really hard to swallow.

There has to be a better way.

Update:

OK, so there' no better way, but I'm still not quite convinced, so I will change the question a bit:

I'd like to put the entire database under version control, what database engine can I use so that I can put the actual database under version control instead of its dump?

Would sqlite be git-friendly?

Since this is only the development environment, I can choose whatever database I want.

Edit2:

What I really want is not to track my development history, but to be able to switch from my "new radical changes" branch to the "current stable branch" and be able for instance to fix some bugs/issues, etc, with the current stable branch. Such that when I switch branches, the database auto-magically becomes compatible with the branch I'm currently on.
I don't really care much about the actual data.

答:
We used to run a social website, on a standard LAMP configuration. We had a Live server, Test server, and Development server, as well as the local developers machines. All were managed using GIT.

On each machine, we had the PHP files, but also the MySQL service, and a folder with Images that users would upload. The Live server grew to have some 100K (!) recurrent users, the dump was about 2GB (!), the Image folder was some 50GB (!). By the time that I left, our server was reaching the limit of its CPU, Ram, and most of all, the concurrent net connection limits (We even compiled our own version of network card driver to max out the server 'lol'). We could not (nor should you assume with your website) put 2GB of data and 50GB of images in GIT.

To manage all this under GIT easily, we would ignore the binary folders (the folders containing the Images) by inserting these folder paths into .gitignore. We also had a folder called SQL outside the Apache documentroot path. In that SQL folder, we would put our SQL files from the developers in incremental numberings (001.florianm.sql, 001.johns.sql, 002.florianm.sql, etc). These SQL files were managed by GIT as well. The first sql file would indeed contain a large set of DB schema. We don't add user-data in GIT (eg the records of the users table, or the comments table), but data like configs or topology or other site specific data, was maintained in the sql files (and hence by GIT). Mostly its the developers (who know the code best) that determine what and what is not maintained by GIT with regards to SQL schema and data.

When it got to a release, the administrator logs in onto the dev server, merges the live branch with all developers and needed branches on the dev machine to an update branch, and pushed it to the test server. On the test server, he checks if the updating process for the Live server is still valid, and in quick succession, points all traffic in Apache to a placeholder site, creates a DB dump, points the working directory from 'live' to 'update', executes all new sql files into mysql, and repoints the traffic back to the correct site. When all stakeholders agreed after reviewing the test server, the Administrator did the same thing from Test server to Live server. Afterwards, he merges the live branch on the production server, to the master branch accross all servers, and rebased all live branches. The developers were responsible themselves to rebase their branches, but they generally know what they are doing.

If there were problems on the test server, eg. the merges had too many conflicts, then the code was reverted (pointing the working branch back to 'live') and the sql files were never executed. The moment that the sql files were executed, this was considered as a non-reversible action at the time. If the SQL files were not working properly, then the DB was restored using the Dump (and the developers told off, for providing ill-tested SQL files).

Today, we maintain both a sql-up and sql-down folder, with equivalent filenames, where the developers have to test that both the upgrading sql files, can be equally downgraded. This could ultimately be executed with a bash script, but its a good idea if human eyes kept monitoring the upgrade process.

It's not great, but its manageable. Hope this gives an insight into a real-life, practical, relatively high-availability site. Be it a bit outdated, but still followed.


问:
I am not able to import beautifulsoup or requests
I have switched from Pycharm to using Sublime Text, and importing/installing beautifulsoup4 and requests, (I will probably have the same problem with other modules) seems rather complicated.
I've tried installing them both by typing the followling in my terminal

```<code>sudo pip install requests
</code>```

and the same for beautifulsoup4 (I have pip installed).
When I, in terminal, type

```<code>python
</code>```

and then

```<code>import requests
</code>```

and

```<code>from bs4 import beautifulsoup4
</code>```

It says for requests:

```<code>ImportError: No module named requests
</code>```

and for soup:

```<code>ImportError: cannot import name beautifulsoup4
</code>```

What am I doing wrong? I haven't even tried doing anything in Sublime Text yet.

答:
cannot import name beautifulsoup4
means that you are trying to this:

```<code>from bs4 import beautifulsoup4
</code>```

instead of:

```<code>from bs4 import BeautifulSoup
</code>```

Body:
I have switched from Pycharm to using Sublime Text, and importing/installing beautifulsoup4 and requests, (I will probably have the same problem with other modules) seems rather complicated.
I've tried installing them both by typing the followling in my terminal

sudo pip install requests

and the same for beautifulsoup4 (I have pip installed).
When I, in terminal, type

python

and then

import requests

and

from bs4 import beautifulsoup4

It says for requests:

ImportError: No module named requests

and for soup:

ImportError: cannot import name beautifulsoup4

What am I doing wrong? I haven't even tried doing anything in Sublime Text yet.

Body:
cannot import name beautifulsoup4
means that you are trying to this:

from bs4 import beautifulsoup4

instead of:

from bs4 import BeautifulSoup


问:
How do you iterate through a mixed List<t> and print contents to console in C#?
I have a List<object> which contains strings and even additional lists.

```<code>List<object> NewArray = new List<object>();
</code>```

so basically the list contains a mixture....

As a sanity check, I want to print out the contents to the console.  I start by iterating through and test to see whether the element is a list.  If it isn't then it will be a string and can be printed to the console.  If it is a list, I want to iterate through and print the string contents to the console but with a tab to indent it.

I have this so far:

```<code>    for (int outer = 0; outer < NewArray.Count; outer++)
            {

                var innerList = NewArray[outer];

                if (innerList.GetType().IsGenericType && innerList.GetType().GetGenericTypeDefinition() == typeof(List<>))
                {

                    for (int inner = 0; inner < innerList.Count; inner++)
                    {

                        //print string
                    }
                }
                else
                {
                    //print string
                }
    }
</code>```

I didn't want to use a foreach loop as I'm not sure the order of the list would be guaranteed and will be in the future adding a increment number (which can be provided by the inner and outer variables).

The issue I am getting is an error here:

```<code>inner < innerList.Count
</code>```

which is:

Operator '<' cannot be applied to operands of type 'int' and 'method group'

What do I need to do to overcome this?  I'm not sure it is the most efficient way of achieving the end result but....

答:
One way you could do it is to check if the object implements ICollection, and if so, iterate over the contents. I created a recursive method to handle cases where a collection contained other collections, which includes an indentAmount argument, so that nested collections are indented by a tab each time they're encountered:

```<code>public static void PrintItem(object item, int indentAmount = 0)
{
    var indent = new string('\t', indentAmount);
    if (item == null) Console.WriteLine($"{indent}<null>");

    if (item is ICollection)
    {
        var innerItems = item as IEnumerable;
        Console.WriteLine($"{indent}Collection type encountered:");
        indentAmount++;
        foreach (var innerItem in innerItems)
        {
            PrintItem(innerItem, indentAmount);
        }
    }
    else
    {
        Console.WriteLine($"{indent}{item}");
    }
}
</code>```

Usage

```<code>private static void Main()
{
    var items = new List<object>
    {
        "first",
        2,
        new List<string> {"listFirst", "listSecond"},
        new[] {"arrayFirst", "arraySecond"},
        new ArrayList {"arrayListFirst", "arrayListSecond"},
        "third",
        new List<List<string>>
        {
            new List<string> {"nestedList1First", "nestedList1Second"},
            new List<string> {"nestedList2First", "nestedList2Second"}
        },
        4f,
        new object[] {5d, "six", new List<object>{"seven", 8} },
        9,
        "ten"
    };

    PrintItem(items);

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}
</code>```

Output

Body:
I have a List<object> which contains strings and even additional lists.

List<object> NewArray = new List<object>();

so basically the list contains a mixture....

As a sanity check, I want to print out the contents to the console.  I start by iterating through and test to see whether the element is a list.  If it isn't then it will be a string and can be printed to the console.  If it is a list, I want to iterate through and print the string contents to the console but with a tab to indent it.

I have this so far:

    for (int outer = 0; outer < NewArray.Count; outer++)
            {

                var innerList = NewArray[outer];

                if (innerList.GetType().IsGenericType && innerList.GetType().GetGenericTypeDefinition() == typeof(List<>))
                {

                    for (int inner = 0; inner < innerList.Count; inner++)
                    {

                        //print string
                    }
                }
                else
                {
                    //print string
                }
    }

I didn't want to use a foreach loop as I'm not sure the order of the list would be guaranteed and will be in the future adding a increment number (which can be provided by the inner and outer variables).

The issue I am getting is an error here:

inner < innerList.Count

which is:

Operator '<' cannot be applied to operands of type 'int' and 'method group'

What do I need to do to overcome this?  I'm not sure it is the most efficient way of achieving the end result but....

Body:
One way you could do it is to check if the object implements ICollection, and if so, iterate over the contents. I created a recursive method to handle cases where a collection contained other collections, which includes an indentAmount argument, so that nested collections are indented by a tab each time they're encountered:

public static void PrintItem(object item, int indentAmount = 0)
{
    var indent = new string('\t', indentAmount);
    if (item == null) Console.WriteLine($"{indent}<null>");

    if (item is ICollection)
    {
        var innerItems = item as IEnumerable;
        Console.WriteLine($"{indent}Collection type encountered:");
        indentAmount++;
        foreach (var innerItem in innerItems)
        {
            PrintItem(innerItem, indentAmount);
        }
    }
    else
    {
        Console.WriteLine($"{indent}{item}");
    }
}

Usage

private static void Main()
{
    var items = new List<object>
    {
        "first",
        2,
        new List<string> {"listFirst", "listSecond"},
        new[] {"arrayFirst", "arraySecond"},
        new ArrayList {"arrayListFirst", "arrayListSecond"},
        "third",
        new List<List<string>>
        {
            new List<string> {"nestedList1First", "nestedList1Second"},
            new List<string> {"nestedList2First", "nestedList2Second"}
        },
        4f,
        new object[] {5d, "six", new List<object>{"seven", 8} },
        9,
        "ten"
    };

    PrintItem(items);

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

Output


问:
Using Active Directory for authorization, or own system?
I am building a website to only be used on my domain and I am trying to design a better login screen then I have used in the past. I have used a script to check if the user was in AD then grab their permissions level from an sql table and use that to drive the application.  Would it be better to authenticate the same way  but to use AD groups to drive what permissions a user does/does not have?</p>

答:
This can only be answered by you. How fine-grained are the permissions you need? Is having an AD group like "Accounting", named after an actual department inside the organisation, specific enough? If not, how easily can you move users in and out of groups?

In short the pros and cons:

Active Directory authorization: good for letting large groups of users, who are already identified by an organizational unit, access course-grained functionality in your application. Less so for very fine-grained control, as it may be cumbersome having multiple AD groups be created in the organization where your application is going to run.

Application-specific role-based authorization (such as ASP.NET Identity): lets you as an application developer create groups and move users in and out of them. This is a negative point in and of itself: you, as a maintainer of the installed application, will have to maintain the users and groups, or instruct the client's applications manager's department how to do so, probably according with creating a UI for it.


问:
PHP PDO - Pass dynamic string array to JavaScript
I have come to an understanding that the problem is that I am trying to pass a string array to a JavaScript.

I do not know how to proceed.

FORM

```<code><input type="hidden" name="id">
<input type="hidden" name="adProd">
</code>```

DB Connection

```<code>$stmt = $conn->prepare("SELECT product_name, product_quantity, product_id FROM product ");
$stmt->execute();

// set the resulting array to associative
$result = $stmt->fetchAll(PDO::FETCH_OBJ);

foreach ($result as $v) {
  echo "<td style='width:150px;border:1px solid black;'>";
  echo "</td>";
  echo '<tr>';
  echo '<td>' .$v->product_name. "</td>";
  echo '<td>' .$v->product_quantity. "</td>";
  echo '<td>' .$v->product_id.  "</td>";
</code>```

product_id below works exactly as it should.

```<code>  echo '<td> <button type="submit" onclick="askForSell('.$v->product_id.')">  Sell  </button>  </td>';
</code>```

product_name on the other hand does not work.

```<code>  echo '<td> <button type="submit" onclick="askForBuy('.$v->product_name.')">   Buy   </button> </td>';
</code>```

JavaScript

```<code>form=document.getElementById("sellAndBuy");
</code>```

Works fine:

```<code>function askForSell(id) {
    form.action="sellProducts.php";
    form['id'].value = id;
    form.submit();
}
</code>```

Does not work:

```<code>function askForBuy(adProd) {
    form.action="buyProducts.php";
    form['adProd'].value = adProd;
    form.submit();
}
</code>```

答:
As the product name is a string, you need to have additional quotes around that name in the HTML. You'll need to escape those, since you already need to use both single and double quotes:

```<code>echo '<td> <button type="submit" onclick="askForBuy(\''.$v->product_name.'\')">   Buy   </button> </td>';
</code>```

Note the \' that were added.

As these escaped quotes can become a pain in more complex situations, and also because it is better practice, you should consider binding event handlers with pure JavaScript code instead of using onclick HTML attributes.

Body:
I have come to an understanding that the problem is that I am trying to pass a string array to a JavaScript.

I do not know how to proceed.

FORM

<input type="hidden" name="id">
<input type="hidden" name="adProd">

DB Connection

$stmt = $conn->prepare("SELECT product_name, product_quantity, product_id FROM product ");
$stmt->execute();

// set the resulting array to associative
$result = $stmt->fetchAll(PDO::FETCH_OBJ);

foreach ($result as $v) {
  echo "";
  echo "	";
  echo '
';
  echo '' .$v->product_name. "	";
  echo '' .$v->product_quantity. "	";
  echo '' .$v->product_id.  "	";

product_id below works exactly as it should.

  echo ' <button type="submit" onclick="askForSell('.$v->product_id.')">  Sell  </button>  	';

product_name on the other hand does not work.

  echo ' <button type="submit" onclick="askForBuy('.$v->product_name.')">   Buy   </button> 	';

JavaScript

form=document.getElementById("sellAndBuy");

Works fine:

function askForSell(id) {
    form.action="sellProducts.php";
    form['id'].value = id;
    form.submit();
}

Does not work:

function askForBuy(adProd) {
    form.action="buyProducts.php";
    form['adProd'].value = adProd;
    form.submit();
}

Body:
As the product name is a string, you need to have additional quotes around that name in the HTML. You'll need to escape those, since you already need to use both single and double quotes:

echo '<td> <button type="submit" onclick="askForBuy(\''.$v->product_name.'\')">   Buy   </button> </td>';

Note the \' that were added.

As these escaped quotes can become a pain in more complex situations, and also because it is better practice, you should consider binding event handlers with pure JavaScript code instead of using onclick HTML attributes.


问:
How to get the relative directory no matter from where it's included in PHP?
If it's Path_To_DocumentRoot/a/b/c.php,should always be /a/b.

I use this:

```<code>dirname($_SERVER["PHP_SELF"])
</code>```

But it won't work when it's included by another file in a different directory.

EDIT

I need a relative path to document root .It's used in web application.

I find there is another question with the same problem,but no accepted answer yet.

PHP - Convert File system path to URL

答:
I know this is an old question but the solutions suggested using DOCUMENT_ROOT assume the web folder structure reflects the server folder structure. I have a situation where this isn't the case. My solution is as follows. You can work out how a server address maps to a web address if you have an example from the same mapped area folders. As long as the root php file that included this file is in the same mapped area you have an example. </p>

<p>$_SERVER['SCRIPT_FILENAME'] is the server address of this file and $_SERVER['PHP_SELF'] is the web relative version. Given these two you can work out what the web relative version of your file is from its server address (__FILE__) as follows.</p>

```<code>function getCurrentFileUrl() {
    $file = __FILE__;
    $script = $_SERVER['SCRIPT_FILENAME'];
    $phpself = $_SERVER['PHP_SELF'];

    // find end of section of $file which is common to $script
    $i = 0;
    while($file[$i] == $script[$i]) {
        $i++;
    }
    // remove end section of $phpself that is the equivalent to the section of $script not included in $file.
    $phpself = substr($phpself, 0, strlen($phpself)-(strlen($script)-$i));
    // append end section of $file onto result
    $phpself .= substr($file, $i, strlen($file)-$i);

    // complete address
    return $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].$phpself;
}
</code>```

Body:
If it's Path_To_DocumentRoot/a/b/c.php,should always be /a/b.

I use this:

dirname($_SERVER["PHP_SELF"])

But it won't work when it's included by another file in a different directory.

EDIT

I need a relative path to document root .It's used in web application.

I find there is another question with the same problem,but no accepted answer yet.

PHP - Convert File system path to URL

Body:
I know this is an old question but the solutions suggested using DOCUMENT_ROOT assume the web folder structure reflects the server folder structure. I have a situation where this isn't the case. My solution is as follows. You can work out how a server address maps to a web address if you have an example from the same mapped area folders. As long as the root php file that included this file is in the same mapped area you have an example.

$_SERVER['SCRIPT_FILENAME'] is the server address of this file and $_SERVER['PHP_SELF'] is the web relative version. Given these two you can work out what the web relative version of your file is from its server address (__FILE__) as follows.

function getCurrentFileUrl() {
    $file = __FILE__;
    $script = $_SERVER['SCRIPT_FILENAME'];
    $phpself = $_SERVER['PHP_SELF'];

    // find end of section of $file which is common to $script
    $i = 0;
    while($file[$i] == $script[$i]) {
        $i++;
    }
    // remove end section of $phpself that is the equivalent to the section of $script not included in $file.
    $phpself = substr($phpself, 0, strlen($phpself)-(strlen($script)-$i));
    // append end section of $file onto result
    $phpself .= substr($file, $i, strlen($file)-$i);

    // complete address
    return $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].$phpself;
}


问:
iOS play file from iTunes library and modify samples on the run
So i am currently starting to develop a iOS app that will need to play audio files from iTunes library and modify audio stream with custom DSP effect that needs to modify RAW data.... I am still trying to decide if i am going to go with swift or objective-c...

I know how to access iTunes library using MediaPlayer framework, but i need a simple way to modify RAW audio data while playing and then play the modified stream back.... So the question is how can i modify the stream and then play it back, and if i use other framework than MediaPlayer framework to play songs with my DSP will my app pass the apple review?

答: This is exactly what AudioUnits are for. You can start here: https://developer.apple.com/documentation/audiounit</p>


问:
Laravel Dusk on Centos: Failed connect to localhost:9515; Connection refused
OK, today is the day. I finally started (again) to use TDD.

I notice that this thing called Dusk has appeared. Great, browser testing.

The only problem is that I get this:

Failed connect to localhost:9515; Connection refused

I did chmod 777 on the chromedriver files and still get the error.

My dev server is a Centos vm. Is this the problem?

Edit:

I think I am making some progress:

yum install GConf2

Now I get:

cannot find Chrome binary

EDIT

I am back on this now.

php artisan dusk gives me:

```<code>Facebook\WebDriver\Exception\UnknownServerException: unknown error: cannot find Chrome binary
  (Driver info: chromedriver=2.28.455506 (18f6627e265f442aeec9b6661a49fe819aeeea1f),platform=Linux 3.10.0-327.3.1.el7.x86_64 x86_64)
</code>```

If I do this:

```<code>./vendor/laravel/dusk/bin/chromedriver-linux
</code>```

I get this:

```<code>Starting ChromeDriver 2.28.455506 (18f6627e265f442aeec9b6661a49fe819aeeea1f) on port 9515
Only local connections are allowed.
</code>```

Any ideas?

Mick

答:
Try running: ./vendor/laravel/dusk/bin/chrome-linux

If you see:
Starting ChromeDriver 2.28.455506 (18f6627e265f442aeec9b6661a49fe819aeeea1f) on port 9515 (or whatever port you are using)
Only local connections are allowed.  Then it is working.  I also had to install the google-chrome binary:
How to install 64-bit Google Chrome on 64-bit RHEL/CentOS 7

The other thing to install is Xvfb.  Then you can run this command in a new terminal: Xvfb :0 -screen 0 1280x960x24 &

This is supposed to be the way to run this.  I however, have not been able to get this to work.  I am hoping someone can also add some input here.

Update:
I got his to work.  Make sure that nothing is running as root.

Body:
OK, today is the day. I finally started (again) to use TDD.

I notice that this thing called Dusk has appeared. Great, browser testing.

The only problem is that I get this:

Failed connect to localhost:9515; Connection refused

I did chmod 777 on the chromedriver files and still get the error.

My dev server is a Centos vm. Is this the problem?

Edit:

I think I am making some progress:

yum install GConf2

Now I get:

cannot find Chrome binary

EDIT

I am back on this now.

php artisan dusk gives me:

Facebook\WebDriver\Exception\UnknownServerException: unknown error: cannot find Chrome binary
  (Driver info: chromedriver=2.28.455506 (18f6627e265f442aeec9b6661a49fe819aeeea1f),platform=Linux 3.10.0-327.3.1.el7.x86_64 x86_64)

If I do this:

./vendor/laravel/dusk/bin/chromedriver-linux

I get this:

Starting ChromeDriver 2.28.455506 (18f6627e265f442aeec9b6661a49fe819aeeea1f) on port 9515
Only local connections are allowed.

Any ideas?

Mick


问:
Asp.Net Core 2.0 Linux Arm - SQLIte issue
we are currently trying to run asp.net core 2.0 (latest preview) on Linux arm (Raspberry Pi - Ubuntu Mate) and we were able to solve almost all the issues so application works very well.

Not we are trying to run it with SQL Db (Sqlite) and on Windows, everything works fine, we can connect and read the DB but on the linux, we are getting following error:
System.DllNotfoundException: Unable to load DLL 'e_sqlite3': The specified module or one of its dependencies could not be found. (Exception from HRESULT: 0x8007007E).

I think I already tried everything, installed sqlite on linux, but nothing helped.

Any idea what might be wrong?

Thanks a lot
Rado

答:
I am having the same issue and I after some investigation I think this happens because e_sqlite3.dll for ARM is not (yet) included the SQLitePCLRaw.bundle_green package.

This package contains the dll for different architectures but linux-arm is not yet mentioned in the dependencies (linux, osx and v110xp (win7) are).

We probably have to wait until the .NET Core ARM team adds it properly...


问:
Hosting Public websites with Django Dev Server
I am trying to host my personal website, I am new to hosting websites business, so this may be a Noob question.

So I made my website using django, and tested everything locally. Now I want to make the site public, then I came across this :
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment
which seemed to be a pain in the arse.

But, Then I figured i could make the website available on all interfaces using:

python manage.py runserver 0.0.0.0:80
  Now I can access the website using  http://myIp/myapp

So my question is, "Is it a good idea to host websites using the django dev server"

The gut feeling is a "No", but I really want to know "Why?"

答: You can use Apache,it's easy, and there are plenty of startup guides with django and apache, even in the django docs. </p>