问:
Laravel 5.4 Eloquent filter from a single input
I'm trying to make a query using laravel eloquent to join companies table with addresses and telephone numbers so a user can type into a single input field e.g address line or number and it will query across multiple tables/columns and only return ones which have a potential match.

I've looked into the wherehas but it seems to stop all results if both numbers and address tables have a match each.
I can get it to work I believe with a standard left join on these tables but I want a clean solution if possible. here is what i'm working with below which doesn't actually return any filtered results so i'm scratching my head a little.

The goal is a single input for ease of use but searching across multiple columns/tables and returning rows only with a match. Is there a wherehas option but for multiple conditions maybe? hope someone can understand what i'm trying to do.

```<code>public function addresses(){
    return $this->hasMany(Company_addresses::class, 'company_id', 'id');
}

public function digits(){
    return $this->hasMany(Company_digit::class, 'company_id', 'id');
}

public static function search($request)
{
    $filters = $request->all();
    $sortby = isset($filters['sortby']) ? $filters['sortby'] : 'created_at';
    $orderby = isset($filters['orderby']) ? $filters['orderby'] : 'desc';

    return static::with([
        'addresses' => function ($query) use ($filters) {
        $query->where('address_line_1', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('address_line_2', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('city', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('county', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('post_code', "LIKE", '%'.$filters['name'].'%');
        },
        'digits' => function ($query) use ($filters) {
        $query->where('number', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('extension', "LIKE", '%'.$filters['name'].'%');
        }])
        ->orderBy('companies.'.$sortby, $orderby)
        ->select(['id', 'registered_name', 'trading_name', 'created_at', 'type'])
        ->paginate(20);
}
</code>```

答:
This is how you would do it with relationship methods.

You indeed need to use ->whereHas(), but you need to wrap both ->whereHas('addresses', ...) and ->orWhereHas('digits', ...) in a ->where(function ($q) ...) method.

Like this:

```<code>public static function search($request)
{
    $filters = $request->all();
    $sortby = isset($filters['sortby']) ? $filters['sortby'] : 'created_at';
    $orderby = isset($filters['orderby']) ? $filters['orderby'] : 'desc';

    return self::where(function ($q) use ($filters) {
            $q->whereHas('addresses', function ($q) use ($filters) {
                $q->where('address_line_1', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('address_line_2', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('city', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('county', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('post_code', "LIKE", '%'.$filters['name'].'%');
            })
            ->orWhereHas('digits', function ($q) use ($filters) {
                $q->where('number', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('extension', "LIKE", '%'.$filters['name'].'%');
            });
        })
        ->with(['addresses', 'digits'])
        ->orderBy('companies.'.$sortby, $orderby)
        ->select(['id', 'registered_name', 'trading_name', 'created_at', 'type'])
        ->paginate(20);
}
</code>```

While the upper code should work, I would recommend rewriting the search method from static method to a scope. I would definitely rewrite it in a way to keep $request out of it as request has nothing to do with the model.

Like this:

```<code>// Use it like: \App\Company::search($request->all())->paginate(20);
public function scopeSearch($q, $filters)
{
    $sortBy = isset($filters['sortby']) ? $filters['sortby'] : 'created_at';
    $orderBy = isset($filters['orderby']) ? $filters['orderby'] : 'desc';

    return $q->where(function ($q) use ($filters) {
            $q->whereHas('addresses', function ($q) use ($filters) {
                $q->where('address_line_1', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('address_line_2', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('city', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('county', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('post_code', "LIKE", '%'.$filters['name'].'%');
            })
            ->orWhereHas('digits', function ($q) use ($filters) {
                $q->where('number', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('extension', "LIKE", '%'.$filters['name'].'%');
            });
        })
        ->with(['addresses', 'digits'])
        ->orderBy('companies.'.$sortby, $orderby)
        ->select(['id', 'registered_name', 'trading_name', 'created_at', 'type']);
}
</code>```

Body:
I'm trying to make a query using laravel eloquent to join companies table with addresses and telephone numbers so a user can type into a single input field e.g address line or number and it will query across multiple tables/columns and only return ones which have a potential match.

I've looked into the wherehas but it seems to stop all results if both numbers and address tables have a match each.
I can get it to work I believe with a standard left join on these tables but I want a clean solution if possible. here is what i'm working with below which doesn't actually return any filtered results so i'm scratching my head a little.

The goal is a single input for ease of use but searching across multiple columns/tables and returning rows only with a match. Is there a wherehas option but for multiple conditions maybe? hope someone can understand what i'm trying to do.

public function addresses(){
    return $this->hasMany(Company_addresses::class, 'company_id', 'id');
}

public function digits(){
    return $this->hasMany(Company_digit::class, 'company_id', 'id');
}

