问:
How to set ArrayList with isChecked in CheckBox android
How to set data with checkbox when user clicks submit? I want to get all data within isChecked()

And I try this code which doesn't work.

myadapter

```<code>viewHoder.cx_select_invite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            Log.d("ChatGroupInviteAdap", "onClick position: " + position);
            Log.d("ChatGroupInviteAdap", "onClick getFirstname: " + chatFriendsListModels.get(position).getFirstname());
            id = chatFriendsListModels.get(position).getId();
            ChatGroupInviteFragment.dataMember.add(id);
        }

        if (!isChecked) {
            id = chatFriendsListModels.get(position).getId();
            ChatGroupInviteFragment.dataMember.remove(id);
        }

    }
});
</code>```

myFragment

user clicks submit when user checks finish

```<code>tx_submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.d(TAG, "OnClick: " + ChatGroupInviteFragment.dataMember.size());

        for (int i=0;i<ChatGroupInviteFragment.dataMember.size();i++){
            Log.d(TAG, "OnClick2 : " + ChatGroupInviteFragment.dataMember.get(i));
        }
    }
});
</code>```

I get error when user unChecked

FATAL EXCEPTION: main
                                                                           Process: xxx.xx.x, PID: 20496
                                                                           java.lang.IndexOutOfBoundsException: Invalid index 36, size is 3

```<code>36 is id unChecked

and 3 = size isChecked
</code>```

How to set it?

答:
The problem seems to be that you are using two different List in the for loop.

```<code> for (int i=0;i<ChatGroupInviteFragment.getListFriend.size();i++){
                    Log.d(TAG, "OnClick2 : " + ChatGroupInviteFragment.dataMember.get(i))
 }
</code>```

Here you are iterating the ChatGroupInviteFragment.getListFriend list which size seems to be 36. while you are getting the data from ChatGroupInviteFragment.dataMember whose size seems to be 3 hence ArrayOutOfBoundException.

You should change to :

```<code>for (int i=0;i<ChatGroupInviteFragment.dataMember.size() - 1;i++)
 {
  Log.d(TAG, "OnClick2 : " + ChatGroupInviteFragment.dataMember.get(i))
 }
</code>```

Body:
How to set data with checkbox when user clicks submit? I want to get all data within isChecked()

And I try this code which doesn't work.

myadapter

viewHoder.cx_select_invite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            Log.d("ChatGroupInviteAdap", "onClick position: " + position);
            Log.d("ChatGroupInviteAdap", "onClick getFirstname: " + chatFriendsListModels.get(position).getFirstname());
            id = chatFriendsListModels.get(position).getId();
            ChatGroupInviteFragment.dataMember.add(id);
        }

        if (!isChecked) {
            id = chatFriendsListModels.get(position).getId();
            ChatGroupInviteFragment.dataMember.remove(id);
        }

    }
});

myFragment

user clicks submit when user checks finish

tx_submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.d(TAG, "OnClick: " + ChatGroupInviteFragment.dataMember.size());

        for (int i=0;i<ChatGroupInviteFragment.dataMember.size();i++){
            Log.d(TAG, "OnClick2 : " + ChatGroupInviteFragment.dataMember.get(i));
        }
    }
});

I get error when user unChecked

FATAL EXCEPTION: main
                                                                           Process: xxx.xx.x, PID: 20496
                                                                           java.lang.IndexOutOfBoundsException: Invalid index 36, size is 3

36 is id unChecked

and 3 = size isChecked

How to set it?

Body:
The problem seems to be that you are using two different List in the for loop.

 for (int i=0;i<ChatGroupInviteFragment.getListFriend.size();i++){
                    Log.d(TAG, "OnClick2 : " + ChatGroupInviteFragment.dataMember.get(i))
 }

Here you are iterating the ChatGroupInviteFragment.getListFriend list which size seems to be 36. while you are getting the data from ChatGroupInviteFragment.dataMember whose size seems to be 3 hence ArrayOutOfBoundException.

You should change to :

for (int i=0;i<ChatGroupInviteFragment.dataMember.size() - 1;i++)
 {
  Log.d(TAG, "OnClick2 : " + ChatGroupInviteFragment.dataMember.get(i))
 }


来源: stackexchange

问:
Force deletion of slot in boost::signals2
I have found that boost::signals2 uses sort of a lazy deletion of connected slots, which makes it difficult to use connections as something that manages lifetimes of objects. I am looking for a way to force slots to be deleted directly when disconnected. Any ideas on how to work around the problem by designing my code differently are also appreciated!

This is my scenario: I have a Command class responsible for doing something that takes time asynchronously, looking something like this (simplified):

```<code>class ActualWorker {
public:
    boost::signals2<void ()> OnWorkComplete;
};

class Command : boost::enable_shared_from_this<Command> {
public:
    ...

    void Execute() {
        m_WorkerConnection = m_MyWorker.OnWorkDone.connect(boost::bind(&Command::Handle_OnWorkComplete, shared_from_this());

        // launch asynchronous work here and return
    }

    boost::signals2<void ()> OnComplete;

private:
    void Handle_OnWorkComplete() {
        // get a shared_ptr to ourselves to make sure that we live through
        // this function but don't keep ourselves alive if an exception occurs.
        shared_ptr<Command> me = shared_from_this();

        // Disconnect from the signal, ideally deleting the slot object
        m_WorkerConnection.disconnect();

        OnComplete();

        // the shared_ptr now goes out of scope, ideally deleting this
    }

    ActualWorker m_MyWorker;
    boost::signals2::connection m_WorkerConnection;
};
</code>```

The class is invoked about like this:

```<code>...
boost::shared_ptr<Command> cmd(new Command);
cmd->OnComplete.connect( foo );
cmd->Execute();
// now go do something else, forget all about the cmd variable etcetera.
</code>```

the Command class keeps itself alive by getting a shared_ptr to itself which is bound to the ActualWorker signal using boost::bind.

When the worker completes, the handler in Command is invoked. Now, since I would like the Command object to be destroyed, I disconnect from the signal as can be seen in the code above. The problem is that the actual slot object is not deleted when disconnected, it is only marked as invalid and then deleted at a later time. This in turn appears to depend on the signal to fire again, which it doesn't do in my case, leading to the slot never expiring. The boost::bind object thus never goes out of scope, holding a shared_ptr to my object that will never get deleted.

I can work around this by binding using the this pointer instead of a shared_ptr and then keeping my object alive using a member shared_ptr which I then release in the handler function, but it kind of makes the design feel a bit overcomplicated. Is there a way to force signals2 to delete the slot when disconnecting? Or is there something else I could do to simplify the design?

Any comments are appreciated!

答:
I ended up doing my own (subset) implementation of a signal, the main requirement being that a slot should be destroyed by a call to connection::disconnect().

The implementation goes along the lines of the signal storing all slots in a map from slot implementation pointer to a shared_ptr for a slot implementation instead of a list/vector, thereby giving quick access to individual slots without having to iterate over all slots. A slot implementation is in my case basically a boost::function.

