问:
Gradual performance degradation of data import using Spring batch, EhCache, and Hibernate
I am using the Spring MVC 4, Spring Batch 3, Hibernate 5, and Ehcache 2.8. Using Spring Batch, I am importing a lot of data from CSV to the DB using Hibernate at chunks of 1000. For additional information, data from the CSV refers to other tables that is why i have a lot of DB queries before the actual insert.

At first, the interval between chunks are small, between 10 seconds. Gradually, after around 100,000 items, the interval between the items are more than 1 minute. I suspect that it is some caching issue as this is gradual degradation. My current hibernate stats are

2nd Level Cache Hit %: 97.8839177750907

Query Cache Hit %: 54.206282344445775

Query Max Time: 4.08s at a query used in the import

Here is my ehcache.xml configuration

```<code><defaultCache
    eternal="false"
    timeToIdleSeconds="180"
    timeToLiveSeconds="240"
    maxEntriesLocalHeap="10000"
    maxEntriesLocalDisk="50000"
    >
    <persistence strategy="localTempSwap" />
</defaultCache>

<cache name="org.hibernate.cache.internal.StandardQueryCache"
    maxEntriesLocalHeap="10000"
    maxEntriesLocalDisk="50000"
    eternal="false"
    timeToIdleSeconds="180"
    timeToLiveSeconds="240"
    >
    <persistence strategy="localTempSwap" />
</cache>

<cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
    eternal="false"
    maxEntriesLocalHeap="0"
/>
</code>```

[EDIT] and here is the source code for the batch job

```<code>@Bean
@StepScope
public static FlatFileItemReader<CsvPayment> paymentReader( @Value( "#{jobParameters[fullPathFileName]}" ) String pathToFile,
                                                            @Value( "#{jobParameters[delimeter]}" ) String delimeter,
                                                            @Value( "#{jobParameters[skipItems]}" ) Long skipItems,
                                                            @Value( "#{jobParameters[limitItems]}" ) Long limitItems )
{
    FlatFileItemReader<CsvPayment> reader = new FlatFileItemReader<>();

    reader.setResource( new FileSystemResource( pathToFile ) );
    reader.setEncoding( GlobalConstants.UTF8 );
    reader.setMaxItemCount( limitItems.intValue() );
    reader.setLinesToSkip( skipItems.intValue() );
    reader.setLineMapper( new CsvPaymentLineMapper( delimeter ) );

    return reader;
}

@Bean( "importPayment" )
public Job importPayment( ItemReader<CsvPayment> paymentReader )
{
    return jobBuilderFactory.get( "paymentReader" ).incrementer( new RunIdIncrementer() ).flow(
        paymentStep1( paymentReader ) ).end().build();
}

@Bean
public Step paymentStep1( ItemReader<CsvPayment> paymentReader )
{
    return stepBuilderFactory.get( "paymentStep1" ).<CsvPayment, OccupancyPayment> chunk( CHUNK_SIZE ).reader(
        paymentReader ).processor( itemProcessor ).faultTolerant().listener(
            new ChunkListenerImpl( logger ) ).writer( itemWriter() ).build();
}

@Bean
public HibernateItemWriter<OccupancyPayment> itemWriter()
{
    HibernateItemWriter<OccupancyPayment> itemWriter = new HibernateItemWriter<>();
    itemWriter.setSessionFactory( sessionFactory );
    itemWriter.setClearSession( true );
    return itemWriter;
}
</code>```

Hopefully, someone could point me to the right direction. Thanks.

答:
The session cache is growing and making your app slower and consuming more memory.

Try this:

```<code>Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.save(customer);
    if ( i % 20 == 0 ) { //20, same as the JDBC batch size
        //flush a batch of inserts and release memory:
        session.flush();
        session.clear();
    }
}

tx.commit();
session.close();
</code>```

Example taken from here and I confirm to you we use the same solution and it works good.

The only downside of the solution is that sometimes you may get NonUniqueObjectException from Hibernate. It comes as a consequence of the session.clear() which makes all Hibernate instances detached. In such a case, you definitely need to read this and probably call session.refresh(instance).

Body:
I am using the Spring MVC 4, Spring Batch 3, Hibernate 5, and Ehcache 2.8. Using Spring Batch, I am importing a lot of data from CSV to the DB using Hibernate at chunks of 1000. For additional information, data from the CSV refers to other tables that is why i have a lot of DB queries before the actual insert.

At first, the interval between chunks are small, between 10 seconds. Gradually, after around 100,000 items, the interval between the items are more than 1 minute. I suspect that it is some caching issue as this is gradual degradation. My current hibernate stats are

2nd Level Cache Hit %: 97.8839177750907

Query Cache Hit %: 54.206282344445775

Query Max Time: 4.08s at a query used in the import

Here is my ehcache.xml configuration

<defaultCache
    eternal="false"
    timeToIdleSeconds="180"
    timeToLiveSeconds="240"
    maxEntriesLocalHeap="10000"
    maxEntriesLocalDisk="50000"
    >
    <persistence strategy="localTempSwap" />
</defaultCache>

<cache name="org.hibernate.cache.internal.StandardQueryCache"
    maxEntriesLocalHeap="10000"
    maxEntriesLocalDisk="50000"
    eternal="false"
    timeToIdleSeconds="180"
    timeToLiveSeconds="240"
    >
    <persistence strategy="localTempSwap" />
</cache>

<cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
    eternal="false"
    maxEntriesLocalHeap="0"
/>

[EDIT] and here is the source code for the batch job

@Bean
@StepScope
public static FlatFileItemReader<CsvPayment> paymentReader( @Value( "#{jobParameters[fullPathFileName]}" ) String pathToFile,
                                                            @Value( "#{jobParameters[delimeter]}" ) String delimeter,
                                                            @Value( "#{jobParameters[skipItems]}" ) Long skipItems,
                                                            @Value( "#{jobParameters[limitItems]}" ) Long limitItems )
{
    FlatFileItemReader<CsvPayment> reader = new FlatFileItemReader<>();

    reader.setResource( new FileSystemResource( pathToFile ) );
    reader.setEncoding( GlobalConstants.UTF8 );
    reader.setMaxItemCount( limitItems.intValue() );
    reader.setLinesToSkip( skipItems.intValue() );
    reader.setLineMapper( new CsvPaymentLineMapper( delimeter ) );

    return reader;
}

@Bean( "importPayment" )
public Job importPayment( ItemReader<CsvPayment> paymentReader )
{
    return jobBuilderFactory.get( "paymentReader" ).incrementer( new RunIdIncrementer() ).flow(
        paymentStep1( paymentReader ) ).end().build();
}

@Bean
public Step paymentStep1( ItemReader<CsvPayment> paymentReader )
{
    return stepBuilderFactory.get( "paymentStep1" ).<CsvPayment, OccupancyPayment> chunk( CHUNK_SIZE ).reader(
        paymentReader ).processor( itemProcessor ).faultTolerant().listener(
            new ChunkListenerImpl( logger ) ).writer( itemWriter() ).build();
}

@Bean
public HibernateItemWriter<OccupancyPayment> itemWriter()
{
    HibernateItemWriter<OccupancyPayment> itemWriter = new HibernateItemWriter<>();
    itemWriter.setSessionFactory( sessionFactory );
    itemWriter.setClearSession( true );
    return itemWriter;
}

Hopefully, someone could point me to the right direction. Thanks.

Body:
The session cache is growing and making your app slower and consuming more memory.

Try this:

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.save(customer);
    if ( i % 20 == 0 ) { //20, same as the JDBC batch size
        //flush a batch of inserts and release memory:
        session.flush();
        session.clear();
    }
}

tx.commit();
session.close();

Example taken from here and I confirm to you we use the same solution and it works good.

The only downside of the solution is that sometimes you may get NonUniqueObjectException from Hibernate. It comes as a consequence of the session.clear() which makes all Hibernate instances detached. In such a case, you definitely need to read this and probably call session.refresh(instance).


来源: stackexchange

问:
UIButton Long Press Event
I want to emulate a long a press button, how can I do this? I think a timer is needed.
I see UILongPressGestureRecognizer but how can I utilize this type?

答:
None worked hence I tried writing longpress code in IBAction or button click from storyboard in Controller instead of writing in viewDidLoad

```<code>- (IBAction)btnClick:(id)sender {

    tag = (int)((UIButton *)sender).tag;

// Long press here instead of in viewDidLoad

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    longPress.cancelsTouchesInView = NO;
    [sender addGestureRecognizer:longPress];

}
</code>```

ContentLicense: CC BY-SA 3.0

Title: UIButton Long Press Event

Body:
None worked hence I tried writing longpress code in IBAction or button click from storyboard in Controller instead of writing in viewDidLoad

- (IBAction)btnClick:(id)sender {

    tag = (int)((UIButton *)sender).tag;

// Long press here instead of in viewDidLoad

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    longPress.cancelsTouchesInView = NO;
    [sender addGestureRecognizer:longPress];

}


问:
Download files with ServiceStack Rest-API
I'm quite new to REST-services in general and I'm playing around with ServiceStack (which is awesome!). I have some services running and now I want to be able to download files (zip) via the service.

My idea is to set a route (/download) to receive files and download them with the client to store them locally.

My current approach looks like this:

```<code>[Route("/download")]
public class DownloadRequest : IReturn<HttpResult>
{

}

public class FileDownloadService : Service
{
    public object Any(DownloadRequest request)
    {
        string fileFullPath = @"C:\Users\marcel\Downloads\test.zip";
        string mimeType = "application/zip";
        FileInfo fi = new FileInfo(fileFullPath);

        byte[] reportBytes = File.ReadAllBytes(fi.FullName);
        HttpResult result = new HttpResult(reportBytes, mimeType);

        result.Headers.Add("Content-Disposition", "attachment;filename=Download.zip;");

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

I'd like to change this implementation to send data as stream. I stumbled upon IStreamWriterAsync, but couldn't really find documentation on usage for this. I'd also like to be able to handle client-side download with the ServiceStack C#-Client.

What would be a good strategy do implement my plan?

Edit: Something like that?

```<code>[Route("/download")]
public class DownloadRequest : IReturn<Stream>
{

}

public class FileDownloadService : Service, IHasOptions
{
    public IDictionary<string, string> Options { get; private set; }