public static function search($request)
{
    $filters = $request->all();
    $sortby = isset($filters['sortby']) ? $filters['sortby'] : 'created_at';
    $orderby = isset($filters['orderby']) ? $filters['orderby'] : 'desc';

    return static::with([
        'addresses' => function ($query) use ($filters) {
        $query->where('address_line_1', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('address_line_2', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('city', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('county', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('post_code', "LIKE", '%'.$filters['name'].'%');
        },
        'digits' => function ($query) use ($filters) {
        $query->where('number', "LIKE", '%'.$filters['name'].'%')
            ->orWhere('extension', "LIKE", '%'.$filters['name'].'%');
        }])
        ->orderBy('companies.'.$sortby, $orderby)
        ->select(['id', 'registered_name', 'trading_name', 'created_at', 'type'])
        ->paginate(20);
}

Body:
This is how you would do it with relationship methods.

You indeed need to use ->whereHas(), but you need to wrap both ->whereHas('addresses', ...) and ->orWhereHas('digits', ...) in a ->where(function ($q) ...) method.

Like this:

public static function search($request)
{
    $filters = $request->all();
    $sortby = isset($filters['sortby']) ? $filters['sortby'] : 'created_at';
    $orderby = isset($filters['orderby']) ? $filters['orderby'] : 'desc';

    return self::where(function ($q) use ($filters) {
            $q->whereHas('addresses', function ($q) use ($filters) {
                $q->where('address_line_1', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('address_line_2', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('city', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('county', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('post_code', "LIKE", '%'.$filters['name'].'%');
            })
            ->orWhereHas('digits', function ($q) use ($filters) {
                $q->where('number', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('extension', "LIKE", '%'.$filters['name'].'%');
            });
        })
        ->with(['addresses', 'digits'])
        ->orderBy('companies.'.$sortby, $orderby)
        ->select(['id', 'registered_name', 'trading_name', 'created_at', 'type'])
        ->paginate(20);
}

While the upper code should work, I would recommend rewriting the search method from static method to a scope. I would definitely rewrite it in a way to keep $request out of it as request has nothing to do with the model.

Like this:

// Use it like: \App\Company::search($request->all())->paginate(20);
public function scopeSearch($q, $filters)
{
    $sortBy = isset($filters['sortby']) ? $filters['sortby'] : 'created_at';
    $orderBy = isset($filters['orderby']) ? $filters['orderby'] : 'desc';

    return $q->where(function ($q) use ($filters) {
            $q->whereHas('addresses', function ($q) use ($filters) {
                $q->where('address_line_1', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('address_line_2', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('city', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('county', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('post_code', "LIKE", '%'.$filters['name'].'%');
            })
            ->orWhereHas('digits', function ($q) use ($filters) {
                $q->where('number', "LIKE", '%'.$filters['name'].'%')
                    ->orWhere('extension', "LIKE", '%'.$filters['name'].'%');
            });
        })
        ->with(['addresses', 'digits'])
        ->orderBy('companies.'.$sortby, $orderby)
        ->select(['id', 'registered_name', 'trading_name', 'created_at', 'type']);
}


来源: stackexchange

问:
Installing Gemstash onto Jenkins Slave

I am trying to cache ruby gems onto a Jenkins slave. I have installed gemstash onto my linux virtualbox which runs the slave, but however, I am not sure if I am installing it in the right location.

Should I be installing it by logging into the Jenkins user in the terminal and installing it there? Because when I created the slave node, I didn't need to install Jenkins onto the box. The source I use for the gemfile is localhost:9292

EDIT:
And how can I check what packages gemstash has cached?

Checking if gemstash has cached packages can be done by following https://github.com/bundler/gemstash#bundling

Any help would be appreciated.

答:
As the README says, have a look in ~/.gemstash:

You might wonder where the gems are stored. After running the commands above, you will find a new directory at ~/.gemstash. This directory holds all the cached and private gems. It also has a server log, the database, and configuration for Gemstash.

ContentLicense: CC BY-SA 3.0

Title: Installing Gemstash onto Jenkins Slave


问:
Change specific value in PHP variable
I have a variable $var and it contain comma separated value.

```<code>$var = 'the_ring,hangover,wonder_woman';
</code>```

I want to make it like below.

```<code>$var = 'The Ring,Hangover,Wonder Woman';
</code>```

I tried $parts = explode(',', $var); also I tried strpos() and  stripos() but not able to figure it out.

What can I do to achieve this?

答:
This is how you replace _ with white spaces using str_replace() function

```<code>$var = 'the_ring,hangover,wonder_woman';
echo str_replace("_"," ",$var);
</code>```

Title: Change specific value in PHP variable

Body:
I have a variable $var and it contain comma separated value.

$var = 'the_ring,hangover,wonder_woman';

I want to make it like below.

$var = 'The Ring,Hangover,Wonder Woman';

I tried $parts = explode(',', $var); also I tried strpos() and  stripos() but not able to figure it out.

What can I do to achieve this?

Body:
This is how you replace _ with white spaces using str_replace() function

$var = 'the_ring,hangover,wonder_woman';
echo str_replace("_"," ",$var);


问:
Peak detection of measured signal
We use a data acquisition card to take readings from a device that increases its signal to a peak and then falls back to near the original value. To find the peak value we currently search the array for the highest reading and use the index to determine the timing of the peak value which is used in our calculations.

This works well if the highest value is the peak we are looking for but if the device is not working correctly we can see a second peak which can be higher than the initial peak. We take 10 readings a second from 16 devices over a 90 second period.

My initial thoughts are to cycle through the readings checking to see if the previous and next points are less than the current to find a peak and construct an array of peaks. Maybe we should be looking at a average of a number of points either side of the current position to allow for noise in the system. Is this the best way to proceed or are there better techniques?

We do use LabVIEW and I have checked the LAVA forums and there are a number of interesting examples. This is part of our test software and we are trying to avoid using too many non-standard VI libraries so I was hoping for feedback on the process/algorithms involved rather than specific code.

答:
There are lots and lots of classic peak detection methods, any of which might work.  You'll have to see what, in particular, bounds the quality of your data.  Here are basic descriptions:

Between any two points in your data, (x(0), y(0)) and (x(n), y(n)), add up y(i + 1) - y(i) for 0 <= i < n and call this T ("travel") and set R ("rise") to y(n) - y(0) + k for suitably small k.  T/R > 1 indicates a peak.  This works OK if large travel due to noise is unlikely or if noise distributes symmetrically around a base curve shape.  For your application, accept the earliest peak with a score above a given threshold, or analyze the curve of travel per rise values for more interesting properties.

Use matched filters to score similarity to a standard peak shape (essentially, use a normalized dot-product against some shape to get a cosine-metric of similarity)

Deconvolve against a standard peak shape and check for high values (though I often find 2 to be less sensitive to noise for simple instrumentation output).

Smooth the data and check for triplets of equally spaced points where, if x0 < x1 < x2, y1 > 0.5 * (y0 + y2), or check Euclidean distances like this:  D((x0, y0), (x1, y1)) + D((x1, y1), (x2, y2)) > D((x0, y0),(x2, y2)), which relies on the triangle inequality.  Using simple ratios will again provide you a scoring mechanism.

Fit a very simple 2-gaussian mixture model to your data (for example, Numerical Recipes has a nice ready-made chunk of code).  Take the earlier peak.  This will deal correctly with overlapping peaks.

Find the best match in the data to a simple Gaussian, Cauchy, Poisson, or what-have-you curve.  Evaluate this curve over a broad range and subtract it from a copy of the data after noting it's peak location.  Repeat.  Take the earliest peak whose model parameters (standard deviation probably, but some applications might care about kurtosis or other features) meet some criterion.  Watch out for artifacts left behind when peaks are subtracted from the data.
Best match might be determined by the kind of match scoring suggested in #2 above.

I've done what you're doing before:  finding peaks in DNA sequence data, finding peaks in derivatives estimated from measured curves, and finding peaks in histograms.

I encourage you to attend carefully to proper baselining.  Wiener filtering or other filtering or simple histogram analysis is often an easy way to baseline in the presence of noise.

Finally, if your data is typically noisy and you're getting data off the card as unreferenced single-ended output (or even referenced, just not differential), and if you're averaging lots of observations into each data point, try sorting those observations and throwing away the first and last quartile and averaging what remains.  There are a host of such outlier elimination tactics that can be really useful.

Title: Peak detection of measured signal

OwnerDisplayName: Thomas Kammeyer


问:
How many variables are too much for a class?
I want to see if anyone has a better design for a class (class as in OOP) I am writing. We have a script that puts shared folder stats in a CSV file. I am reading that in and putting it in a Share class.

My boss wants to know information like:

Total Number of Files

Total Size of Files

Number of Office Files

Size of Office Files

Number of Exe Files

Size of Exe Files

etc ....

I have a class with variables like $numOfficeFiles, $sizeOfficeFiles, etc. with a ton of get/set methods. Isn't there a better way to do this? What is the general rule if you have a class with a lot of variables/properties?

I think of this as a language agnostic question, but if it matters, I am using PHP.

答:
"A class should do one thing, and do it well"

If you're not breaking this rule, then I'd say there aren't too many.

However it depends.

If by too many you mean 100's, then you might want to break it into a data class and collection as shown in the edit below.

Then you've only one get/set operation, however there are pros and cons to this "lazyness".

EDIT:

On second glance, you've pairs of variables, Count and Size.
There should be another class e.g. FileInfo with count and class, now your frist class just has FileInfo classes.

You can also put file type e.g. "All", "Exe" . . . on the File Info class.
Now the parent class becomes a collection of FileInfo objects.

Personally, I think I'd go for that.

OwnerDisplayName: Ben

LastEditorDisplayName: mmyers

OwnerDisplayName: Binary Worrier

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Binary Worrier


问:
How to create a ellipse shaped window with VC++ using win32 API
I am creating a window program using VC++ through win32 API. I wanted to create a ellipse shaped window how this can be achived. </p>

答:
well, this is so late reply but I thought it would be important for you to know.
There is a freeware generates source code for VB, C++, C# and Delphi.All you have to do is design your form in photoshop or whatever painter, let that software detect the shape you designed and generate a code for you. You can study that code or just use it. Don't forget to read the help coz there are some issues concerning compiling. Happy Shaping.
http://www.byalexv.co.uk/</p>


问:
Two different named tables with same structure (GreenDAO)
I'm trying to create two same structure tables with greendao. So basically, I'm doing following to achieve. Create Position.class:

```<code>public class Position {

    protected double longitude;
    protected double latitude;

    public Position(double longitude, double latitude) {
        this.longitude = longitude;
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public double getLatitude() {
        return latitude;
    }
</code>```

And then create second class CurrentRouePosition.class

```<code>@Entity(
        generateConstructors = false,
        nameInDb = "CURRENT_POSITIONS"
    )
    public class CurrentPosition extends Position{

    public CurrentPosition(double longitude, double latitude) {
        super(longitude, latitude);
    }
</code>```

Unfortunately it doesn't create DAO classes. What could I do to achieve same structure different name tables in GreenDAO?

答:
GreenDAO does not support Entity inheritance as of now. There are approaches to achieve something similar, but they involve using the older generator approach (which you shouldn’t use).
https://github.com/greenrobot/greenDAO/issues/362

In general I don’t see why you want to implement another class which is exactly the same as the first. The only thing which differs is the time of insertion into the database.
Instead I would suggest to explicitly define an auto increment id to your Entity. By doing so you can query the last result (=highest id) from your DAO class which then would be your current position.

@Entity
public class Position {

    @Id(autoincrement = true)
    private Long id;

    protected double longitude;

    protected double latitude;
}
```

<p>Query current position:</p>

<pre class="lang-java prettyprint-override"><code>Position currentPosition = positionDao.queryBuilder()
    .orderDesc(PositionDao.Properties.Id).limit(1).unique();
</code>```

Body:
I'm trying to create two same structure tables with greendao. So basically, I'm doing following to achieve. Create Position.class:

public class Position {

    protected double longitude;
    protected double latitude;

    public Position(double longitude, double latitude) {
        this.longitude = longitude;
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public double getLatitude() {
        return latitude;
    }

And then create second class CurrentRouePosition.class

@Entity(
        generateConstructors = false,
        nameInDb = "CURRENT_POSITIONS"
    )
    public class CurrentPosition extends Position{

    public CurrentPosition(double longitude, double latitude) {
        super(longitude, latitude);
    }

Unfortunately it doesn't create DAO classes. What could I do to achieve same structure different name tables in GreenDAO?

Body:
GreenDAO does not support Entity inheritance as of now. There are approaches to achieve something similar, but they involve using the older generator approach (which you shouldn’t use).
https://github.com/greenrobot/greenDAO/issues/362

In general I don’t see why you want to implement another class which is exactly the same as the first. The only thing which differs is the time of insertion into the database.
Instead I would suggest to explicitly define an auto increment id to your Entity. By doing so you can query the last result (=highest id) from your DAO class which then would be your current position.

@Entity
public class Position {

    @Id(autoincrement = true)
    private Long id;

    protected double longitude;

    protected double latitude;
}

Query current position:

Position currentPosition = positionDao.queryBuilder()
    .orderDesc(PositionDao.Properties.Id).limit(1).unique();


问:
Change the delimiter in saveAsTextFile Option in Pyspark rdd
I have my dataset available in HDFS. I am reading it and performing filter operation.

```<code>dir = sc.textFile('/datasets/DelayedFlights.csv').filter(lambda x:
int(x.split(',')[24]) == 1).map(lambda y: y.split(','))
The output of above operation is
[u'1763', u'2008', u'1', u'3', u'4', u'922.0', u'915', u'', u'1050', u'WN',
u'1069', u'N630WN', u'', u'95.0', u'', u'', u'7.0', u'SAN', u'SMF', u'480',
u'', u'12.0', u'0', u'N', u'1', u'', u'', u'', u'', u'']
[u'1911', u'2008', u'1', u'3', u'4', u'2325.0', u'1900', u'', u'2030',
u'WN', u'2092', u'N302SW', u'', u'90.0', u'', u'', u'265.0', u'SFO', u'SAN',
u'447', u'', u'11.0', u'0', u'N', u'1', u'', u'', u'', u'', u'']
[u'2651', u'2008', u'1', u'4', u'5', u'1949.0', u'1905', u'', u'1910',
u'WN', u'1403', u'N504SW', u'', u'65.0', u'', u'', u'44.0', u'BOI', u'RNO',
u'335', u'', u'11.0', u'0', u'N', u'1', u'', u'', u'', u'', u'']
</code>```

I want to change save the above file to HDFS path using saveAsTextFile with tab delimiter
Can any one say me how to change delimiter from comma to tab in python

答:
One way to achieve this to convert the RDD to a dataframe and save the dataframe with format csv with delimiter option set to tab as shown below.

```<code>rdd = spark.sparkContext.parallelize([['1763', '2008', '1', '3', '4', '922.0'], ['1763', '2008', '1', '3', '4', '922.0'], ['1763', '2008', '1', '3', '4', '922.0']])
df = spark.createDataFrame(rdd.map(lambda x: tuple(x)))
df.write.format('com.databricks.spark.csv').option("delimiter", '\t').save('/path/to/csv/file/')
</code>```

If you dont want to convert your rdd to dataframe the follow the below snippet.

```<code>rdd.map(lambda x: '\t'.join(x)).saveAsTextFile('test_dir/output')
</code>```

The DataFrame approach is recommended over the above approach.

Body:
I have my dataset available in HDFS. I am reading it and performing filter operation.

dir = sc.textFile('/datasets/DelayedFlights.csv').filter(lambda x:
int(x.split(',')[24]) == 1).map(lambda y: y.split(','))
The output of above operation is
[u'1763', u'2008', u'1', u'3', u'4', u'922.0', u'915', u'', u'1050', u'WN',
u'1069', u'N630WN', u'', u'95.0', u'', u'', u'7.0', u'SAN', u'SMF', u'480',
u'', u'12.0', u'0', u'N', u'1', u'', u'', u'', u'', u'']
[u'1911', u'2008', u'1', u'3', u'4', u'2325.0', u'1900', u'', u'2030',
u'WN', u'2092', u'N302SW', u'', u'90.0', u'', u'', u'265.0', u'SFO', u'SAN',
u'447', u'', u'11.0', u'0', u'N', u'1', u'', u'', u'', u'', u'']
[u'2651', u'2008', u'1', u'4', u'5', u'1949.0', u'1905', u'', u'1910',
u'WN', u'1403', u'N504SW', u'', u'65.0', u'', u'', u'44.0', u'BOI', u'RNO',
u'335', u'', u'11.0', u'0', u'N', u'1', u'', u'', u'', u'', u'']

I want to change save the above file to HDFS path using saveAsTextFile with tab delimiter
Can any one say me how to change delimiter from comma to tab in python

Body:
One way to achieve this to convert the RDD to a dataframe and save the dataframe with format csv with delimiter option set to tab as shown below.

rdd = spark.sparkContext.parallelize([['1763', '2008', '1', '3', '4', '922.0'], ['1763', '2008', '1', '3', '4', '922.0'], ['1763', '2008', '1', '3', '4', '922.0']])
df = spark.createDataFrame(rdd.map(lambda x: tuple(x)))
df.write.format('com.databricks.spark.csv').option("delimiter", '\t').save('/path/to/csv/file/')

If you dont want to convert your rdd to dataframe the follow the below snippet.

rdd.map(lambda x: '\t'.join(x)).saveAsTextFile('test_dir/output')

The DataFrame approach is recommended over the above approach.


问:
Teamcity does not start build on git remote change
I'm trying to run build steps on Teamcity 2017.1.1 when changes are made on a git branch. I set up a VCS trigger and changes are seen by Teamcity because each time I commit, I can see on my project that there are some pending changes as you can see in the picture below:

Unfortunately, it does not run the build steps because I need to manually click on "run" to start build...

This is the VCS trigger I set in TeamCity to run build steps when an update is made on the dev branch on the git repository:

What is wrong in my config and why TeamCity does not automatically run build when changes are made?

Thanks in advance

答:
You see Pending changes and that means your VCS Root is configured and TeamCity has latest commits.
Your trigger configuration looks valid.

So the only possible problem here is that commits are done not for dev branch your trigger is configured.

As a general rule you can do localization of the problem. Try to perform small steps and check current behaviour.


问:
Enable/Disable console.log in production version
Based on a flag I want to enable or disable the console.log in the production versions. But I don't want to expose that option to my users because then everyone will ask about it and waste my time.

If I allow such flag to be stored in user preferences thru the Options dialog, till those preferences are loaded, my code will be spewing out the console.log output till that flag is loaded from the chrome storage.

I can create a debug flag cookie using extensions but unfortunately my extension works on many sites.

If I disable console.log altogether in production versions but when clients face problem then at that moment I'll not be able to look into the console.log to debug it. So this is not feasible.

Is there any what my extension can know from the first line that console.log needs to be bypassed or not every time the extension is run( includes BG script, content script and the options dialog)?

Body:
There is nothing that will set a value in all contexts which you don't have to obtain asynchronously. You're going to have to deal with it.

Primary method: Wait for the info. Delay execution until available.

The normal way to deal with this type of situation, is to just put all processing which might need the information into the program flow that begins with the callback of the the asynchronous call to storage.*. This is normal and expected with asynchronous programming. In almost all cases, this is how you should deal with it.

Waiting for the info should be easy for scripts in the background context (the background script/event page, popups, options pages, etc.) For anything other than a background script, these scripts are almost all user-interaction based functionality, which means the delay for a fetch to storage.local should be trivial. If it's not, you can always copy the value to a variable in the background page, which can be synchronously accessed directly by any script in the background context (see: Communicate between scripts in the background context (background script, browser action, page action, options page, etc.)).

For the background script, you could also use localStorage, which is synchronous. However, the data will not be available in all contexts.

For content scripts, needing to delay for the asynchronous data might mean moving your injection time earlier. In other words, you might need to inject (run_at or runAt) at document_start instead of document_idle or document_end. You would then need to delay the rest of processing until after the document is ready/loaded.

For content scripts already loaded at document_start

Specifically for console.log()

For your specific issue, output via console.log(), you can queue the output which would normally be sent to console.log() until after you have the data back from the async call to storage.local. Once you have the data, you can then either A) output everything in the queue and set everything to output normally, or B) dump everything in the queue and set every call to be dropped.

All of this can easily be done with just overwriting the function pointer at console.log to point to the queue function, the normal console.log(), or a null function. Thus, there would be no need to change how the rest of your script calls console.log(). If you are using other functions in console, it would get a bit more complicated, but console.log() is easy (I've done it, for performance reasons during testing, not for this particular issue).

In general (i.e. for things which can not be queue'ed for later)

This one is at best, non-trivial. There's no good solution for scripts injected via a manifest.json content_scripts entry.

Partition your code

Separate your code into what must be done immediately and what can wait for the callback. This may require you to manipulate the page such that some actions in the normal loading process are delayed until after you have the information. What you would actually need to do here will vary depending on exactly what you are wanting to accomplish. The best solution may end up being to have your code error on one side or the other of what your configuration would change, then patch things up to what they should be once you get the configuration information that indicates it should be the other way.

For example, an extension that is intended to prevent JavaScript from running in the page, but has a whitelist of permitted scripts/domains could just go ahead and remove all of the <script> elements as they are inserted. Then, once the configuration information is available, the permitted <scripts> could be re-inserted into the DOM.

Use chrome.tabs.executeScript()

With chrome.tabs.executeScript() you can inject a constructed script with configuration information prior to the injection of your main script. These scripts are in the same context so the first script can set variable(s) containing config information. For more information see: Pass a parameter to a content script injected using chrome.tabs.executeScript()

The background script (which executes the chrome.tabs.executeScript()) is in a different process than the process for the tab (the one that actually injects the script). Thus, when exactly a script is injected is going to be indeterminate due to the asynchronous nature of having multiple proceses. This means that you can not 100% guarantee that your script will be injected prior to the initial HTML being loaded into the DOM. You can usually inject prior to that, but not always.

When to inject for the earliest possible time is a bit complicated. One of the problems is that if you call tabs.executeScript() too early in the process of loading a new page, the injection does not take place in the new page. My testing (which I need to go back an re-do as I believe it could be improved) indicated:

Chrome: the earliest possible time for a consistently functional call to tabs.executeScript() is the webRequest.onHeadersReceived event after the webNavigation.onBeforeNavigate event.

head and body are usually null, but are sometimes populated

Firefox: the earliest possible time for a consistently functional call to tabs.executeScript() is the webRequest.onSendHeaders event after the webNavigation.onBeforeNavigate event.

head and body are null, but insufficient testing to say that this will always be the case.

Related: Google chrome extension: how to inject script immediately after page reload?


问:
Track error of subprocess and failures
I'm maintaining a Perforce server via a Unix executable which logs the errors in the terminal whenever something happens to it. What I would like to do is use Python to start the executable, and then have it watch for any errors being logged in the terminal window from the application it's executing.

The following code works for execution, but I have no idea how to get data back from the subprocess when it gets logged to the terminal via some form of callback.

```<code>import subprocess
subprocess.call(["./p4d"])
</code>```

答:
process.stdout and process.stdout are file-like objects that you can read from. Assuming things are logged to stdout:

```<code>proc = Popen(['./p4d'], stdout=PIPE, encoding='utf-8')  # Or whatever encoding suits
for line in proc.stdout:
    # Note that line will end in `\n`, unless it is the last line.
    line = line.rstrip('\n')

    # Do something depending on the line
</code>```

Title: Track error of subprocess and failures

Body:
I'm maintaining a Perforce server via a Unix executable which logs the errors in the terminal whenever something happens to it. What I would like to do is use Python to start the executable, and then have it watch for any errors being logged in the terminal window from the application it's executing.

The following code works for execution, but I have no idea how to get data back from the subprocess when it gets logged to the terminal via some form of callback.

import subprocess
subprocess.call(["./p4d"])

Body:
process.stdout and process.stdout are file-like objects that you can read from. Assuming things are logged to stdout:

proc = Popen(['./p4d'], stdout=PIPE, encoding='utf-8')  # Or whatever encoding suits
for line in proc.stdout:
    # Note that line will end in `\n`, unless it is the last line.
    line = line.rstrip('\n')

    # Do something depending on the line


问:
popup once every 5 minute
i have a bootstrap modal popup with following code that runs every time page loads.
I need the script run once for each session with cookie and cookie will expire after 5 minutes. can you please help?

here's the code:

```<code>$(window).on('load',function(){
    $('#myModal').modal('show');
});
</code>```

答:
```<code>setInterval(showModal, 300000);

function showModal()
{
  $('#myModal').modal('show');
}
</code>```

Title: popup once every 5 minute

Body:
i have a bootstrap modal popup with following code that runs every time page loads.
I need the script run once for each session with cookie and cookie will expire after 5 minutes. can you please help?

here's the code:

$(window).on('load',function(){
    $('#myModal').modal('show');
});


答:
1.use str_replace to replace something in the string. In your case _ is replaced with space
2.use ucFirst method to capitalize every first character in the strings  </p>

```<code>$replaced = str_replace('_', ' ', $var);
$changed = ucfirst($replaced);
</code>```

Title: Change specific value in PHP variable

Body:
1.use str_replace to replace something in the string. In your case _ is replaced with space
2.use ucFirst method to capitalize every first character in the strings

$replaced = str_replace('_', ' ', $var);
$changed = ucfirst($replaced);


问:
javascript regular expression match a string at some rules?
My purpose is to find a function that checks if a string starts with a lower-case letter, ends with a lower-case letter, may contain only one or no hyphen -, and is less than or equal to 32 characters.

The following is my code:

var ss = /^[a-z]+([A-Za-z0-9_]|(-?)|[a-z]+$){1,31}/;
str="ss-fjdkkldjkskjdskjdksjdkjdkjklskssdkdkffdkdfkdfk";
ss.test(str);```

test string
result with true
aJDS-a a234bds aHJH878sjkJSK-ja

My function is currently returning true and doesn't match my requirement.
If the test string match reg requirement, the result should return true.
I don't know why.

答:
Note that [A-Za-z0-9_] in JS regex is equal to \w. So, here are several solutions to your problem:

The length of the whole string is checked either with code (str.length > 0 && str.length <= 32) or using a (?=.{1,32}$) positive lookahead after ^ start-of-string anchor in the regex suggestions below

If you need to only match a string when it contains a single - somewhere inside, use an optional non-capturing group like this - ^[a-z]\w*(?:-\w*[a-z])?$ (=> ^(?=.{1,31}$)[a-z]\w*(?:-\w*[a-z])?$)

If that hyphen is optional, add ? quantifier after it: ^[a-z]\w*(?:-?\w*[a-z])?$ (=> ^(?=.{1,31}$)[a-z]\w*(?:-?\w*[a-z])?$)

If you need to only match a string when it contains any number of - somewhere inside, use ^[a-z](?:[-\w]*[a-z])?$ (=> ^(?=.{1,31}$)[a-z](?:[-\w]*[a-z])?$).

Body:
My purpose is to find a function that checks if a string starts with a lower-case letter, ends with a lower-case letter, may contain only one or no hyphen -, and is less than or equal to 32 characters.

The following is my code:

var ss = /^[a-z]+([A-Za-z0-9_]|(-?)|[a-z]+$){1,31}/;
str="ss-fjdkkldjkskjdskjdksjdkjdkjklskssdkdkffdkdfkdfk";
ss.test(str);

test string
result with true
aJDS-a a234bds aHJH878sjkJSK-ja

My function is currently returning true and doesn't match my requirement.
If the test string match reg requirement, the result should return true.
I don't know why.


问:
Android: keep web server running
I am running a web server (NanoHTTPD) in an Android Service.

onStartCommand() returns the value from the overridden method in Service, so it should be "sticky".

However the service seems to stop, or at least the webserver stops responding. This happens mostly when the device has been inactive for a while, with the screen off. But also sometimes when it is seemingly running normally. The notification icon of the service keeps being displayed.

The device is not doing anything else, and it is plugged into power.

What can be done to keep the web server responding to requests? Or at least reduce the frequency of outages?

答:
The best chances not being killed by the system in your case:

Start the service by startForeground

Prompt your users to include your app in the "ignore battery optimizations" list (you can not do this programmatically):

Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
startActivity(intent);

Title: Android: keep web server running


问:
c++ pass two integers into queue
i have created a queue class using array, that must hold two integers at most. But how do i pass two integers to the array at once? using bool Queue::enqueue(int, int)

Also i need a dequeue() which prints both integers and throws them away from the queue. Any suggestions how to accomplish this?

```<code>class Queue {
private:
  int * table;
  int front;
  int length;
  const int size=2;
public:
  Queue(int n);
  ~Queue();
  bool isEmpty();
  bool enqueue(int, int);
  bool dequeue();
  void print();
};

Queue::Queue(int n){
n=size;
length=0;
front=0;
table=new int[n];
}

Queue::~Queue(){
delete [] table;
}

bool Queue::isEmpty(){
if(length==size)
    return false;
else
    return true;
}

bool Queue::enqueue(int , int){
if (length == size)
  return -1; // Error, Queue is full
now i need to pass two integers if it it empty
</code>```

答:
Why do you want to play with the definition of a Queue? Seems like there is a flaw in your design. However I have still written a working code using a vector which will solve your purpose (though I doubt about what you want to achieve by adding/removing 2 items in enqueue/dequeue operations)</p>

```<code>#include <iostream>
#include <vector>

using namespace std;

class Queue {

  vector<int> table;
  const int CAPACITY = 2;

public:
  bool isEmpty();
  bool enqueue(int, int);
  void dequeue();
  void print();
};

bool Queue::isEmpty(){
    if(table.size())
        return false;
    else
        return true;
}

bool Queue::enqueue(int a, int b){
    if (table.size())
        return false; // Error, Queue is full
    table.push_back(a);
    table.push_back(b);
    return true;
}

void Queue::dequeue(){
    if(!table.size())
        return; //queue is empty
    table.pop_back();
    table.pop_back();
}

void Queue::print(){
    if(!table.size()){
        cout << "Queue is empty" << endl;
        return;
    }
    cout << table[0] << "," << table[1] << endl;
}

int main()
{
    //Make a variable of our container
    Queue queue;
    queue.enqueue(1,2);
    queue.print();
    queue.dequeue();
    queue.print();
    return 0;
}
</code>```

Title: c++ pass two integers into queue

Body:
i have created a queue class using array, that must hold two integers at most. But how do i pass two integers to the array at once? using bool Queue::enqueue(int, int)

Also i need a dequeue() which prints both integers and throws them away from the queue. Any suggestions how to accomplish this?

class Queue {
private:
  int * table;
  int front;
  int length;
  const int size=2;
public:
  Queue(int n);
  ~Queue();
  bool isEmpty();
  bool enqueue(int, int);
  bool dequeue();
  void print();
};

Queue::Queue(int n){
n=size;
length=0;
front=0;
table=new int[n];
}

Queue::~Queue(){
delete [] table;
}

bool Queue::isEmpty(){
if(length==size)
    return false;
else
    return true;
}

bool Queue::enqueue(int , int){
if (length == size)
  return -1; // Error, Queue is full
now i need to pass two integers if it it empty

Body:
Why do you want to play with the definition of a Queue? Seems like there is a flaw in your design. However I have still written a working code using a vector which will solve your purpose (though I doubt about what you want to achieve by adding/removing 2 items in enqueue/dequeue operations)

#include <iostream>
#include <vector>

using namespace std;

class Queue {

  vector<int> table;
  const int CAPACITY = 2;

public:
  bool isEmpty();
  bool enqueue(int, int);
  void dequeue();
  void print();
};

bool Queue::isEmpty(){
    if(table.size())
        return false;
    else
        return true;
}

bool Queue::enqueue(int a, int b){
    if (table.size())
        return false; // Error, Queue is full
    table.push_back(a);
    table.push_back(b);
    return true;
}

void Queue::dequeue(){
    if(!table.size())
        return; //queue is empty
    table.pop_back();
    table.pop_back();
}

void Queue::print(){
    if(!table.size()){
        cout << "Queue is empty" << endl;
        return;
    }
    cout << table[0] << "," << table[1] << endl;
}

int main()
{
    //Make a variable of our container
    Queue queue;
    queue.enqueue(1,2);
    queue.print();
    queue.dequeue();
    queue.print();
    return 0;
}


问:
Can you log or block automatic command line actions?
In the past week, I have been seeing the command line pop and close every 10-15 minutes. Very concerned about some type of malware or even a program causing it that I can remove.

I have read much here about logging output from the command line but is it possible to log activity or even block the command line from working/.

答:
you can use CurrPorts,This software allows you to see processes that use the network and to kill processes

http://www.nirsoft.net/utils/cports.html


答:
You can use array_walk to do your replace and uppercase:

```<code>$var = 'the_ring,hangover,wonder_woman';

$parts = explode(',', $var);

array_walk($parts, function(&$item){
    $item = str_replace('_', ' ', $item);
    $item = ucwords($item);
});

$var = implode(',', $parts);
</code>```

Title: Change specific value in PHP variable

Body:
You can use array_walk to do your replace and uppercase:

$var = 'the_ring,hangover,wonder_woman';

$parts = explode(',', $var);

array_walk($parts, function(&$item){
    $item = str_replace('_', ' ', $item);
    $item = ucwords($item);
});

$var = implode(',', $parts);


问:
Remove rows based on groupby of multiple columns resulting in lowest value only
I have the following data in a pandas dataframe in Python. I would like to group the data based on the Name and Property column, and keep only the lowest value within the Date.

Before:

```<code>  Name  Property                         Date
0   X1      Cash  621 days 00:00:00.000000000
1   X1      Cash  256 days 00:00:00.000000000
2   X1      Cash  101 days 00:00:00.000000000
3   X1  Overflow  352 days 00:00:00.000000000
4   X1  Overflow  101 days 00:00:00.000000000
5   X1  Overflow   53 days 00:00:00.000000000
</code>```

Repeat for X2/X3 etc.

After:

```<code>  Name  Property                         Date
2   X1      Cash  101 days 00:00:00.000000000
5   X1  Overflow   53 days 00:00:00.000000000
</code>```

I am attempting to play around with the syntax but unable to get it right:

```<code>df1 = df1[df1.groupby(['Name', 'Property'])['Date'].min()]
</code>```

答:
You can try transform in pandas , also it will not remove your additional columns.

```<code>DF = df[df.groupby(['Property'])['Date'].transform(min) == df['Date']]

   Name Property    Date

2   X1  Cash        101 days

5   X1  Overflow    53  days
</code>```

Body:
I have the following data in a pandas dataframe in Python. I would like to group the data based on the Name and Property column, and keep only the lowest value within the Date.

Before:

  Name  Property                         Date
0   X1      Cash  621 days 00:00:00.000000000
1   X1      Cash  256 days 00:00:00.000000000
2   X1      Cash  101 days 00:00:00.000000000
3   X1  Overflow  352 days 00:00:00.000000000
4   X1  Overflow  101 days 00:00:00.000000000
5   X1  Overflow   53 days 00:00:00.000000000

Repeat for X2/X3 etc.

After:

  Name  Property                         Date
2   X1      Cash  101 days 00:00:00.000000000
5   X1  Overflow   53 days 00:00:00.000000000

I am attempting to play around with the syntax but unable to get it right:

df1 = df1[df1.groupby(['Name', 'Property'])['Date'].min()]

Body:
You can try transform in pandas , also it will not remove your additional columns.

DF = df[df.groupby(['Property'])['Date'].transform(min) == df['Date']]

   Name Property    Date

2   X1  Cash        101 days

5   X1  Overflow    53  days


问:
Using PayPal for a membership site
I have a membership site in which users register an email and password, and also subscribe to a monthly plan. The frontend is jquery/ajax and the backend is PHP/Slim. So far I have integrated Stripe as a payment method because it offers a simple way to serialize a credit card, fire it off to Stripe servers, get a response, and carry on registering the user to my website.

Paypal is different however, as users may have to log in to their Paypal account. Paypal doesn't seem to offer the same ease of use as Stripe, and you must take care of serializing credit cards and other details on your own. I do not want to get into that territory of saving cards etc.

How then can I use Paypal inside of a signup form (where a user creates their credentials for my site) and know if their Paypal payment was successful to continue on creating their user for my site?

答:
Use Express Checkout -- https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/

It handles every different payment method supported by PayPal, including guest checkout without a PayPal account.

Title: Using PayPal for a membership site


答:
```<code>$var = 'the_ring,hangover,wonder_woman';
$var1 = explode(',' $var);

foreach ($var1 as $key => $value) {
   $var1[$key]=str_replace("_"," ",$value);
   $var1[$key]=ucwords($var1[$key]);
}
</code>```

$var = implode(',', $var1);

Title: Change specific value in PHP variable

Body:
I have a variable $var and it contain comma separated value.

$var = 'the_ring,hangover,wonder_woman';

I want to make it like below.

$var = 'The Ring,Hangover,Wonder Woman';

I tried $parts = explode(',', $var); also I tried strpos() and  stripos() but not able to figure it out.

What can I do to achieve this?

Body:
$var = 'the_ring,hangover,wonder_woman';
$var1 = explode(',' $var);

foreach ($var1 as $key => $value) {
   $var1[$key]=str_replace("_"," ",$value);
   $var1[$key]=ucwords($var1[$key]);
}

$var = implode(',', $var1);


问:
How to pull YTD with xpath from this site?
I'm importing data from etf.com to my Google Sheets. For the VTI ETF I want
pull the "YTD" element.

Chrome inspection says that I should use the following

```<code>xpath=IMPORTXML("http://www.etf.com/VTI","//*[@id='form-reports-overview']/div[1]/div[5]/table/tbody/tr[2]/td[4]")
</code>```

This returns nothing though.

However I can extract most of the other fields just fine.

答:
You can try either:

```<code>=index(IMPORTXML("http://www.etf.com/VTI","//td[@class='col4']"),1,1)*100&"%"
</code>```

or:

```<code>=index(importhtml("http://www.etf.com/VTI","table",5),2,4)*100&"%"
</code>```

Body:
I'm importing data from etf.com to my Google Sheets. For the VTI ETF I want
pull the "YTD" element.

Chrome inspection says that I should use the following

xpath=IMPORTXML("http://www.etf.com/VTI","//*[@id='form-reports-overview']/div[1]/div[5]/table/tbody/tr[2]/td[4]")

This returns nothing though.

However I can extract most of the other fields just fine.

Body:
You can try either:

=index(IMPORTXML("http://www.etf.com/VTI","//td[@class='col4']"),1,1)*100&"%"

or:

=index(importhtml("http://www.etf.com/VTI","table",5),2,4)*100&"%"


问:
Converting a string dateTime to a joda date time and add it to the database
As the tittle say I'm trying to retrieve a Date Time from HTML5 date time input and add it to my database here's the code

```<code>private void HandleDate(String date, Test test) {
   DateTime dt = null;
   try {
       dt = CheckDateValidity(date);
   } catch (TestManagementException e) {
       setErrors(FIELD_DATE, e.getMessage());
   }
   test.setDate(dt);
</code>```

}

```<code>private DateTime CheckDateValidity(String date) throws TestManagementException {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-mm-dd hh:mm:ss");
    DateTime dateTime;
    try {
        dateTime = formatter.parseDateTime(date);
    } catch (Exception e) {
        throw new TestManagementException("date couldn't be converted");
    }
    return dateTime;
}
</code>```

everything seems good no errors detected but the database stayed the same no raw was added.
what's wrong ? :/
another problem or a question:
what's the pattern that i should use in the input so that the user should enter only this kind of date:

```<code>yyyy-mm-dd HH:mm:ss
</code>```

ps:

when i tried doing this:

```<code> private void HandleDate(String date, Test test) {
    DateTime dt = null;
   try {
       CheckDateValidity(date, dt);
   } catch (TestManagementException e) {
       setErrors(FIELD_DATE, e.getMessage());
   }
   test.setDate(dt);
</code>```

}

```<code>private void CheckDateValidity(String date, DateTime dateTime) throws TestManagementException {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-mm-dd hh:mm:ss");
   // DateTime dateTime;
    try {
        dateTime = formatter.parseDateTime(date);
    } catch (Exception e) {
        throw new TestManagementException("date couldn't be converted");
    }
   // return dateTime;
}
</code>```

it was added to the database but the date value was empty

答:
For those of you having the same problem, I just found the problem and the solution.
The problem is that: when I converted the string to a date I got this form :

```<code>yyyy-mm-ddThh:mm:ss.sss+01:00
</code>```

while the database field is of this form :

```<code>yyyy-mm-dd hh:mm:ss
</code>```

that's the reason why it couldn't be added to the database so the solution I found was this :

```<code>private void HandleDate(String date, Test test) {
    DateTime dt = null;
   try {
       dt = CheckDateValidity(date);
   } catch (TestManagementException e) {
       setErrors(FIELD_DATE, e.getMessage());
   }
   test.setDate(dt);
}

private DateTime CheckDateValidity(String date) throws TestManagementException {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTime dateTime;

    try {
        dateTime = formatter.parseDateTime(date);
    } catch (Exception e) {
        throw new TestManagementException("Date couldn't be converted");
    }
    return dateTime;
}
</code>```

the code did not change but I added this in the preparedStatement

```<code>        /****** connect to test table ******/
        Timestamp dt = new Timestamp(test.getDate().getMillis());
        preparedStatement = preparedStatementInitialisation(connection, SQL_INSERT,true,
                test.getTeacherId(),test.getModuleId(), dt, test.getType());
        int status = preparedStatement.executeUpdate();
        if (status == 0){
            throw new DAOException("Error while creating a user, 0 line added to the table!");
        }
</code>```

so instead of coping directly the date from the test bean I converted it to a timeStamp and now it works perfectly

for the DateTime pattern in the html input I just made this one

```<code><input type="datetime" name="date" id="date" placeholder="yyyy-mm-dd hh:mm:ss" pattern="[1-2]{1}[0-9]{3}-(0[0-9]{1}|1[0-2]{1})-([0-2]{1}[0-9]{1}|3[0-1]{1}) ([0-1]{1}[0-9]{1}|2[0-3]{1}):[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}">
</code>```

and it works perfectly now the user must enter a date of a this type yyyy-MM-dd HH:mm:ss

I discovered another weird thing is that in formatter pattern when I used "yyyy-mm-dd hh:mm:ss" I had a problem in the month and hours when I converted the month it started from 01 and when I add a 00 as hours it didn't work but when I used yyyy-MM-dd HH:mm:ss it worked o.O weird heh

Body:
As the tittle say I'm trying to retrieve a Date Time from HTML5 date time input and add it to my database here's the code

private void HandleDate(String date, Test test) {
   DateTime dt = null;
   try {
       dt = CheckDateValidity(date);
   } catch (TestManagementException e) {
       setErrors(FIELD_DATE, e.getMessage());
   }
   test.setDate(dt);

}

private DateTime CheckDateValidity(String date) throws TestManagementException {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-mm-dd hh:mm:ss");
    DateTime dateTime;
    try {
        dateTime = formatter.parseDateTime(date);
    } catch (Exception e) {
        throw new TestManagementException("date couldn't be converted");
    }
    return dateTime;
}

everything seems good no errors detected but the database stayed the same no raw was added.
what's wrong ? :/
another problem or a question:
what's the pattern that i should use in the input so that the user should enter only this kind of date:

yyyy-mm-dd HH:mm:ss

ps:

when i tried doing this:

 private void HandleDate(String date, Test test) {
    DateTime dt = null;
   try {
       CheckDateValidity(date, dt);
   } catch (TestManagementException e) {
       setErrors(FIELD_DATE, e.getMessage());
   }
   test.setDate(dt);

}

private void CheckDateValidity(String date, DateTime dateTime) throws TestManagementException {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-mm-dd hh:mm:ss");
   // DateTime dateTime;
    try {
        dateTime = formatter.parseDateTime(date);
    } catch (Exception e) {
        throw new TestManagementException("date couldn't be converted");
    }
   // return dateTime;
}

it was added to the database but the date value was empty

Body:
For those of you having the same problem, I just found the problem and the solution.
The problem is that: when I converted the string to a date I got this form :

yyyy-mm-ddThh:mm:ss.sss+01:00

while the database field is of this form :

yyyy-mm-dd hh:mm:ss

that's the reason why it couldn't be added to the database so the solution I found was this :

private void HandleDate(String date, Test test) {
    DateTime dt = null;
   try {
       dt = CheckDateValidity(date);
   } catch (TestManagementException e) {
       setErrors(FIELD_DATE, e.getMessage());
   }
   test.setDate(dt);
}

private DateTime CheckDateValidity(String date) throws TestManagementException {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTime dateTime;

    try {
        dateTime = formatter.parseDateTime(date);
    } catch (Exception e) {
        throw new TestManagementException("Date couldn't be converted");
    }
    return dateTime;
}

the code did not change but I added this in the preparedStatement

        /****** connect to test table ******/
        Timestamp dt = new Timestamp(test.getDate().getMillis());
        preparedStatement = preparedStatementInitialisation(connection, SQL_INSERT,true,
                test.getTeacherId(),test.getModuleId(), dt, test.getType());
        int status = preparedStatement.executeUpdate();
        if (status == 0){
            throw new DAOException("Error while creating a user, 0 line added to the table!");
        }

so instead of coping directly the date from the test bean I converted it to a timeStamp and now it works perfectly

for the DateTime pattern in the html input I just made this one

<input type="datetime" name="date" id="date" placeholder="yyyy-mm-dd hh:mm:ss" pattern="[1-2]{1}[0-9]{3}-(0[0-9]{1}|1[0-2]{1})-([0-2]{1}[0-9]{1}|3[0-1]{1}) ([0-1]{1}[0-9]{1}|2[0-3]{1}):[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}">

and it works perfectly now the user must enter a date of a this type yyyy-MM-dd HH:mm:ss

I discovered another weird thing is that in formatter pattern when I used "yyyy-mm-dd hh:mm:ss" I had a problem in the month and hours when I converted the month it started from 01 and when I add a 00 as hours it didn't work but when I used yyyy-MM-dd HH:mm:ss it worked o.O weird heh


问:
Why does my loop iterate only twice?
I have defined two structs and when I loop to set their values, it only loop twice as printf return. Any ideas?

```<code>typedef struct {
  int x;
  int y;
  unsigned char status;
} Cell;

typedef struct {
  int sizeX;
  int sizeY;
  Cell cell[];
} World;

int main() {
  int i, x, y;
  i = 0;
  World grid;
  grid.sizeX = 10;
  grid.sizeY = 10;

  for (x = 0; x < grid.sizeX; x++) {
    for (y = 0; y < grid.sizeY; y++) {
      Cell cell;
      cell.x = x;
      cell.y = y;

      printf("%d,%d: ", cell.x, cell.y);

      grid.cell[i] = cell;
      i++;
    }
  }

    return 0;
}
</code>```

EDIT :

Correct answer given below, thanks for comments and your patience for a C noob !

答:
grid.cell[] is not have been allocated any memory space. You should allocate it a memory by adding following line before starting of the loop:

```<code> grid.cell = Cell[100];
</code>```

The size 100 is based on the fact that grid.sizeX = 10; and grid.sizeY = 10;. There is no need of using malloc() because the size is fixed.

If size is not fixed for grid.sizeX and grid.sizeYthen, you should add following line instead of grid.cell = Cell[100];:

```<code> grid.cell = (Cell*)malloc(sizeof(Cell) *(grid.xSize  * grid.ySize ));
</code>```

The line World *grid = malloc(sizeof(World) + xSize * ySize * sizeof(Cell)); which is added by you is just a tricked way and not much clear. Even it is logically correct!!!

Title: Why does my loop iterate only twice?

Body:
I have defined two structs and when I loop to set their values, it only loop twice as printf return. Any ideas?

typedef struct {
  int x;
  int y;
  unsigned char status;
} Cell;

typedef struct {
  int sizeX;
  int sizeY;
  Cell cell[];
} World;

int main() {
  int i, x, y;
  i = 0;
  World grid;
  grid.sizeX = 10;
  grid.sizeY = 10;

  for (x = 0; x < grid.sizeX; x++) {
    for (y = 0; y < grid.sizeY; y++) {
      Cell cell;
      cell.x = x;
      cell.y = y;

      printf("%d,%d: ", cell.x, cell.y);

      grid.cell[i] = cell;
      i++;
    }
  }

    return 0;
}

EDIT :

Correct answer given below, thanks for comments and your patience for a C noob !

Body:
grid.cell[] is not have been allocated any memory space. You should allocate it a memory by adding following line before starting of the loop:

 grid.cell = Cell[100];

The size 100 is based on the fact that grid.sizeX = 10; and grid.sizeY = 10;. There is no need of using malloc() because the size is fixed.

If size is not fixed for grid.sizeX and grid.sizeYthen, you should add following line instead of grid.cell = Cell[100];:

 grid.cell = (Cell*)malloc(sizeof(Cell) *(grid.xSize  * grid.ySize ));

The line World *grid = malloc(sizeof(World) + xSize * ySize * sizeof(Cell)); which is added by you is just a tricked way and not much clear. Even it is logically correct!!!


问:
MobX decorators not working
I'm having trouble getting decorators such as @observable and @computed to work in my project.

Here are my files.

package.json:

```<code>{
  "name": "heroku-react",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "babel-plugin-syntax-decorators": "^6.13.0",
    "mobx": "^3.1.11",
    "mobx-react": "^4.2.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  },
  "devDependencies": {
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-stage-1": "^6.24.1",
    "react-scripts": "1.0.7"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}
</code>```

App.js:

```<code>import React, { Component } from 'react';
import './App.css';
import GameBoard from './components/game-board';
import { inject, observer } from 'mobx-react';

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
        </div>
        <GameBoard />
      </div>
    );
  }
}

export default App;
</code>```

.babelrc:

```<code>{
  "presets": [
    "es2015",
    "react",
    "stage-1"
  ],
  "plugins": ["transform-decorators-legacy"]
}
</code>```

When I add the @observer decorator like so (@observer class App extends Component {...}) before my class declaration I receive this error:

```<code>Failed to compile
./src/App.js
Syntax error: Unexpected token (7:0)

   5 | import { inject, observer } from 'mobx-react';
   6 |
>  7 | @observer class App extends Component {
     | ^
   8 |   render() {
   9 |     return (
  10 |       <div className="App">
</code>```

答: Look like you are using create-react-app and didn't make eject. In order to use decorators you should make it. Or use custom-react-scripts as alternative.

Title: MobX decorators not working

Body:
I'm having trouble getting decorators such as @observable and @computed to work in my project.

Here are my files.

package.json:

{
  "name": "heroku-react",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "babel-plugin-syntax-decorators": "^6.13.0",
    "mobx": "^3.1.11",
    "mobx-react": "^4.2.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  },
  "devDependencies": {
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-stage-1": "^6.24.1",
    "react-scripts": "1.0.7"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

App.js:

import React, { Component } from 'react';
import './App.css';
import GameBoard from './components/game-board';
import { inject, observer } from 'mobx-react';

class App extends Component {
  render() {
    return (

        <GameBoard />

    );
  }
}

export default App;

.babelrc:

{
  "presets": [
    "es2015",
    "react",
    "stage-1"
  ],
  "plugins": ["transform-decorators-legacy"]
}

When I add the @observer decorator like so (@observer class App extends Component {...}) before my class declaration I receive this error:

Failed to compile
./src/App.js
Syntax error: Unexpected token (7:0)

   5 | import { inject, observer } from 'mobx-react';
   6 |
>  7 | @observer class App extends Component {
     | ^
   8 |   render() {
   9 |     return (
  10 |


问:
HTML Color Codes: Red to Yellow to Green
I would like to come up with as many HEX HTML values to have a smooth color gradient from red to green:

I would like this to be similar to the following:
http://www.utexas.edu/learn/html/colors.html

I don't have the best eye for color choices, so I'm hoping a standard chart is already put together showing how to transition from red through yellow to green smoothly.

On that website "1 of 6" is most similar to what I'm looking for, but that example is limited to 11 colors:

```<code>(1) FF0000 Red,
(2) FF3300 Red(Orange)
(3) ff6600
(4) ff9900
(5) FFCC00 Gold
(6) FFFF00 Yellow
(7) ccff00
(8) 99ff00
(9) 66ff00
(10) 33ff00
(11) 00FF00 Lime
</code>```

It would be great to be able to double the number of colors, but yet make them transition smoothly.

Thanks for any insights and help.

答:
Here is nice looking gradient from green to red

    /* Green - Yellow - Red */
    .gradient_0    {background: #57bb8a;}
    .gradient_5    {background: #63b682;}
    .gradient_10   {background: #73b87e;}
    .gradient_15   {background: #84bb7b;}
    .gradient_20   {background: #94bd77;}
    .gradient_25   {background: #a4c073;}
    .gradient_30   {background: #b0be6e;}
    .gradient_35   {background: #c4c56d;}
    .gradient_40   {background: #d4c86a;}
    .gradient_45   {background: #e2c965;}
    .gradient_50   {background: #f5ce62;}
    .gradient_55   {background: #f3c563;}
    .gradient_60   {background: #e9b861;}
    .gradient_65   {background: #e6ad61;}
    .gradient_70   {background: #ecac67;}
    .gradient_75   {background: #e9a268;}
    .gradient_80   {background: #e79a69;}
    .gradient_85   {background: #e5926b;}
    .gradient_90   {background: #e2886c;}
    .gradient_95   {background: #e0816d;}
    .gradient_100  {background: #dd776e;}

    /* Red - Yellow - Green */
    .anti-gradient_100  {background: #57bb8a;}
    .anti-gradient_95   {background: #63b682;}
    .anti-gradient_90   {background: #73b87e;}
    .anti-gradient_85   {background: #84bb7b;}
    .anti-gradient_80   {background: #94bd77;}
    .anti-gradient_75   {background: #a4c073;}
    .anti-gradient_70   {background: #b0be6e;}
    .anti-gradient_65   {background: #c4c56d;}
    .anti-gradient_60   {background: #d4c86a;}
    .anti-gradient_55   {background: #e2c965;}
    .anti-gradient_50   {background: #f5ce62;}
    .anti-gradient_45   {background: #f3c563;}
    .anti-gradient_40   {background: #e9b861;}
    .anti-gradient_35   {background: #e6ad61;}
    .anti-gradient_30   {background: #ecac67;}
    .anti-gradient_25   {background: #e9a268;}
    .anti-gradient_20   {background: #e79a69;}
    .anti-gradient_15   {background: #e5926b;}
    .anti-gradient_10   {background: #e2886c;}
    .anti-gradient_5    {background: #e0816d;}
    .anti-gradient_0    {background: #dd776e;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="gradient_0">0</div>
<div class="gradient_5">5</div>
<div class="gradient_10">10</div>
<div class="gradient_15">15</div>
<div class="gradient_20">20</div>
<div class="gradient_25">25</div>
<div class="gradient_30">30</div>
<div class="gradient_35">35</div>
<div class="gradient_40">40</div>
<div class="gradient_45">45</div>
<div class="gradient_50">50</div>
<div class="gradient_55">55</div>
<div class="gradient_60">60</div>
<div class="gradient_65">65</div>
<div class="gradient_70">70</div>
<div class="gradient_75">75</div>
<div class="gradient_80">80</div>
<div class="gradient_85">85</div>
<div class="gradient_90">90</div>
<div class="gradient_95">95</div>
<div class="gradient_100">100</div></code>```

Body:
I would like to come up with as many HEX HTML values to have a smooth color gradient from red to green:

I would like this to be similar to the following:
http://www.utexas.edu/learn/html/colors.html

I don't have the best eye for color choices, so I'm hoping a standard chart is already put together showing how to transition from red through yellow to green smoothly.

On that website "1 of 6" is most similar to what I'm looking for, but that example is limited to 11 colors:

(1) FF0000 Red,
(2) FF3300 Red(Orange)
(3) ff6600
(4) ff9900
(5) FFCC00 Gold
(6) FFFF00 Yellow
(7) ccff00
(8) 99ff00
(9) 66ff00
(10) 33ff00
(11) 00FF00 Lime

It would be great to be able to double the number of colors, but yet make them transition smoothly.

Thanks for any insights and help.

Body:
Here is nice looking gradient from green to red

    /* Green - Yellow - Red */
    .gradient_0    {background: #57bb8a;}
    .gradient_5    {background: #63b682;}
    .gradient_10   {background: #73b87e;}
    .gradient_15   {background: #84bb7b;}
    .gradient_20   {background: #94bd77;}
    .gradient_25   {background: #a4c073;}
    .gradient_30   {background: #b0be6e;}
    .gradient_35   {background: #c4c56d;}
    .gradient_40   {background: #d4c86a;}
    .gradient_45   {background: #e2c965;}
    .gradient_50   {background: #f5ce62;}
    .gradient_55   {background: #f3c563;}
    .gradient_60   {background: #e9b861;}
    .gradient_65   {background: #e6ad61;}
    .gradient_70   {background: #ecac67;}
    .gradient_75   {background: #e9a268;}
    .gradient_80   {background: #e79a69;}
    .gradient_85   {background: #e5926b;}
    .gradient_90   {background: #e2886c;}
    .gradient_95   {background: #e0816d;}
    .gradient_100  {background: #dd776e;}

    /* Red - Yellow - Green */
    .anti-gradient_100  {background: #57bb8a;}
    .anti-gradient_95   {background: #63b682;}
    .anti-gradient_90   {background: #73b87e;}
    .anti-gradient_85   {background: #84bb7b;}
    .anti-gradient_80   {background: #94bd77;}
    .anti-gradient_75   {background: #a4c073;}
    .anti-gradient_70   {background: #b0be6e;}
    .anti-gradient_65   {background: #c4c56d;}
    .anti-gradient_60   {background: #d4c86a;}
    .anti-gradient_55   {background: #e2c965;}
    .anti-gradient_50   {background: #f5ce62;}
    .anti-gradient_45   {background: #f3c563;}
    .anti-gradient_40   {background: #e9b861;}
    .anti-gradient_35   {background: #e6ad61;}
    .anti-gradient_30   {background: #ecac67;}
    .anti-gradient_25   {background: #e9a268;}
    .anti-gradient_20   {background: #e79a69;}
    .anti-gradient_15   {background: #e5926b;}
    .anti-gradient_10   {background: #e2886c;}
    .anti-gradient_5    {background: #e0816d;}
    .anti-gradient_0    {background: #dd776e;}

<div class="gradient_0">0</div>
<div class="gradient_5">5</div>
<div class="gradient_10">10</div>
<div class="gradient_15">15</div>
<div class="gradient_20">20</div>
<div class="gradient_25">25</div>
<div class="gradient_30">30</div>
<div class="gradient_35">35</div>
<div class="gradient_40">40</div>
<div class="gradient_45">45</div>
<div class="gradient_50">50</div>
<div class="gradient_55">55</div>
<div class="gradient_60">60</div>
<div class="gradient_65">65</div>
<div class="gradient_70">70</div>
<div class="gradient_75">75</div>
<div class="gradient_80">80</div>
<div class="gradient_85">85</div>
<div class="gradient_90">90</div>
<div class="gradient_95">95</div>
<div class="gradient_100">100</div>


问:
Node.js AWS deployment Error: Cannot find module
I am attempting to upload a simple Node?JS app onto elastic beanstalk. All dependencies are listed in my package.json file and the app is listening on 8081 through nginx proxy.

The following error is being thrown from the node log file. Are the modules placed differently on the server ?

Server running at http://127.0.0.1:8081/ module.js:471
      throw err;
       './routes/FtseData'
      at Function.Module._resolveFilename (module.js:469:15)
      at Function.Module._load (module.js:417:25)
      at Module.require (module.js:497:17)
      at require (internal/module.js:20:19)
      at Object. (/var/app/current/routes.js:7:20)
      at Module._compile (module.js:570:32)
      at Object.Module._extensions..js (module.js:579:10)
      at Module.load (module.js:487:32)
      at tryModuleLoad (module.js:446:12)
      at Function.Module._load (module.js:438:3) module.js:471
      throw err;
      ^

Error: Cannot find module './routes/FtseData'
      at Function.Module._resolveFilename (module.js:469:15)
      at Function.Module._load (module.js:417:25)
      at Module.require (module.js:497:17)
      at require (internal/module.js:20:19)
      at Object. (/var/app/current/routes.js:7:20)
      at Module._compile (module.js:570:32)
      at Object.Module._extensions..js (module.js:579:10)
      at Module.load (module.js:487:32)
      at tryModuleLoad (module.js:446:12)
      at Function.Module._load (module.js:438:3) module.js:471
      throw err;
      ^

Here is my server.js file

```<code>var express = require('express');
var basicAuth = require('express-basic-auth')
var bodyParser = require('body-parser')
var cors = require('cors');
var app = express();

app.use(cors());

app.get('/', function (req, res) {
//    res.send('Hello World');
    res.sendFile(__dirname + '/views/index.html');
})

var routes = require('./routes');
app.use('/api', routes);

var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port

   console.log("App listening at http://%s:%s", host, port)
})
</code>```

routes.js

```<code>var express = require('express');
var basicAuth = require('express-basic-auth')
var app = express();
var router = express.Router();

//var profCtrl = require('./routes/profileController');
var ftseDataCtrl = require('./routes/FtseData');
var ftseDivCtrl = require('./routes/FtseDiv');

//routes not needing auth
router.route('/FtseDivGet').get(ftseDivCtrl.get);
//routes needing auth
 router.use(basicAuth({
     users: { 'admin': 'supersecret' }
 }))
//router.route('/FtseDataScrape').get(ftseDataCtrl.scrape);
router.route('/FtseDivScrape').get(ftseDivCtrl.scrape);
//http://localhost:8081/api/profile

module.exports = router;
</code>```

package.json

```<code>{
  "name": "StockTracker",
  "version": "1.0.0",
  "description": "Stock-Tracker",
  "dependencies": {
    "express": "*",
    "express-basic-auth": "*",
    "request": "*",
    "cheerio": "*",
    "body-parser": "*",
    "cheerio-tableparser": "*",
    "cors": "*",
    "csv-load-sync": "*"
  },
  "scripts": {
    "start": "node server.js"
  }
}
</code>```

答:
My file was /routes/FtseData.js

This caused the error

```<code>var ftseDataCtrl = require('./routes/FTSEData');
</code>```

Case needed to match file

```<code>var ftseDataCtrl = require('./routes/FtseData');
</code>```

Body:
I am attempting to upload a simple Node?JS app onto elastic beanstalk. All dependencies are listed in my package.json file and the app is listening on 8081 through nginx proxy.

The following error is being thrown from the node log file. Are the modules placed differently on the server ?

Server running at http://127.0.0.1:8081/ module.js:471
      throw err;
       './routes/FtseData'
      at Function.Module._resolveFilename (module.js:469:15)
      at Function.Module._load (module.js:417:25)
      at Module.require (module.js:497:17)
      at require (internal/module.js:20:19)
      at Object. (/var/app/current/routes.js:7:20)
      at Module._compile (module.js:570:32)
      at Object.Module._extensions..js (module.js:579:10)
      at Module.load (module.js:487:32)
      at tryModuleLoad (module.js:446:12)
      at Function.Module._load (module.js:438:3) module.js:471
      throw err;
      ^

Error: Cannot find module './routes/FtseData'
      at Function.Module._resolveFilename (module.js:469:15)
      at Function.Module._load (module.js:417:25)
      at Module.require (module.js:497:17)
      at require (internal/module.js:20:19)
      at Object. (/var/app/current/routes.js:7:20)
      at Module._compile (module.js:570:32)
      at Object.Module._extensions..js (module.js:579:10)
      at Module.load (module.js:487:32)
      at tryModuleLoad (module.js:446:12)
      at Function.Module._load (module.js:438:3) module.js:471
      throw err;
      ^

Here is my server.js file

var express = require('express');
var basicAuth = require('express-basic-auth')
var bodyParser = require('body-parser')
var cors = require('cors');
var app = express();

app.use(cors());

app.get('/', function (req, res) {
//    res.send('Hello World');
    res.sendFile(__dirname + '/views/index.html');
})

var routes = require('./routes');
app.use('/api', routes);

var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port

   console.log("App listening at http://%s:%s", host, port)
})

routes.js

var express = require('express');
var basicAuth = require('express-basic-auth')
var app = express();
var router = express.Router();

//var profCtrl = require('./routes/profileController');
var ftseDataCtrl = require('./routes/FtseData');
var ftseDivCtrl = require('./routes/FtseDiv');

//routes not needing auth
router.route('/FtseDivGet').get(ftseDivCtrl.get);
//routes needing auth
 router.use(basicAuth({
     users: { 'admin': 'supersecret' }
 }))
//router.route('/FtseDataScrape').get(ftseDataCtrl.scrape);
router.route('/FtseDivScrape').get(ftseDivCtrl.scrape);
//http://localhost:8081/api/profile

module.exports = router;

package.json

{
  "name": "StockTracker",
  "version": "1.0.0",
  "description": "Stock-Tracker",
  "dependencies": {
    "express": "*",
    "express-basic-auth": "*",
    "request": "*",
    "cheerio": "*",
    "body-parser": "*",
    "cheerio-tableparser": "*",
    "cors": "*",
    "csv-load-sync": "*"
  },
  "scripts": {
    "start": "node server.js"
  }
}

Body:
My file was /routes/FtseData.js

This caused the error

var ftseDataCtrl = require('./routes/FTSEData');

Case needed to match file

var ftseDataCtrl = require('./routes/FtseData');


问:
Write a recursive function that takes an array and displays the elements in reverse order without starting the index of the array at the end
My question is: Am I doing this right or not?
Because no one can tell me exactly...

Write a recursive function that takes an array and displays the elements in reverse order
without starting the index of the array at the end. (In other words, don’t write the equivalent of
a loop that starts printing at the end of the array.)

```<code>int bleah(int arr[], int number)
{
    cout << arr[number] << ' ';
    if (number <= 0)
    {
        return 1;
    }
    cout << arr[number] << ' ';
    return bleah(arr, number - 1);
}

int main()
{
    int arr[31] = {0};
    for (int i = 0; i <= 30; i++)
    {
        arr[i] = i;
    }
    bleah(arr, 30);

    cin.get();
    cin.ignore();
    return 0;
}
</code>```

答:
Sorry people for wasting your time!
I finally got the answer and looked for it on Github.
This is the right answer</p>

```<code>void bleah(int arr[], int number)
{
    if (number + 1 < 10)
    {
        bleah(arr, number + 1);
    }
    cout << arr[number] << ' ';
}

int main()
{
    int arr[11] = { 34,5,8,3,6,678,8,87,67,8 };
    for (int i = 0; i < 10; i++)
    {
        cout << arr[i] << ' ';
    }
    cout << endl;
    bleah(arr, 0);

    cin.get();
    cin.ignore();
    return 0;
}
</code>```

Body:
My question is: Am I doing this right or not?
Because no one can tell me exactly...

Write a recursive function that takes an array and displays the elements in reverse order
without starting the index of the array at the end. (In other words, don’t write the equivalent of
a loop that starts printing at the end of the array.)

int bleah(int arr[], int number)
{
    cout << arr[number] << ' ';
    if (number <= 0)
    {
        return 1;
    }
    cout << arr[number] << ' ';
    return bleah(arr, number - 1);
}

int main()
{
    int arr[31] = {0};
    for (int i = 0; i <= 30; i++)
    {
        arr[i] = i;
    }
    bleah(arr, 30);

    cin.get();
    cin.ignore();
    return 0;
}

Body:
Sorry people for wasting your time!
I finally got the answer and looked for it on Github.
This is the right answer

void bleah(int arr[], int number)
{
    if (number + 1 < 10)
    {
        bleah(arr, number + 1);
    }
    cout << arr[number] << ' ';
}

int main()
{
    int arr[11] = { 34,5,8,3,6,678,8,87,67,8 };
    for (int i = 0; i < 10; i++)
    {
        cout << arr[i] << ' ';
    }
    cout << endl;
    bleah(arr, 0);

    cin.get();
    cin.ignore();
    return 0;
}


问:
Check if user is close to scrolling to bottom of element
My website has a Bootstrap modal. My end goal is to add infinite scrolling to the modal so that when the user scrolls down to the bottom of the modal, it loads more data from the server and appends the data to the modal.

Here is my code so far. All I have right now is a scroll event on the modal:

http://jsfiddle.net/DTcHh/33247/

Note: The height of the modal on my website can vary. Sometimes it can be just 1 paragraph of text.

My question is, how can I check if the user is close to scrolling to the bottom of the modal?

In more technical terms, how can I check if the bottom of the window is at the same position as the bottom of the modal?

Update

I found that this solution works, however, it seems a bit complicated/long. Any way to shorten it?

http://jsfiddle.net/DTcHh/33271/

HTML:

```<code><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
</code>```

JS:

```<code>$("#exampleModalLong").on("scroll", function() {
    console.log("scroll");
});
</code>```

答:
To check if you have reached the bottom of the bootstrap modal, you can use the below code snippet :

```<code>$('.modal').scroll(function() {
    if($(this).scrollTop() + $(this).innerHeight() >= this.scrollHeight) {
        alert('You have reached the bottom of the modal')
    }
});
</code>```

Hope this helps !!!

Body:
My website has a Bootstrap modal. My end goal is to add infinite scrolling to the modal so that when the user scrolls down to the bottom of the modal, it loads more data from the server and appends the data to the modal.

Here is my code so far. All I have right now is a scroll event on the modal:

http://jsfiddle.net/DTcHh/33247/

Note: The height of the modal on my website can vary. Sometimes it can be just 1 paragraph of text.

My question is, how can I check if the user is close to scrolling to the bottom of the modal?

In more technical terms, how can I check if the bottom of the window is at the same position as the bottom of the modal?

Update

I found that this solution works, however, it seems a bit complicated/long. Any way to shorten it?

http://jsfiddle.net/DTcHh/33271/

HTML:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong">
  Launch demo modal
</button>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

JS:

$("#exampleModalLong").on("scroll", function() {
    console.log("scroll");
});

Body:
To check if you have reached the bottom of the bootstrap modal, you can use the below code snippet :

$('.modal').scroll(function() {
    if($(this).scrollTop() + $(this).innerHeight() >= this.scrollHeight) {
        alert('You have reached the bottom of the modal')
    }
});

Hope this helps !!!


问:
Angular 4 Lazy Loading and Routes not working
I have a module with the routes of my app. One of this routes is a lazy loading module.

The problem is that this lazy loading module haves inside a routes for child components. But on my router config this routes don't appears... So when i call the lazy module don't show anything on my screen.

Here is my router config (main module):

```<code>export const MODULE_ROUTES: Route[] =[
    { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
    { path: 'dashboard', component: HomeComponent, canActivate: [AuthGuard] },
    { path: 'calendar', loadChildren: 'app/dashboard/calendar/calendar-module.module#CalendarModuleModule',canActivate: [AuthGuard]},
    { path: '**', component: NoPageFoundComponent, pathMatch: 'full' }
]
.
.
.

@NgModule({
    imports: [
        RouterModule.forChild(MODULE_ROUTES)
.
.
.
</code>```

On my lazy module:

```<code>export const MODULE_CALENDAR_ROUTES: Route[] = [
    {
        path: 'calendar', component: CalendarComponent, canActivateChild: [AuthGuard, CalendarGuard],
        children: [
            {
                path: '', component: MainCalendarComponent, canActivateChild: [AuthGuard, CalendarGuard]
            },
            {

                path: 'user', component: EditEventComponent, canActivateChild: [AuthGuard, CalendarGuard]
            }
        ]
    }
]

.
.
.

@NgModule({
    imports: [
        SharedModule,
.
.
.
        RouterModule.forChild(MODULE_CALENDAR_ROUTES)
</code>```

If i print my router config this routes declaren on my lazy module don't show:

```<code>Routes:  [
  {
    "path": "dashboard",
    "canActivate": [
      null
    ]
  },
  {
    "path": "calendar",
    "loadChildren": "app/dashboard/calendar/calendar-module.module#CalendarModuleModule",
    "canActivate": [
      null
    ]
  },
  {
    "path": "**",
    "pathMatch": "full"
  },
  {
    "path": "dashboard"
  }
]
</code>```

Can you help me?

答:
The problem was with the way I've declared my route on my lazy module:

```<code>export const MODULE_CALENDAR_ROUTES: Route[] = [
    {
        path: 'calendar',
        component: CalendarComponent,
        canActivateChild: [AuthGuard, CalendarGuard],
        children: [
            {
                path: '',
                component: MainCalendarComponent,
                canActivateChild: [AuthGuard, CalendarGuard]
            },
            {

                path: 'user',
                component: EditEventComponent,
                canActivateChild: [AuthGuard, CalendarGuard]
            }
        ]
    }
]
</code>```

The path of CalendarComponent had to change from:

```<code>path: 'calendar', // wrong
component: CalendarComponent,
...
</code>```

to the below:

```<code>path: '', // right
component: CalendarComponent,
...
</code>```

Thanks to @jotatoledo on gitter that help me to solve this.

Body:
I have a module with the routes of my app. One of this routes is a lazy loading module.

The problem is that this lazy loading module haves inside a routes for child components. But on my router config this routes don't appears... So when i call the lazy module don't show anything on my screen.

Here is my router config (main module):

export const MODULE_ROUTES: Route[] =[
    { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
    { path: 'dashboard', component: HomeComponent, canActivate: [AuthGuard] },
    { path: 'calendar', loadChildren: 'app/dashboard/calendar/calendar-module.module#CalendarModuleModule',canActivate: [AuthGuard]},
    { path: '**', component: NoPageFoundComponent, pathMatch: 'full' }
]
.
.
.

@NgModule({
    imports: [
        RouterModule.forChild(MODULE_ROUTES)
.
.
.

On my lazy module:

export const MODULE_CALENDAR_ROUTES: Route[] = [
    {
        path: 'calendar', component: CalendarComponent, canActivateChild: [AuthGuard, CalendarGuard],
        children: [
            {
                path: '', component: MainCalendarComponent, canActivateChild: [AuthGuard, CalendarGuard]
            },
            {

                path: 'user', component: EditEventComponent, canActivateChild: [AuthGuard, CalendarGuard]
            }
        ]
    }
]

.
.
.

@NgModule({
    imports: [
        SharedModule,
.
.
.
        RouterModule.forChild(MODULE_CALENDAR_ROUTES)

If i print my router config this routes declaren on my lazy module don't show:

Routes:  [
  {
    "path": "dashboard",
    "canActivate": [
      null
    ]
  },
  {
    "path": "calendar",
    "loadChildren": "app/dashboard/calendar/calendar-module.module#CalendarModuleModule",
    "canActivate": [
      null
    ]
  },
  {
    "path": "**",
    "pathMatch": "full"
  },
  {
    "path": "dashboard"
  }
]

Can you help me?

Body:
The problem was with the way I've declared my route on my lazy module:

export const MODULE_CALENDAR_ROUTES: Route[] = [
    {
        path: 'calendar',
        component: CalendarComponent,
        canActivateChild: [AuthGuard, CalendarGuard],
        children: [
            {
                path: '',
                component: MainCalendarComponent,
                canActivateChild: [AuthGuard, CalendarGuard]
            },
            {

                path: 'user',
                component: EditEventComponent,
                canActivateChild: [AuthGuard, CalendarGuard]
            }
        ]
    }
]

The path of CalendarComponent had to change from:

path: 'calendar', // wrong
component: CalendarComponent,
...

to the below:

path: '', // right
component: CalendarComponent,
...

Thanks to @jotatoledo on gitter that help me to solve this.


问:
Remove or trim carriage return at the end of string

Possible Duplicate:

  Removing carriage return and new-line from the end of a string in c#

How do I remove the carriage return at the end of string.
I have already google out this but I cannot find the code I need.

This is my current code:

return s.Replace("\n", "").Replace("\r", "").Replace("\r\n", "").Trim();

but of course all the occurrence of the old character will be replaced.

I have tried these:

public string trim(string s)
{

```<code>string[] whiteSpace = {"\r", "\n", "\r\n"};

foreach(string ws in whiteSpace)
{
    if (s.EndsWith(ws))
    {
        s = s.Substring(0, s.Length - 1);
    }
}
return s;
</code>```

}

but is not working for me, maybe I miss something or there's a wrong with my code

I have also try using regular expression but I can't get what I need.

I get the string from word document then will be transfered to another docs.

I'll appreciate any help.Tnx

答: See this answer:  Removing carriage return and new-line from the end of a string in c#</p>

Body:
Possible Duplicate:

  Removing carriage return and new-line from the end of a string in c#

How do I remove the carriage return at the end of string.
I have already google out this but I cannot find the code I need.

This is my current code:

return s.Replace("\n", "").Replace("\r", "").Replace("\r\n", "").Trim();

but of course all the occurrence of the old character will be replaced.

I have tried these:

public string trim(string s)
{

string[] whiteSpace = {"\r", "\n", "\r\n"};

foreach(string ws in whiteSpace)
{
    if (s.EndsWith(ws))
    {
        s = s.Substring(0, s.Length - 1);
    }
}
return s;

}

but is not working for me, maybe I miss something or there's a wrong with my code

I have also try using regular expression but I can't get what I need.

I get the string from word document then will be transfered to another docs.

I'll appreciate any help.Tnx