Connections have a weak_ptr to the internal implementation class for the signal and a weak_ptr to the slot implementation type to allow the signal to go out of scope and to use the slot pointer as the key into the signal map as well as an indication on whether the connection is still active (can't use a raw pointer as that could potentially be reused).

When disconnect is called, both of these weak pointers are converted to shared_ptrs and if both of these succeed, the signal implementation is asked to disconnect the slot given by the pointer. This is done by simple erasing it from the map.

The map is protected by a mutex to allow for multithreaded use. To prevent deadlocks, the mutex is not held while calling the slots, however this means that a slot may be disconnected from a different thread just prior to being called by the signal. This is also the case with regular boost::signals2 and in both of these scenarios one needs to be able to handle a callback from a signal even after one has disconnected.

To simplify the code for when the signal is fired, I am forcing all slots to be disconnected during this. This is different from boost::signals2, that does a copy of the list of slots before calling them in order to handle disconnections/connections while firing the signal.

The above works well for my scenario, where the signal of interest is fired very seldom (and in that case only once) but there are a lot of short-lived connections that otherwise use up a lot of memory even when using the trick outlined in the question.

For other scenarios, I've been able to replace the use of a signal with just a boost::function (thus requiring that there can only be a single connection) or just by sticking with the workaround in the question where the listener itself manages its lifetime.

ContentLicense: CC BY-SA 2.5

Body:
I have found that boost::signals2 uses sort of a lazy deletion of connected slots, which makes it difficult to use connections as something that manages lifetimes of objects. I am looking for a way to force slots to be deleted directly when disconnected. Any ideas on how to work around the problem by designing my code differently are also appreciated!

This is my scenario: I have a Command class responsible for doing something that takes time asynchronously, looking something like this (simplified):

class ActualWorker {
public:
    boost::signals2<void ()> OnWorkComplete;
};

class Command : boost::enable_shared_from_this<Command> {
public:
    ...

    void Execute() {
        m_WorkerConnection = m_MyWorker.OnWorkDone.connect(boost::bind(&Command::Handle_OnWorkComplete, shared_from_this());

        // launch asynchronous work here and return
    }

    boost::signals2<void ()> OnComplete;

private:
    void Handle_OnWorkComplete() {
        // get a shared_ptr to ourselves to make sure that we live through
        // this function but don't keep ourselves alive if an exception occurs.
        shared_ptr<Command> me = shared_from_this();

        // Disconnect from the signal, ideally deleting the slot object
        m_WorkerConnection.disconnect();

        OnComplete();

        // the shared_ptr now goes out of scope, ideally deleting this
    }

    ActualWorker m_MyWorker;
    boost::signals2::connection m_WorkerConnection;
};

The class is invoked about like this:

...
boost::shared_ptr<Command> cmd(new Command);
cmd->OnComplete.connect( foo );
cmd->Execute();
// now go do something else, forget all about the cmd variable etcetera.

the Command class keeps itself alive by getting a shared_ptr to itself which is bound to the ActualWorker signal using boost::bind.

When the worker completes, the handler in Command is invoked. Now, since I would like the Command object to be destroyed, I disconnect from the signal as can be seen in the code above. The problem is that the actual slot object is not deleted when disconnected, it is only marked as invalid and then deleted at a later time. This in turn appears to depend on the signal to fire again, which it doesn't do in my case, leading to the slot never expiring. The boost::bind object thus never goes out of scope, holding a shared_ptr to my object that will never get deleted.

I can work around this by binding using the this pointer instead of a shared_ptr and then keeping my object alive using a member shared_ptr which I then release in the handler function, but it kind of makes the design feel a bit overcomplicated. Is there a way to force signals2 to delete the slot when disconnecting? Or is there something else I could do to simplify the design?

Any comments are appreciated!


问:
What regular expression would match the first email + 1st comma/nothing [PHP]?
I have the following examples:

```<code>$ex1 = '123456@gmail.com,abc@yahoo.com';
$ex2 = '123456@gmail.com';
$result = preg_replace('/123456@gmail.com/','',$ex1); //$ex1 or $ex1
</code>```

The $result would be empty for $ex2, which is good. However, it doesnt remove comma when $ex1 is used (for $ex1, the $result should be 'abc@yahoo.com'). Please help. Basically, it should also match comma if there is comma after the string '123456@gmail.com'.

答:
Use this one it should work</p>

```<code>$result = preg_replace('/(123456@gmail.com)?[ ,]+/','',$ex1);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following examples:

$ex1 = '123456@gmail.com,abc@yahoo.com';
$ex2 = '123456@gmail.com';
$result = preg_replace('/123456@gmail.com/','',$ex1); //$ex1 or $ex1

The $result would be empty for $ex2, which is good. However, it doesnt remove comma when $ex1 is used (for $ex1, the $result should be 'abc@yahoo.com'). Please help. Basically, it should also match comma if there is comma after the string '123456@gmail.com'.

Body:
Use this one it should work

$result = preg_replace('/(123456@gmail.com)?[ ,]+/','',$ex1);


问:
What does Java byte code look like?
On the Wikipedia page http://en.wikipedia.org/wiki/Java_bytecode#Instructions it says Java byte code looks like this:

```<code>0:   iconst_2
1:   istore_1
2:   iload_1
3:   sipush  1000
6:   if_icmpge       44
9:   iconst_2
10:  istore_2
11:  iload_2
12:  iload_1
13:  if_icmpge       31
</code>```

I thought that Java byte code was executed like a series of integers in hexadecimal or binary?

答: Java is compiled from .java files to .class files. The .class files consist of a bunch of bytecodes. Bytecode is to Java what assembler is to C++. Each bytecode is a number no larger than a byte and has a mnemonic. The numbers and their mnemonic are what you have listed in your question.

Title: What does Java byte code look like?

Body:
On the Wikipedia page http://en.wikipedia.org/wiki/Java_bytecode#Instructions it says Java byte code looks like this:

0:   iconst_2
1:   istore_1
2:   iload_1
3:   sipush  1000
6:   if_icmpge       44
9:   iconst_2
10:  istore_2
11:  iload_2
12:  iload_1
13:  if_icmpge       31

I thought that Java byte code was executed like a series of integers in hexadecimal or binary?


问:
How can I merge two LINQ queries into one query?
I have the following SQL query:

```<code>select
    [Event2].EventType AS 'Event type',
    SUM (1)            AS 'Number of events',
    AVG(DATEDIFF(Second, [Event1].CreationDate, [Event2].CreationDate)) AS 'Time'
from [Event] as [Event1]
join [Event] as [Event2] on [Event1].Id = [Event2].ParentId
group by [Event2].EventTypeId;
</code>```

for which I found two LINQ queries.

```<code>// This query brings the event types and the differences between the events.
var rows = from event1 in _eventRepository.AsQueryable()
           join event2 in _eventRepository.AsQueryable() on event1.Id equals event2.ParentId
           select new
           {
               EventId = event2.EventId,
               TimeInSeconds = DbFunctions.DiffSeconds(event1.CreationDate, event2.CreationDate)
           };

// This query groups the rows before by Event type.
var groups = (from item in rows
              group item by item.EventTypeId into g
              select new EventModel
              {
                  EventTypeId = g.Key,
                  NumberOfEvents = g.Sum(x => 1),
                  Time = (int) g.Average(x => x.TimeInSeconds)
              }).ToList();
</code>```

I have to merge this queries into a single one.
The result must contain three elements: Event Type, The number of events, The Average of the time elapsed between the creation date of first event and the creation date of the second event.

答:
You should just add the grouping statement to the first query (instead of the select):

```<code>var result = (from event1 in _eventRepository
              join event2 in _eventRepository on event1.Id equals event2.ParentId

              group new {
                EventId =  event2.EventId,
                TimeInSeconds = DbFunctions.DiffSeconds(event1.CreationDate, event2.CreationDate)
              }
              by event2.EventTypeId into g

              select new EventModel {
                EventTypeId = g.Key,
                NumberOfEvents = g.Count(),
                Time = (int) g.Average(x => x.TimeInSeconds)
              }).ToList();
</code>```

You can also not specify the fields in the grouping but just in the select statement but left it as that is the original

Body:
I have the following SQL query:

select
    [Event2].EventType AS 'Event type',
    SUM (1)            AS 'Number of events',
    AVG(DATEDIFF(Second, [Event1].CreationDate, [Event2].CreationDate)) AS 'Time'
from [Event] as [Event1]
join [Event] as [Event2] on [Event1].Id = [Event2].ParentId
group by [Event2].EventTypeId;

for which I found two LINQ queries.

// This query brings the event types and the differences between the events.
var rows = from event1 in _eventRepository.AsQueryable()
           join event2 in _eventRepository.AsQueryable() on event1.Id equals event2.ParentId
           select new
           {
               EventId = event2.EventId,
               TimeInSeconds = DbFunctions.DiffSeconds(event1.CreationDate, event2.CreationDate)
           };

// This query groups the rows before by Event type.
var groups = (from item in rows
              group item by item.EventTypeId into g
              select new EventModel
              {
                  EventTypeId = g.Key,
                  NumberOfEvents = g.Sum(x => 1),
                  Time = (int) g.Average(x => x.TimeInSeconds)
              }).ToList();

I have to merge this queries into a single one.
The result must contain three elements: Event Type, The number of events, The Average of the time elapsed between the creation date of first event and the creation date of the second event.

Body:
You should just add the grouping statement to the first query (instead of the select):

var result = (from event1 in _eventRepository
              join event2 in _eventRepository on event1.Id equals event2.ParentId

              group new {
                EventId =  event2.EventId,
                TimeInSeconds = DbFunctions.DiffSeconds(event1.CreationDate, event2.CreationDate)
              }
              by event2.EventTypeId into g

              select new EventModel {
                EventTypeId = g.Key,
                NumberOfEvents = g.Count(),
                Time = (int) g.Average(x => x.TimeInSeconds)
              }).ToList();

You can also not specify the fields in the grouping but just in the select statement but left it as that is the original


问:
Gradle Jacoco and JUnit5
We just ported our unit tests to JUnit5. Realizing that this is still rather early adoption with little hints on google.

The most challenging was to get jacoco code coverage for the Junit5 tests which we use on jenkins. Since this took me almost a day to figure out, I thought I share. Nevertheless, if you know of a better solution I would be interested to know!

buildscript {

    dependencies {
       // dependency needed to run junit 5 tests
       classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.0-M2'
   }
}

// include the jacoco plugin
plugins {
    id 'jacoco'
}

dependencies {
    testCompile "org.junit.jupiter:junit-jupiter-api:5.0.0-M2"
    runtime "org.junit.jupiter:junit-jupiter-engine:5.0.0-M2"
    runtime "org.junit.vintage:junit-vintage-engine:4.12.0-M2"
}

apply plugin: 'org.junit.platform.gradle.plugin'
```

<p>Then the problem seems to be that junitPlatformTest as defined in the org.junit.platform.gradle.plugin is defined too
late in the gradle lifecycle phase and hence is unknown when the script is parsed.</p>

<p>The following hack is needed in order to still be able to define a jacoco task which observes the junitPlatformTest task.</p>

<pre class="lang-groovy prettyprint-override"><code>tasks.whenTaskAdded { task ->
    if (task.name.equals('junitPlatformTest')) {
        System.out.println("ADDING TASK " + task.getName() + " to the project!")

    // configure jacoco to analyze the junitPlatformTest task
    jacoco {
        // this tool version is compatible with
        toolVersion = "0.7.6.201602180812"
        applyTo task
    }

    // create junit platform jacoco task
    project.task(type: JacocoReport, "junitPlatformJacocoReport",
            {
                sourceDirectories = files("./src/main")
                classDirectories = files("$buildDir/classes/main")
                executionData task
            })
    }
}
</code>```

Finally it is necessary to configure the junitPlatform plugin. The following code allows command line configuration of which junit 5 tags shall be run:
You can run all tests with 'unit' tag by running:

gradle clean junitPlatformTest -PincludeTags=unit
```

<p>You can run all tests which are missing both unit and integ tag using</p>

<pre class="lang-groovy prettyprint-override"><code>gradle clean junitPlatformTest -PexcludeTags=unit,integ
</code>```

If no tags are provided all tests will be run (default).

junitPlatform {

    engines {
        include 'junit-jupiter'
        include 'junit-vintage'
    }

    reportsDir = file("$buildDir/test-results")

    tags {
        if (project.hasProperty('includeTags')) {
            for (String t : includeTags.split(',')) {
                include t
            }
        }

        if (project.hasProperty('excludeTags')) {
            for (String t : excludeTags.split(',')) {
                exclude t
            }
        }
    }

    enableStandardTestTask false
}
```

答:
Can be also resolved with direct agent injection:

```<code>subprojects {
   apply plugin: 'jacoco'

   jacoco {
        toolVersion = "0.7.9"
   }

   configurations {
        testAgent {
            transitive = false
        }
   }

   dependencies {
        testAgent("org.jacoco:org.jacoco.agent:0.7.9:runtime")
   }

   tasks.withType(JavaExec) {
        if (it.name == 'junitPlatformTest') {
            doFirst {
                jvmArgs "-javaagent:${configurations.testAgent.singleFile}=destfile=${project.buildDir.name}/jacoco/test.exec"
            }
        }
    }
}
</code>```

then report will be available with jacocoTestReport task

Title: Gradle Jacoco and JUnit5

Body:
We just ported our unit tests to JUnit5. Realizing that this is still rather early adoption with little hints on google.

The most challenging was to get jacoco code coverage for the Junit5 tests which we use on jenkins. Since this took me almost a day to figure out, I thought I share. Nevertheless, if you know of a better solution I would be interested to know!

buildscript {

    dependencies {
       // dependency needed to run junit 5 tests
       classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.0-M2'
   }
}

// include the jacoco plugin
plugins {
    id 'jacoco'
}

dependencies {
    testCompile "org.junit.jupiter:junit-jupiter-api:5.0.0-M2"
    runtime "org.junit.jupiter:junit-jupiter-engine:5.0.0-M2"
    runtime "org.junit.vintage:junit-vintage-engine:4.12.0-M2"
}

apply plugin: 'org.junit.platform.gradle.plugin'

Then the problem seems to be that junitPlatformTest as defined in the org.junit.platform.gradle.plugin is defined too
late in the gradle lifecycle phase and hence is unknown when the script is parsed.

The following hack is needed in order to still be able to define a jacoco task which observes the junitPlatformTest task.

tasks.whenTaskAdded { task ->
    if (task.name.equals('junitPlatformTest')) {
        System.out.println("ADDING TASK " + task.getName() + " to the project!")

    // configure jacoco to analyze the junitPlatformTest task
    jacoco {
        // this tool version is compatible with
        toolVersion = "0.7.6.201602180812"
        applyTo task
    }

    // create junit platform jacoco task
    project.task(type: JacocoReport, "junitPlatformJacocoReport",
            {
                sourceDirectories = files("./src/main")
                classDirectories = files("$buildDir/classes/main")
                executionData task
            })
    }
}

Finally it is necessary to configure the junitPlatform plugin. The following code allows command line configuration of which junit 5 tags shall be run:
You can run all tests with 'unit' tag by running:

gradle clean junitPlatformTest -PincludeTags=unit

You can run all tests which are missing both unit and integ tag using

gradle clean junitPlatformTest -PexcludeTags=unit,integ

If no tags are provided all tests will be run (default).

junitPlatform {

    engines {
        include 'junit-jupiter'
        include 'junit-vintage'
    }

    reportsDir = file("$buildDir/test-results")

    tags {
        if (project.hasProperty('includeTags')) {
            for (String t : includeTags.split(',')) {
                include t
            }
        }

        if (project.hasProperty('excludeTags')) {
            for (String t : excludeTags.split(',')) {
                exclude t
            }
        }
    }

    enableStandardTestTask false
}

Body:
Can be also resolved with direct agent injection:

subprojects {
   apply plugin: 'jacoco'

   jacoco {
        toolVersion = "0.7.9"
   }

   configurations {
        testAgent {
            transitive = false
        }
   }

   dependencies {
        testAgent("org.jacoco:org.jacoco.agent:0.7.9:runtime")
   }

   tasks.withType(JavaExec) {
        if (it.name == 'junitPlatformTest') {
            doFirst {
                jvmArgs "-javaagent:${configurations.testAgent.singleFile}=destfile=${project.buildDir.name}/jacoco/test.exec"
            }
        }
    }
}

then report will be available with jacocoTestReport task


问:
List files but exclude certain directories in Unix
I am attempting to list files in a folder with sub folders recursively, but trying to avoid going into one folder as they are duplicates.

This is the command I run but it doesn't do anything.

```<code>ls -lR /opt/elk/data/syslogs | grep -v .log. | grep --exclude-dir="cam" * > /tmp/logs.log
</code>```

If there any changes I can make to this?

Thanks.

答:
Options to different versions of find vary greatly, but you may try:

```<code>find /opt/elk/data/syslogs -name cam -prune -o -print
</code>```

On RHEL, you probably have gnu find, and if you want file size and modification time, you might try:

```<code>find /opt/elk/data/syslogs -name cam -prune -o -printf "%p %s %t\n"
</code>```

Body:
I am attempting to list files in a folder with sub folders recursively, but trying to avoid going into one folder as they are duplicates.

This is the command I run but it doesn't do anything.

ls -lR /opt/elk/data/syslogs | grep -v .log. | grep --exclude-dir="cam" * > /tmp/logs.log

If there any changes I can make to this?

Thanks.

Body:
Options to different versions of find vary greatly, but you may try:

find /opt/elk/data/syslogs -name cam -prune -o -print

On RHEL, you probably have gnu find, and if you want file size and modification time, you might try:

find /opt/elk/data/syslogs -name cam -prune -o -printf "%p %s %t\n"


问:
multiple MySQL rows into one field
I tried a solution in a similar question here at stackoverflow, but with no success.
Here is mysql query:

```<code>$sql= "SET group_concat_max_len = 2048";
$sql = "select p.id,p.name,p.logo,p.short_description,  GROUP_CONCAT(c.category_name SEPARATOR ', ')  from eshop p, eshop_cat c  GROUP BY p.id";
</code>```

I can't understand what is wrong with the query, but the c.category is resulting empty. If i do this without group concat and use inner join i receive all the data right. But i have multiple rows for the same product for each category of every product. (ex if a product have 3 categories, then it shows the product 3 times.) I just want to have 1 row for every product and the categories together separated by comma
Can you help me please

答:
Try like this

```<code>$sql= "SET group_concat_max_len = 2048";
$sql = "select p.id,p.name,p.logo,p.short_description,  GROUP_CONCAT(c.category_name SEPARATOR ', ') as category_names   from eshop p join  eshop_cat c on
p.id=c.id GROUP BY p.id";
</code>```

Just place your relational column  p.id=c.id then it will work for you.

Title: multiple MySQL rows into one field

Body:
I tried a solution in a similar question here at stackoverflow, but with no success.
Here is mysql query:

$sql= "SET group_concat_max_len = 2048";
$sql = "select p.id,p.name,p.logo,p.short_description,  GROUP_CONCAT(c.category_name SEPARATOR ', ')  from eshop p, eshop_cat c  GROUP BY p.id";

I can't understand what is wrong with the query, but the c.category is resulting empty. If i do this without group concat and use inner join i receive all the data right. But i have multiple rows for the same product for each category of every product. (ex if a product have 3 categories, then it shows the product 3 times.) I just want to have 1 row for every product and the categories together separated by comma
Can you help me please

Body:
Try like this

$sql= "SET group_concat_max_len = 2048";
$sql = "select p.id,p.name,p.logo,p.short_description,  GROUP_CONCAT(c.category_name SEPARATOR ', ') as category_names   from eshop p join  eshop_cat c on
p.id=c.id GROUP BY p.id";

Just place your relational column  p.id=c.id then it will work for you.


问:
Object to database with PDO, is it possible?
I'm using PDO's fetch_class feature to retrieve data from my database row into object, It's pretty convenient, but how can I do to do the opposite (object to database row) ? without using serialization of course.</p>

答:
without using an ORM, you have to create your own save method.

Bye.


问:
Angular 2 form Data and JSON data post in same request
I am doing a file upload operation using Angular 2 and HTML file upload control.
My code for uploading the file is as follows -

```<code>saveDocument(value: any) {
        let apiEndPoint: any = 'http://localhost:58736/LandingPage/addUpdateDocument';
        let fi = this.FileInput.nativeElement;
        if (fi.files && fi.files[0]) {
            let fileToUpload = fi.files[0];
            let formData: FormData = new FormData();
            formData.append('newDocument', fileToUpload, value);
            let headers = new Headers();
            headers.append('Accept', 'application/json');
            let options = new RequestOptions({ headers: headers });
            this._http.post(`${apiEndPoint}`, formData , options).map(res => res.json()).catch(error => Observable.throw(error)).subscribe(
                data => console.log('success'),
                error => console.log(error))
        }
    }
</code>```

I have a ASP.Net MVC server side method as follows --

```<code>[System.Web.Http.HttpPost]
        public string addUpdateDocument(HttpPostedFileBase newDocument)
        {
            string responseMessage = string.Empty;
            try
            {
                if (newDocument.ContentLength > 0)
                {
                    string _FileName = Path.GetFileName(newDocument.FileName);
                    string _path = Path.Combine(Server.MapPath("~/upload"), _FileName);
                    newDocument.SaveAs(_path);
                }
                responseMessage = "Upload Successfull !!";
            }
            catch(Exception ex)
            {
                responseMessage = "Upload Successfull !!";
            }

            return responseMessage;
        }

    }
</code>```

This is working fine as long as I am uploading only the file. But I want to send some more information apart from the File. I tried to implement the function as follows --

```<code>this._http.post(`${apiEndPoint}`,{'newDocument':formData,'documentMetaData':value} , options).map(res => res.json()).catch(error => Observable.throw(error)).subscribe(
                data => console.log('success'),
                error => console.log(error))
</code>```

and then I modified the server side method as follows -

```<code>[System.Web.Http.HttpPost]
public string addUpdateDocument(HttpPostedFileBase newDocument, BlankFormsModels documentMetaData)
</code>```

Where BlankFormsModels is just a class. When I do this, the the Meta data is received in the server side but the file is not received. It comes as null. Please suggest how can POST form data and JSON data in the same request.

答:
You can send data like this:

```<code>var obj = {
   formData : formData,
   otherInfo : otherInfo
}
</code>```

And on server side, while uploading file, use the key formData of obj instead of entire object. And after that post another data.
Use promises for proper Sync.

Body:
I am doing a file upload operation using Angular 2 and HTML file upload control.
My code for uploading the file is as follows -

saveDocument(value: any) {
        let apiEndPoint: any = 'http://localhost:58736/LandingPage/addUpdateDocument';
        let fi = this.FileInput.nativeElement;
        if (fi.files && fi.files[0]) {
            let fileToUpload = fi.files[0];
            let formData: FormData = new FormData();
            formData.append('newDocument', fileToUpload, value);
            let headers = new Headers();
            headers.append('Accept', 'application/json');
            let options = new RequestOptions({ headers: headers });
            this._http.post(`${apiEndPoint}`, formData , options).map(res => res.json()).catch(error => Observable.throw(error)).subscribe(
                data => console.log('success'),
                error => console.log(error))
        }
    }

I have a ASP.Net MVC server side method as follows --

[System.Web.Http.HttpPost]
        public string addUpdateDocument(HttpPostedFileBase newDocument)
        {
            string responseMessage = string.Empty;
            try
            {
                if (newDocument.ContentLength > 0)
                {
                    string _FileName = Path.GetFileName(newDocument.FileName);
                    string _path = Path.Combine(Server.MapPath("~/upload"), _FileName);
                    newDocument.SaveAs(_path);
                }
                responseMessage = "Upload Successfull !!";
            }
            catch(Exception ex)
            {
                responseMessage = "Upload Successfull !!";
            }

            return responseMessage;
        }

    }

This is working fine as long as I am uploading only the file. But I want to send some more information apart from the File. I tried to implement the function as follows --

this._http.post(`${apiEndPoint}`,{'newDocument':formData,'documentMetaData':value} , options).map(res => res.json()).catch(error => Observable.throw(error)).subscribe(
                data => console.log('success'),
                error => console.log(error))

and then I modified the server side method as follows -

[System.Web.Http.HttpPost]
public string addUpdateDocument(HttpPostedFileBase newDocument, BlankFormsModels documentMetaData)

Where BlankFormsModels is just a class. When I do this, the the Meta data is received in the server side but the file is not received. It comes as null. Please suggest how can POST form data and JSON data in the same request.

Body:
You can send data like this:

var obj = {
   formData : formData,
   otherInfo : otherInfo
}

And on server side, while uploading file, use the key formData of obj instead of entire object. And after that post another data.
Use promises for proper Sync.


问:
i have a Vue JS template how to create toggle animation?
How to create transition animation on change class fa-toggle-off with fa-toggle-on

i have this code

Vue.component('ios-button', {
    template: '#iosButton',
    data:function(){
      return {
        toggled:true,
        label:'',
      }
    },
    methods:{
      change:function(){
        this.toggled=!this.toggled;
        this.$emit('change');
      }
    }
  });
new Vue({
  el:"#square",
  data:{
    show:true,
  },
  methods:{
    checkIfCheched:function(){
      this.show=!this.show;
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.square{
  width:100px;
  height:100px;
  margin:0 auto;
  background-color:red;
}
#square{
  height:110px;

}
#square span{
  font-size:25px;
  cursor:pointer;
  transition: all 0.9s ease;
}</code>```

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <ios-button v-on:change='checkIfCheched'></ios-button>

<template id="iosButton">
     {{label}}
</template>```

jsfiddle my example

答:
Your toggle contains of two font icons, so it's not possible to animate part of font icon.

It's like to animate letter "A" to "V" - just flip letter vertically and remove middle line of "A". (Not possible)

```<code>Here is example of correct implementation of animated toggle button.
</code>```

fiddle example

Body:
How to create transition animation on change class fa-toggle-off with fa-toggle-on

i have this code

Vue.component('ios-button', {
    template: '#iosButton',
    data:function(){
      return {
        toggled:true,
        label:'',
      }
    },
    methods:{
      change:function(){
        this.toggled=!this.toggled;
        this.$emit('change');
      }
    }
  });
new Vue({
  el:"#square",
  data:{
    show:true,
  },
  methods:{
    checkIfCheched:function(){
      this.show=!this.show;
    }
  }
});

.square{
  width:100px;
  height:100px;
  margin:0 auto;
  background-color:red;
}
#square{
  height:110px;

}
#square span{
  font-size:25px;
  cursor:pointer;
  transition: all 0.9s ease;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <ios-button v-on:change='checkIfCheched'></ios-button>

<template id="iosButton">
     {{label}}
</template>

jsfiddle my example

Body:
Your toggle contains of two font icons, so it's not possible to animate part of font icon.

It's like to animate letter "A" to "V" - just flip letter vertically and remove middle line of "A". (Not possible)

Here is example of correct implementation of animated toggle button.

fiddle example


问:
Conflict window.size and some jquery
I have a problem I cant figure out. So hope someone can help me.

I have this code in the footer of an iframe:

```<code><script type="text/javascript" src="https://sinsio.dk/iframe-resizer-master/js/iframeResizer.contentWindow.min.js" defer></script>
<script>
jQuery( ".sidebar a" ).click(function() {
window.parentIFrame.size(1250);
jQuery('.content').css('display', 'none');
});
</script>
</code>```

I want to resize an iframe and hide some content when clicking a link in the sidebar.

Scenario 1 (working):
If I only have window.parentIFrame.size(1250) in the click function it resizes the iframe.

Scenario 2 (working):
If i add alert(jQuery(this).attr('class')); to the function it resizes and alert the class from the clicked element. Did this to test if jQuery worked - it did.

Scenario 3 (not working but needed):
If I instead of the alert add jQuery('.content').css('display', 'none'); it removes the content div as i want but the resize no longer works.

Any ideas what is wrong? Doesn't make sense to me.

Kind regards,
Michael

答:
I had a conflict with a height attribute on the body element of the iframe. Removing this was the solution.

Thanks for taking the time to look at my post.

Kind regards,
Michael

Title: Conflict window.size and some jquery

Body:
I have a problem I cant figure out. So hope someone can help me.

I have this code in the footer of an iframe:

I want to resize an iframe and hide some content when clicking a link in the sidebar.

Scenario 1 (working):
If I only have window.parentIFrame.size(1250) in the click function it resizes the iframe.

Scenario 2 (working):
If i add alert(jQuery(this).attr('class')); to the function it resizes and alert the class from the clicked element. Did this to test if jQuery worked - it did.

Scenario 3 (not working but needed):
If I instead of the alert add jQuery('.content').css('display', 'none'); it removes the content div as i want but the resize no longer works.

Any ideas what is wrong? Doesn't make sense to me.

Kind regards,
Michael


问:
Qtip Ajax Request not working on first hover
I want to show ajax loaded content when mouse hovers over element, I'm using qTip to achieve this, however it works only when I hover for the second time. </p>

```<code>$(document).on('mouseenter', 'span', function(){
if(!$(this).data('qtip')){
    $.ajax({
        context : this,
        url     : '/',
        success : function(html) {
            $(this).qtip({
                content: "..now it works.",
                position: {
                    my: 'top left',
                    target: 'mouse',
                    //viewport: $(window), // Keep it on-screen at all times if possible
                    adjust: {
                        x: 10,  y: 10
                    }
                },
            });
        },
        error   : function(err){
            console.log(err.reponseText);
        }
    });
}
</code>```

<p>});
Here is my fiddle.</p>