    public Stream Any(DownloadRequest request)
    {
        string fileFullPath = @"C:\Users\marcel\Downloads\test.zip";
        FileInfo fi = new FileInfo(fileFullPath);

        Options = new Dictionary<string, string>
        {
            {"Content-Type","application/zip" },
            {"Content-Disposition", "attachment;filename=Download.zip;" }
        };

        return fi.OpenRead();
    }
}
</code>```

答:
An easy way to download a file is to return the fileInfo in a HttpResult, e.g:

```<code>return new HttpResult(new FileInfo(fileFullPath), asAttachment:true);
</code>```

Or by using the Virtual File System

```<code>return new HttpResult(
    VirtualFileSources.GetFile(virtualPath), asAttachment:true);
</code>```

Both of these APIs already write the file bytes as a Stream so there's no need to try manually doing it yourself.

Note: HttpResult is just a server wrapper object not the response body itself so it should never be used in an IReturn<T> interface whose purpose is to tell clients what Response Type the Service returns.

The IReturn<T> should specify what the Response Body is, in this case since it's not a Response DTO it can be either:

```<code>IReturn<byte[]> or IReturn<Stream>
</code>```

Or you can just leave it unspecified as you'll still be able to download it using the ServiceClient's raw data APIs:

With IReturn<Stream> interface:

```<code>using (Stream stream = client.Get(new DownloadRequest())) {
   ...
}
</code>```

Or you can just easily download the response as a Stream without the IReturn<T> by specifying how you want to access the raw data on the call-site, e.g:

```<code>Stream stream = client.Get<Stream>(new DownloadRequest());
byte[] bytes = client.Get<byte[]>("/download");
</code>```

If you want to also access the Response HTTP Headers you can also request the raw HttpWebResponse to be returned which will let you access the Response HTTP Headers:

```<code>using (var webRes = client.Get<HttpWebResponse>(new DownloadRequest()))
using (var stream = webRes.GetResponseStream())
{
    var contentDisposition = webRes.Headers[HttpHeaders.ContentDisposition];
}
</code>```

Alternatively you can also use HTTP Utils to download arbitrary files, e.g:

```<code> string info = null;
 var bytes = baseUrl.CombineWith("download").GetBytesFromUrl(
     responseFilter: res => info = res.Headers[HttpHeaders.ContentDisposition]);
</code>```

Body:
I'm quite new to REST-services in general and I'm playing around with ServiceStack (which is awesome!). I have some services running and now I want to be able to download files (zip) via the service.

My idea is to set a route (/download) to receive files and download them with the client to store them locally.

My current approach looks like this:

[Route("/download")]
public class DownloadRequest : IReturn<HttpResult>
{

}

public class FileDownloadService : Service
{
    public object Any(DownloadRequest request)
    {
        string fileFullPath = @"C:\Users\marcel\Downloads\test.zip";
        string mimeType = "application/zip";
        FileInfo fi = new FileInfo(fileFullPath);

        byte[] reportBytes = File.ReadAllBytes(fi.FullName);
        HttpResult result = new HttpResult(reportBytes, mimeType);

        result.Headers.Add("Content-Disposition", "attachment;filename=Download.zip;");

        return result;
    }
}

I'd like to change this implementation to send data as stream. I stumbled upon IStreamWriterAsync, but couldn't really find documentation on usage for this. I'd also like to be able to handle client-side download with the ServiceStack C#-Client.

What would be a good strategy do implement my plan?

Edit: Something like that?

[Route("/download")]
public class DownloadRequest : IReturn<Stream>
{

}

public class FileDownloadService : Service, IHasOptions
{
    public IDictionary<string, string> Options { get; private set; }

    public Stream Any(DownloadRequest request)
    {
        string fileFullPath = @"C:\Users\marcel\Downloads\test.zip";
        FileInfo fi = new FileInfo(fileFullPath);

        Options = new Dictionary<string, string>
        {
            {"Content-Type","application/zip" },
            {"Content-Disposition", "attachment;filename=Download.zip;" }
        };

        return fi.OpenRead();
    }
}

Body:
An easy way to download a file is to return the fileInfo in a HttpResult, e.g:

return new HttpResult(new FileInfo(fileFullPath), asAttachment:true);

Or by using the Virtual File System

return new HttpResult(
    VirtualFileSources.GetFile(virtualPath), asAttachment:true);

Both of these APIs already write the file bytes as a Stream so there's no need to try manually doing it yourself.

Note: HttpResult is just a server wrapper object not the response body itself so it should never be used in an IReturn<T> interface whose purpose is to tell clients what Response Type the Service returns.

The IReturn<T> should specify what the Response Body is, in this case since it's not a Response DTO it can be either:

IReturn<byte[]> or IReturn<Stream>

Or you can just leave it unspecified as you'll still be able to download it using the ServiceClient's raw data APIs:

With IReturn<Stream> interface:

using (Stream stream = client.Get(new DownloadRequest())) {
   ...
}

Or you can just easily download the response as a Stream without the IReturn<T> by specifying how you want to access the raw data on the call-site, e.g:

Stream stream = client.Get<Stream>(new DownloadRequest());
byte[] bytes = client.Get<byte[]>("/download");

If you want to also access the Response HTTP Headers you can also request the raw HttpWebResponse to be returned which will let you access the Response HTTP Headers:

using (var webRes = client.Get<HttpWebResponse>(new DownloadRequest()))
using (var stream = webRes.GetResponseStream())
{
    var contentDisposition = webRes.Headers[HttpHeaders.ContentDisposition];
}

Alternatively you can also use HTTP Utils to download arbitrary files, e.g:

 string info = null;
 var bytes = baseUrl.CombineWith("download").GetBytesFromUrl(
     responseFilter: res => info = res.Headers[HttpHeaders.ContentDisposition]);


问:
Get week in array of days
I have a array of days:

```<code>var days = [1,5,7,9,12,16,23,27,45,66];
</code>```

Now I want to find out which days belong to which week. i.e.

```<code>Week 1: 1,5,7
Week 2: 9,12
Week 3: 23,27
</code>```

and so on.

How can I achieve that?

答:
You could calculate the week with a division by 7 and round up the value to the next integer value.

var days = [1, 5, 7, 9, 12, 16, 23, 27, 45, 66],
    weeks = {};

days.forEach(function (d) {
    var w = Math.ceil(d / 7);
    weeks[w] = weeks[w] || [];
    weeks[w].push(d);
});

console.log(weeks);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Get week in array of days

Body:
I have a array of days:

var days = [1,5,7,9,12,16,23,27,45,66];

Now I want to find out which days belong to which week. i.e.

Week 1: 1,5,7
Week 2: 9,12
Week 3: 23,27

and so on.

How can I achieve that?

Body:
You could calculate the week with a division by 7 and round up the value to the next integer value.

var days = [1, 5, 7, 9, 12, 16, 23, 27, 45, 66],
    weeks = {};

days.forEach(function (d) {
    var w = Math.ceil(d / 7);
    weeks[w] = weeks[w] || [];
    weeks[w].push(d);
});

console.log(weeks);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Dual-Core Hyperthreading: Should I use 4 threads or 3 or 2?
If you're spawning multiple threads (or processes) concurrently, is it better to spawn as many as the number of physical processors or the number of logical processors, assuming the task is CPU-bound? Or is it better to do something in between (say, 3 threads)?

Does the performance depend on the kind of instructions that are getting executed (say, would non-local memory access be much different from cache hits)? If so, in which cases is it better to take advantage of hyperthreading?

Update:

The reason I'm asking is, I remember reading somewhere that if you have as many tasks as the number of virtual processors, tasks on the same physical core can sometimes starve some CPU resources and prevent each other from getting as many resources as needed, possibly decreasing performance. That's why I'm wondering if having as many threads as virtual cores is a good idea.

答:
I remember info that hyperthreading can give you up to 30% of performance boost. in general you'd better to treat them as 4 different cores. of course in some specific circumstances (e.g. having the same long running task bound to each core) you can divide your processing better taking into account that some cores are just logical ones

more info about hyperthreading itself here

ContentLicense: CC BY-SA 2.5


问:
Group by LINQ vs group by SQL
I have the following query in SQL which I would like to convert to LINQ statement.

```<code>select AreaId, BrandId, MilestoneId, DocumentCategoryId
from Document
group by AreaId, Brandid, MilestoneId, DocumentCategoryId
</code>```

I have tried, e.g.,

```<code>var docs =
    from d in documents
    group d by new
    {
        d.Area,
        d.Brand,
        d.MilestoneId,
        d.DocumentCategoryId
    } into gcs
    select new Group()
    {
        Area = gcs.Key.Area,
        Brand = gcs.Key.Brand,
        MilestoneId = gcs.Key.MilestoneId,
        DocumentCategoryId = gcs.Key.DocumentCategoryId,
    };
</code>```

And

```<code>var docs = documents
    .GroupBy(d => new Group
    {
        Area = d.Area,
        Brand = d.Brand,
        MilestoneId = d.MilestoneId,
        DocumentCategoryId = d.DocumentCategoryId,
    })
</code>```

but the result in SQL returns 88 rows (the aim), in query syntax 78 rows and in LINQ 270 (total number).

I would like a LINQ statement for to return 88 rows.

答:
I expect the final version is essentially switching to LINQ-to-Objects - i.e. populating a Group object per row, then grouping in .NET terms, which will mean one row per group as I doubt your Group implements the right patterns for equality. To get LINQ to treat the last version correctly, you probably need to add an anonymous type into the mix (LINQ understands this should behave like a tuple):

```<code>var docs = documents
    .GroupBy(d => new
    {
        Area = d.Area,
        Brand = d.Brand,
        MilestoneId = d.MilestoneId,
        DocumentCategoryId = d.DocumentCategoryId,
    }).Select(grp => new Group {
        Area = grp.Key.Area,
        Brand = grp.Key.Brand,
        MilestoneId = grp.Key.MilestoneId,
        DocumentCategoryId = grp.Key.DocumentCategoryId,
    });