答:
First - The easiest soultion here will be to use the qtip Ajax plugin - So you won't need to deal with it.

However, just to explain what went wrong with your code -
The problem is that you are initializing qtip only on the first mouse hover on the element.

So, you need to split your code into 2:

qtip Init: (Note that content must hold at least one character)

```<code>$('span').qtip({
  content: " ",
  position: {
    my: 'top left',
    target: 'mouse',
    //viewport: $(window), // Keep it on-screen at all times if possible
    adjust: {
      x: 10,  y: 10
    }
  },
});
</code>```

The actual mouseenter event, which changes the qtip 'content' using qtip API (http://qtip2.com/api)

```<code>$(document).on('mouseenter', 'span', function(){
        $.ajax({
        context : this,
        url     : '/',
        success : function(html) {
            $(this).qtip('option', 'content.text', 'response');
        },
        error   : function(err){
            console.log(err.reponseText);
        }
    });
});
</code>```

Body:
I want to show ajax loaded content when mouse hovers over element, I'm using qTip to achieve this, however it works only when I hover for the second time.

$(document).on('mouseenter', 'span', function(){
if(!$(this).data('qtip')){
    $.ajax({
        context : this,
        url     : '/',
        success : function(html) {
            $(this).qtip({
                content: "..now it works.",
                position: {
                    my: 'top left',
                    target: 'mouse',
                    //viewport: $(window), // Keep it on-screen at all times if possible
                    adjust: {
                        x: 10,  y: 10
                    }
                },
            });
        },
        error   : function(err){
            console.log(err.reponseText);
        }
    });
}

});
Here is my fiddle.

Body:
First - The easiest soultion here will be to use the qtip Ajax plugin - So you won't need to deal with it.

However, just to explain what went wrong with your code -
The problem is that you are initializing qtip only on the first mouse hover on the element.

So, you need to split your code into 2:

qtip Init: (Note that content must hold at least one character)

$('span').qtip({
  content: " ",
  position: {
    my: 'top left',
    target: 'mouse',
    //viewport: $(window), // Keep it on-screen at all times if possible
    adjust: {
      x: 10,  y: 10
    }
  },
});

The actual mouseenter event, which changes the qtip 'content' using qtip API (http://qtip2.com/api)

$(document).on('mouseenter', 'span', function(){
        $.ajax({
        context : this,
        url     : '/',
        success : function(html) {
            $(this).qtip('option', 'content.text', 'response');
        },
        error   : function(err){
            console.log(err.reponseText);
        }
    });
});


问:
Why does Rails use plurals for new and create?
I understand why a Rails index method would use the plural form of a resource - we're showing all projects, for example.

And I understand why the show method would use the singular form - we only want to see one project, with a particular ID.

But I don't understand why new and create would use the plural. Is there a way to create more than one project at a time? Is there some other reasoning for using the plural here that someone could explain?

答:
New and Create aren't plural, in the way I think about REST. Instead, I think about it like:

whatever.com is your base domain, and whatever.com/books means that you have a collection of resources each named book. The collection itself is named books.

So, when you want to create a new book, you are asking the collection for the information needed to create a new book. This becomes /books/new

When you actually create the book, you are posting information to /books. The HTTP verb is POST, so when you POST to your collection, you execute the create action.

This looks like a good starting point on REST.


问:
Choosing specific python interpreter in the shell
I've been developing a set of scripts in PyCharm using C:/Python27/python.exe interpreter...

I'm creating a batch file and then running all of the scripts through this file from the cmd shell however the shell is not recognizing most modules because it is using the wrong interpreter (path for anaconda instead)...

How do I change the shell to use the C:/Python27/python.exe interpreter as default all the time instead?

I've tried looking this up but it all points to just adding the interpreter path, which I have... but the shell still uses the anaconda interpreter.

Any help appreicated

答:
Take a look at : https://docs.python.org/3.3/using/windows.html#shebang-lines

Shebang lines at the beginning of scripts tells how a script should be executed.


问:
Angular 2 and Bootstrap 3. Different integration approaches
I'm trying to integrate Bootstrap 3 into my Angular 2 project.
I have two choices:

Use npm install bootstrap --save command and install Bootstrap 3
to my project.

Install angular bootstrap using npm install ngx-bootstrap --save,
which is based on Angular and there won't be any jquery dependancies.

What is the main difference between these two approaches. Which one is better for single page applications?

答:
In short both are good however

Having Angular and Bootstrap in a single project is very common and both serve different purpose. At the end of the day think about including js and css to help html and if you can manage these dependencies then that is cream on top. You can manage through npm, webpack or on your own.

Others can only tell you not to mix these things so you dont have to run npm install, gulp update-dependecies and then grunt resolve etc tasks just to make sure your dependency files are loaded. I would say carry on with any and enjoy development rather than worrying about such things.


问:
Java - Read resource with getResourceAsStream(String)
Can someone explain why Java does not find resource if using File.separator in the String for search path in getResourceAsStream(String name)? I have this code:

```<code>private final String RESOURCE_PATH = File.separator + "dir" + File.separator;
private final String SAME_PATH_HARDCODED = "/dir/";

public void findResource(String fileName) {
    InputStream file1 = ThisClass.class
            .getResourceAsStream(RESOURCE_PATH + fileName);  // returns null

    InputStream file2 = ThisClass.class
            .getResourceAsStream(SAME_PATH_HARDCODED + fileName);  // returns file
}
</code>```

I have found out, that File.separator used Backslashes instead of Slashes. But I hoped that File.separator is more flexible. In this case, it isnt. And I want to know, why. Thanks alot.

答:
Because when you pass \\ separator to getResourceAsStream() method it interprets path to your dir in another way, added package name before dir actually.

Class javadoc

Before delegation, an absolute resource name is constructed from the
  given resource name using this algorithm:

```<code>If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:

    modified_package_name/name

Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
</code>```

Your File.separator returns different result for unix and windows machines. If you use mack or unix in this case your code will works but in win machine fails.

File javadoc

public static final char separatorChar

The system-dependent default name-separator character. This field is
  initialized to contain the first character of the value of the system
  property file.separator. On UNIX systems the value of this field is
  '/'; on Microsoft Windows systems it is '\'.

Body:
Can someone explain why Java does not find resource if using File.separator in the String for search path in getResourceAsStream(String name)? I have this code:

private final String RESOURCE_PATH = File.separator + "dir" + File.separator;
private final String SAME_PATH_HARDCODED = "/dir/";

public void findResource(String fileName) {
    InputStream file1 = ThisClass.class
            .getResourceAsStream(RESOURCE_PATH + fileName);  // returns null

    InputStream file2 = ThisClass.class
            .getResourceAsStream(SAME_PATH_HARDCODED + fileName);  // returns file
}

I have found out, that File.separator used Backslashes instead of Slashes. But I hoped that File.separator is more flexible. In this case, it isnt. And I want to know, why. Thanks alot.

Body:
Because when you pass \\ separator to getResourceAsStream() method it interprets path to your dir in another way, added package name before dir actually.

Class javadoc

Before delegation, an absolute resource name is constructed from the
  given resource name using this algorithm:

If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:

    modified_package_name/name

Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

Your File.separator returns different result for unix and windows machines. If you use mack or unix in this case your code will works but in win machine fails.

File javadoc

public static final char separatorChar

The system-dependent default name-separator character. This field is
  initialized to contain the first character of the value of the system
  property file.separator. On UNIX systems the value of this field is
  '/'; on Microsoft Windows systems it is '\'.


问:
Not able to set label text in asp.net master page controls from content page
I am trying to change the text of label in master page which is inside modal and from content page i am trying to set the text.
This is my master page:

```<code><%@ Master Language="C#" AutoEventWireup="true"
CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1 maximum-
    scale=1, user-scalable=no" />
    <link href="../Content/bootstrap.min.css" rel="stylesheet" />
    <link href="../Style/StyleSheet.css" rel="stylesheet" />
    <link href="../Content/font-awesome.min.css" rel="stylesheet" />
    <link href="http://fonts.googleapis.com/css?
    family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet"
    type="text/css" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-footable/0.1.0/css/footable.min.css" rel="stylesheet" type="text/css" />
    <script src="../Scripts/jquery-1.9.1.min.js"></script>
    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
    </asp:ContentPlaceHolder>
</head>
    <body>
    <div id="header">
        <form id="Form1" runat="server">
            <header>
            </header>
            <div class="container-fluid" id="body">
                <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
                </asp:ContentPlaceHolder>
                <div class="modal fade" id="myModal">
                    <div class="modal-dialog">
                        <div class="modal-content" style="width: 400px;margin: 0 auto;">
                            <div class="modal-header" runat="server">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">×</span></button>
                                <h4 class="modal-title"><asp:Label ID="lblMasterMessage" runat="server" Text="Label"></asp:Label> </h4>
                            </div>
                            <div class="modal-body">
                                <asp:Label ID="lblMasterbodyMessage" runat="server" Text="gh" />
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <footer class="panel-footer white">
                <div class="row">
                </div>
            </footer>
        </form>
    </div>
    <script src="../Scripts/bootstrap.min.js"></script>
    </body>
</html>
</code>```

script in child page which opens modal:

```<code><script type="text/javascript">
     function openModal(message) {
          $('#myModal').modal('show');
      }
 </script>
</code>```

code behind child page calling the script and changing text of label in modalpopup

```<code>    ScriptManager.RegisterStartupScript(this, this.GetType(), "LaunchServerSide", "$(function() { openModal(); });", true);
    Label lblMaster = (Label)Master.FindControl("lblMasterbodyMessage");
    string message = "something";
    lblMaster.Text = message;
</code>```

i also tried the second approach by setting properties in master page but text in the popup is not getting updated. any help will be appreciated

答:
Best approach will be to provide a get/set property in your master page that will accept value and assign it to the label value property.

Master Page

```<code>public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public string MasterBodyMessage // you can use some meaningfull name over here.
    {
        get { return this.lblMasterbodyMessage.Text; }
        set { this.lblMasterbodyMessage.Text = value; }
    }
}
</code>```

Child Page

```<code>ScriptManager.RegisterStartupScript(this, this.GetType(), "LaunchServerSide", "$(function() { openModal(); });", true);
var master = this.Master as MasterPage;
if (master != null)
{
    master.MasterBodyMessage = "Some Meaningful Message!!!";
}
</code>```

Else you can do some work around using javascript/jQuery to add message into label in master page. For this you will need to amend following changes.

HTML Aspx Page

```<code><div class="modal-content" style="width: 400px;margin: 0 auto;">
    <div class="modal-header">
        <button aria-label="Close" class="close" data-dismiss="modal" type="button"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title"><label id="lblMasterMessage"></label></h4>
    </div>
    <div class="modal-body">
        <label id="lblMasterbodyMessage"></label>
    </div>
    <div class="modal-footer">
        <button class="btn btn-primary" data-dismiss="modal" type="button">Close</button>
    </div>
</div>
</code>```

Code Behind Page

```<code>string message = "Some Meaningful Message!!!";
ScriptManager.RegisterStartupScript(this, this.GetType(), "LaunchServerSide", "openModal('"+ message +"');", true);
</code>```

jQuery Script

```<code><script type="text/javascript">
     function openModal(message) {
          $('#myModal').modal('show');
         $('#lblMasterbodyMessage').html(message);
      }
 </script>
</code>```

Body:
I am trying to change the text of label in master page which is inside modal and from content page i am trying to set the text.
This is my master page:

<%@ Master Language="C#" AutoEventWireup="true"
CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

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

    <title></title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1 maximum-
    scale=1, user-scalable=no" />
    <link href="../Content/bootstrap.min.css" rel="stylesheet" />
    <link href="../Style/StyleSheet.css" rel="stylesheet" />
    <link href="../Content/font-awesome.min.css" rel="stylesheet" />
    <link href="http://fonts.googleapis.com/css?
    family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet"
    type="text/css" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-footable/0.1.0/css/footable.min.css" rel="stylesheet" type="text/css" />

    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
    </asp:ContentPlaceHolder>

        <form id="Form1" runat="server">

                <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
                </asp:ContentPlaceHolder>

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

<asp:Label ID="lblMasterMessage" runat="server" Text="Label"></asp:Label>

                                <asp:Label ID="lblMasterbodyMessage" runat="server" Text="gh" />

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

        </form>

script in child page which opens modal:

code behind child page calling the script and changing text of label in modalpopup

    ScriptManager.RegisterStartupScript(this, this.GetType(), "LaunchServerSide", "$(function() { openModal(); });", true);
    Label lblMaster = (Label)Master.FindControl("lblMasterbodyMessage");
    string message = "something";
    lblMaster.Text = message;

i also tried the second approach by setting properties in master page but text in the popup is not getting updated. any help will be appreciated

Body:
Best approach will be to provide a get/set property in your master page that will accept value and assign it to the label value property.

Master Page

public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public string MasterBodyMessage // you can use some meaningfull name over here.
    {
        get { return this.lblMasterbodyMessage.Text; }
        set { this.lblMasterbodyMessage.Text = value; }
    }
}

Child Page

ScriptManager.RegisterStartupScript(this, this.GetType(), "LaunchServerSide", "$(function() { openModal(); });", true);
var master = this.Master as MasterPage;
if (master != null)
{
    master.MasterBodyMessage = "Some Meaningful Message!!!";
}

Else you can do some work around using javascript/jQuery to add message into label in master page. For this you will need to amend following changes.

HTML Aspx Page

<div class="modal-content" style="width: 400px;margin: 0 auto;">
    <div class="modal-header">
        <button aria-label="Close" class="close" data-dismiss="modal" type="button"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title"><label id="lblMasterMessage"></label></h4>
    </div>
    <div class="modal-body">
        <label id="lblMasterbodyMessage"></label>
    </div>
    <div class="modal-footer">
        <button class="btn btn-primary" data-dismiss="modal" type="button">Close</button>
    </div>
</div>

Code Behind Page

string message = "Some Meaningful Message!!!";
ScriptManager.RegisterStartupScript(this, this.GetType(), "LaunchServerSide", "openModal('"+ message +"');", true);

jQuery Script

<script type="text/javascript">
     function openModal(message) {
          $('#myModal').modal('show');
         $('#lblMasterbodyMessage').html(message);
      }
 </script>


问:
Stop Setinterval after 1 run
I've made a little script which places a button in an ID 'AddToCartLayer' which is loaded dynamically.

```<code>var myVar;
myVar = setInterval(str, 1000);

function str() {
  var str = '<a href="google.nl" style="font-size:18px;" class="btn btn-secondary btn-lg active" role="button" aria-pressed="true">Google</a>',
    div = document.getElementById( 'addToCartLayer' );

div.insertAdjacentHTML( 'beforeend', str );
}
</code>```

Now, I can't really figure out how I can stop the script from running once the button is placed in the ID.

Could someone please help me with this. Thanks!

答: i think setTimeout() will work.

Title: Stop Setinterval after 1 run

Body:
I've made a little script which places a button in an ID 'AddToCartLayer' which is loaded dynamically.

var myVar;
myVar = setInterval(str, 1000);

function str() {
  var str = 'Google',
    div = document.getElementById( 'addToCartLayer' );

div.insertAdjacentHTML( 'beforeend', str );
}

Now, I can't really figure out how I can stop the script from running once the button is placed in the ID.

Could someone please help me with this. Thanks!

Body: i think setTimeout() will work.


问:
What is the need of JSF, when UI can be achieved with JavaScript libraries such as jQuery and AngularJS
I was reading about JSF that it's a UI framework and provides some UI components. But how is it better or different from number of components that are available from jQueryUI, AngularJS, React, Vue.js, Svelte, ExtJS, or even plain HTML, CSS and JavaScript.

Why should someone learn JSF?

答:
Here are the biggest differences between jQuery & JSF:

no MVC architecture

no state control (store date in session or conversation, auto-clean up, etc.)

no (default) validation library

no templating library

no advanced navigation/routing

client side

jQuery was never intended to be used as a full stack webframework. It was more intended for replacing low-level JS code so that writing JS becomes easier and more powerfull in less lines of code.

And it should thus mostly be used to add behaviour on HTML elements.

ContentLicense: CC BY-SA 4.0


问:
Visual Basic, End of Statement Expected - array?
I've been having issues trying to fix an "End of Statement Expected" BC30205 Error for this program, it is an Interpolation subroutine of the FCC Curves Calculation Program. I'm trying to convert a function in javascript to VB.NET. I've added the code below.

```<code>'------- ITPLBV --------------------------------------------------------------------------------------------------
        'Interpolation subroutine
        'Arguments:
        'lx  Number of columns in table.
        'ly  Number of rows in table.
        'x   Column enumeration values.
        'y   Row enumeration values.
        'z   Data table.
        'n   Number of points to lookup.
        'u   Column values for lookup points.
        'v   Row values for lookup points.
        'w   Return result of lookups.

Private Sub Itplbv(lx As Double, ly As Double, x As Double, y As Double, z As Double, n As Double, u As Double, v As Double, w As Double)
    'declarations and initializations
    Dim lxm1, lxp1, lym1, lyp1, ixpv, iypv, k, ix, iy, imn, imx, jx, jy, jx1, jy1 As Double
    lxm1 = lxp1 = lym1 = lyp1 = ixpv = iypv = k = ix = iy = imn = imx = jx = jy = jx1 = jy1 = 0

    Dim za_row0 = {0, 0}
    Dim za_row1 = {0, 0}
    Dim za_row2 = {0, 0}
    Dim za_row3 = {0, 0}
    Dim za_row4 = {0, 0}
    Dim za = {za_row0, za_row1, za_row2, za_row3, za_row4}   'za[5, 2]

    Dim zb_row0 = {0, 0, 0, 0, 0}
    Dim zb_row1 = {0, 0, 0, 0, 0}
    Dim zb = {zb_row0, zb_row1}                              'zb[2, 5]

    Dim zab_row0 = {0, 0, 0}
    Dim zab_row1 = {0, 0, 0}
    Dim zab_row2 = {0, 0, 0}
    Dim zab = {zab_row0, zab_row1, zab_row2}                  'zab[3, 3]

    Dim zx_row0 = {0, 0, 0, 0}
    Dim zx_row1 = {0, 0, 0, 0}
    Dim zx_row2 = {0, 0, 0, 0}
    Dim zx_row3 = {0, 0, 0, 0}
    Dim zx = {zx_row0, zx_row1, zx_row2, zx_row3}             'zx[4, 4]

    Dim zy_row0 = {0, 0, 0, 0}
    Dim zy_row1 = {0, 0, 0, 0}
    Dim zy_row2 = {0, 0, 0, 0}
    Dim zy_row3 = {0, 0, 0, 0}
    Dim zy = {zy_row0, zy_row1, zy_row2, zy_row3}             'zy[4, 4]

    Dim zxy_row0 = {0, 0, 0, 0}
    Dim zxy_row1 = {0, 0, 0, 0}
    Dim zxy_row2 = {0, 0, 0, 0}
    Dim zxy_row3 = {0, 0, 0, 0}
    Dim zxy = {zxy_row0, zxy_row1, zxy_row2, zxy_row3}         'zxy[4, 4]

    Dim x3, x4, a3, y3, y4, b3, z33, z43, z34, z44, x2, a2, z23, z24, x5, a4, z53, z54 As Double
    x3 = x4 = a3 = y3 = y4 = b3 = z33 = z43 = z34 = z44 = x2 = a2 = z23 = z24 = x5 = a4 = z53 = z54 = 0.0

    Dim a1, a5, y2, b2, z32, z42, y5, b4, z35, z45, b1, b5, w2, w3, sw, wx2, wx3, wy2, wy3, w1, w4, w5 As Double
    a1 = a5 = y2 = b2 = z32 = z42 = y5 = b4 = z35 = z45 = b1 = b5 = w2 = w3 = sw = wx2 = wx3 = wy2 = wy3 = w1 = w4 = w5 = 0.0

    Dim zx3b3, zx4b3, zy3a3, zy4a3, a, b, c, d, e, a3sq, b3sq, p02, p03, p12, p13, p20, p21, p22 As Double
    zx3b3 = zx4b3 = zy3a3 = zy4a3 = a = b = c = d = e = a3sq = b3sq = p02 = p03 = p12 = p13 = p20 = p21 = p22 = 0.0

    Dim p23, p30, p31, p32, p33, dy, q0, q1, q2, q3, dx As Double
    p23 = p30 = p31 = p32 = p33 = dy = q0 = q1 = q2 = q3 = dx = 0.0

    '------------
    'Calculations begin

    lx = Math.Floor(lx)
    ly = Math.Floor(ly)

    lxm1 = Math.Floor(lx - 1)
    lxp1 = Math.Floor(lx + 1)
    lym1 = Math.Floor(ly - 1)
    lyp1 = Math.Floor(ly + 1)
    ixpv = -1
    iypv = -1

    For k = 0 To n Step -1

        If u{k} >= x{lxm1} Then
            ix = lx
        ElseIf u{k} < x{0} Then
            ix = 0
        Else
            imn = 1
            imx = lxm1
            Do
                ix = Math.Floor((imn + imx) / 2)
                If u{k} >= x{ix} Then
                    imn = ix + 1
                Else
                    imx = ix
                End If
            Loop While (imx > imn)
            ix = imx
        End If
        ix = Math.Floor(ix)

    Next k

End Sub
</code>```

The exact position that I'm getting this error is;

```<code> If u{k} >= x{lxm1} Then
                ix = lx
            ElseIf u{k} < x{0} Then
                ix = 0
</code>```

Just in u{k}, as you can see here
I haven't worked in VB since a lot... so... Thanks for the help you can send me and sorry for my english.

答:
You cannot add curly braces near the double datatype. Curly braces are used to initialize an array.

If you want to compare an array:

```<code>Dim IntArray As Integer = {2, 0} 'This array has 2 value, 2 and 0.
'Compare it
If IntArray(1) >= 7 Then 'You can only compare with one value in an array
    Console.WriteLine("It is more than 7!")
End If
</code>```

Note that an array is a zero-based index means that if you want to assign or read the first object of an array, you should do like this: IntArray(0)

Body:
I've been having issues trying to fix an "End of Statement Expected" BC30205 Error for this program, it is an Interpolation subroutine of the FCC Curves Calculation Program. I'm trying to convert a function in javascript to VB.NET. I've added the code below.

'------- ITPLBV --------------------------------------------------------------------------------------------------
        'Interpolation subroutine
        'Arguments:
        'lx  Number of columns in table.
        'ly  Number of rows in table.
        'x   Column enumeration values.
        'y   Row enumeration values.
        'z   Data table.
        'n   Number of points to lookup.
        'u   Column values for lookup points.
        'v   Row values for lookup points.
        'w   Return result of lookups.

Private Sub Itplbv(lx As Double, ly As Double, x As Double, y As Double, z As Double, n As Double, u As Double, v As Double, w As Double)
    'declarations and initializations
    Dim lxm1, lxp1, lym1, lyp1, ixpv, iypv, k, ix, iy, imn, imx, jx, jy, jx1, jy1 As Double
    lxm1 = lxp1 = lym1 = lyp1 = ixpv = iypv = k = ix = iy = imn = imx = jx = jy = jx1 = jy1 = 0

    Dim za_row0 = {0, 0}
    Dim za_row1 = {0, 0}
    Dim za_row2 = {0, 0}
    Dim za_row3 = {0, 0}
    Dim za_row4 = {0, 0}
    Dim za = {za_row0, za_row1, za_row2, za_row3, za_row4}   'za[5, 2]

    Dim zb_row0 = {0, 0, 0, 0, 0}
    Dim zb_row1 = {0, 0, 0, 0, 0}
    Dim zb = {zb_row0, zb_row1}                              'zb[2, 5]

    Dim zab_row0 = {0, 0, 0}
    Dim zab_row1 = {0, 0, 0}
    Dim zab_row2 = {0, 0, 0}
    Dim zab = {zab_row0, zab_row1, zab_row2}                  'zab[3, 3]

    Dim zx_row0 = {0, 0, 0, 0}
    Dim zx_row1 = {0, 0, 0, 0}
    Dim zx_row2 = {0, 0, 0, 0}
    Dim zx_row3 = {0, 0, 0, 0}
    Dim zx = {zx_row0, zx_row1, zx_row2, zx_row3}             'zx[4, 4]

    Dim zy_row0 = {0, 0, 0, 0}
    Dim zy_row1 = {0, 0, 0, 0}
    Dim zy_row2 = {0, 0, 0, 0}
    Dim zy_row3 = {0, 0, 0, 0}
    Dim zy = {zy_row0, zy_row1, zy_row2, zy_row3}             'zy[4, 4]

    Dim zxy_row0 = {0, 0, 0, 0}
    Dim zxy_row1 = {0, 0, 0, 0}
    Dim zxy_row2 = {0, 0, 0, 0}
    Dim zxy_row3 = {0, 0, 0, 0}
    Dim zxy = {zxy_row0, zxy_row1, zxy_row2, zxy_row3}         'zxy[4, 4]

    Dim x3, x4, a3, y3, y4, b3, z33, z43, z34, z44, x2, a2, z23, z24, x5, a4, z53, z54 As Double
    x3 = x4 = a3 = y3 = y4 = b3 = z33 = z43 = z34 = z44 = x2 = a2 = z23 = z24 = x5 = a4 = z53 = z54 = 0.0

    Dim a1, a5, y2, b2, z32, z42, y5, b4, z35, z45, b1, b5, w2, w3, sw, wx2, wx3, wy2, wy3, w1, w4, w5 As Double
    a1 = a5 = y2 = b2 = z32 = z42 = y5 = b4 = z35 = z45 = b1 = b5 = w2 = w3 = sw = wx2 = wx3 = wy2 = wy3 = w1 = w4 = w5 = 0.0

    Dim zx3b3, zx4b3, zy3a3, zy4a3, a, b, c, d, e, a3sq, b3sq, p02, p03, p12, p13, p20, p21, p22 As Double
    zx3b3 = zx4b3 = zy3a3 = zy4a3 = a = b = c = d = e = a3sq = b3sq = p02 = p03 = p12 = p13 = p20 = p21 = p22 = 0.0

    Dim p23, p30, p31, p32, p33, dy, q0, q1, q2, q3, dx As Double
    p23 = p30 = p31 = p32 = p33 = dy = q0 = q1 = q2 = q3 = dx = 0.0

    '------------
    'Calculations begin

    lx = Math.Floor(lx)
    ly = Math.Floor(ly)

    lxm1 = Math.Floor(lx - 1)
    lxp1 = Math.Floor(lx + 1)
    lym1 = Math.Floor(ly - 1)
    lyp1 = Math.Floor(ly + 1)
    ixpv = -1
    iypv = -1

    For k = 0 To n Step -1

        If u{k} >= x{lxm1} Then
            ix = lx
        ElseIf u{k} < x{0} Then
            ix = 0
        Else
            imn = 1
            imx = lxm1
            Do
                ix = Math.Floor((imn + imx) / 2)
                If u{k} >= x{ix} Then
                    imn = ix + 1
                Else
                    imx = ix
                End If
            Loop While (imx > imn)
            ix = imx
        End If
        ix = Math.Floor(ix)

    Next k

End Sub

The exact position that I'm getting this error is;

 If u{k} >= x{lxm1} Then
                ix = lx
            ElseIf u{k} < x{0} Then
                ix = 0

Just in u{k}, as you can see here
I haven't worked in VB since a lot... so... Thanks for the help you can send me and sorry for my english.

Body:
You cannot add curly braces near the double datatype. Curly braces are used to initialize an array.

If you want to compare an array:

Dim IntArray As Integer = {2, 0} 'This array has 2 value, 2 and 0.
'Compare it
If IntArray(1) >= 7 Then 'You can only compare with one value in an array
    Console.WriteLine("It is more than 7!")
End If

Note that an array is a zero-based index means that if you want to assign or read the first object of an array, you should do like this: IntArray(0)


问:
Using bindData method outside of controller
I was wondering if anyone had an idea for the best way to provide the
functionality of bindData() outside of my grails controllers. In my current
project I have created several groovy classes to model objects returned by
an api. In these classes I have a static method that parses xml and returns
a List of objects of the class. I would like to skip all the type casting
nonsense by using the bindData method in these classes. Any suggestions on
how to do this would be appreciated.</p>

答:
I was looking for a similar solution, to use bindData in a service class. I found a solution in JT's blog. The solution is basically to import:

```<code>import org.codehaus.groovy.grails.web.metaclass.BindDynamicMethod
</code>```

then add this to your code:

```<code>def foo = new Foo()
BindDynamicMethod bind = new BindDynamicMethod()
def args =  [ foo, params, [exclude:['name', 'mail']] ] // for example
bind.invoke( foo, 'bind', (Object[])args)
</code>```

The (Object[]) cast is necessary du to Groovy/Java compatability. (Groovy is treating the ‘args’ object as an ArrayList, not an array of Objects.)

Body:
I was looking for a similar solution, to use bindData in a service class. I found a solution in JT's blog. The solution is basically to import:

import org.codehaus.groovy.grails.web.metaclass.BindDynamicMethod

then add this to your code:

def foo = new Foo()
BindDynamicMethod bind = new BindDynamicMethod()
def args =  [ foo, params, [exclude:['name', 'mail']] ] // for example
bind.invoke( foo, 'bind', (Object[])args)

The (Object[]) cast is necessary du to Groovy/Java compatability. (Groovy is treating the ‘args’ object as an ArrayList, not an array of Objects.)


问:
How to parse a TypeScript code base into ASTs
I want to parse TypeScript projects into ASTs.

I can parse single file by :

```<code>import ts = require("typescript");
var fs          = require('fs');
var util      = require('util');

const ast = ts.createSourceFile('sample.ts', fs.readFileSync('sample.ts').toString(), ts.ScriptTarget.ES6, true);

console.log("AST:"+util.inspect(ast));
</code>```

I can even loop through the files and filter files by extension and run above code to generate ASt.

However I want to parse the whole project in such a way that the relationships (like imports) will be preserved in AST.

For example:

If, a.ts is referencing var x from b.ts as below:

a.ts:

```<code>var y = x;
</code>```

b.ts:

```<code>var x = 5;
</code>```

In this case signature of x in a .ts should be resolved as : b.ts.x or equivalent.

I just want all such relationships resolved in the ASts as I parse the .ts files one by one.

答:
You can load your project using

ts.createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program)

rootNames is the list of all typescript files in your project. As far as I know, unless you declare type explicitly, AST will have no reference to it.

for eg. If you have

```<code>class MyClass {
   // some code
}

let instance1 = new MyClass();
let instance2: MyClass = new MyClass();
</code>```

In AST, node for instance1 will have type property as undefined, for instance2 type property will have proper TypeReference

For type checking you can use Program.getTypeChecker(). This returns a TypeChecker which can be used to analyse files in the program.

Body:
I want to parse TypeScript projects into ASTs.

I can parse single file by :

import ts = require("typescript");
var fs          = require('fs');
var util      = require('util');

const ast = ts.createSourceFile('sample.ts', fs.readFileSync('sample.ts').toString(), ts.ScriptTarget.ES6, true);

console.log("AST:"+util.inspect(ast));

I can even loop through the files and filter files by extension and run above code to generate ASt.

However I want to parse the whole project in such a way that the relationships (like imports) will be preserved in AST.

For example:

If, a.ts is referencing var x from b.ts as below:

a.ts:

var y = x;

b.ts:

var x = 5;

In this case signature of x in a .ts should be resolved as : b.ts.x or equivalent.

I just want all such relationships resolved in the ASts as I parse the .ts files one by one.

Body:
You can load your project using

ts.createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program)