</code>```

As for the 88 vs 78: have you looked at what SQL is being issued? That should tell you what it is doing differently.

Title: Group by LINQ vs group by SQL

Body:
I have the following query in SQL which I would like to convert to LINQ statement.

select AreaId, BrandId, MilestoneId, DocumentCategoryId
from Document
group by AreaId, Brandid, MilestoneId, DocumentCategoryId

I have tried, e.g.,

var docs =
    from d in documents
    group d by new
    {
        d.Area,
        d.Brand,
        d.MilestoneId,
        d.DocumentCategoryId
    } into gcs
    select new Group()
    {
        Area = gcs.Key.Area,
        Brand = gcs.Key.Brand,
        MilestoneId = gcs.Key.MilestoneId,
        DocumentCategoryId = gcs.Key.DocumentCategoryId,
    };

And

var docs = documents
    .GroupBy(d => new Group
    {
        Area = d.Area,
        Brand = d.Brand,
        MilestoneId = d.MilestoneId,
        DocumentCategoryId = d.DocumentCategoryId,
    })

but the result in SQL returns 88 rows (the aim), in query syntax 78 rows and in LINQ 270 (total number).

I would like a LINQ statement for to return 88 rows.

Body:
I expect the final version is essentially switching to LINQ-to-Objects - i.e. populating a Group object per row, then grouping in .NET terms, which will mean one row per group as I doubt your Group implements the right patterns for equality. To get LINQ to treat the last version correctly, you probably need to add an anonymous type into the mix (LINQ understands this should behave like a tuple):

var docs = documents
    .GroupBy(d => new
    {
        Area = d.Area,
        Brand = d.Brand,
        MilestoneId = d.MilestoneId,
        DocumentCategoryId = d.DocumentCategoryId,
    }).Select(grp => new Group {
        Area = grp.Key.Area,
        Brand = grp.Key.Brand,
        MilestoneId = grp.Key.MilestoneId,
        DocumentCategoryId = grp.Key.DocumentCategoryId,
    });

As for the 88 vs 78: have you looked at what SQL is being issued? That should tell you what it is doing differently.


问:
Importing functions from in the same file as declared
I would like to place a function at the end of a script which is used in the script. This, of course, does not work as the function is not known yet.
Can I therefore import this funtion in the same script?

If I do it like the following, I get the error " ImportError: cannot import name:'subfunction' "

```<code>from the_script_in_use import subfuction

a=subfunction(b)

def subfunction(value)
    do something
    return a
</code>```

答:
One way to do this in Python is writing:

```<code>def main():
    b = 5
    a = subfunction(b)
    print a

def subfunction(value):
    a = value + 10
    return a

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

This way you can write your code in the order you like, as long as you keep calling the function main at the end.

Body:
I would like to place a function at the end of a script which is used in the script. This, of course, does not work as the function is not known yet.
Can I therefore import this funtion in the same script?

If I do it like the following, I get the error " ImportError: cannot import name:'subfunction' "

from the_script_in_use import subfuction

a=subfunction(b)

def subfunction(value)
    do something
    return a

Body:
One way to do this in Python is writing:

def main():
    b = 5
    a = subfunction(b)
    print a

def subfunction(value):
    a = value + 10
    return a

if __name__ == '__main__':
    main()

This way you can write your code in the order you like, as long as you keep calling the function main at the end.


问:
How to access the model of another RequestMapping in the same Controller?
How do I make the objects associated to a RequestMapping in a controller be accessible by another RequestMapping in the same controller that returns to the same view page? Thank you.

Here is my sample code which is placed in only one controller:

```<code>@RequestMapping(value="firstMapping",method=RequestMethod.POST)
public ModelAndView firstMapping (HttpServletRequest request) {

    //myObject is processed here

    ModelAndView mav = new ModelAndView();
    mav.setViewName("samplepage");
    mav.addObject("myObject",myObject); //How do I pass this object to the mapping below?
    return mav;
}

@RequestMapping(value="secondMapping",method=RequestMethod.POST)
public ModelAndView secondMapping (HttpServletRequest request) {

    //I want to do something else here but I need the object from
    //the mapping above. For example myObject2 is processed here

    ModelAndView mav = new ModelAndView();
    mav.setViewName("samplepage");

    mav.addObject("myObject",myObject);
    mav.addObject("myObject2",myObject2);
    return mav;
}
</code>```

答:
In the first method, instead of setting a view you should forward the request to the second method after setting the attribute.Set view in second method.By using this request is forwarded to the second method after processing.

```<code>@RequestMapping(value="firstMapping",method=RequestMethod.POST)
public ModelAndView firstMapping (HttpServletRequest request) {
    Object myObject=new Object();
   request.setAttribute("myObject",myObject);
    return "forward:/secondMapping";
}
</code>```

you can also use ModelandView to carry object from method 1 to 2.

Body:
How do I make the objects associated to a RequestMapping in a controller be accessible by another RequestMapping in the same controller that returns to the same view page? Thank you.

Here is my sample code which is placed in only one controller:

@RequestMapping(value="firstMapping",method=RequestMethod.POST)
public ModelAndView firstMapping (HttpServletRequest request) {

    //myObject is processed here

    ModelAndView mav = new ModelAndView();
    mav.setViewName("samplepage");
    mav.addObject("myObject",myObject); //How do I pass this object to the mapping below?
    return mav;
}

@RequestMapping(value="secondMapping",method=RequestMethod.POST)
public ModelAndView secondMapping (HttpServletRequest request) {

    //I want to do something else here but I need the object from
    //the mapping above. For example myObject2 is processed here

    ModelAndView mav = new ModelAndView();
    mav.setViewName("samplepage");

    mav.addObject("myObject",myObject);
    mav.addObject("myObject2",myObject2);
    return mav;
}

Body:
In the first method, instead of setting a view you should forward the request to the second method after setting the attribute.Set view in second method.By using this request is forwarded to the second method after processing.

@RequestMapping(value="firstMapping",method=RequestMethod.POST)
public ModelAndView firstMapping (HttpServletRequest request) {
    Object myObject=new Object();
   request.setAttribute("myObject",myObject);
    return "forward:/secondMapping";
}

you can also use ModelandView to carry object from method 1 to 2.


问:
SQL - how to update a column with each row value incremented by 1?
For the selected rows in a column, how to update each row sequentially from the beginning to the end, with each row value incremented by 1 (or certain number). I know this can be done in excel in few seconds but I could figure out how to achieve in SQL server. For instance:

customer id is NULL now
update customer id with every row incremented by 1 (i.e. first row = 1, second row = 2, .....nth row = n)

```<code>ship-to party   customer id
0002018092      NULL
0002008127      NULL
0002000129      NULL
0002031592      NULL
0002034232      NULL
</code>```

desired output

```<code>ship-to party   customer id
0002018092      1
0002008127      2
0002000129      3
0002031592      4
0002034232      5
</code>```

Also, for the selected rows in a column, how to update each row with the row number? I know there is a row_number() function but didn't succeed in producing the desired result. for instance

column A is NULL now
update Column A with every row incremented by 1 (i.e. first row = row number 1, second row = row number 2, .....nth row = row number n)

Any demonstration would be very helpful.thkans

答:
First problem:

you want to increase values in every row in certain column by 1 (or other nuber), try this:

```<code>update TABLE_NAME set column_to_increase = column_to_increase + 1
</code>```

Second problem:

you want to get row number for only certain rows. Solution: first create column holding all row numbers, then get the rows:

```<code>select * from (
    select column1, column2, ..., columnN, row_number() over (order by (select null)) as [rn] from MY_TABLE
) where *condition*
</code>```

FYI: select null in over clause does exactly nothing, it's just there, because window functions (such as row_number) have to have over clause and some of them require order by.

Body:
For the selected rows in a column, how to update each row sequentially from the beginning to the end, with each row value incremented by 1 (or certain number). I know this can be done in excel in few seconds but I could figure out how to achieve in SQL server. For instance:

customer id is NULL now
update customer id with every row incremented by 1 (i.e. first row = 1, second row = 2, .....nth row = n)

ship-to party   customer id
0002018092      NULL
0002008127      NULL
0002000129      NULL
0002031592      NULL
0002034232      NULL

desired output

ship-to party   customer id
0002018092      1
0002008127      2
0002000129      3
0002031592      4
0002034232      5

Also, for the selected rows in a column, how to update each row with the row number? I know there is a row_number() function but didn't succeed in producing the desired result. for instance

column A is NULL now
update Column A with every row incremented by 1 (i.e. first row = row number 1, second row = row number 2, .....nth row = row number n)

Any demonstration would be very helpful.thkans

Body:
First problem:

you want to increase values in every row in certain column by 1 (or other nuber), try this:

update TABLE_NAME set column_to_increase = column_to_increase + 1

Second problem:

you want to get row number for only certain rows. Solution: first create column holding all row numbers, then get the rows:

select * from (
    select column1, column2, ..., columnN, row_number() over (order by (select null)) as [rn] from MY_TABLE
) where *condition*

FYI: select null in over clause does exactly nothing, it's just there, because window functions (such as row_number) have to have over clause and some of them require order by.


问:
awk split question
I wrote a small script, using awk 'split' command to get the current directory name.

echo $PWD

I need to replace '8' with the number of tokens as a result of the split operation.
// If PWD = /home/username/bin. I am trying to get "bin" into package.

```<code>package="`echo $PWD | awk '{split($0,a,"/"); print a[8] }'`"
echo $package
</code>```

Can you please tell me what do I substitute in place of 'print a[8]'  to get the script working for any directory path ?

-Sachin

答:
You could use print a[length(a)] but it's better to avoid splitting and use custom fields separator and $NF:

```<code>echo $PWD | awk -F/ '{print $NF}'
</code>```

But in that specific case you should rather use basename:

```<code>basename "$PWD"
</code>```

Title: awk split question

Body:
I wrote a small script, using awk 'split' command to get the current directory name.

echo $PWD

I need to replace '8' with the number of tokens as a result of the split operation.
// If PWD = /home/username/bin. I am trying to get "bin" into package.

package="`echo $PWD | awk '{split($0,a,"/"); print a[8] }'`"
echo $package

Can you please tell me what do I substitute in place of 'print a[8]'  to get the script working for any directory path ?

-Sachin

Body:
You could use print a[length(a)] but it's better to avoid splitting and use custom fields separator and $NF:

echo $PWD | awk -F/ '{print $NF}'

But in that specific case you should rather use basename:

basename "$PWD"


问:
ssh from vagrant and my username
I'd like to have access to ssh keys on a vagrant box so that I can access other hosts from there.  I do this

```<code>Vagrant::Config.run do |config|
   config.ssh.forward_agent = true
end
</code>```

and this in ~/.ssh/config

```<code>Host 127.0.0.1
  ForwardAgent yes
</code>```

(note to future generations: not localhost), then vagrant reload.  Good.

```<code>╭╴ (master *$%=)╶╮
╰ jeff@birdsong:analytics $ vagrant ssh
Welcome to Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-101-generic x86_64)
[...]
[T] ubuntu@ubuntu-xenial:~ $ ssh-add -l
[...we have identities!...]
[T] ubuntu@ubuntu-xenial:~
</code>```

But now I still have to explicitly use my username, since user vagrant is not what I want when I jump to other worlds through ssh.  I'd like to script this and share the scripts within my team, so just typing my name isn't the answer.

```<code>#!/bin/bash
ssh -L 1234:host.example.com:1234 jeff@some.host.somewhere
</code>```

We could all agree to set an environment variable, like for me VAGRANT_SSH_USER=jeff and then use that in our scripts.  But perhaps there is a better way that doesn't require everyone to set environment variables?

```<code>#!/bin/bash
ssh -L 1234:host.example.com:1234 $VAGRANT_SSH_USER@some.host.somewhere
</code>```

Thanks.

答:
You can pass $USER into your ssh script. VAGRANT_SSH_USER=$USER.

hope this helps

Title: ssh from vagrant and my username

Body:
I'd like to have access to ssh keys on a vagrant box so that I can access other hosts from there.  I do this

Vagrant::Config.run do |config|
   config.ssh.forward_agent = true
end

and this in ~/.ssh/config

Host 127.0.0.1
  ForwardAgent yes

(note to future generations: not localhost), then vagrant reload.  Good.

╭╴ (master *$%=)╶╮
╰ jeff@birdsong:analytics $ vagrant ssh
Welcome to Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-101-generic x86_64)
[...]
[T] ubuntu@ubuntu-xenial:~ $ ssh-add -l
[...we have identities!...]
[T] ubuntu@ubuntu-xenial:~

But now I still have to explicitly use my username, since user vagrant is not what I want when I jump to other worlds through ssh.  I'd like to script this and share the scripts within my team, so just typing my name isn't the answer.

#!/bin/bash
ssh -L 1234:host.example.com:1234 jeff@some.host.somewhere

We could all agree to set an environment variable, like for me VAGRANT_SSH_USER=jeff and then use that in our scripts.  But perhaps there is a better way that doesn't require everyone to set environment variables?

#!/bin/bash
ssh -L 1234:host.example.com:1234 $VAGRANT_SSH_USER@some.host.somewhere

Thanks.


问:
React js. Passing Props to the index.js file gives me an 'undefined' error
Here's my ToDoComp.js file

```<code>class ToDoComp extends Component {

    render () {
        return (
            <div>
            <h1> {this.props.product.name} </h1>

            </div>
            );
    }
}

 var prod={"id":2,"name":"An ice sculpture","price":"12.50"};
 export default ToDoComp;
</code>```

my index.js file

```<code>ReactDOM.render(<ToDoComp  product={prod} />, document.getElementById('root'));
registerServiceWorker();
</code>```

I'm getting an error like this

./src/index.js

Line 8:  'prod' is not defined  no-undef

答:
And indeed (as the error says) prod is not defined, since you did not exported it in ToDoComp.js.

You can do something like this at the end of your ToDoComp.js:
export prod; and then at the begginning of index.js you can import it and use it.

Body:
Here's my ToDoComp.js file

class ToDoComp extends Component {

    render () {
        return (

 {this.props.product.name}

            );
    }
}

 var prod={"id":2,"name":"An ice sculpture","price":"12.50"};
 export default ToDoComp;

my index.js file

ReactDOM.render(<ToDoComp  product={prod} />, document.getElementById('root'));
registerServiceWorker();

I'm getting an error like this

./src/index.js

Line 8:  'prod' is not defined  no-undef


问:
how to match statement that combine word,/,digits like /dev/home/hello-world
i want to match following statement in regex:

```<code>/
/dev/shm
/var/lib/snap/hello-world/27
</code>```

any idea?
and this is my last try:

```<code>\/((\w+)|(\/\w+-\w+))+
</code>```

but it seems that, dash-statements treat like a seperate part.

答:
thanks everyone. all your answers works. but i find a simple approach:

```<code>(\/([\w\d\-\/])*)
</code>```

RegEx Demo

Body:
i want to match following statement in regex:

/
/dev/shm
/var/lib/snap/hello-world/27

any idea?
and this is my last try:

\/((\w+)|(\/\w+-\w+))+

but it seems that, dash-statements treat like a seperate part.

Body:
thanks everyone. all your answers works. but i find a simple approach:

(\/([\w\d\-\/])*)

RegEx Demo


问:
New class does not show in reference object browser
I added a new class to my Class Library Domain called SongPlayDaily.cs but for some reason it does not display in my reference object browser. See image and correlated numbers:

Observe that the new class exists in my Domain class library

See that I reference this Class Library in my Unearth project.

Upon double clicking the Domain in the references dropdown below Unearth the object browser opens and you can see that SongPlayDaily is not referenced here

This is the console error I experience.

Right clicking on the SongPlayDaily.cs in the Class Library I can confirm that the Build Action: Compile

What other things can I check to see why this new class may not be showing up?

Thanks!

答: So dumb, I switched my Domain Class Library framework from 4.6.1 to 4.0 back to 4.6.1, rebuilt my solution and it is now referenced....


问:
applicationDidEnterBackground: and time to write on a database
When the application terminates, I write data on a database.

As from iOS 4 applicationWillTerminate: isn't called, I've put the same saving code both in applicationDidEnterBackground: and applicationWillTerminate:

I read that the task performed in applicationDidEnterBackground: has to take a few time.

So, if the writing on the db takes more, how could I manage this?

答:
You get 5 seconds to perform any saving etc in the applicationDidEnterBackground: method.

If you need more than 5 seconds there is this UIApplication method to request a background thread which will allow for more time to do whatever you need:

```<code>- (UIBackgroundTaskIdentifier)beginBackgroundTaskWithExpirationHandler:(void(^)(void))handler
</code>```

Here is Apple's example code for this:

http://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH5-SW12

ContentLicense: CC BY-SA 4.0

Body:
You get 5 seconds to perform any saving etc in the applicationDidEnterBackground: method.

If you need more than 5 seconds there is this UIApplication method to request a background thread which will allow for more time to do whatever you need:

- (UIBackgroundTaskIdentifier)beginBackgroundTaskWithExpirationHandler:(void(^)(void))handler

Here is Apple's example code for this:

http://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH5-SW12


问:
How to Render Two Components Conditionally?

How can I render these two components conditionally?