rootNames is the list of all typescript files in your project. As far as I know, unless you declare type explicitly, AST will have no reference to it.

for eg. If you have

class MyClass {
   // some code
}

let instance1 = new MyClass();
let instance2: MyClass = new MyClass();

In AST, node for instance1 will have type property as undefined, for instance2 type property will have proper TypeReference

For type checking you can use Program.getTypeChecker(). This returns a TypeChecker which can be used to analyse files in the program.


问:
Searching for a substring in a dataframe and replacing it
I have a condition where spurious data is created and I am trying to clean it.

eg...

```<code>www.one@foxturn.com/!ut/5 #RealLink
www.one@foxturn.com/ut1/5_RTFDEERERTGFEFD # System adds junks to it
www.one@foxturn.com/ut1/5_dvkerfddfrejermsdkasmf # System adds junks to it
</code>```

I am trying to clean this up by dropping everything after !ut

So far I have tried :

```<code>SPA_MX = Mexico['Page URL'].str.startswith("http://www.www.one@foxturn.com/ut1")
</code>```

but this returns a boolean.

I would like advise on the most efficient way to achieve this.

答:
You can do this using apply on the column and then use find to return the index of the pattern and slice the str if found:

```<code>In[69]:

df['url'].apply(lambda x: x[:x.find('!ut') + 3] if x.find('!ut') != -1 else x)

Out[69]:
0                             www.one@foxturn.com/!ut
1           www.one@foxturn.com/ut1/5_RTFDEERERTGFEFD
2    www.one@foxturn.com/ut1/5_dvkerfddfrejermsdkasmf
Name: url, dtype: object
</code>```

Body:
I have a condition where spurious data is created and I am trying to clean it.

eg...

www.one@foxturn.com/!ut/5 #RealLink
www.one@foxturn.com/ut1/5_RTFDEERERTGFEFD # System adds junks to it
www.one@foxturn.com/ut1/5_dvkerfddfrejermsdkasmf # System adds junks to it

I am trying to clean this up by dropping everything after !ut

So far I have tried :

SPA_MX = Mexico['Page URL'].str.startswith("http://www.www.one@foxturn.com/ut1")

but this returns a boolean.

I would like advise on the most efficient way to achieve this.

Body:
You can do this using apply on the column and then use find to return the index of the pattern and slice the str if found:

In[69]:

df['url'].apply(lambda x: x[:x.find('!ut') + 3] if x.find('!ut') != -1 else x)

Out[69]:
0                             www.one@foxturn.com/!ut
1           www.one@foxturn.com/ut1/5_RTFDEERERTGFEFD
2    www.one@foxturn.com/ut1/5_dvkerfddfrejermsdkasmf
Name: url, dtype: object


问:
WebApp ignores patched perl pm file
I never really came in touch with perl before, so I really hope, this is a real newbie question and I can solve the problem pretty quick...

We've one perl based web application installed on a windows 2003 server environment. The installed version contains a bug and I know where to apply the patch. Basically: I have carefully changed two lines in one of the web apps pm files.