import React, { Component } from 'react';
import { Container, Header, Content, Card, CardItem, Text, Body } from 'native-base';
export default class CardHeaderFooterExample extends Component {
  render() {

    return (
      <Card>
        <CardItem header>
          <Text>NativeBase</Text>
        </CardItem>
        <CardItem>

            <Text>
              //Your text here
            </Text>

        </CardItem>
        <CardItem footer>
          <Text>GeekyAnts</Text>
        </CardItem>
      </Card>
```

<p>lets say:  </p>

<pre class="lang-js prettyprint-override"><code>if logedin={true}
  return
    <Card>
      <CardItem header>
        <Text>NativeBase</Text>
      </CardItem>
      <CardItem>
        <Body>
          <Text>
            //Your text here
          </Text>
        </Body>
      </CardItem>
      <CardItem footer>
        <Text>GeekyAnts</Text>
      </CardItem>
    </Card>

else return

  <Text> signup to access this content </Text>
</code>```

How can be this conditional rendering be done for this situation? Those components should be rendered based on boolean logedin.

答:
I think what you need is

return logedin==true ? (
  <Card>
    <CardItem header>
      <Text>NativeBase</Text>
    </CardItem>
    <CardItem>

        <Text>
          //Your text here
        </Text>

    </CardItem>
    <CardItem footer>
      <Text>GeekyAnts</Text>
    </CardItem>
  </Card>
) : (
  <Text> signup to access this content </Text>
)
```

remember change to this.props.logedin or this.state.logedin if they're belong to props or state.

Body:
How can I render these two components conditionally?

import React, { Component } from 'react';
import { Container, Header, Content, Card, CardItem, Text, Body } from 'native-base';
export default class CardHeaderFooterExample extends Component {
  render() {

    return (
      <Card>
        <CardItem header>
          <Text>NativeBase</Text>
        </CardItem>
        <CardItem>

            <Text>
              //Your text here
            </Text>

        </CardItem>
        <CardItem footer>
          <Text>GeekyAnts</Text>
        </CardItem>
      </Card>

lets say:

if logedin={true}
  return
    <Card>
      <CardItem header>
        <Text>NativeBase</Text>
      </CardItem>
      <CardItem>

          <Text>
            //Your text here
          </Text>

      </CardItem>
      <CardItem footer>
        <Text>GeekyAnts</Text>
      </CardItem>
    </Card>

else return

  <Text> signup to access this content </Text>

How can be this conditional rendering be done for this situation? Those components should be rendered based on boolean logedin.

Body:
I think what you need is

return logedin==true ? (
  <Card>
    <CardItem header>
      <Text>NativeBase</Text>
    </CardItem>
    <CardItem>
      <Body>
        <Text>
          //Your text here
        </Text>
      </Body>
    </CardItem>
    <CardItem footer>
      <Text>GeekyAnts</Text>
    </CardItem>
  </Card>
) : (
  <Text> signup to access this content </Text>
)

remember change to this.props.logedin or this.state.logedin if they're belong to props or state.


问:
Tell waf to wait for task to finish before staring next task
I have two Tasks in waf and they need to be exectued in the correct order, and the second task, has to wait until the first task has finished.

To show that it's behaving the way I expected it to work, I wait inside the tasks, in the first task (t_1) 4 seconds and in the second task (t_2) 1 second. And the second task finishes first. This can be seen, as the folders I create after waiting have timestamps t_2 < t_1.

In one Question:
How can I tell waf, that t_2 is exectued after t_1 finished successfully?

MWE: wscript

```<code>from waflib import Context, Options
from waflib import Task, TaskGen
from waflib.Tools.compiler_c import c_compiler

def options(opt):
    opt.load('compiler_c')

def configure(cnf):
    cnf.load('compiler_c')

def build(bld):
    bld.program(features=['t_1', 't_2'], source='main.c', target='abc')

class t_1(Task.Task):
    always_run = True
    run_str = 'echo start t_1 && python -c "import time; time.sleep(4)" && echo end t_1 && mkdir t_1'
    color = 'RED'

@TaskGen.feature('t_1')
@TaskGen.after('apply_link')
@TaskGen.before('t_2')
def add_t_1_task(self):
    self.create_task('t_1')

class t_2(Task.Task):
    always_run = True
    run_str = 'echo start t_2 && python -c "import time; time.sleep(1)" && echo end t_2 && mkdir t_2'
    color = 'RED'

@TaskGen.feature('t_2')
@TaskGen.after('apply_link', 't_1')
def add_t_2_task(self):
    self.create_task('t_2')
</code>```

答:
You have to specify the task which has to run before (in that example t_1) in after attribute of the task which should "wait" for the the other task to finish (in that example (t_2).
It is specified like this: after = ['t_1']

The documentation to this can be found here in section build order constraints in the waf book.

The documentation that explains generic task generator is §9.3 in the current waf book (waf 2.0), especially §9.3.4 explains the task generator execution order.

The complete example MWE looks then like this:

```<code>from waflib import Context, Options
from waflib import Task, TaskGen
from waflib.Tools.compiler_c import c_compiler

def options(opt):
    opt.load('compiler_c')

def configure(cnf):
    cnf.load('compiler_c')

def build(bld):
    bld.program(features=['t_1', 't_2'], source='main.c', target='abc')

class t_1(Task.Task):
    always_run = True
    run_str = 'date && echo 1 && echo start t_1 && python -c "import time; time.sleep(4)" && echo end t_1 && mkdir t_1 && date && echo 1'
    color = 'RED'

@TaskGen.feature('t_1')
@TaskGen.after('apply_link')
@TaskGen.before('t_2')
def add_t_1_task(self):
    self.create_task('t_1')

class t_2(Task.Task):
    always_run = True
    after = ['t_1'] # <---------------------------- **The problems solution**
    run_str = 'date && echo 1 && echo start t_2 && python -c "import time; time.sleep(1)" && echo end t_2 && mkdir t_2 && date && echo 2'
    color = 'RED'

@TaskGen.feature('t_2')
@TaskGen.after('apply_link', 't_1')
def add_t_2_task(self):
    self.create_task('t_2')
</code>```

Body:
I have two Tasks in waf and they need to be exectued in the correct order, and the second task, has to wait until the first task has finished.

To show that it's behaving the way I expected it to work, I wait inside the tasks, in the first task (t_1) 4 seconds and in the second task (t_2) 1 second. And the second task finishes first. This can be seen, as the folders I create after waiting have timestamps t_2 < t_1.

In one Question:
How can I tell waf, that t_2 is exectued after t_1 finished successfully?

MWE: wscript

from waflib import Context, Options
from waflib import Task, TaskGen
from waflib.Tools.compiler_c import c_compiler

def options(opt):
    opt.load('compiler_c')

def configure(cnf):
    cnf.load('compiler_c')

def build(bld):
    bld.program(features=['t_1', 't_2'], source='main.c', target='abc')

class t_1(Task.Task):
    always_run = True
    run_str = 'echo start t_1 && python -c "import time; time.sleep(4)" && echo end t_1 && mkdir t_1'
    color = 'RED'

@TaskGen.feature('t_1')
@TaskGen.after('apply_link')
@TaskGen.before('t_2')
def add_t_1_task(self):
    self.create_task('t_1')

class t_2(Task.Task):
    always_run = True
    run_str = 'echo start t_2 && python -c "import time; time.sleep(1)" && echo end t_2 && mkdir t_2'
    color = 'RED'

@TaskGen.feature('t_2')
@TaskGen.after('apply_link', 't_1')
def add_t_2_task(self):
    self.create_task('t_2')

Body:
You have to specify the task which has to run before (in that example t_1) in after attribute of the task which should "wait" for the the other task to finish (in that example (t_2).
It is specified like this: after = ['t_1']

The documentation to this can be found here in section build order constraints in the waf book.

The documentation that explains generic task generator is §9.3 in the current waf book (waf 2.0), especially §9.3.4 explains the task generator execution order.

The complete example MWE looks then like this:

from waflib import Context, Options
from waflib import Task, TaskGen
from waflib.Tools.compiler_c import c_compiler

def options(opt):
    opt.load('compiler_c')

def configure(cnf):
    cnf.load('compiler_c')

def build(bld):
    bld.program(features=['t_1', 't_2'], source='main.c', target='abc')

class t_1(Task.Task):
    always_run = True
    run_str = 'date && echo 1 && echo start t_1 && python -c "import time; time.sleep(4)" && echo end t_1 && mkdir t_1 && date && echo 1'
    color = 'RED'

@TaskGen.feature('t_1')
@TaskGen.after('apply_link')
@TaskGen.before('t_2')
def add_t_1_task(self):
    self.create_task('t_1')

class t_2(Task.Task):
    always_run = True
    after = ['t_1'] # <---------------------------- **The problems solution**
    run_str = 'date && echo 1 && echo start t_2 && python -c "import time; time.sleep(1)" && echo end t_2 && mkdir t_2 && date && echo 2'
    color = 'RED'

@TaskGen.feature('t_2')
@TaskGen.after('apply_link', 't_1')
def add_t_2_task(self):
    self.create_task('t_2')


问:
[PHP][CRON] How can I reload page in cron?
I made a script which iterates through a couple pages of a third party website looking for data. I have table in database, where I have links to those pages.

There are about 1500 rows in table, so it's impossible to do it at once. So I have to reload site, changing the offset every time (offset+=limit). It works fine in my browser, but in CRON it doesn't. I can't use JavaScript reload, meta http-equiv="refresh". I try ignore_user_abort(true); set_time_limit(0); and then sleep, but gives me  504 too. Any ideas how to reload page with new $_GET['offset']?

答:
Increase your script execution time limit set_time_limit ( int $seconds ) so your script will have time to execute. You can even add sleep(1) to each iteration so your CPU can take a breath.
If that doesn`t  work check php error log for the problem.


问:
repeating previous regex
I have a line (and a arbitrary number of them)
0    1   1   75     55

I can get it by doing

```<code>x = re.search("\d+\s+\d+\s+(\d+)\s+(\d+)\s+(\d+)", line)
    if x != None:
        print(x.group(1))
        print(x.group(2))
        print(x.group(3))
</code>```

But there must be a neater way to write this. I was looking at the docs for something to repeat the previous expression and found (exp){m times}.

So I try

```<code>x = re.search("(\d+\s+){5}", line)
</code>```

and then expect x.group(1) to be 0, 2 to be 1, 3 to be 1 and so on
but x.group(1) ouputs 55 (the last number). Im sort of confused. Thanks.

Also on a side note. Do you guys have any recommendations for online tutorials (or free to download books) on regex?

答:
Have you considered findall which repeats the search until the input string is exhausted and returns all matches in a list?</p>

```<code>>>> import re
>>> line = '0 1 1 75 55'
>>> x = re.findall("(\d+)", line)
>>> print x
['0', '1', '1', '75', '55']
</code>```

Title: repeating previous regex

Body:
I have a line (and a arbitrary number of them)
0    1   1   75     55

I can get it by doing

x = re.search("\d+\s+\d+\s+(\d+)\s+(\d+)\s+(\d+)", line)
    if x != None:
        print(x.group(1))
        print(x.group(2))
        print(x.group(3))

But there must be a neater way to write this. I was looking at the docs for something to repeat the previous expression and found (exp){m times}.

So I try

x = re.search("(\d+\s+){5}", line)

and then expect x.group(1) to be 0, 2 to be 1, 3 to be 1 and so on
but x.group(1) ouputs 55 (the last number). Im sort of confused. Thanks.

Also on a side note. Do you guys have any recommendations for online tutorials (or free to download books) on regex?

Body:
Have you considered findall which repeats the search until the input string is exhausted and returns all matches in a list?

>>> import re
>>> line = '0 1 1 75 55'
>>> x = re.findall("(\d+)", line)
>>> print x
['0', '1', '1', '75', '55']


问:
How to call the method of an anonymous class when the anonymous class is passed as a parameter to the class method of a normal class?
I'm using PHP 7.1.11

I've tried following code for an Anonymous Class which is declared as a parameter to a class method. I want to call the method present in an anonymous class. But I'm getting a fatal error. How should I call the anonymous class method successfully?

```<code><?php

class Util {

    private $logger;

    public function __construct(){}

    public function getLogger($logger) {
        $this->logger = $logger;
    }

    public function setLogger($logger) {

        $this->logger = $logger;
    }
}

$util = new Util();

  $util->setLogger(new class {
    public function log($msg) {
      echo $msg;
    }
  });

  $util->setLogger()->log('Phil runs very fast'); // Ioutput should be : Phil runs very fast
?>
</code>```

Output I'm currently getting :

```<code>Fatal error: Uncaught ArgumentCountError: Too few arguments to function Util::setLogger(), 0 passed in anonymous_class_ex.php on line 27 and exactly 1 expected in anonymous_class_ex.php:13 Stack trace: #0 anonymous_class_ex.php(https://stackoverflow.com/posts/47605127/edit27): Util->setLogger() #1 {main} thrown in anonymous_class_ex.php on line 13
</code>```

答:
I see 2 issues with your code.

You are not using the right method on $util

Instead of
$util->setLogger()->log('Phil runs very fast');
your code should be $util->getLogger()->log('Phil runs very fast');.
You want to getLogger since it was already set before.

Your implementation of getLogger() might be flawed

In my opinion, this method should not have any parameter and it should return something, which is actually missing in your code.
So instead of

public function getLogger($logger) {
    $this->logger = $logger;
}
```

<p>you should have something like </p>

<pre class="lang-php prettyprint-override"><code>public function getLogger() {
    return $this->logger;
}
</code>```

With those 2 points addressed, your code works as expected. See here for yourself https://ideone.com/V2slho.

Body:
I'm using PHP 7.1.11

I've tried following code for an Anonymous Class which is declared as a parameter to a class method. I want to call the method present in an anonymous class. But I'm getting a fatal error. How should I call the anonymous class method successfully?

<?php

class Util {

    private $logger;

    public function __construct(){}

    public function getLogger($logger) {
        $this->logger = $logger;
    }

    public function setLogger($logger) {

        $this->logger = $logger;
    }
}

$util = new Util();

  $util->setLogger(new class {
    public function log($msg) {
      echo $msg;
    }
  });

  $util->setLogger()->log('Phil runs very fast'); // Ioutput should be : Phil runs very fast
?>

Output I'm currently getting :

Fatal error: Uncaught ArgumentCountError: Too few arguments to function Util::setLogger(), 0 passed in anonymous_class_ex.php on line 27 and exactly 1 expected in anonymous_class_ex.php:13 Stack trace: #0 anonymous_class_ex.php(https://stackoverflow.com/posts/47605127/edit27): Util->setLogger() #1 {main} thrown in anonymous_class_ex.php on line 13

Body:
I see 2 issues with your code.

You are not using the right method on $util

Instead of
$util->setLogger()->log('Phil runs very fast');
your code should be $util->getLogger()->log('Phil runs very fast');.
You want to getLogger since it was already set before.

Your implementation of getLogger() might be flawed

In my opinion, this method should not have any parameter and it should return something, which is actually missing in your code.
So instead of

public function getLogger($logger) {
    $this->logger = $logger;
}

you should have something like

public function getLogger() {
    return $this->logger;
}

With those 2 points addressed, your code works as expected. See here for yourself https://ideone.com/V2slho.


问:
Finding non-numeric values in varchar column
Requirement :

Generic query/function to check if the value provided in a varchar column in a table is actually a number & the precision does not exceed the allowed precision.

Available values:

Table_Name, Column_Name, Allowed Precision, Allowed Scale

General advise would be to create a function & use to_number() to validate the value however it won't validate the allowed length (precision-scale).

My solution:

Validate Number using Regexp NOT REGEXP_LIKE(COLUMN_NAME, '^-?[0-9.]+$')

Validate Length of left component (before decimal) (I have no idea what's its actually called) because for scale, oracle automatically rounds off if required. As the actual column is varchar i will use substr, instr to find the component on the left of decimal point.

As above Regexp allows number like 123...123124..55 I will also validate the number of decimal points. [If > 1 then error]

Query to find invalid number's:

```<code>Select * From Table_Name
Where
(NOT REGEXP_LIKE(COLUMN_NAME, '^-?[0-9.]+$')
OR
Function_To_Fetch_Left_Component(COLUMN_NAME) > (Precision-Scale)
/* Can use regexp_substr now but i already had a function for that */
OR
LENGTH(Column_Name) - LENGTH(REPLACE(Column_Name,'.','')) > 1
/* Can use regexp_count aswell*/)
</code>```

I was happy & satisfied with my solution until a column with only '.' value escaped my check and I saw the limitation of my checks. Although adding another check to validate this as well will solve my problem the solution as a whole looks very inefficient to me.

I will really appreciate a better solution [in any way].

Thanks in advance.

答:
Look for:

One-or-more digits optionally followed by a decimal point and zero-or-more digits; or

A leading decimal point (no preceding unit digit) and then one or more (decimal) digits.

Like this:

```<code>Select *
From   Table_Name
Where  NOT REGEXP_LIKE(COLUMN_NAME, '^[+-]?(\d+(\.\d*)?|\.\d+)$')
</code>```

If you do not want zero-padded values in the number string then:

```<code>Select *
From   Table_Name
Where  NOT REGEXP_LIKE(COLUMN_NAME, '^[+-]?(([1-9]\d*|0)(\.\d*)?|\.\d+)$')
</code>```

With precision and scale (assuming it works as per a NUMBER( precision, scale ) data type and scale < precision):

```<code>Select *
From   Table_Name
Where  NOT REGEXP_LIKE(COLUMN_NAME, '^[+-]?(\d{1,'||(precision-scale)||'}(\.\d{0,'||scale||'})?|\.\d{1,'||scale||'})$')
</code>```

or, for non-zero-padded numbers with precision and scale:

```<code>Select *
From   Table_Name
Where  NOT REGEXP_LIKE(COLUMN_NAME, '^[+-]?(([1-9]\d{0,'||(precision-scale-1)||'}|0)(\.\d{0,'||scale||'})?|\.\d{1,'||scale||'})$')
</code>```

or, for any precision and scale:

```<code>Select *
From   Table_Name
Where  NOT REGEXP_LIKE(
             COLUMN_NAME,
             CASE
               WHEN scale <= 0
               THEN '^[+-]?(\d{1,'||precision||'}0{'||(-scale)||'})$'
               WHEN scale < precision
               THEN '^[+-]?(\d{1,'||(precision-scale)||'}(\.\d{0,'||scale||'})?|\.\d{1,'||scale||'})$'
               WHEN scale >= precision
               THEN '^[+-]?(0(\.0{0,'||scale||'})?|0?\.0{'||(scale-precision)||'}\d{1,'||precision||'})$'
             END
           )
</code>```

Body:
Requirement :

Generic query/function to check if the value provided in a varchar column in a table is actually a number & the precision does not exceed the allowed precision.

Available values:

Table_Name, Column_Name, Allowed Precision, Allowed Scale

General advise would be to create a function & use to_number() to validate the value however it won't validate the allowed length (precision-scale).

My solution:

Validate Number using Regexp NOT REGEXP_LIKE(COLUMN_NAME, '^-?[0-9.]+$')

Validate Length of left component (before decimal) (I have no idea what's its actually called) because for scale, oracle automatically rounds off if required. As the actual column is varchar i will use substr, instr to find the component on the left of decimal point.

As above Regexp allows number like 123...123124..55 I will also validate the number of decimal points. [If > 1 then error]

Query to find invalid number's:

Select * From Table_Name
Where
(NOT REGEXP_LIKE(COLUMN_NAME, '^-?[0-9.]+$')
OR
Function_To_Fetch_Left_Component(COLUMN_NAME) > (Precision-Scale)
/* Can use regexp_substr now but i already had a function for that */
OR
LENGTH(Column_Name) - LENGTH(REPLACE(Column_Name,'.','')) > 1
/* Can use regexp_count aswell*/)

I was happy & satisfied with my solution until a column with only '.' value escaped my check and I saw the limitation of my checks. Although adding another check to validate this as well will solve my problem the solution as a whole looks very inefficient to me.

I will really appreciate a better solution [in any way].

Thanks in advance.

Body:
Look for:

One-or-more digits optionally followed by a decimal point and zero-or-more digits; or

A leading decimal point (no preceding unit digit) and then one or more (decimal) digits.

Like this:

Select *
From   Table_Name
Where  NOT REGEXP_LIKE(COLUMN_NAME, '^[+-]?(\d+(\.\d*)?|\.\d+)$')

If you do not want zero-padded values in the number string then:

Select *
From   Table_Name
Where  NOT REGEXP_LIKE(COLUMN_NAME, '^[+-]?(([1-9]\d*|0)(\.\d*)?|\.\d+)$')

With precision and scale (assuming it works as per a NUMBER( precision, scale ) data type and scale < precision):

Select *
From   Table_Name
Where  NOT REGEXP_LIKE(COLUMN_NAME, '^[+-]?(\d{1,'||(precision-scale)||'}(\.\d{0,'||scale||'})?|\.\d{1,'||scale||'})$')

or, for non-zero-padded numbers with precision and scale:

Select *
From   Table_Name
Where  NOT REGEXP_LIKE(COLUMN_NAME, '^[+-]?(([1-9]\d{0,'||(precision-scale-1)||'}|0)(\.\d{0,'||scale||'})?|\.\d{1,'||scale||'})$')

or, for any precision and scale:

Select *
From   Table_Name
Where  NOT REGEXP_LIKE(
             COLUMN_NAME,
             CASE
               WHEN scale <= 0
               THEN '^[+-]?(\d{1,'||precision||'}0{'||(-scale)||'})$'
               WHEN scale < precision
               THEN '^[+-]?(\d{1,'||(precision-scale)||'}(\.\d{0,'||scale||'})?|\.\d{1,'||scale||'})$'
               WHEN scale >= precision
               THEN '^[+-]?(0(\.0{0,'||scale||'})?|0?\.0{'||(scale-precision)||'}\d{1,'||precision||'})$'
             END
           )


问:
What's the best way to select multiple M:N relationships in SQL?
I've embarked on a project which is encouraging me to expand my knowledge of SQL.  I've already learned quite a bit, but I've gotten myself to a point where I can see a problem, but I don't know enough to properly research a solution.  I've hit SO, Google, and the MySQL docs, but either I'm asking the wrong questions or I don't know how to ask the right ones.  My data is structured with three primary tables, one of which has M:N relationships with the other two.  I'm storing those relationships in another pair of tables, as I'm under the impression that's the "best way":

```<code>books (book_id INT PRIMARY KEY, book_title VARCHAR)
authors (author_id INT PRIMARY KEY, author_name VARCHAR)
subjects (subject_id INT PRIMARY KEY, subject_name VARCHAR)
book_authors (book_id INT, author_id INT)
book_subjects (book_id INT, subject_id INT)
</code>```

(The first three tables actually have more than two columns, but they aren't relevant.)

Edit:

Obviously, I suck at asking clear questions, but then I already knew that. :-)

The issue I'm trying to solve is how to most effectively/efficiently get the data from the database into my app. Once I have it there, I can rearrange it however I need, and I trust I can do that regardless of how the data is "shaped" coming out of the database. It would be trivial to do with five separate SELECT * FROM … statements and it would be trivial to do with with the cross-product "frankenjoin" I had posted earlier. However, I know enough about SQL to spot that the former robs the database engine of the opportunity to do its job. I don't know enough about SQL to say whether the latter is equally bad.

So how about this: instead of asking what's wrong with the solution I came up with, what would be your solution? If you had data related this way, how would you select it out of the database? (And for what reasons?) Would you perhaps even arrange the tables differently?

答:
What do you think should come back? You can't have lists inside a tuple coming back from a query, so your current results seems like the only way to get back all the data in one query.

UPDATE: SQL doesn't support hierarchical structures, so you'll have to build that yourself (assuming you aren't using an ORM tool that can do it for you). One way would be to make a trip to the DB to get all the books to process, then for each book make one trip for the authors of that book and one trip for the subjects of that book. That can be an awful lot of DB trips, though. Another way would be to bring back all the data (as in your question) and then build a hierarchical structure out of that. Which one is better depends on a lot of factors. I would probably go for the one DB trip solution, even though the client code is probably more complicated; the general rule is that roundtrips to the database are expensive, so I'd tend toward the solution that doesn't increase the number of such trips linearly with the number of results.

OwnerDisplayName: Ben Blank

Body:
I've embarked on a project which is encouraging me to expand my knowledge of SQL.  I've already learned quite a bit, but I've gotten myself to a point where I can see a problem, but I don't know enough to properly research a solution.  I've hit SO, Google, and the MySQL docs, but either I'm asking the wrong questions or I don't know how to ask the right ones.  My data is structured with three primary tables, one of which has M:N relationships with the other two.  I'm storing those relationships in another pair of tables, as I'm under the impression that's the "best way":

books (book_id INT PRIMARY KEY, book_title VARCHAR)
authors (author_id INT PRIMARY KEY, author_name VARCHAR)
subjects (subject_id INT PRIMARY KEY, subject_name VARCHAR)
book_authors (book_id INT, author_id INT)
book_subjects (book_id INT, subject_id INT)

(The first three tables actually have more than two columns, but they aren't relevant.)

Edit:

Obviously, I suck at asking clear questions, but then I already knew that. :-)

The issue I'm trying to solve is how to most effectively/efficiently get the data from the database into my app. Once I have it there, I can rearrange it however I need, and I trust I can do that regardless of how the data is "shaped" coming out of the database. It would be trivial to do with five separate SELECT * FROM … statements and it would be trivial to do with with the cross-product "frankenjoin" I had posted earlier. However, I know enough about SQL to spot that the former robs the database engine of the opportunity to do its job. I don't know enough about SQL to say whether the latter is equally bad.

So how about this: instead of asking what's wrong with the solution I came up with, what would be your solution? If you had data related this way, how would you select it out of the database? (And for what reasons?) Would you perhaps even arrange the tables differently?

LastEditorDisplayName: Ben Blank

OwnerDisplayName: Hank Gay

LastEditorDisplayName: Hank Gay


问:
Qt C++ - displaying the links in QText Browser
Right now I am displaying the result in QTextBrowser. Results will be something like /home/User/, /media/Arena/ etc i.e path to different folders. Now I want to open the folder in a window by clicking on this result which is displayed in QTextBrowser. But I have no ideas how to do that. So can anyone let me know how to do it.

Thanx in advance.

P.S. I am using QtCreator & see the image http://i53.tinypic.com/qyxp1s.png.

答: BasementCat's right. You can use setHtml QTextBrowser's method to set HTML into the widget. You'll then probably need to call setOpenLinks(false) to disable default behavior and connect custom slot to widget's anchorClicked(QUrl const&) signal to handle links.

OwnerDisplayName: Winbros


答:
Your both columns, ThirdPartySourceCodeId and ThirdPartySourcePriority, after join are of integerType, so na.fill("") didn't work for them and thus when you used concat, all null integer values got filtered out.

the solution to your problem is to cast the two columns into stringType before applying na.fill

so changing

```<code>val dfMainOutputFinal = dfMainOutput.na.fill("").select($"DataPartition",concat_ws("|^|", dfMainOutput.schema.fieldNames.filter(_ != "DataPartition").map(c => col(c)): _*).as("concatenated"))
</code>```

to

```<code>val dfMainOutputFinal = dfMainOutput.withColumn("ThirdPartySourcePriority", $"ThirdPartySourcePriority".cast(StringType)).withColumn("ThirdPartySourceCodeId", $"ThirdPartySourceCodeId".cast(StringType)).na.fill("").select($"DataPartition",concat_ws("|^|", dfMainOutput.schema.fieldNames.filter(_ != "DataPartition").map(c => col(c)): _*).as("concatenated"))
</code>```

should solve your issue

Title: Why outer join does not preserve all mentioned columns after data frame join in scala spark?

Body:
Your both columns, ThirdPartySourceCodeId and ThirdPartySourcePriority, after join are of integerType, so na.fill("") didn't work for them and thus when you used concat, all null integer values got filtered out.

the solution to your problem is to cast the two columns into stringType before applying na.fill

so changing

val dfMainOutputFinal = dfMainOutput.na.fill("").select($"DataPartition",concat_ws("|^|", dfMainOutput.schema.fieldNames.filter(_ != "DataPartition").map(c => col(c)): _*).as("concatenated"))

to

val dfMainOutputFinal = dfMainOutput.withColumn("ThirdPartySourcePriority", $"ThirdPartySourcePriority".cast(StringType)).withColumn("ThirdPartySourceCodeId", $"ThirdPartySourceCodeId".cast(StringType)).na.fill("").select($"DataPartition",concat_ws("|^|", dfMainOutput.schema.fieldNames.filter(_ != "DataPartition").map(c => col(c)): _*).as("concatenated"))

should solve your issue


问:
Corda generateSpend pay coins add memo
Hi Is there a way to use Cash.generateSpend and allocate a message memo together with it?

My use case is simple, where when i spend the case i would like to tag the cash into some generic categories for example, manually-transferred or auto-transferred to a specific party.
I've been going through https://docs.corda.net/api/kotlin/corda/net.corda.finance.contracts.asset/-cash/index.html but there were no methods to add a tagging to the asset transferred purpose.

The main purpose is so when i query my history transactions i could see the movement of my funds.

答:
You can add a note to any transaction from within a flow as follows:

```<code>serviceHub.vaultService.addNoteToTransaction(
    theTransactionToAddANoteTo.id,
    "The note to add to the transaction."
)
</code>```

If you want, you can add multiple notes to the same transaction.

You can then view the notes associated with a given transaction from within a flow:

```<code>serviceHub.vaultService.getTransactionNotes(
    theTransactionToGetNotesFor.id
)
</code>```

You can also log directly into your node's database and check the contents of the VAULT_TRANSACTION_NOTES table.

Title: Corda generateSpend pay coins add memo

Body:
You can add a note to any transaction from within a flow as follows:

serviceHub.vaultService.addNoteToTransaction(
    theTransactionToAddANoteTo.id,
    "The note to add to the transaction."
)

If you want, you can add multiple notes to the same transaction.

You can then view the notes associated with a given transaction from within a flow:

serviceHub.vaultService.getTransactionNotes(
    theTransactionToGetNotesFor.id
)

You can also log directly into your node's database and check the contents of the VAULT_TRANSACTION_NOTES table.


问:
Soft Keyboard copies UI part
I am new to android and creating an registration form in app. When we click on edit text soft keyboard opens. but when keyboard opens it shows part of ui in keyboard suggestion. the image is below.

thanks in advance for any help.

The image link is below

答:
In AndroidManifest file,add the following code to the activity:</p>

```<code>android:windowSoftInputMode="adjustPan"
</code>```

Title: Soft Keyboard copies UI part

Body:
In AndroidManifest file,add the following code to the activity:

android:windowSoftInputMode="adjustPan"


问:
How to take plan details in onclick the button
Here i have one form and three button,suppose if i am clicking Enroll Now button means i have take the plan details like

Contacts details up to ?

Bonus Contact details up to  ?

Area Master Assistance : No ?

Contact details through sms ?

Above values i want to take how can take ? i tried i can able to take plan name which i have selected but i am not able to take plan details

  $(".payNow").on("click", function(e) {
    var $list = $(this).closest(".pricing-table");
      name = $list.find(".myTitle").text();

    console.log(name);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<body>
  <div class="container-fluid plan-background" style="margin-top: 0%;padding-right: 0px;padding-left: 0px;">
  <div class="container main_btm" style="padding-left: 0px;padding-right: 0px; ">

  <div class="row top" style="margin-left: 0px;margin-right: 0px;margin-top:22px;">

  <div class="col-md-5 col-sm-6 hidden-xs" class-align="right" style="margin-top: 10px;padding:left:23px; ">

  </div>
  <div class="col-md-3 col-sm-6 col-xs-12 mobile-property-list" style="margin-top: 10px; padding-left: 27px;"><h4 style="color:#fff;font-size:20px;"> Select Your Plan</h4></br>  </div>
  <div class="col-md-4 col-sm-0 hidden-xs"></div>

  </div>

  <div class="row mobile-filter"  style="margin-top: 5px; margin-left: 0px;margin-right: 0px;margin-bottom:5%;" >

  <div class="col-md-1"></div>
  <div class="col-md-10 top-a rentListing" style="padding-left:0px;">

  <section id="pricing-table">
                <div class="row pricelistNew">
                    <div class="pricing">

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Easy Plan </p>
         <input type="hidden" value="1 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 1000 <br><span>Including All Tax</span></p>

          Buy Now

                                </div>

                                <div class="pricing-list">
                                    <ul>
           <li>Contacts details up to : 25</li>
            <li>Bonus Contact details up to : 2</li>
            <li>Area Master Assistance : No</li>
            <li>Contact details through sms : Yes</li>
           </ul>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Cool Plan </p>
         <input type="hidden" value="2 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 2000 <br><span>Including All Tax</span></p>

         Buy Now

                                </div>

                                <div class="pricing-list">
                                    <ul>
           <li>Contacts details up to : 48</li>
            <li>Bonus Contact details up to : 4</li>
            <li>Area Master Assistance : Yes</li>
            <li>Contact details through sms : Yes</li>
           </ul>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Free Plan </p>
         <input type="hidden" value="3 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 0 <br><span>Including All Tax</span></p>

                                    Enroll Now

                                </div>

                                <div class="pricing-list">
                                    <ul>
           <li>Contacts details up to : 5</li>
            <li>Bonus Contact details up to : 00</li>
            <li>Area Master Assistance : No</li>
            <li>Contact details through sms : Yes</li>
           </ul>
                                </div>
                            </div>
                        </div>
                       </div>
                </div>
        </section>

  </div>

  <div class="col-md-1 "></div>
  </div>

  </div>
 </code>```

答:
Just wrap you text values inside span tag and give a suitable class.

  $(function(){

  $(".payNow").on("click", function(e) {
    var $list = $(this).closest(".pricing-table");
      name = $list.find(".myTitle").text();
      console.log(name);
   var parentEl= $(this).parents().closest('.pricing-header');
   var nextEl= $(parentEl).next().children();
   console.log('Contact Details :'+$(nextEl).children().find('.contactDetails').text());
   console.log('Bonus Contact :'+$(nextEl).children().find('.bonusContacts').text());
   console.log('Area Master :'+$(nextEl).children().find('.areaMaster').text());
   console.log('Contact details SMS :'+$(nextEl).children().find('.ContactDetailsSMS').text());
  });
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<body>
  <div class="container-fluid plan-background" style="margin-top: 0%;padding-right: 0px;padding-left: 0px;">
  <div class="container main_btm" style="padding-left: 0px;padding-right: 0px; ">

  <div class="row top" style="margin-left: 0px;margin-right: 0px;margin-top:22px;">

  <div class="col-md-5 col-sm-6 hidden-xs" class-align="right" style="margin-top: 10px;padding:left:23px; ">

  </div>
  <div class="col-md-3 col-sm-6 col-xs-12 mobile-property-list" style="margin-top: 10px; padding-left: 27px;"><h4 style="color:#fff;font-size:20px;"> Select Your Plan</h4></br>  </div>
  <div class="col-md-4 col-sm-0 hidden-xs"></div>

  </div>

  <div class="row mobile-filter"  style="margin-top: 5px; margin-left: 0px;margin-right: 0px;margin-bottom:5%;" >

  <div class="col-md-1"></div>
  <div class="col-md-10 top-a rentListing" style="padding-left:0px;">

  <section id="pricing-table">
                <div class="row pricelistNew">
                    <div class="pricing">

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Easy Plan </p>
         <input type="hidden" value="1 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 1000 <br><span>Including All Tax</span></p>

          Buy Now

                                </div>

                                <div class="pricing-list">
                                    <ul>
           <li>Contacts details up to : <span class='contactDetails'>05</span></li>
            <li>Bonus Contact details up to : <span class="bonusContacts"> 20</span></li>
            <li>Area Master Assistance : <span class='areaMaster'>No </span></li>
            <li>Contact details through sms : <span class='ContactDetailsSMS'>No</span></li>
           </ul>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Cool Plan </p>
         <input type="hidden" value="2 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 2000 <br><span>Including All Tax</span></p>

         Buy Now

                                </div>

                                <div class="pricing-list">
                                    <ul>
           <li>Contacts details up to : <span class='contactDetails'>50</span></li>
            <li>Bonus Contact details up to : <span class="bonusContacts"> 8</span></li>
            <li>Area Master Assistance : <span class='areaMaster'>Yes</span></li>
            <li>Contact details through sms : <span class='ContactDetailsSMS'>Yes</span></li>
           </ul>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Free Plan </p>
         <input type="hidden" value="3 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 0 <br><span>Including All Tax</span></p>

                                    Enroll Now

                                </div>

                                <div class="pricing-list">
                                    <ul>
           <li>Contacts details up to : <span class='contactDetails'>25</span></li>
            <li>Bonus Contact details up to : <span class="bonusContacts"> 2</span></li>
            <li>Area Master Assistance : <span class='areaMaster'>No </span></li>
            <li>Contact details through sms : <span class='ContactDetailsSMS'>Yes</span></li>
           </ul>
                                </div>
                            </div>
                        </div>
                       </div>
                </div>
        </section>

  </div>

  <div class="col-md-1 "></div>
  </div>

  </div>
 </code>```

Body:
Here i have one form and three button,suppose if i am clicking Enroll Now button means i have take the plan details like

Contacts details up to ?

Bonus Contact details up to  ?

Area Master Assistance : No ?

Contact details through sms ?

Above values i want to take how can take ? i tried i can able to take plan name which i have selected but i am not able to take plan details

  $(".payNow").on("click", function(e) {
    var $list = $(this).closest(".pricing-table");
      name = $list.find(".myTitle").text();

    console.log(name);
  });

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

 Select Your Plan

Easy Plan

         <input type="hidden" value="1 " name="plan_Id" class="plan_Id">

₹ 1000
Including All Tax

          Buy Now

Contacts details up to : 25

Bonus Contact details up to : 2

Area Master Assistance : No

Contact details through sms : Yes

Cool Plan

         <input type="hidden" value="2 " name="plan_Id" class="plan_Id">

₹ 2000
Including All Tax

         Buy Now

Contacts details up to : 48

Bonus Contact details up to : 4

Area Master Assistance : Yes

Contact details through sms : Yes

Free Plan

         <input type="hidden" value="3 " name="plan_Id" class="plan_Id">

₹ 0
Including All Tax

                                    Enroll Now

Contacts details up to : 5

Bonus Contact details up to : 00

Area Master Assistance : No

Contact details through sms : Yes

Body:
Just wrap you text values inside span tag and give a suitable class.

  $(function(){

  $(".payNow").on("click", function(e) {
    var $list = $(this).closest(".pricing-table");
      name = $list.find(".myTitle").text();
      console.log(name);
   var parentEl= $(this).parents().closest('.pricing-header');
   var nextEl= $(parentEl).next().children();
   console.log('Contact Details :'+$(nextEl).children().find('.contactDetails').text());
   console.log('Bonus Contact :'+$(nextEl).children().find('.bonusContacts').text());
   console.log('Area Master :'+$(nextEl).children().find('.areaMaster').text());
   console.log('Contact details SMS :'+$(nextEl).children().find('.ContactDetailsSMS').text());
  });
  });

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<body>
  <div class="container-fluid plan-background" style="margin-top: 0%;padding-right: 0px;padding-left: 0px;">
  <div class="container main_btm" style="padding-left: 0px;padding-right: 0px; ">

  <div class="row top" style="margin-left: 0px;margin-right: 0px;margin-top:22px;">

  <div class="col-md-5 col-sm-6 hidden-xs" class-align="right" style="margin-top: 10px;padding:left:23px; ">

  </div>
  <div class="col-md-3 col-sm-6 col-xs-12 mobile-property-list" style="margin-top: 10px; padding-left: 27px;"><h4 style="color:#fff;font-size:20px;"> Select Your Plan</h4></br>  </div>
  <div class="col-md-4 col-sm-0 hidden-xs"></div>

  </div>

  <div class="row mobile-filter"  style="margin-top: 5px; margin-left: 0px;margin-right: 0px;margin-bottom:5%;" >

  <div class="col-md-1"></div>
  <div class="col-md-10 top-a rentListing" style="padding-left:0px;">

  <section id="pricing-table">
                <div class="row pricelistNew">
                    <div class="pricing">

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Easy Plan </p>
         <input type="hidden" value="1 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 1000 <br><span>Including All Tax</span></p>

          <a class="btn btn-custom payNow">Buy Now</a>

                                </div>

                                <div class="pricing-list">
                                    <ul>
           <li>Contacts details up to : <span class='contactDetails'>05</span></li>
            <li>Bonus Contact details up to : <span class="bonusContacts"> 20</span></li>
            <li>Area Master Assistance : <span class='areaMaster'>No </span></li>
            <li>Contact details through sms : <span class='ContactDetailsSMS'>No</span></li>
           </ul>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Cool Plan </p>
         <input type="hidden" value="2 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 2000 <br><span>Including All Tax</span></p>

         <a class="btn btn-custom payNow">Buy Now</a>

                                </div>

                                <div class="pricing-list">
                                    <ul>
           <li>Contacts details up to : <span class='contactDetails'>50</span></li>
            <li>Bonus Contact details up to : <span class="bonusContacts"> 8</span></li>
            <li>Area Master Assistance : <span class='areaMaster'>Yes</span></li>
            <li>Contact details through sms : <span class='ContactDetailsSMS'>Yes</span></li>
           </ul>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Free Plan </p>
         <input type="hidden" value="3 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 0 <br><span>Including All Tax</span></p>

                                    <a class="btn btn-custom payNow" style="">Enroll Now</a>

                                </div>

                                <div class="pricing-list">
                                    <ul>
           <li>Contacts details up to : <span class='contactDetails'>25</span></li>
            <li>Bonus Contact details up to : <span class="bonusContacts"> 2</span></li>
            <li>Area Master Assistance : <span class='areaMaster'>No </span></li>
            <li>Contact details through sms : <span class='ContactDetailsSMS'>Yes</span></li>
           </ul>
                                </div>
                            </div>
                        </div>
                       </div>
                </div>
        </section>

  </div>

  <div class="col-md-1 "></div>
  </div>

  </div>


问:
Need to add @Inject decorator manually in constructor
I set up a new Angular 5 project and it seems @Injectable decorator doesn't work. I have to inject manually with @Inject decorator for each parameter of constructors.
I'm using Angular 5.0.5 with TS 2.4.2.
This is my tsconfig.json:

```<code>{ "compileOnSave": false, "compilerOptions": { "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es5", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2017", "dom" ] } }
</code>```

I lost a lot of time on it and i really don't understand what happens.
Do you have an idea of the problem ?

答:
My guess is that you are maybe trying to inject an interface:

```<code>constructor(someDependency: SomeInterface) { /* ... */ }
</code>```

The @inject decorator will be required.

If you are trying to inject a class:

```<code>constructor(someDependency: SomeClass) { /* ... */ }
</code>```

The @injectable annotation should be enough.

Learn more at Is it possible to inject interface with angular2?

If this is not your problem maybe there is something wrong with your project. Maybe you are importing the "reflect-metadata" module more than once?

Body:
I set up a new Angular 5 project and it seems @Injectable decorator doesn't work. I have to inject manually with @Inject decorator for each parameter of constructors.
I'm using Angular 5.0.5 with TS 2.4.2.
This is my tsconfig.json:

{ "compileOnSave": false, "compilerOptions": { "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es5", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2017", "dom" ] } }

I lost a lot of time on it and i really don't understand what happens.
Do you have an idea of the problem ?

Body:
My guess is that you are maybe trying to inject an interface:

constructor(someDependency: SomeInterface) { /* ... */ }

The @inject decorator will be required.

If you are trying to inject a class:

constructor(someDependency: SomeClass) { /* ... */ }

The @injectable annotation should be enough.

Learn more at Is it possible to inject interface with angular2?

If this is not your problem maybe there is something wrong with your project. Maybe you are importing the "reflect-metadata" module more than once?


问:
Cookie secure flag using javascript
I want inform about how to set cookie secure flag and http flag using javascript. When I open in chrome developer tools with F12 and click "Application->cookies" I see no flag here (in secure and http column), this is my code to set cookie:

```<code>document.cookie = name+'='+value+'; expires='+expires+'; path=/;';
</code>```

I also find this topic, but this not help me: How to set cookie secure flag using javascript

答:
It is impossible to create HttpOnly cookie with JavaScript. **HttpOnly** Cookie means it is not accessible by scripting languages. And therefore it cannot be created by Javascript.

To prevent cross-site scripting (XSS) attacks, HttpOnly cookies are inaccessible to JavaScript's Document.cookie API; they are only sent to the server. For example, cookies that persist server-side sessions don't need to be available to JavaScript, and the HttpOnly flag should be set.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

Title: Cookie secure flag using javascript

Body:
I want inform about how to set cookie secure flag and http flag using javascript. When I open in chrome developer tools with F12 and click "Application->cookies" I see no flag here (in secure and http column), this is my code to set cookie:

document.cookie = name+'='+value+'; expires='+expires+'; path=/;';

I also find this topic, but this not help me: How to set cookie secure flag using javascript