To my surprise, the file change is ignored and I still get the same error messages with references to the old version of the file - clearly identifiable by the line numbers.

I've cleared the browser caches, restarted the web application (including apache) - no luck.

Now I think/hope that this is some kind of perl feature, but I even don't know enough of that language to ask google the right questions. One tutorial said, that perl is an interpreted language and that changes to source files are effective immediately. This isn't true for my site...

Are there some more caches/files I have to touch or delete in order to make my changes effective?

答:
Are you sure your Perl is actually using the latest version of said pm file? There is no other version somewhere else included which is getting used?

Take a look at @INC

Step through your programming using a debugger

Sprinkle warnings around the code and see if it gets called.

Title: WebApp ignores patched perl pm file


问:
Entity Framework - The context cannot be used while the model is being created
I am trying to create a console application where I am trying to use Entity Framework to dynamically create database and tables to store the data. However, when I am trying to add data to my DbSet. I am getting the following error.

An unhandled exception of type 'System.InvalidOperationException'
  occurred in EntityFramework.dll

Additional information: The context cannot be used while the model is
  being created. This exception may be thrown if the context is used
  inside the OnModelCreating method or if the same context instance is
  accessed by multiple threads concurrently. Note that instance members
  of DbContext and related classes are not guaranteed to be thread safe.

I have referred to other posts with similar error but none of the solutions worked. This is a single threaded application.

The error occurs at line

```<code>this.context.Environments.Add(entity)
</code>```

DataSource.cs

```<code>public class DataSource
{
        private static DataSource instance;

        public DataSource()
        {
            this.context = new CounterContext();
        }

        public static DataSource Instance
        {
            get
            {
                return instance ?? (instance = new DataSource());
            }
        }

        private CounterContext context;

        public void AddCockpitEnvironmentDetails(IList<Environment> environmentList)
        {
            foreach (var entity in environmentList)
            {
                this.context.Environments.Add(entity);
            }

            this.context.SaveChanges();
        }
...
}
</code>```

My context:

```<code>public class CounterContext : DbContext
{
        public CounterContext()
            : base("name=CounterDbString")
        {
            Database.SetInitializer<CounterContext>(new CreateDatabaseIfNotExists<CounterContext>());
        }
        public DbSet<CounterData> CounterDetails { get; set; }

        public DbSet<Environment> Environments { get; set; }
    }
</code>```

Model

```<code>public class Environment
{
    [Key]
    public Guid Id { get; set; }
    public string EnvironmentName { get; set; }
    public string EnvironmentNotes { get; set; }

    public virtual ICollection<CounterDetail> CounterDetails { get; set; }
};

public class CounterData
{
    [Key]
    [Column(Order = 1)]
    public DateTime counterTime { get; set; }
    [Key]
    [Column(Order = 2)]
    public int counterName { get; set; }
    [Key]
    [Column(Order = 3)]
    public Guid EnvId {get; set;}
    public int count { get; set; }

    [ForeignKey("EnvId")]
    public virtual CockpitEnvironment Machine { get; set; }
}
</code>```

App.config:

```<code><connectionStrings>
    <add name="CounterDbString"
         connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Counters_Test;Integrated Security=True;Connect Timeout=30"
         providerName="System.Data.SqlClient"/>
</connectionStrings>
</code>```

答: Using VS2015, I was getting this error when debugging (F5). After simply stopping the debugger and restarting the problem went away.</p>

Body:
I am trying to create a console application where I am trying to use Entity Framework to dynamically create database and tables to store the data. However, when I am trying to add data to my DbSet. I am getting the following error.

An unhandled exception of type 'System.InvalidOperationException'
  occurred in EntityFramework.dll

Additional information: The context cannot be used while the model is
  being created. This exception may be thrown if the context is used
  inside the OnModelCreating method or if the same context instance is
  accessed by multiple threads concurrently. Note that instance members
  of DbContext and related classes are not guaranteed to be thread safe.

I have referred to other posts with similar error but none of the solutions worked. This is a single threaded application.

The error occurs at line

this.context.Environments.Add(entity)

DataSource.cs

public class DataSource
{
        private static DataSource instance;

        public DataSource()
        {
            this.context = new CounterContext();
        }

        public static DataSource Instance
        {
            get
            {
                return instance ?? (instance = new DataSource());
            }
        }

        private CounterContext context;

        public void AddCockpitEnvironmentDetails(IList<Environment> environmentList)
        {
            foreach (var entity in environmentList)
            {
                this.context.Environments.Add(entity);
            }

            this.context.SaveChanges();
        }
...
}

My context:

public class CounterContext : DbContext
{
        public CounterContext()
            : base("name=CounterDbString")
        {
            Database.SetInitializer<CounterContext>(new CreateDatabaseIfNotExists<CounterContext>());
        }
        public DbSet<CounterData> CounterDetails { get; set; }

        public DbSet<Environment> Environments { get; set; }
    }

Model

public class Environment
{
    [Key]
    public Guid Id { get; set; }
    public string EnvironmentName { get; set; }
    public string EnvironmentNotes { get; set; }

    public virtual ICollection<CounterDetail> CounterDetails { get; set; }
};

public class CounterData
{
    [Key]
    [Column(Order = 1)]
    public DateTime counterTime { get; set; }
    [Key]
    [Column(Order = 2)]
    public int counterName { get; set; }
    [Key]
    [Column(Order = 3)]
    public Guid EnvId {get; set;}
    public int count { get; set; }

    [ForeignKey("EnvId")]
    public virtual CockpitEnvironment Machine { get; set; }
}

App.config:

<connectionStrings>
    <add name="CounterDbString"
         connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Counters_Test;Integrated Security=True;Connect Timeout=30"
         providerName="System.Data.SqlClient"/>
</connectionStrings>


问:
Delete card from Tispr card stack
I want to do a delete function with Thispr Card. Can you guide me how to do that. I did reloading the view after remove an object from the stack but it's crashing for me.

After I go to the next view and perform the delete action. then when come back my stack should be refreshed. In viewdidappear() I did this

```<code>override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(true)

    if(dm.cardshouldRefresh || isFirsttimeLoad)
    {

        com.showProgress()

        self.getAuthorizations() { (status) in

            self.dm.cardshouldRefresh=false
            self.isFirsttimeLoad=false
            self.com.removeProgress()
            if (status)
            {
                self.setupCardView()

            }

        }
    }

    else
    {
        print(arrayAuthorization)

    }

}

func makecollectionViewEmpty()
{
    arrayAuthorization.removeAll()
    vwBtnPanelBottom.removeFromSuperview()
    self.collectionView?.reloadData()
}
</code>```

But this is crashing once I try to swipe after loading.
Please help me.
Thanks

答:
Add below methods in TisprCardStackExample project and you will get remove method.

TisprCardStackDemoViewController.swift

```<code>//method to remove card
@IBAction func addNewCards(_ sender: AnyObject) {
    countOfCards -= 1
    if(countOfCards >= 0){
        cardWasRemoved()
    }
}
</code>```

TisprCardStackViewController.swift

```<code>open func cardWasRemoved() {
    if layout.newCardShouldAppearOnTheBottom {
        layout.cardDidRemoved(0)
    } else {
        layout.cardDidRemoved(numberOfCards() - 1)
    }
}
</code>```

TisprCardStackViewLayout.swift

```<code>func cardDidRemoved(_ newCardIndex:Int) {
    collectionView?.performBatchUpdates({ [weak self] _ in
        self?.collectionView?.deleteItems(at: [IndexPath(item: newCardIndex, section: 0)])
        }, completion: { _ in
    })
}
</code>```

Title: Delete card from Tispr card stack

Body:
I want to do a delete function with Thispr Card. Can you guide me how to do that. I did reloading the view after remove an object from the stack but it's crashing for me.

After I go to the next view and perform the delete action. then when come back my stack should be refreshed. In viewdidappear() I did this

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(true)

    if(dm.cardshouldRefresh || isFirsttimeLoad)
    {

        com.showProgress()

        self.getAuthorizations() { (status) in

            self.dm.cardshouldRefresh=false
            self.isFirsttimeLoad=false
            self.com.removeProgress()
            if (status)
            {
                self.setupCardView()

            }

        }
    }

    else
    {
        print(arrayAuthorization)

    }

}

func makecollectionViewEmpty()
{
    arrayAuthorization.removeAll()
    vwBtnPanelBottom.removeFromSuperview()
    self.collectionView?.reloadData()
}

But this is crashing once I try to swipe after loading.
Please help me.
Thanks

Body:
Add below methods in TisprCardStackExample project and you will get remove method.

TisprCardStackDemoViewController.swift

//method to remove card
@IBAction func addNewCards(_ sender: AnyObject) {
    countOfCards -= 1
    if(countOfCards >= 0){
        cardWasRemoved()
    }
}

TisprCardStackViewController.swift

open func cardWasRemoved() {
    if layout.newCardShouldAppearOnTheBottom {
        layout.cardDidRemoved(0)
    } else {
        layout.cardDidRemoved(numberOfCards() - 1)
    }
}

TisprCardStackViewLayout.swift

func cardDidRemoved(_ newCardIndex:Int) {
    collectionView?.performBatchUpdates({ [weak self] _ in
        self?.collectionView?.deleteItems(at: [IndexPath(item: newCardIndex, section: 0)])
        }, completion: { _ in
    })
}


问:
Improve quality of image for tesseract OCR
With regard to this question and this question, where I ask how to download thousands of PDF and processes them to extract their texts with OCR, I am hitting a brick wall again when it comes to enhancing the text outputs.

I am interested to extract texts of a bunch of PDF in order to search for surnames in the text (I do not need necessarily to be able to read the rest of the text). The PDF represent old newspaper articles, published between 1810 and 1832 and written in German Fraktur. This font seems to be particularly challenging for tesseract.

Q: How can I further improve the image quality for tesseract to - at least - have a change to find the surnames in the text? Which procedure would you suggest?

If we take this pdf as an example, I receive the following image when applying

```<code>convert -colorspace GRAY -resize 3000x -units PixelsPerInch example.pdf example-page.jpg
</code>```

If I now use tesseract with

```<code>tesseract --tessdata-dir /usr/local/share/tessdata/ -l deu_frak example-page.jpg example-page.txt
</code>```

it would perform terrible on that image with roughly 360 diacritics detected only. My text output is entirely scrambled.

When I use Fred's ImageMagick script textcleaner, applying either

```<code>textcleaner -g -e stretch -f 25 -o 10 -u -s 1 -T -p 10
</code>```

or

```<code>textcleaner -g -e stretch -f 25 -o 20 -t 30 -u -s 1 -T -p 20
</code>```

I get something like this

When I then run again tesseract with the above mentioned command, the resulting text is much better (around 700-800 diacritics detected) but still scrambled enough not to find most surnames of the text.

I know that the example page is a particular hard one, however, even pages, which are not inky prints and not skewed to begin with, yield mostly scrambled outputs and undecipherable surnames when processing them with tesseract and the above command.

For example this page

Q: How can I further improve the image quality for tesseract to - at least - have a change to find the surnames in the text? Which procedure would you suggest?

Edit:
I do not know, whether training tesseract is needed or a good idea to deal with the given German Fraktur font, as GUI box editor seems to work reliably on MacOS, see for example, jTessBoxEditor, Qt-box-editor, or Tesseract-Box-Editor, nor did I understand how to train tesseract, see the tesseract training wiki here and another tutorial here.

答:
My father had a similar problem with his old newspaper clippings, and I had moderately good success by preprocessing with GhostScript and then applying Tesseract.  Your mileage may vary.  My commands (Windows) were

```<code>set nm=%1
set d=%2
"C:\Program Files\gs\gs9.21\bin\gswin32.exe" -dSAFER -dBATCH -dNOPAUSE -sDEVICE=pgmraw -r150 -dTextAlphaBits=4 -sOutputFile="%nm%-%%00d.pgm" %nm%.pdf
echo. 2>"%nm%.txt"

for %%f in (%nm%*.pgm) do (
    echo %%~nf
    "C:\Program Files\Tesseract-OCR\tesseract.exe" "%%~nf.pgm" "%%~nf"
    cat "%%~nf.txt" >> "%nm%.txt"
    del  "%%~nf.pgm"
    del  "%%~nf.txt"
)
"C:\Program Files\Microsoft Office\Office11\winword.exe" "%nm%.txt"
</code>```

EDIT: response to comment

First, install ghostscript on your mac.  See https://wiki.scribus.net/canvas/Installation_and_Configuration_of_Ghostscript#Installing_Ghostscript_on_Mac_OS_X

Then do

```<code>gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=pgmraw -r150 -dTextAlphaBits=4 -sOutputFile='paper-%00d.pgm' paper.pdf
</code>```

This will create rasterized files paper-01.pgm, paper-02.pgm etc (this is in case your pdf has multiple pages).  You can replace the "paper" with the basename of your original pdf.  You can also mess with the resolution.  That and other things can be found at https://ghostscript.com/doc/9.19/Use.htm

Then use tesseract on each pgm file.

Body:
With regard to this question and this question, where I ask how to download thousands of PDF and processes them to extract their texts with OCR, I am hitting a brick wall again when it comes to enhancing the text outputs.

I am interested to extract texts of a bunch of PDF in order to search for surnames in the text (I do not need necessarily to be able to read the rest of the text). The PDF represent old newspaper articles, published between 1810 and 1832 and written in German Fraktur. This font seems to be particularly challenging for tesseract.

Q: How can I further improve the image quality for tesseract to - at least - have a change to find the surnames in the text? Which procedure would you suggest?

If we take this pdf as an example, I receive the following image when applying

convert -colorspace GRAY -resize 3000x -units PixelsPerInch example.pdf example-page.jpg

If I now use tesseract with

tesseract --tessdata-dir /usr/local/share/tessdata/ -l deu_frak example-page.jpg example-page.txt

it would perform terrible on that image with roughly 360 diacritics detected only. My text output is entirely scrambled.

When I use Fred's ImageMagick script textcleaner, applying either

textcleaner -g -e stretch -f 25 -o 10 -u -s 1 -T -p 10

or

textcleaner -g -e stretch -f 25 -o 20 -t 30 -u -s 1 -T -p 20

I get something like this

When I then run again tesseract with the above mentioned command, the resulting text is much better (around 700-800 diacritics detected) but still scrambled enough not to find most surnames of the text.

I know that the example page is a particular hard one, however, even pages, which are not inky prints and not skewed to begin with, yield mostly scrambled outputs and undecipherable surnames when processing them with tesseract and the above command.

For example this page

Q: How can I further improve the image quality for tesseract to - at least - have a change to find the surnames in the text? Which procedure would you suggest?

Edit:
I do not know, whether training tesseract is needed or a good idea to deal with the given German Fraktur font, as GUI box editor seems to work reliably on MacOS, see for example, jTessBoxEditor, Qt-box-editor, or Tesseract-Box-Editor, nor did I understand how to train tesseract, see the tesseract training wiki here and another tutorial here.

Body:
My father had a similar problem with his old newspaper clippings, and I had moderately good success by preprocessing with GhostScript and then applying Tesseract.  Your mileage may vary.  My commands (Windows) were

set nm=%1
set d=%2
"C:\Program Files\gs\gs9.21\bin\gswin32.exe" -dSAFER -dBATCH -dNOPAUSE -sDEVICE=pgmraw -r150 -dTextAlphaBits=4 -sOutputFile="%nm%-%%00d.pgm" %nm%.pdf
echo. 2>"%nm%.txt"

for %%f in (%nm%*.pgm) do (
    echo %%~nf
    "C:\Program Files\Tesseract-OCR\tesseract.exe" "%%~nf.pgm" "%%~nf"
    cat "%%~nf.txt" >> "%nm%.txt"
    del  "%%~nf.pgm"
    del  "%%~nf.txt"
)
"C:\Program Files\Microsoft Office\Office11\winword.exe" "%nm%.txt"

EDIT: response to comment

First, install ghostscript on your mac.  See https://wiki.scribus.net/canvas/Installation_and_Configuration_of_Ghostscript#Installing_Ghostscript_on_Mac_OS_X

Then do

gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=pgmraw -r150 -dTextAlphaBits=4 -sOutputFile='paper-%00d.pgm' paper.pdf

This will create rasterized files paper-01.pgm, paper-02.pgm etc (this is in case your pdf has multiple pages).  You can replace the "paper" with the basename of your original pdf.  You can also mess with the resolution.  That and other things can be found at https://ghostscript.com/doc/9.19/Use.htm

Then use tesseract on each pgm file.