问:
How to distinguish two regular expressions, with one being the substring of the other?
I have two types of patterns, as below:

Type I: ${<varName>}

Type II: $${<varName>}

The patterns can be found standing alone, or contained multiple matches in a string. I need to find the occurrences of these patterns, so I wrote a query to search by matching regex. However, the problem is that for any Type II pattern, they themselves contain a match for Type I pattern. For example, $${newVar} will be detected twice as $${newVar} and ${newVar}. I only want the former to be returned. The regular expressions I used are:

Type I: \$\{[a-zA-Z0-9]+\}

Type II: \$\$\{[a-zA-Z0-9]+\}

You can see an example of the detected string here (below)

Note that the second detection is correct, whereas the first detection is unwanted.

Is there anyway too modify these regular expressions to meet my need? Or is there any alternatives? Please feel free to suggest. All answers are welcome!! Thank you all.

答:
It seems you need to find the occurrences of both Type I and Type II patterns, so you should do that in one scan.

That can be done like this:

```<code>String input = "adklsfjb$${xxx}dklsjfnsdklj${yyy}";

Pattern p = Pattern.compile("(\\$)?\\$\\{([^}]+)}");
for (Matcher m = p.matcher(input); m.find(); ) {
    if (m.start(1) == -1) {
        System.out.println("Found Type I match for variable '" + m.group(2) + "'" +
                           " at index " + m.start() + "-" + m.end());
    } else {
        System.out.println("Found Type II match for variable '" + m.group(2) + "'" +
                           " at index " + m.start() + "-" + m.end());
    }
}
</code>```

Output

Found Type II match for variable 'xxx' at index 8-15
Found Type I match for variable 'yyy' at index 27-33
```

<hr>

<p><strong>UPDATE</strong></p>

<p>If you want to replace the patterns with values, you can use <code>appendReplacement()</code> and <code>appendTail()</code>.</p>

<p>Example:</p>

```String input = "adklsfjb$${xxx}dklsjfnsdklj${yyy}adljfhjh";

Map<String, String> type1 = new HashMap<>();
type1.put("xxx", "[type I with x's]");
type1.put("yyy", "[type I with y's]");

Map<String, String> type2 = new HashMap<>();
type2.put("xxx", "{TYPE 2 WITH x's}");
type2.put("yyy", "{TYPE 2 WITH y's}");

StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile("(\\$)?\\$\\{([^}]+)}").matcher(input);
while (m.find()) {
    String var = m.group(2);
    String repl = (m.start(1) == -1 ? type1.get(var) : type2.get(var));
    if (repl != null)
        m.appendReplacement(buf, Matcher.quoteReplacement(repl));
}
String output = m.appendTail(buf).toString();

System.out.println(output);
```

<p><em>Output</em></p>

<pre class="lang-none prettyprint-override"><code>adklsfjb{TYPE 2 WITH x's}dklsjfnsdklj[type I with y's]adljfhjh
</code>```

Body:
It seems you need to find the occurrences of both Type I and Type II patterns, so you should do that in one scan.

That can be done like this:

String input = "adklsfjb$${xxx}dklsjfnsdklj${yyy}";

Pattern p = Pattern.compile("(\\$)?\\$\\{([^}]+)}");
for (Matcher m = p.matcher(input); m.find(); ) {
    if (m.start(1) == -1) {
        System.out.println("Found Type I match for variable '" + m.group(2) + "'" +
                           " at index " + m.start() + "-" + m.end());
    } else {
        System.out.println("Found Type II match for variable '" + m.group(2) + "'" +
                           " at index " + m.start() + "-" + m.end());
    }
}

Output

Found Type II match for variable 'xxx' at index 8-15
Found Type I match for variable 'yyy' at index 27-33

UPDATE

If you want to replace the patterns with values, you can use appendReplacement() and appendTail().

Example:

String input = "adklsfjb$${xxx}dklsjfnsdklj${yyy}adljfhjh";

Map<String, String> type1 = new HashMap<>();
type1.put("xxx", "[type I with x's]");
type1.put("yyy", "[type I with y's]");

Map<String, String> type2 = new HashMap<>();
type2.put("xxx", "{TYPE 2 WITH x's}");
type2.put("yyy", "{TYPE 2 WITH y's}");

StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile("(\\$)?\\$\\{([^}]+)}").matcher(input);
while (m.find()) {
    String var = m.group(2);
    String repl = (m.start(1) == -1 ? type1.get(var) : type2.get(var));
    if (repl != null)
        m.appendReplacement(buf, Matcher.quoteReplacement(repl));
}
String output = m.appendTail(buf).toString();

System.out.println(output);

Output

adklsfjb{TYPE 2 WITH x's}dklsjfnsdklj[type I with y's]adljfhjh


来源: stackexchange

问:
How can I search Notes by sequence number
I use Evernote C# API. I understand how filters working.

```<code>ENNoteStoreClient store = ENSessionAdvanced.SharedSession.PrimaryNoteStore;
            SyncState currentState = store.GetSyncState();
            int currentUpdateCount = currentState.UpdateCount;

            if (currentUpdateCount > latestUpdateCount)
            {
                latestUpdateCount = currentUpdateCount;
                // Here synchronization code
            }
</code>```

I have latestUpdateCount and how I can get notes with sequence number >= this number?

答:
You'll want to use GetFilteredSyncChunk using code something like the following:</p>

```<code>List<SyncChunk> syncBlocks = new List<SyncChunk>();
int maxEntries = 250;

// These are sample filter settings; you should use what's appropriate for you based on
// what data you want returned in your note objects.
SyncChunkFilter filter = new SyncChunkFilter();
filter.IncludeNotes = true;
filter.IncludeNoteAttributes = true;
filter.IncludeNotebooks = true;
filter.IncludeTags = false;
filter.IncludeSearches = false;
filter.IncludeResources = false;
filter.IncludeLinkedNotebooks = false;
filter.IncludeExpunged = false;
filter.IncludeNoteApplicationDataFullMap = false;
filter.IncludeResourceApplicationDataFullMap = false;
filter.IncludeNoteResourceApplicationDataFullMap = false;

do
{
    SyncChunk chunk = store.getFilteredSyncChunk(currentUpdateCount, maxEntries, filter);
    if (chunk == null)
    {
        return null;      // This can happen if there is a "503 - Service unavailable" error accessing this person's Evernote info
    }
    syncBlocks.Add(chunk);
    currentUpdateCount = chunk.ChunkHighUSN;
} while (currentUpdateCount < serverSyncState.UpdateCount);

foreach (SyncChunk chunk in syncBlocks)
{
    if (chunk != null && chunk.Notes != null)
    {
        foreach (Note chunkNote in chunk.Notes)
        {
            // do something with the retrieved chunkNote object
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use Evernote C# API. I understand how filters working.

ENNoteStoreClient store = ENSessionAdvanced.SharedSession.PrimaryNoteStore;
            SyncState currentState = store.GetSyncState();
            int currentUpdateCount = currentState.UpdateCount;

            if (currentUpdateCount > latestUpdateCount)
            {
                latestUpdateCount = currentUpdateCount;
                // Here synchronization code
            }

I have latestUpdateCount and how I can get notes with sequence number >= this number?

Body:
You'll want to use GetFilteredSyncChunk using code something like the following:

List<SyncChunk> syncBlocks = new List<SyncChunk>();
int maxEntries = 250;

// These are sample filter settings; you should use what's appropriate for you based on
// what data you want returned in your note objects.
SyncChunkFilter filter = new SyncChunkFilter();
filter.IncludeNotes = true;
filter.IncludeNoteAttributes = true;
filter.IncludeNotebooks = true;
filter.IncludeTags = false;
filter.IncludeSearches = false;
filter.IncludeResources = false;
filter.IncludeLinkedNotebooks = false;
filter.IncludeExpunged = false;
filter.IncludeNoteApplicationDataFullMap = false;
filter.IncludeResourceApplicationDataFullMap = false;
filter.IncludeNoteResourceApplicationDataFullMap = false;

do
{
    SyncChunk chunk = store.getFilteredSyncChunk(currentUpdateCount, maxEntries, filter);
    if (chunk == null)
    {
        return null;      // This can happen if there is a "503 - Service unavailable" error accessing this person's Evernote info
    }
    syncBlocks.Add(chunk);
    currentUpdateCount = chunk.ChunkHighUSN;
} while (currentUpdateCount < serverSyncState.UpdateCount);

foreach (SyncChunk chunk in syncBlocks)
{
    if (chunk != null && chunk.Notes != null)
    {
        foreach (Note chunkNote in chunk.Notes)
        {
            // do something with the retrieved chunkNote object
        }
    }
}


问:
"this" pointer in C (not C++)
I'm trying to create a stack in C for fun, and came up with the idea of using struct to represent the stack. Then I add function pointers to the struct for push() and pop() operations.

So far all is good it seems, but, for the implementation of the push() and pop() functions I need to refer to *this somehow. How can that (can it?) be done?

This is my struct

```<code>struct Stack {
    int *data;
    int current_size;
    int max_size;
    int (*push)(int);
    int (*pop)();
};
</code>```

And as an example here's push

```<code>int push(int val) {
    if(current_size == max_size -1)
            return 0;

    data[current_size] = val;
    current_size++;

    return 1;
}
</code>```

As you can imagine, the compiler has no idea what current_size is, as it would expect something like stack->current_size.

Is this possible to overcome somehow?

答: Your function pointers aren't methods so they don't have any information about the calling object.  The only way to do what you want is to either pass in a pointer to the object, or make that pointer global (the latter is not recommended).</p>

ContentLicense: CC BY-SA 2.5

Title: "this" pointer in C (not C++)

Body:
I'm trying to create a stack in C for fun, and came up with the idea of using struct to represent the stack. Then I add function pointers to the struct for push() and pop() operations.

So far all is good it seems, but, for the implementation of the push() and pop() functions I need to refer to *this somehow. How can that (can it?) be done?

This is my struct

struct Stack {
    int *data;
    int current_size;
    int max_size;
    int (*push)(int);
    int (*pop)();
};

And as an example here's push

int push(int val) {
    if(current_size == max_size -1)
            return 0;

    data[current_size] = val;
    current_size++;

    return 1;
}

As you can imagine, the compiler has no idea what current_size is, as it would expect something like stack->current_size.

Is this possible to overcome somehow?


问:
How to open a Bootstrap modal window using jQuery?
I'm using Twitter Bootstrap modal window functionality. When someone clicks submit on my form, I want to show the modal window upon clicking the "submit button" in the form.

```<code><form id="myform" class="form-wizard">
    <h2 class="form-wizard-heading">BootStap Wizard Form</h2>
    <input type="text" value=""/>
    <input type="submit"/>
</form>

<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Modal header</h3>
    </div>
    <div class="modal-body">
        <p>One fine body…</p>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button class="btn btn-primary">Save changes</button>
    </div>
</div>
</code>```

jQuery:

```<code>$('#myform').on('submit', function(ev) {
    $('#my-modal').modal({
        show: 'false'
    });

    var data = $(this).serializeObject();
    json_data = JSON.stringify(data);
    $("#results").text(json_data);
    $(".modal-body").text(json_data);

    // $("#results").text(data);

    ev.preventDefault();
});
</code>```

答:
I tried several methods which failed, but the below worked for me like a charm:</p>

```<code>$('#myModal').appendTo("body").modal('show');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using Twitter Bootstrap modal window functionality. When someone clicks submit on my form, I want to show the modal window upon clicking the "submit button" in the form.

<form id="myform" class="form-wizard">

BootStap Wizard Form

    <input type="text" value=""/>
    <input type="submit"/>
</form>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal header

One fine body…

        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button class="btn btn-primary">Save changes</button>

jQuery:

$('#myform').on('submit', function(ev) {
    $('#my-modal').modal({
        show: 'false'
    });

    var data = $(this).serializeObject();
    json_data = JSON.stringify(data);
    $("#results").text(json_data);
    $(".modal-body").text(json_data);

    // $("#results").text(data);

    ev.preventDefault();
});

Body:
I tried several methods which failed, but the below worked for me like a charm:

$('#myModal').appendTo("body").modal('show');


问:
jquery add dash between characters if length is greater than x
I am trying to format a US zip code as the user types, and need to add a dash between the 5th and and 6th characters if the user types more than 5 so the the zip code is formatted like

55555 or 55555-5555

what I have now adds a dash, but regardless if a 6th number is added

```<code>//zip code formatting
$(".zip-val").keyup(function() {
    if($(this).val().length == 5) {
        $(this).val($(this).val() + "-");
    }
});
</code>```

答:
How about this?</p>

```<code>//zip code formatting
$(".zip-val").keyup(function() {
    zipcode = $(this).val();
    zipcode = zipcode.replace(/-/g, '');      // remove all occurrences of '-'

    if(zipcode.length > 5) {
        $(this).val(zipcode.substring(0, 5) + "-" + zipcode.substring(5));
    }
});
</code>```

Body:
I am trying to format a US zip code as the user types, and need to add a dash between the 5th and and 6th characters if the user types more than 5 so the the zip code is formatted like

55555 or 55555-5555

what I have now adds a dash, but regardless if a 6th number is added

//zip code formatting
$(".zip-val").keyup(function() {
    if($(this).val().length == 5) {
        $(this).val($(this).val() + "-");
    }
});

Body:
How about this?

//zip code formatting
$(".zip-val").keyup(function() {
    zipcode = $(this).val();
    zipcode = zipcode.replace(/-/g, '');      // remove all occurrences of '-'

    if(zipcode.length > 5) {
        $(this).val(zipcode.substring(0, 5) + "-" + zipcode.substring(5));
    }
});


问:
Trying to understand why function is returning undefined in recursive function
I am having trouble understanding whats happening in this recursive function.
Why does y === undefined??

```<code>function f(num){
  if(num !== 10){
    f(num + 1);
  } else {
    return num;
  }

}

var y = f(0);
console.log(y);
</code>```

If I log "num" right before its returned the value is 10.
Here is a jsfiddle:
https://jsfiddle.net/

答:
You should rather return f(num + 1) inside if block.
 Without which it returns nothing except when "num" reaches 10.</p>

```<code> function f(num){
      if(num !== 10){
        return f(num + 1);
      } else {
        return num;
      }
    }
var y = f(0);
console.log(y);
// 10
</code>```

Body:
I am having trouble understanding whats happening in this recursive function.
Why does y === undefined??

function f(num){
  if(num !== 10){
    f(num + 1);
  } else {
    return num;
  }

}

var y = f(0);
console.log(y);

If I log "num" right before its returned the value is 10.
Here is a jsfiddle:
https://jsfiddle.net/

Body:
You should rather return f(num + 1) inside if block.
 Without which it returns nothing except when "num" reaches 10.

 function f(num){
      if(num !== 10){
        return f(num + 1);
      } else {
        return num;
      }
    }
var y = f(0);
console.log(y);
// 10


问:
Get input type=password to look like type=text
I have an input with type=password which I want to show stars like an input with type=text.

```<code><input type="password" name=""/>
</code>```

My purpose is to click on the input box when calling the input password when the keyboard, using a lot of methods can not be achieved, so I would like to try this way.

答:
Prepare CSS for showing Password stars like normal stars.
look into this given reference CSS script .i think it will help.</p>

Body:
I have an input with type=password which I want to show stars like an input with type=text.

<input type="password" name=""/>

My purpose is to click on the input box when calling the input password when the keyboard, using a lot of methods can not be achieved, so I would like to try this way.


问:
MYSQL driver class not found
Please i'm trying to have a DB data from a jsp file, but the driver class is not found (output error), it works good when i'm executing the java class directly but it's not found when i'm calling it from the jsp file.

Here is the jsp code

```<code><%@page import="java.util.*"%>
<%@page import="java.lang.Class"%>
<%@ page language="java" import="DAO.*"%>

<%
 try{
   List<String> names=DB.getNames();
   out.print(names);
   out.flush();
    }
 catch(Exception e)
    {
   e.printStackTrace();
    }
   %>
</code>```

And basically the same in the java class when executing the main .

```<code>public static void main(String[] args){
for(Iterator it=DB.getNames().iterator(); it.hasNext();)
    System.out.println(it.next());

 }
</code>```

Works good from java directly but not found when called from jsp.

The error shows the problem in the db connection function an especialy in this line com.mysql.jdbc.Driver

```<code>java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at DAO.DB.connect(DB.java:21)
at DAO.DB.getNames(DB.java:35)
</code>```

答:
This issue is being faced because, your Tomcat is unable to find this class that is being referenced in your JSP / Java code.

You need to place your MySQL Connector/J jar in your CATALINA_HOME/lib folder or in <yourApplicationWAR>/WEB-INF/lib, hoping that your DB related code is in the JSP itself. Latter is preferred over placing your Connector/J in your Tomcat (or any such similar app-server)

If the code is in your JAVA class, then you would need to put it in your IDE classpath & preferably into your CLASSPATH environment variable.

Title: MYSQL driver class not found

Body:
Please i'm trying to have a DB data from a jsp file, but the driver class is not found (output error), it works good when i'm executing the java class directly but it's not found when i'm calling it from the jsp file.

Here is the jsp code

<%@page import="java.util.*"%>
<%@page import="java.lang.Class"%>
<%@ page language="java" import="DAO.*"%>

<%
 try{
   List<String> names=DB.getNames();
   out.print(names);
   out.flush();
    }
 catch(Exception e)
    {
   e.printStackTrace();
    }
   %>

And basically the same in the java class when executing the main .

public static void main(String[] args){
for(Iterator it=DB.getNames().iterator(); it.hasNext();)
    System.out.println(it.next());

 }

Works good from java directly but not found when called from jsp.

The error shows the problem in the db connection function an especialy in this line com.mysql.jdbc.Driver

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at DAO.DB.connect(DB.java:21)
at DAO.DB.getNames(DB.java:35)


问:
Unable to set runtime Local Server Port in Spring Boot Test 1.5
I am using Spring Boot 1.5 for my application. In integration testing I want to fetch the runtime port number of the web server(note: TestRestTemplate is not useful in my case.). There are a few approaches I have tried but none of them seem to work. Below are my approaches.

First Approach

```<code>@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.DEFINED_PORT)
public class RestServiceTest {

@LocalServerPort
protected int port;
</code>```

In my src/main/resources/config/application.properties file I have defined server port as

server.port = 8081

But With this code I am getting error

Could not resolve placeholder 'local.server.port' in value "${local.server.port}"

Second Approach

I have changed

webEnvironment =WebEnvironment.DEFINED_PORT

to

webEnvironment =WebEnvironment.RANDOM_PORT

and in my src/main/resources/config/application.properties file I have defined

server.port = 0

This throws the same as error as the first approach.

Third Approach

In third approach I have tried to use

```<code>protected int port;

@Autowired
Environment environment

this.port = this.environment.getProperty("local.server.port");
</code>```

this returns null value

Fourth Approach

Lastly I have tried to use ApplicationEvents to find out the port number by creating an event listener to listen to EmbeddedServletContainerIntialize

```<code>@EventListener(EmbeddedServletContainerInitializedEvent.class)
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
this.port = event.getEmbeddedServletContainer().getPort();
}

public int getPort() {
return this.port;
}
</code>```

Added the same to TestConfig

Now, In my test class I have tried use this listener to get the port

```<code>@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.RANDOM_PORT)
public class RestServiceTest {

protected int port;

@Autowired
EmbeddedServletContainerIntializedEventListener embeddedServletcontainerPort;

this.port = this.embeddedServletcontainerPort.getPort();
</code>```

this returns 0. Also, I have found out listener event is never triggered.

It is very straight forward as in the docs and other posts but somehow It is not working for me. Help is much appreciated.

答:
You forgot to put @RunWith(SpringRunner.class) above your class decoration.

So, try this.

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.DEFINED_PORT)
public class RestServiceTest {
     @LocalServerPort
     int randomServerPort;
     ...
}
</code>```

Body:
I am using Spring Boot 1.5 for my application. In integration testing I want to fetch the runtime port number of the web server(note: TestRestTemplate is not useful in my case.). There are a few approaches I have tried but none of them seem to work. Below are my approaches.

First Approach

@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.DEFINED_PORT)
public class RestServiceTest {

@LocalServerPort
protected int port;

In my src/main/resources/config/application.properties file I have defined server port as

server.port = 8081

But With this code I am getting error

Could not resolve placeholder 'local.server.port' in value "${local.server.port}"

Second Approach

I have changed

webEnvironment =WebEnvironment.DEFINED_PORT

to

webEnvironment =WebEnvironment.RANDOM_PORT

and in my src/main/resources/config/application.properties file I have defined

server.port = 0

This throws the same as error as the first approach.

Third Approach

In third approach I have tried to use

protected int port;

@Autowired
Environment environment

this.port = this.environment.getProperty("local.server.port");

this returns null value

Fourth Approach

Lastly I have tried to use ApplicationEvents to find out the port number by creating an event listener to listen to EmbeddedServletContainerIntialize

@EventListener(EmbeddedServletContainerInitializedEvent.class)
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
this.port = event.getEmbeddedServletContainer().getPort();
}

public int getPort() {
return this.port;
}

Added the same to TestConfig

Now, In my test class I have tried use this listener to get the port

@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.RANDOM_PORT)
public class RestServiceTest {

protected int port;

@Autowired
EmbeddedServletContainerIntializedEventListener embeddedServletcontainerPort;

this.port = this.embeddedServletcontainerPort.getPort();

this returns 0. Also, I have found out listener event is never triggered.

It is very straight forward as in the docs and other posts but somehow It is not working for me. Help is much appreciated.

Body:
You forgot to put @RunWith(SpringRunner.class) above your class decoration.

So, try this.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.DEFINED_PORT)
public class RestServiceTest {
     @LocalServerPort
     int randomServerPort;
     ...
}


问:
Advanced image editing off the web
I'm building an app in ASP.NET that will store some pictures of objects. The pictures will be uploaded by suppliers and downloaded by subscribers. In between, they will have to be edited before becoming available to subscribers.

The editing involves creating a cropping path tightly around the object in the picture, in which some advanced desktop image software will have to be used I suppose.

My problem is in exchanging pictures between my ASP.NET app and the desktop software in a manner that is easy and transparent for the user.

I've done some thinking and I've come up with:
- Manually downloading and uploading the image (Not much user friendly...)
- An image editing program that can upload to a web service (Haven't found yet...)
- Develop a plug-in for an image editing program (Too advanced...)

I'd appreciate any suggestions you may have, thank you!

答:
Meanwhile I came out with another possible solution.

I'm thinking of having our own windows app on the editor's computers. This app will be associated with a custom extension. When an editor downloads a file (with this extension) for editing, it will be opened in our application which in turn will open the image in some editor program.

This app will be monitoring the files for changes, and in such case, it will upload these images.

Any thoughts on this?

Title: Advanced image editing off the web


问:
Laravel 5.1 What's the difference of lockForUpdate in DB builder and Eloquent?
Using lockForUpdate on Eloquent seems not always working.

```<code>       DB::beginTransaction();
       User::find(1)->lockForUpdate();
       ... (doing some logic)
       DB::commit();
</code>```

But using

```<code>DB::table('users')->where('id', '=', $userId)->lockForUpdate()
</code>```

always works. What's the differences between those two lockForUpdate()?

Laravel Version: 5.1

PHP Version: 5.7

Database Driver & Version: MySQL 14.14

答:
```<code>User::lockForUpdate()->find(1);
</code>```

this would be work

find() will return a Model not a query Builder.

lockForUpdate() is a method from query Builder

Body:
Using lockForUpdate on Eloquent seems not always working.

       DB::beginTransaction();
       User::find(1)->lockForUpdate();
       ... (doing some logic)
       DB::commit();

But using

DB::table('users')->where('id', '=', $userId)->lockForUpdate()

always works. What's the differences between those two lockForUpdate()?

Laravel Version: 5.1

PHP Version: 5.7

Database Driver & Version: MySQL 14.14

Body:
User::lockForUpdate()->find(1);

this would be work

find() will return a Model not a query Builder.

lockForUpdate() is a method from query Builder


答:
Could try this, splitting it and keeping the number groups then recreating the string with formats. This even deletes the - if you are not in a group of 5.

You could also modify this to fit into a credit card number system.

//zip code formatting
$(".zip-val").keyup(function() {
    let val = $(this).val();
    if(val.length > 5) {
        let digits = val.split(/(\d{1,5})/);
        let str = "";
        for (let group of digits)
        {
          if (/^\d+$/.test(group))
          {
            str += group + "-";
          }
        }
        str = str.substring(0, str.length - 1);
        $(this).val(str);
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="zip-val" /></code>```

Title: jquery add dash between characters if length is greater than x

Body:
Could try this, splitting it and keeping the number groups then recreating the string with formats. This even deletes the - if you are not in a group of 5.

You could also modify this to fit into a credit card number system.

//zip code formatting
$(".zip-val").keyup(function() {
    let val = $(this).val();
    if(val.length > 5) {
        let digits = val.split(/(\d{1,5})/);
        let str = "";
        for (let group of digits)
        {
          if (/^\d+$/.test(group))
          {
            str += group + "-";
          }
        }
        str = str.substring(0, str.length - 1);
        $(this).val(str);
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="zip-val" />


问:
Linq to make sure that no two objects have same property value
I've a class called Alarm with a property called Description.

```<code>public class Alarm
{
    public string Description { get; set; }
}
</code>```

In a list of Alarms, I've to make sure that no two Alarm in the list have same Description.

I want to use linq to do this check and get a list of alarms with duplicate description.

答:
If you don't care to find which alarms are duplicated, you can also do this:</p>

```<code>if (list.Select(alarm => alarm.Description).Distinct().Count() != list.Count)
{
    // Has duplicate
}
</code>```

Body:
I've a class called Alarm with a property called Description.

public class Alarm
{
    public string Description { get; set; }
}

In a list of Alarms, I've to make sure that no two Alarm in the list have same Description.

I want to use linq to do this check and get a list of alarms with duplicate description.

Body:
If you don't care to find which alarms are duplicated, you can also do this:

if (list.Select(alarm => alarm.Description).Distinct().Count() != list.Count)
{
    // Has duplicate
}


问:
Using different Hystrix command name for metrics
I am working on a system where Hystrix commands are created dynamically. There is only a single implementation of HystrixCommand which receives its configuration as well as the code (Callable) to be executed inside run method.

Commands calling the same remote service have different command keys based on the component they are executed in so their circuit breakers are independent on each other. However, I would like to have them aggregated in the metrics stream under a single name depending on the remote service being called. Is that possible?

I can see there is a command group property and I set it to my remote service name but it seems that Hystrix Dashboard groups the entries together based on a command name.

答:
Would something like this provide the behaviour that you are looking for?

public class NamedHystrixCommand extends HystrixCommand<Object> {

    private static final HystrixCommandGroupKey GROUP_KEY =
        HystrixCommandGroupKey.Factory.asKey("Host Routing");
    private static final HystrixThreadPoolProperties.Setter THREAD_POOL_PROPERTIES =
        HystrixThreadPoolProperties.Setter()
                .withMaximumSize(100);
    private static final HystrixCommandProperties.Setter COMMAND_PROPERTIES =
        HystrixCommandProperties.Setter()
                .withExecutionTimeoutInMilliseconds(5000)
                .withMetricsHealthSnapshotIntervalInMilliseconds(1000);

    private final Callable<Object> callable;

    public NamedHystrixCommand(
        String metricName,
        Callable<Object> callable) {
        super(HystrixCommand.Setter
            .withGroupKey(GROUP_KEY)
            .andThreadPoolPropertiesDefaults(THREAD_POOL_PROPERTIES)
            .andCommandPropertiesDefaults(COMMAND_PROPERTIES)
            .andCommandKey(HystrixCommandKey.Factory.asKey(metricName)));
        this.callable = callable;
    }

    @Override
    protected Object run() throws Exception {
        return callable.call();
    }
}
```


问:
How do I add a border to a Collection View in Swift?
Not a collection view cell, I figured that out by applying specific border functions such as borderColor and cornerRadius methods in my ViewController. I'm talking about encapsulating the whole view of cells with one border, kind of like this:

Much appreciated.

答:
in your ViewDidLoad function, just add this type of line(choose your value).

```<code>collectionView.layer.borderColor = UIColor.green.cgColor
collectionView.layer.borderWidth = 3.0
collectionView.layer.cornerRadius = 3.0//if you want corner radius.addtional
</code>```

Body:
in your ViewDidLoad function, just add this type of line(choose your value).

collectionView.layer.borderColor = UIColor.green.cgColor
collectionView.layer.borderWidth = 3.0
collectionView.layer.cornerRadius = 3.0//if you want corner radius.addtional


问:
Do you recommend using semicolons after every statement in JavaScript?
In many situations, JavaScript parsers will insert semicolons for you if you leave them out. My question is, do you leave them out?

If you're unfamiliar with the rules, there's a description of semicolon insertion on the Mozilla site. Here's the key point:

If the first through the nth tokens of a JavaScript program form are grammatically valid but the first through the n+1st tokens are not and there is a line break between the nth tokens and the n+1st tokens, then the parser tries to parse the program again after inserting a virtual semicolon token between the nth and the n+1st tokens.

That description may be incomplete, because it doesn't explain @Dreas's example. Anybody have a link to the complete rules, or see why the example gets a semicolon? (I tried it in JScript.NET.)

This stackoverflow question is related, but only talks about a specific scenario.

答:
I use semicolon, since it is my habit.
Now I understand why I can't have string split into two lines... it puts semicolon at the end of each line.</p>

OwnerDisplayName: anon

LastEditorDisplayName: anon

OwnerDisplayName: Perime


问:
Change Network Settings in C
How change I change the network settings (IP address, DNS Server, Gateway, DHCP server) from C not C++, also preferably with windows api calls and not WMI.

Thanks!

答:
Check out the IP Helper API.

The Internet Protocol Helper (IP
  Helper) API enables the retrieval and
  modification of network configuration
  settings for the local computer.

Title: Change Network Settings in C


问:
How to use jQuery autocomplete multiple on a cloned form
I'm trying to use jQuery autocomplete to show a list of moderators under a comment form, which users can select to be notified about their comment.

The commenting system is nested, and when a user clicks "reply" on a previously existing comment, a clone of the main comment form is appended to that comment. Autocomplete works fine on the main comment form, but not on any cloned form. This is a simplified version of the code:

```<code><form id="myForm" action="submitComment.php" method="post"   onsubmit="event.preventDefault();" >
        <table>
            <tr>
                <th class="small"> Username </th>
                <th colspan="4">
                    <span>New Post</span><br/><br/>
                    <input name="subject" class="small"  value="" placeholder="Optional subject (25 char max)." />
                </th>
            </tr>
            <tr>
                <td>User Avatar</td>
                <td colspan="4" >
                    <strong>Body</strong>
                    <br/>
                    <br/>
                    <textarea name="body" rows="4" placeholder="Comment body." > </textarea>
                    <br/>
                    <br/>
                    <input name="alert" class="alert"  value="" placeholder="Notify mod(s) (Optional) "/>
                </td>
            </tr>
            <tr>
                <td></td>
                <td colspan="4" ><input id="submit" type="submit" name="submit" value="Submit"/></td>
            </tr>
        </table>
    </form>

    <div id="comments">

        <div id="comment 1" class="comment dark">
            <div class="comment-holder">
                <div class="body">Comment 1</div>
                <div class="meta">
                    USERNAME DATE <span class="reply"> REPLY</span>
                </div>
            </div>

        </div>

        <div id="comment 2" class="comment dark">
            <div class="comment-holder">
                <div class="body">Comment 2</div>
                <div class="meta">
                    USERNAME DATE <span class="reply"> REPLY</span>
                </div>
            </div>

        </div>
        <div class="spacer" style="clear: both;"></div>
    </div>

    <script>

        //Append Level 1 comment reply form
        $(document).on('click','.reply',function(e){
            if (e.target !== this)
                return;

            $(this).addClass("active");

            var form = $('#myForm').clone(true, true);
            var target = $(e.target);
            var isFormAvailable = $("#myForm", target).length > 0;
            var level = 2;

            if(!isFormAvailable) {
                $(e.target).append(form);
                $('textarea', form).focus();
                $(form).addClass("child");
                $(form).append("<span class=\"cancel\" style=\"color:red\">CANCEL</span>");
                $(".cancel").click(function(){
                    $(this).parents(".reply").removeClass("active");
                    $(this).closest(form).remove();
                });
            }
        });

        $( function() {
            var availableTags = [ "@user1", "@user2", "@user3"];
            function split( val ) {
              return val.split( /,\s*/ );
            }
            function extractLast( term ) {
              return split( term ).pop();
            }

            $( "body" )
              // don't navigate away from the field on tab when selecting an item
              .on( "keydown click", ".alert", function( event ) {
                if ( event.keyCode === $.ui.keyCode.TAB &&
                    $( this ).autocomplete( "instance" ).menu.active ) {
                  event.preventDefault();
                }
              })
              .autocomplete({
                minLength: 1,
                source: function( request, response ) {
                  // delegate back to autocomplete, but extract the last term
                  response( $.ui.autocomplete.filter(
                    availableTags, extractLast( request.term ) ) );
                },
                focus: function() {
                  // prevent value inserted on focus
                  return false;
                },
                select: function( event, ui ) {
                  var terms = split( this.value );
                  // remove the current input
                  terms.pop();
                  // add the selected item
                  terms.push( ui.item.value );
                  // add placeholder to get the comma-and-space at the end
                  terms.push( "" );
                  this.value = terms.join( ", " );
                  return false;
                }
              });
          } );
    </script>
</code>```

Fiddle: https://jsfiddle.net/crashTestDummy/gbLz53re/

答:
try to add autocomplete to the newly cloned elements.

source: https://forum.jquery.com/topic/autocomplete-to-new-appended-items

Body:
I'm trying to use jQuery autocomplete to show a list of moderators under a comment form, which users can select to be notified about their comment.

The commenting system is nested, and when a user clicks "reply" on a previously existing comment, a clone of the main comment form is appended to that comment. Autocomplete works fine on the main comment form, but not on any cloned form. This is a simplified version of the code:

<form id="myForm" action="submitComment.php" method="post"   onsubmit="event.preventDefault();" >

                 Username

                    New Post

                    <input name="subject" class="small"  value="" placeholder="Optional subject (25 char max)." />

                User Avatar

                    Body

                    <textarea name="body" rows="4" placeholder="Comment body." > </textarea>

                    <input name="alert" class="alert"  value="" placeholder="Notify mod(s) (Optional) "/>

                <input id="submit" type="submit" name="submit" value="Submit"/>

    </form>

Comment 1

                    USERNAME DATE  REPLY

Comment 2

                    USERNAME DATE  REPLY

Fiddle: https://jsfiddle.net/crashTestDummy/gbLz53re/


问:
Use a bash script/grep/sed in order to replace class names with the file name itself
I currently have a directory that contains numerous .java files, all with different names. ie. name.java, name2.java, name3.java

I am trying to write a script that loops through all of the files in the directory and changes their class names (inside the file) to match the file name itself.

Currently, all of the .java files contain the class name MyCritter. I want to change all instances of MyCritter in each of the files to the name of the particular java file itself. I wrote a script to try and replace all of the MyCritter terms, however I am getting no change in output. The code is getting frozen after printing the echo line for the first name of the file:

```<code>#!/bin/bash

dir1="/Users/path to folder"
subs=`ls $dir1`
for a in $subs;
do
  echo a
  [ -f "$a" ]
  grep -lr "MyCritter" * | xargs sed “s/MyCritter/$a/g”
done
</code>```

output to terminal: name.java --> then infinite loop/gets stuck

The above code prints the name of the first file in the directory once, but then gets stuck. When I change my second line to this: [ -f "$a" ] || continue  it runs through the whole code, but fails to update the files.

I've tried other variations of grep including:

```<code>grep -lr -e "MyCritter" * | xargs sed -i “s/MyCritter/$a/g”
grep -lr -e "MyCritter" . | xargs sed -i “s/MyCritter/$a/g”
grep -lr -e "MyCritter" . | xargs sed “s/MyCritter/$a/g”
</code>```

I was primarily using this site to guide me: http://isaacsukin.com/news/2013/06/command-line-tip-replace-word-all-files-directory

Any push in the right direction would be much appreciated!

答:
With GNU awk for inplace editing:

```<code>awk -i inplace '{gsub(/MyCritter/,FILENAME)} 1' *.java
</code>```

or if you want to strip off the ".java":

```<code>awk -i inplace 'FNR==1{f=FILENAME; sub(/\.java$/,"",f)} {gsub(/MyCritter/,f)} 1' *.java
</code>```

Body:
I currently have a directory that contains numerous .java files, all with different names. ie. name.java, name2.java, name3.java

I am trying to write a script that loops through all of the files in the directory and changes their class names (inside the file) to match the file name itself.

Currently, all of the .java files contain the class name MyCritter. I want to change all instances of MyCritter in each of the files to the name of the particular java file itself. I wrote a script to try and replace all of the MyCritter terms, however I am getting no change in output. The code is getting frozen after printing the echo line for the first name of the file:

#!/bin/bash

dir1="/Users/path to folder"
subs=`ls $dir1`
for a in $subs;
do
  echo a
  [ -f "$a" ]
  grep -lr "MyCritter" * | xargs sed “s/MyCritter/$a/g”
done

output to terminal: name.java --> then infinite loop/gets stuck

The above code prints the name of the first file in the directory once, but then gets stuck. When I change my second line to this: [ -f "$a" ] || continue  it runs through the whole code, but fails to update the files.

I've tried other variations of grep including:

grep -lr -e "MyCritter" * | xargs sed -i “s/MyCritter/$a/g”
grep -lr -e "MyCritter" . | xargs sed -i “s/MyCritter/$a/g”
grep -lr -e "MyCritter" . | xargs sed “s/MyCritter/$a/g”

I was primarily using this site to guide me: http://isaacsukin.com/news/2013/06/command-line-tip-replace-word-all-files-directory

Any push in the right direction would be much appreciated!

Body:
With GNU awk for inplace editing:

awk -i inplace '{gsub(/MyCritter/,FILENAME)} 1' *.java

or if you want to strip off the ".java":

awk -i inplace 'FNR==1{f=FILENAME; sub(/\.java$/,"",f)} {gsub(/MyCritter/,f)} 1' *.java


问:
Why is the big o of this function xn^2?
I have the following function:

```<code>public String joinWords(String[] words) {
  String sentence = "";
  for(String w : words) {
    sentence = sentence + w;
  }
}
</code>```

I am told this is a O(n^2)? Why is that? Is it not O(n) for having one loop?

答:
Loops with string concatenation are weird. The compiler can convert the concatenations to stringBuilders but not in loops as such, though this should be well within the realm of compiler ability.

The typical java compiler converts your statement to:

```<code>public String joinWords(String[] words) {
  String sentence = "";
  for(String w : words) {
    sentence = new StringBuilder().append(sentence).append(w).toString()
  }
}
</code>```

So each time it does this you still end up copying each digit to the new String.  Which is the source of the other loop.

You can obviously convert this to things like (in Android):

```<code>TextUtils.join("",words);
</code>```

Or the String.join() command in Java8. And there's more than a few useful ways to do this with streams. But, due to the internals yeah, that loops going to be O(N^2).

Obviously:

```<code>public String joinWords(String[] words) {
      String sentence = "";
      StringBuilder sb = new StringBuilder();
      for(String w : words) {
          sb.append(w);
      }
      return sb.toString();
}
</code>```

Fixes it too.

The extra loop doesn't need to be there. But with string concatenation in a loop it is.

Title: Why is the big o of this function xn^2?

Body:
I have the following function:

public String joinWords(String[] words) {
  String sentence = "";
  for(String w : words) {
    sentence = sentence + w;
  }
}

I am told this is a O(n^2)? Why is that? Is it not O(n) for having one loop?

Body:
Loops with string concatenation are weird. The compiler can convert the concatenations to stringBuilders but not in loops as such, though this should be well within the realm of compiler ability.

The typical java compiler converts your statement to:

public String joinWords(String[] words) {
  String sentence = "";
  for(String w : words) {
    sentence = new StringBuilder().append(sentence).append(w).toString()
  }
}

So each time it does this you still end up copying each digit to the new String.  Which is the source of the other loop.

You can obviously convert this to things like (in Android):

TextUtils.join("",words);

Or the String.join() command in Java8. And there's more than a few useful ways to do this with streams. But, due to the internals yeah, that loops going to be O(N^2).

Obviously:

public String joinWords(String[] words) {
      String sentence = "";
      StringBuilder sb = new StringBuilder();
      for(String w : words) {
          sb.append(w);
      }
      return sb.toString();
}

Fixes it too.

The extra loop doesn't need to be there. But with string concatenation in a loop it is.


答:
you should check if the length is 6 or not. Also, you can add more check, if the users use backspace on the 6th character, it would also delete the '-' character

```<code>$(".zip-val").keyup(function(e) {
    if(e.keyCode == 8)
    {
        if($(this).val().length == 6){
        var newText = $(this).val().substring(0 , 5);
        $(this).val(newText);
      }
    }
    else if($(this).val().length == 6) {
        var newText = $(this).val().substring(0 , 5) + '-' + $(this).val().substring(5);
        $(this).val(newText);
    }
});
</code>```

demo : https://jsfiddle.net/sn5ghvb8/

Body:
I am trying to format a US zip code as the user types, and need to add a dash between the 5th and and 6th characters if the user types more than 5 so the the zip code is formatted like

55555 or 55555-5555

what I have now adds a dash, but regardless if a 6th number is added

//zip code formatting
$(".zip-val").keyup(function() {
    if($(this).val().length == 5) {
        $(this).val($(this).val() + "-");
    }
});

Body:
you should check if the length is 6 or not. Also, you can add more check, if the users use backspace on the 6th character, it would also delete the '-' character

$(".zip-val").keyup(function(e) {
    if(e.keyCode == 8)
    {
        if($(this).val().length == 6){
        var newText = $(this).val().substring(0 , 5);
        $(this).val(newText);
      }
    }
    else if($(this).val().length == 6) {
        var newText = $(this).val().substring(0 , 5) + '-' + $(this).val().substring(5);
        $(this).val(newText);
    }
});

demo : https://jsfiddle.net/sn5ghvb8/


问:
Unable to resolve org.scalatest#scalatest;3.0.1: not found dependency issue
Newbie in scala here, going through a scala tutorial.

I am trying to use scalatest as mentioned in the tutorial but getting this error:

```<code>[error] (*:update) sbt.ResolveException: unresolved dependency: org.scalatest#scalatest;3.0.1: not found

> scalaVersion
[info] 2.10.6
</code>```

My build.sbt file looks like this:

```<code>name := "tasky"
version := "0.1.0"
libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.1"
libraryDependencies += "org.scalatest" % "scalatest" % "3.0.1" % "test"
</code>```

Also as mentioned here, I have created the global.sbt and plugins.sbt file at the respective locations with the required details. But, I am still getting the error:

```<code>[info] Updating {file:/home/tushar/lsbt/tasky/}tasky...
[info] Resolving org.scalatest#scalatest;3.0.1 ...
[warn]  module not found: org.scalatest#scalatest;3.0.1
[warn] ==== local: tried
[warn]   /home/tushar/.ivy2/local/org.scalatest/scalatest/3.0.1/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/scalatest/scalatest/3.0.1/scalatest-3.0.1.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /home/tushar/.sbt/preloaded/org.scalatest/scalatest/3.0.1/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////home/tushar/.sbt/preloaded/org/scalatest/scalatest/3.0.1/scalatest-3.0.1.pom
[warn] ==== Artima Maven Repository: tried
[warn]   http://repo.artima.com/releases/org/scalatest/scalatest/3.0.1/scalatest-3.0.1.pom
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.scalatest#scalatest;3.0.1: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]
[warn]  Note: Unresolved dependencies path:
[warn]      org.scalatest:scalatest:3.0.1 (/home/tushar/lsbt/tasky/built.sbt#L4-5)
[warn]        +- default:tasky_2.10:0.1.0
[trace] Stack trace suppressed: run last *:update for the full output.
[error] (*:update) sbt.ResolveException: unresolved dependency: org.scalatest#scalatest;3.0.1: not found
</code>```

Any pointers to resolve this issue?

答:
you should use %% instead of a single % as shown below. the %% changes the artifact from scalatest to scalatest_2.10 since the version of scala used in the project is 2.10.

```<code>libraryDependencies +=  "org.scalatest" %% "scalatest" % "3.0.1" % "test"
</code>```

You can either use %% or specify the artifact_id explicitly as below

```<code>libraryDependencies +=  "org.scalatest" % "scalatest_2.10" % "3.0.1" % "test"
</code>```

the former approach is recommended over the later.

Explanation

Scala's minor version's are not backward compatible. so a library compiled with 2.10 version cannot be used in a project using scala 2.11. So a library has to be published by compiling it for each versions separately (2.10, 2.11 and 2.12 for eg).

thus all Scala artifacts are published with scala version suffixed at the end. Thus scalatest has a artifact scalatest_2.10,scalatest_2.11 and scalatest_2.12.

In order to make it easier to select the right version of the artifact in your SBT build depending on your scala version , SBT provides a convient symbol %% that will change the artifact id by appending the scala version for you. Thus if "org.scalatest" %% "scalatest" % "3.0.1" would translate to org.scalatest#scalatest_2.10;3.0.1 on your build dynamically.

Body:
Newbie in scala here, going through a scala tutorial.

I am trying to use scalatest as mentioned in the tutorial but getting this error:

[error] (*:update) sbt.ResolveException: unresolved dependency: org.scalatest#scalatest;3.0.1: not found

> scalaVersion
[info] 2.10.6

My build.sbt file looks like this:

name := "tasky"
version := "0.1.0"
libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.1"
libraryDependencies += "org.scalatest" % "scalatest" % "3.0.1" % "test"

Also as mentioned here, I have created the global.sbt and plugins.sbt file at the respective locations with the required details. But, I am still getting the error:

[info] Updating {file:/home/tushar/lsbt/tasky/}tasky...
[info] Resolving org.scalatest#scalatest;3.0.1 ...
[warn]  module not found: org.scalatest#scalatest;3.0.1
[warn] ==== local: tried
[warn]   /home/tushar/.ivy2/local/org.scalatest/scalatest/3.0.1/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/scalatest/scalatest/3.0.1/scalatest-3.0.1.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /home/tushar/.sbt/preloaded/org.scalatest/scalatest/3.0.1/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////home/tushar/.sbt/preloaded/org/scalatest/scalatest/3.0.1/scalatest-3.0.1.pom
[warn] ==== Artima Maven Repository: tried
[warn]   http://repo.artima.com/releases/org/scalatest/scalatest/3.0.1/scalatest-3.0.1.pom
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.scalatest#scalatest;3.0.1: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]
[warn]  Note: Unresolved dependencies path:
[warn]      org.scalatest:scalatest:3.0.1 (/home/tushar/lsbt/tasky/built.sbt#L4-5)
[warn]        +- default:tasky_2.10:0.1.0
[trace] Stack trace suppressed: run last *:update for the full output.
[error] (*:update) sbt.ResolveException: unresolved dependency: org.scalatest#scalatest;3.0.1: not found

Any pointers to resolve this issue?

Body:
you should use %% instead of a single % as shown below. the %% changes the artifact from scalatest to scalatest_2.10 since the version of scala used in the project is 2.10.

libraryDependencies +=  "org.scalatest" %% "scalatest" % "3.0.1" % "test"

You can either use %% or specify the artifact_id explicitly as below

libraryDependencies +=  "org.scalatest" % "scalatest_2.10" % "3.0.1" % "test"

the former approach is recommended over the later.

Explanation

Scala's minor version's are not backward compatible. so a library compiled with 2.10 version cannot be used in a project using scala 2.11. So a library has to be published by compiling it for each versions separately (2.10, 2.11 and 2.12 for eg).

thus all Scala artifacts are published with scala version suffixed at the end. Thus scalatest has a artifact scalatest_2.10,scalatest_2.11 and scalatest_2.12.

In order to make it easier to select the right version of the artifact in your SBT build depending on your scala version , SBT provides a convient symbol %% that will change the artifact id by appending the scala version for you. Thus if "org.scalatest" %% "scalatest" % "3.0.1" would translate to org.scalatest#scalatest_2.10;3.0.1 on your build dynamically.


问:
Is it possible to write xml into json object?
I'm having issues in javascript with putting a var that contains xml string into a object and then send it via ajax with jQuery.

The question would be: is it possible to have a xml string into a json object ?

```<code>{"a":"a","b":"b", "xml":"<test r='r'></test>"}
</code>```

Thanks in advance

答:
Your XML will be like this:

```<code>< test r="r"> </test>
</code>```

Replace as follows:

```<code>& = &

" = "

' = '

< = <

> = >

/ = /
</code>```

Body:
I'm having issues in javascript with putting a var that contains xml string into a object and then send it via ajax with jQuery.

The question would be: is it possible to have a xml string into a json object ?

{"a":"a","b":"b", "xml":"<test r='r'></test>"}

Thanks in advance

Body:
Your XML will be like this:

&lt; test r=&quot;r&quot;&gt; &lt;&#x2F;test&gt;

Replace as follows:

& = &amp;

" = &quot;

' = &#39;

< = &lt;

> = &gt;

/ = &#x2F;


问:
IndexError: list index out of range python sorting array
i write this code to sort the element of an array but iam getting this error
    line 9, in
    if(a[i]>a[j]):
    IndexError: list index out of range
    the same logic for sorting array elements work with java or c correctly.
     help me to find why this is happening in python .
     is this due to python syntax or another</p>

```<code>from array import *
a=[]
n=int(input("enter number of elements:"))
for i in range(0,n):
    b=input("enter element")
    a.append(b)
for i in range(0,n):
    for j in range(i+1,n):
        if(a[i]>a[j]):
            temp=a[i]
            a[i]=a[j]
            a[j]=temp
print("sorted")
for i in range(0,n-1):
    print(a[i])
    print(a[n-1])
</code>```

答:
first you don't need to write list sort method yourself python does it for you. and second no need of third temporary variable to swap value between two variable in python simply a,b=b,a will swap value between a and b

```<code>a=[1,5,4,7,8,3,5,4]
for i in range(len(a)):
    for j in range(i+1,len(a)):
        if a[i]>a[j]:
            a[i],a[j]=a[j],a[i]

print(a)
</code>```

the above code works sorts in ascending order.
for descending order change the > to <.
it is better to use builtin list sort methods and sorted function to sort any list.

Body:
i write this code to sort the element of an array but iam getting this error
    line 9, in
    if(a[i]>a[j]):
    IndexError: list index out of range
    the same logic for sorting array elements work with java or c correctly.
     help me to find why this is happening in python .
     is this due to python syntax or another

from array import *
a=[]
n=int(input("enter number of elements:"))
for i in range(0,n):
    b=input("enter element")
    a.append(b)
for i in range(0,n):
    for j in range(i+1,n):
        if(a[i]>a[j]):
            temp=a[i]
            a[i]=a[j]
            a[j]=temp
print("sorted")
for i in range(0,n-1):
    print(a[i])
    print(a[n-1])

Body:
first you don't need to write list sort method yourself python does it for you. and second no need of third temporary variable to swap value between two variable in python simply a,b=b,a will swap value between a and b

a=[1,5,4,7,8,3,5,4]
for i in range(len(a)):
    for j in range(i+1,len(a)):
        if a[i]>a[j]:
            a[i],a[j]=a[j],a[i]

print(a)

the above code works sorts in ascending order.
for descending order change the > to <.
it is better to use builtin list sort methods and sorted function to sort any list.


问:
mget cannot get primitive function like get
I can use get to get primitive function, like:

```<code>get('$')
.Primitive("$")
</code>```

However, mget failed:

```<code>mget('$')
Error: value for ‘$’ not found
</code>```

Why? How to fix this?

答:
The default for get is to use inherits = TRUE (I think, based on the docs, for historical reasons), while the default for mget is inherits = FALSE. So using inherits = TRUE should make it work like get.

If you'd like a really detailed (but also very very good) dive into exactly what's happening here read this. Or just skip to the "Map of the World" section, and remember that $, being a primitive function, is in the environment of the of the base namespace (package:base, essentially).

Body:
I can use get to get primitive function, like:

get('$')
.Primitive("$")

However, mget failed:

mget('$')
Error: value for ‘$’ not found

Why? How to fix this?


问:
Active clickable area for UIButton with rounded corners?
So I have created a button with a border in my storyboard.

and then I rounded its corners and added a border color:

```<code>button.layer.cornerRadius = button.bounds.size.width / 2
button.layer.borderColor = greenColor
</code>```

So the runtime result looks like this:

However the user can tap slightly outside the area of the button (where the corners used to be) and still call the button function. Is there a way to restrict the enabled area of the button to just be the circle?

答:
With other answers you block the touch, I needed it to fall through.
And its even easier:

1) Setup your preferred path (for me circle)

```<code>private var touchPath: UIBezierPath {return UIBezierPath(ovalIn: self.bounds)}
</code>```

2) Override point inside function

```<code>override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    return touchPath.contains(point)
}
</code>```

All inside you UIButton subclass.

Body:
So I have created a button with a border in my storyboard.

and then I rounded its corners and added a border color:

button.layer.cornerRadius = button.bounds.size.width / 2
button.layer.borderColor = greenColor

So the runtime result looks like this:

However the user can tap slightly outside the area of the button (where the corners used to be) and still call the button function. Is there a way to restrict the enabled area of the button to just be the circle?

Body:
With other answers you block the touch, I needed it to fall through.
And its even easier:

1) Setup your preferred path (for me circle)

private var touchPath: UIBezierPath {return UIBezierPath(ovalIn: self.bounds)}

2) Override point inside function

override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    return touchPath.contains(point)
}

All inside you UIButton subclass.


问:
implement file data and using Dijkstra function to work in python
I created a function by using dijkstra module to work on map shortest path.
And now, I'm trying to implement a file data and use that function to work on it.

Here is my function code:

```<code>nodes = {'A', 'B', 'C', 'D', 'E'}

edges = [('A', 'B', 3), ('B', 'A', 3), ('A', 'C', 5), ('C', 'A', 5),
         ('A', 'E', 2), ('E', 'A', 2), ('B', 'D', 2), ('D', 'B', 2),
         ('D', 'C', 1), ('C', 'D', 1), ('C', 'E', 2), ('E', 'C', 2),
         ('D', 'E', 4), ('E', 'D', 4)]

g = (nodes, edges)
src = 'D'

prev, dist = dijkstra(g, src)
</code>```

And here is my file data:

```<code>4 5 0.35
5 4 0.35
4 7 0.37
5 7 0.28
7 5 0.28
5 1 0.32
0 4 0.38
0 2 0.26
7 3 0.39
1 3 0.29
2 7 0.34
6 2 0.40
3 6 0.52
6 0 0.58
6 4 0.93
</code>```

How to implement the file and replace the nodes and edges by the data of the file?

答:
```<code>nodes = set()
edges = list()
f = open('data.txt')
for line in f:
    node_1, node_2, length = line.split()
    nodes.add(node_1)
    nodes.add(node_2)
    edges.append((node_1, node_2, length))
</code>```

will do the trick.

Body:
I created a function by using dijkstra module to work on map shortest path.
And now, I'm trying to implement a file data and use that function to work on it.

Here is my function code:

nodes = {'A', 'B', 'C', 'D', 'E'}

edges = [('A', 'B', 3), ('B', 'A', 3), ('A', 'C', 5), ('C', 'A', 5),
         ('A', 'E', 2), ('E', 'A', 2), ('B', 'D', 2), ('D', 'B', 2),
         ('D', 'C', 1), ('C', 'D', 1), ('C', 'E', 2), ('E', 'C', 2),
         ('D', 'E', 4), ('E', 'D', 4)]

g = (nodes, edges)
src = 'D'

prev, dist = dijkstra(g, src)

And here is my file data:

4 5 0.35
5 4 0.35
4 7 0.37
5 7 0.28
7 5 0.28
5 1 0.32
0 4 0.38
0 2 0.26
7 3 0.39
1 3 0.29
2 7 0.34
6 2 0.40
3 6 0.52
6 0 0.58
6 4 0.93

How to implement the file and replace the nodes and edges by the data of the file?

Body:
nodes = set()
edges = list()
f = open('data.txt')
for line in f:
    node_1, node_2, length = line.split()
    nodes.add(node_1)
    nodes.add(node_2)
    edges.append((node_1, node_2, length))

will do the trick.


问:
Codename One:SIM detection and sms reading through app
I want to detect SIM card and read messages like OTP messages through my app in codename one. I just created the app using codename one and I want above features in my app.

Is it possible using codename one? If yes, how?

答: You can do these with native interfaces on Android but those things are impossible on other platforms since they aren't supported natively. </p>


问:
Fetch data from MySQL DB with Drupal for AngularJS
Good evening!

I have a problem with fetching data from DB.

There are the project Drupal+AngularJS.

Without the Drupal I was able to get the data from MySQL with PHP for Angular:
in the file index.php:
`...

```<code>var app = angular.module("myapp", []);
    app.controller("usercontroller", function ($scope, $http) {
        $scope.displayData = function () {
            $http.get("select.php")
                .success(function (data) {
                    $scope.names = data;
                });
        }
    });`
</code>```

and in the file select.php:

```<code><?php
//select.php

$connect = mysqli_connect("localhost", "root", "root", "testing");
$output = array();

$query = "SELECT * FROM tbl_user";

$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0) {

    while($row = mysqli_fetch_array($result))
    {
        $output[] = $row;
    }
    echo json_encode($output);
}

?>
</code>```

But, how can I do it WITH Drupal? How can I create the page like select.php?
I don't understand, help me please ))

Thank you all!

答: You can use a module like https://www.drupal.org/project/services, also check about the Drupal headless</p>

Body:
Good evening!

I have a problem with fetching data from DB.

There are the project Drupal+AngularJS.

Without the Drupal I was able to get the data from MySQL with PHP for Angular:
in the file index.php:
`...

var app = angular.module("myapp", []);
    app.controller("usercontroller", function ($scope, $http) {
        $scope.displayData = function () {
            $http.get("select.php")
                .success(function (data) {
                    $scope.names = data;
                });
        }
    });`

and in the file select.php:

<?php
//select.php

$connect = mysqli_connect("localhost", "root", "root", "testing");
$output = array();

$query = "SELECT * FROM tbl_user";

$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0) {

    while($row = mysqli_fetch_array($result))
    {
        $output[] = $row;
    }
    echo json_encode($output);
}

?>

But, how can I do it WITH Drupal? How can I create the page like select.php?
I don't understand, help me please ))

Thank you all!


问:
Simple jQuery problem
This one should be easy

I've got this HTML

```<code><table class="PageNumbers">
<tr>
    <td colspan="3">text3
    </td>
</tr>
<tr>
    <td colspan="2">text
    </td>
    <td>text2
    </td>
</tr>
<tr>
    <td>moretext
    </td>
    <td>moretext2
    </td>
<td>moretext3
    </td>
</tr>
</table>
</code>```

I need to change the colspan of the first rows first column to one

This is what i've got

```<code>$('.PageNumbers tr:first td:first').attr('colspan') = '1'
</code>```

Doesn't seem to work though

Any ideas?

Thanks

答:
You can use this selector:

```<code>$('table.PageNumbers > tr:first > td:first').attr('colspan', '1');
</code>```

Check out the jQuery selectors for more information :)

Title: Simple jQuery problem

Body:
This one should be easy

I've got this HTML

    text3

    text

    text2

    moretext

    moretext2

moretext3

I need to change the colspan of the first rows first column to one

This is what i've got

$('.PageNumbers tr:first td:first').attr('colspan') = '1'

Doesn't seem to work though

Any ideas?

Thanks

Body:
You can use this selector:

$('table.PageNumbers > tr:first > td:first').attr('colspan', '1');

Check out the jQuery selectors for more information :)


问:
How To Set Sources For Jupyter Notebooks
I've just bought a new computer, and can't remember/don't know how I had Jupyter notebooks set up on my old machine. Specifically, how do you tell Jupyter about sources.

If I have a conda environment called django, and I do source activate django followed by jupyter notebook, I end up with a notebook, but then when I do from django.http import HttpResponse I get the error message

```<code>ModuleNotFoundError: No module named 'django'
</code>```

Which is bizarre (I think), because Django is definitely installed in the Django environment.

How do I set up my Jupyter notebooks so that they know about the various sources that I want them to know about?

答:
It is very likely your conda environment django doesn't have iPython Kernel installed which jupyter notebook needs. You can run jupyter notebook without activating a conda environment as notebook allows you to select any conda environment with ipykernel installed.

Try:

run in terminal : source activate django

run in terminal : conda install ipykernel

run in terminal : source deactivate

run in terminal : jupyter notebook

select django for your kernel

Body:
I've just bought a new computer, and can't remember/don't know how I had Jupyter notebooks set up on my old machine. Specifically, how do you tell Jupyter about sources.

If I have a conda environment called django, and I do source activate django followed by jupyter notebook, I end up with a notebook, but then when I do from django.http import HttpResponse I get the error message

ModuleNotFoundError: No module named 'django'

Which is bizarre (I think), because Django is definitely installed in the Django environment.

How do I set up my Jupyter notebooks so that they know about the various sources that I want them to know about?


问:
Using std::map to find duplicates in data and its performance issue. Can I pre-allocate it?
My goal is to check for duplicate IDs in my custom data structure. I'm coding it with Visual Studio 2008 Sp1. So I wrote the following debugger-only function that does "sanity checks" on the data as I work with the code.

I'm using the following approach:

I enumerate through all elements in my data structure (which by itself is relatively fast.)

I then use std::map to collect IDs of all elements as keys, while I make the value part point to the data structure element itself (which will help me quickly identify the duplicate.)

For each element in my data structure I see if its ID is in my std::map, and if so, the function asserts. Otherwise it adds it to the map.

Here's a pseudo-code for that:

```<code>std::map<ULONGLONG, BIN_XML_TAG*> dicTagIDs;

for(std::vector<MY_ELEMENT>::const_iterator iTag = arrNode.begin(); iTag != arrNode.end(); ++iTag)
{
    std::map<ULONGLONG, MY_ELEMENT*>::const_iterator itrT = dicTagIDs.find(iTag->uiTagID);
    if(itrT != dicTagIDs.end())
    {
        //Duplicate tag ID!
        MY_ELEMENT* pDuplicateToTag = itrT->second;
        ASSERT(NULL);
    }

    //If not, then add it
    dicTagIDs[iTag->uiTagID] = iTag._Myptr;

    //... may later call itself recursively
}
</code>```

This works, except that the function above gets exponentially slower as the size of my data structure grows. And since I use it everywhere throughout my "debugger-build" code, it'd be nice to speed it up.

So I was thinking to pre-allocate std::map. I don't know the exact number of elements in my data structure (it is structured kinda like an XML file) but I can make an approximate guess that I could use for preallocation.

But std::map doesn't seem to provide a reserve() method.

So any suggestions how to speed this up?

答:
Map uses a tree so keys can be traversed in sorted order, so insertion and lookup both occur in lg(n) time.  Additionally, insertion can trigger rebalancing the tree.  An unordered map uses a hash table, which allows for constant time insertion and lookup, at the cost of traversing the keys.  Here is an interesting performance study similar to your use case.

As some have pointed out, you may not have access to unordered maps in VS2008.  You could get some of the benefit by using a hash table of your own: just use an array of H maps, and lookup/insert to the array using modulo H.  The average depth of the trees underlying the maps will decrease by lg(H), and rebalances should be less costly as well.  Example:

```<code>std::map<int, int> dicts[HASHKEY]; // array of H maps
dicts[id % HASHKEY][id] = whatever; // insertion
auto it = dicts[id % HASHKEY].find(id); // lookup
</code>```

Here is some example code that demonstrates the speedup:

```<code>#include <cstdlib>
#include <random>
#include <vector>
#include <map>
#include <iostream>
#include <ctime>
#include <cassert>

#define MAX_HASH 16384

int main() {
    unsigned int nIDs = 1 << 21;
    std::vector<int> IDs(nIDs);

    // random fill
    std::random_device rnd;
    std::mt19937 mersenne_engine(rnd());
    std::uniform_int_distribution<int> dist(0, nIDs); // get some collisions
    auto gen = std::bind(dist, mersenne_engine);
    generate(begin(IDs), end(IDs), gen);

    std::map<int, int> dicts[MAX_HASH];

    // time insertion into 1..MAX_HASH maps
    for (unsigned int hash = 1; hash <= MAX_HASH; hash <<= 1) {
        for (unsigned int i = 0; i < hash; ++i)
            dicts[i].clear();

        // time simple insertion/overwrite
        clock_t start = clock();

        for (unsigned int i = 0; i < nIDs; ++i) {
            int id = IDs[i];
            dicts[id % hash][id] = 1;
        }

        double insert_elapsed = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;

        // time lookup
        // shuffle the vector to avoid optimal lookups
        std::shuffle(begin(IDs), end(IDs), mersenne_engine);
        start = clock();

        for (unsigned int i = 0; i < nIDs; ++i) {
            int id = IDs[i];
            auto it = dicts[id % hash].find(id);
            assert(it->second == 1);
        }

        double lookup_elapsed = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;

        // time lookup+insertion
        for (unsigned int i = 0; i < hash; ++i)
            dicts[i].clear();

        start = clock();

        for (unsigned int i = 0; i < nIDs; ++i) {
            int id = IDs[i];
            unsigned int dnum = id % hash;
            auto it = dicts[dnum].find(id);

            if (it == dicts[dnum].end())
                dicts[dnum][id] = 1;
        }

        double cond_elapsed = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;

        printf("%5d maps, avg. %7ld keys - lookup: %1.3f, lookup: %1.3f, conditional insert: %1.3f\n",
            hash, IDs.size()/hash, insert_elapsed, lookup_elapsed, cond_elapsed);
    }
}
</code>```

Output:

```<code>    1 maps, avg. 2097152 keys - insert: 1.958, lookup: 2.010, conditional insert: 2.473
    2 maps, avg. 1048576 keys - insert: 1.956, lookup: 1.988, conditional insert: 2.390
    4 maps, avg.  524288 keys - insert: 1.911, lookup: 1.982, conditional insert: 2.416
    8 maps, avg.  262144 keys - insert: 1.848, lookup: 1.956, conditional insert: 2.407
   16 maps, avg.  131072 keys - insert: 1.846, lookup: 1.973, conditional insert: 2.312
   32 maps, avg.   65536 keys - insert: 1.814, lookup: 1.882, conditional insert: 2.303
   64 maps, avg.   32768 keys - insert: 1.796, lookup: 1.973, conditional insert: 2.258
  128 maps, avg.   16384 keys - insert: 1.807, lookup: 1.879, conditional insert: 2.250
  256 maps, avg.    8192 keys - insert: 1.785, lookup: 1.849, conditional insert: 2.158
  512 maps, avg.    4096 keys - insert: 1.731, lookup: 1.820, conditional insert: 2.229
 1024 maps, avg.    2048 keys - lookup: 1.743, lookup: 1.787, conditional insert: 2.050
 2048 maps, avg.    1024 keys - lookup: 1.614, lookup: 1.709, conditional insert: 1.993
 4096 maps, avg.     512 keys - lookup: 1.628, lookup: 1.638, conditional insert: 1.963
 8192 maps, avg.     256 keys - lookup: 1.549, lookup: 1.568, conditional insert: 1.803
16384 maps, avg.     128 keys - lookup: 1.468, lookup: 1.474, conditional insert: 1.688
</code>```

As you can see, the performance gets better as the number of maps increases, at the cost of more memory allocated to the map objects.

Body:
My goal is to check for duplicate IDs in my custom data structure. I'm coding it with Visual Studio 2008 Sp1. So I wrote the following debugger-only function that does "sanity checks" on the data as I work with the code.

I'm using the following approach:

I enumerate through all elements in my data structure (which by itself is relatively fast.)

I then use std::map to collect IDs of all elements as keys, while I make the value part point to the data structure element itself (which will help me quickly identify the duplicate.)

For each element in my data structure I see if its ID is in my std::map, and if so, the function asserts. Otherwise it adds it to the map.

Here's a pseudo-code for that:

std::map<ULONGLONG, BIN_XML_TAG*> dicTagIDs;

for(std::vector<MY_ELEMENT>::const_iterator iTag = arrNode.begin(); iTag != arrNode.end(); ++iTag)
{
    std::map<ULONGLONG, MY_ELEMENT*>::const_iterator itrT = dicTagIDs.find(iTag->uiTagID);
    if(itrT != dicTagIDs.end())
    {
        //Duplicate tag ID!
        MY_ELEMENT* pDuplicateToTag = itrT->second;
        ASSERT(NULL);
    }

    //If not, then add it
    dicTagIDs[iTag->uiTagID] = iTag._Myptr;

    //... may later call itself recursively
}

This works, except that the function above gets exponentially slower as the size of my data structure grows. And since I use it everywhere throughout my "debugger-build" code, it'd be nice to speed it up.

So I was thinking to pre-allocate std::map. I don't know the exact number of elements in my data structure (it is structured kinda like an XML file) but I can make an approximate guess that I could use for preallocation.

But std::map doesn't seem to provide a reserve() method.

So any suggestions how to speed this up?

Body:
Map uses a tree so keys can be traversed in sorted order, so insertion and lookup both occur in lg(n) time.  Additionally, insertion can trigger rebalancing the tree.  An unordered map uses a hash table, which allows for constant time insertion and lookup, at the cost of traversing the keys.  Here is an interesting performance study similar to your use case.

As some have pointed out, you may not have access to unordered maps in VS2008.  You could get some of the benefit by using a hash table of your own: just use an array of H maps, and lookup/insert to the array using modulo H.  The average depth of the trees underlying the maps will decrease by lg(H), and rebalances should be less costly as well.  Example:

std::map<int, int> dicts[HASHKEY]; // array of H maps
dicts[id % HASHKEY][id] = whatever; // insertion
auto it = dicts[id % HASHKEY].find(id); // lookup

Here is some example code that demonstrates the speedup:

#include <cstdlib>
#include <random>
#include <vector>
#include <map>
#include <iostream>
#include <ctime>
#include <cassert>

#define MAX_HASH 16384

int main() {
    unsigned int nIDs = 1 << 21;
    std::vector<int> IDs(nIDs);

    // random fill
    std::random_device rnd;
    std::mt19937 mersenne_engine(rnd());
    std::uniform_int_distribution<int> dist(0, nIDs); // get some collisions
    auto gen = std::bind(dist, mersenne_engine);
    generate(begin(IDs), end(IDs), gen);

    std::map<int, int> dicts[MAX_HASH];

    // time insertion into 1..MAX_HASH maps
    for (unsigned int hash = 1; hash <= MAX_HASH; hash <<= 1) {
        for (unsigned int i = 0; i < hash; ++i)
            dicts[i].clear();

        // time simple insertion/overwrite
        clock_t start = clock();

        for (unsigned int i = 0; i < nIDs; ++i) {
            int id = IDs[i];
            dicts[id % hash][id] = 1;
        }

        double insert_elapsed = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;

        // time lookup
        // shuffle the vector to avoid optimal lookups
        std::shuffle(begin(IDs), end(IDs), mersenne_engine);
        start = clock();

        for (unsigned int i = 0; i < nIDs; ++i) {
            int id = IDs[i];
            auto it = dicts[id % hash].find(id);
            assert(it->second == 1);
        }

        double lookup_elapsed = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;

        // time lookup+insertion
        for (unsigned int i = 0; i < hash; ++i)
            dicts[i].clear();

        start = clock();

        for (unsigned int i = 0; i < nIDs; ++i) {
            int id = IDs[i];
            unsigned int dnum = id % hash;
            auto it = dicts[dnum].find(id);

            if (it == dicts[dnum].end())
                dicts[dnum][id] = 1;
        }

        double cond_elapsed = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;

        printf("%5d maps, avg. %7ld keys - lookup: %1.3f, lookup: %1.3f, conditional insert: %1.3f\n",
            hash, IDs.size()/hash, insert_elapsed, lookup_elapsed, cond_elapsed);
    }
}

Output:

    1 maps, avg. 2097152 keys - insert: 1.958, lookup: 2.010, conditional insert: 2.473
    2 maps, avg. 1048576 keys - insert: 1.956, lookup: 1.988, conditional insert: 2.390
    4 maps, avg.  524288 keys - insert: 1.911, lookup: 1.982, conditional insert: 2.416
    8 maps, avg.  262144 keys - insert: 1.848, lookup: 1.956, conditional insert: 2.407
   16 maps, avg.  131072 keys - insert: 1.846, lookup: 1.973, conditional insert: 2.312
   32 maps, avg.   65536 keys - insert: 1.814, lookup: 1.882, conditional insert: 2.303
   64 maps, avg.   32768 keys - insert: 1.796, lookup: 1.973, conditional insert: 2.258
  128 maps, avg.   16384 keys - insert: 1.807, lookup: 1.879, conditional insert: 2.250
  256 maps, avg.    8192 keys - insert: 1.785, lookup: 1.849, conditional insert: 2.158
  512 maps, avg.    4096 keys - insert: 1.731, lookup: 1.820, conditional insert: 2.229
 1024 maps, avg.    2048 keys - lookup: 1.743, lookup: 1.787, conditional insert: 2.050
 2048 maps, avg.    1024 keys - lookup: 1.614, lookup: 1.709, conditional insert: 1.993
 4096 maps, avg.     512 keys - lookup: 1.628, lookup: 1.638, conditional insert: 1.963
 8192 maps, avg.     256 keys - lookup: 1.549, lookup: 1.568, conditional insert: 1.803
16384 maps, avg.     128 keys - lookup: 1.468, lookup: 1.474, conditional insert: 1.688

As you can see, the performance gets better as the number of maps increases, at the cost of more memory allocated to the map objects.


问:
How to send notification between two application
I want to send push notification from Device "A" with Application "A" to Device "B" with application "B" how I can achieve that?

Any help will be appreciated.

can I use firebase with that?

With parse I can define that with number like :

```<code>ParseQuery query = ParseInstallation.getQuery();
query.whereEqualTo("phone", "1234567890");
ParsePush push = new ParsePush();
push.setQuery(query);
push.sendPushInBackground();
</code>```

how can I achieve that in other cases ?

答:
You'd probably have to go with something like this:

Create two separate Firebase Projects for each app with FCM enabled. (Project A and B)

Implement FCM for both Apps and generate tokens for each project to both apps (i.e. App A has tokenA and tokenB, App B has tokenC and tokenD). See my answer here.

Store the tokens to the corresponding servers.

From there, the flow of interaction should be something like:

```<code>App A > sends data > Server A // (contains App B's tokenC)
Server A > sends notification > App B // (by using tokenC)
</code>```

and vice versa:

```<code>App B > sends data > Server B // (contains App A's tokenB)
Server B > sends notification > App A // (by using tokenB)
</code>```

That's pretty much the general idea.

With all that said, "how can I achieve that in other cases?" is too broad of a question.

Body:
I want to send push notification from Device "A" with Application "A" to Device "B" with application "B" how I can achieve that?

Any help will be appreciated.

can I use firebase with that?

With parse I can define that with number like :

ParseQuery query = ParseInstallation.getQuery();
query.whereEqualTo("phone", "1234567890");
ParsePush push = new ParsePush();
push.setQuery(query);
push.sendPushInBackground();

how can I achieve that in other cases ?

Body:
You'd probably have to go with something like this:

Create two separate Firebase Projects for each app with FCM enabled. (Project A and B)

Implement FCM for both Apps and generate tokens for each project to both apps (i.e. App A has tokenA and tokenB, App B has tokenC and tokenD). See my answer here.

Store the tokens to the corresponding servers.

From there, the flow of interaction should be something like:

App A > sends data > Server A // (contains App B's tokenC)
Server A > sends notification > App B // (by using tokenC)

and vice versa:

App B > sends data > Server B // (contains App A's tokenB)
Server B > sends notification > App A // (by using tokenB)

That's pretty much the general idea.

With all that said, "how can I achieve that in other cases?" is too broad of a question.


问:
Transition div when fixed position gets applied
I have the following code which applies the .stick class to #s-nav when the user scrolls.

```<code>$(document).ready(function() {

$(window).scroll(function() {
  if ($(window).scrollTop() > 300) {
    $('#s-nav').addClass('stick');
    $('#s-nav_placeholder').css({display: 'block'});
  }
  if ($(window).scrollTop() < 300) {
    $('#s-nav').removeClass('stick');
    $('#s-nav_placeholder').css({display: 'none'});
  }
});

});
</code>```

css

```<code>#s-nav {
  height: 70px;
  width: 100%;
  position: relative;
  -webkit-transition: top 0.75s ease;
  -moz-transition: top 0.75s ease;
  -ms-transition: top 0.75s ease;
  -o-transition: top 0.75s ease;
  transition: top 0.75s ease;
}

#s-nav_placeholder {
  height: 70px;
  width: 100%;
  display: none;
}

#s-nav.stick {
  position: fixed;
  top: 0; left: 0; right: 0;
  z-index: 999;
}
</code>```

When .stick class gets applied I want it to transition down from the top. The problem is I don't know how to 'start' the div out of screen since It becomes part of the content <300 px from the top

答:
try this .
modify css to

```<code>#s-nav.stick {
  position: fixed;
  top: -100%; left: 0; right: 0;
  z-index: 999;
 -webkit-transition:  0.75s  ;
 -moz-transition:     0.75s  ;
 -ms-transition:      0.75s  ;
 -o-transition:       0.75s  ;
 transition:          0.75s  ;
}
</code>```

then add  $('#s-nav').css('top','0'); like this.

```<code>$(document).ready(function() {

$(window).scroll(function() {
  if ($(window).scrollTop() > 300) {
    $('#s-nav').addClass('stick');

    /*new line of code */
    $('#s-nav').css('top','0');

    $('#s-nav_placeholder').css({display: 'block'});
  }
  if ($(window).scrollTop() < 300) {
    $('#s-nav').removeClass('stick');

    /*new line of code */
    $('#s-nav').css('top','-50%');

    $('#s-nav_placeholder').css({display: 'none'});
  }
});

});
</code>```

check this jsfiddle : https://jsfiddle.net/jayakrishnancn/61s0oLLs/1/

Body:
I have the following code which applies the .stick class to #s-nav when the user scrolls.

$(document).ready(function() {

$(window).scroll(function() {
  if ($(window).scrollTop() > 300) {
    $('#s-nav').addClass('stick');
    $('#s-nav_placeholder').css({display: 'block'});
  }
  if ($(window).scrollTop() < 300) {
    $('#s-nav').removeClass('stick');
    $('#s-nav_placeholder').css({display: 'none'});
  }
});

});

css

#s-nav {
  height: 70px;
  width: 100%;
  position: relative;
  -webkit-transition: top 0.75s ease;
  -moz-transition: top 0.75s ease;
  -ms-transition: top 0.75s ease;
  -o-transition: top 0.75s ease;
  transition: top 0.75s ease;
}

#s-nav_placeholder {
  height: 70px;
  width: 100%;
  display: none;
}

#s-nav.stick {
  position: fixed;
  top: 0; left: 0; right: 0;
  z-index: 999;
}

When .stick class gets applied I want it to transition down from the top. The problem is I don't know how to 'start' the div out of screen since It becomes part of the content <300 px from the top

Body:
try this .
modify css to

#s-nav.stick {
  position: fixed;
  top: -100%; left: 0; right: 0;
  z-index: 999;
 -webkit-transition:  0.75s  ;
 -moz-transition:     0.75s  ;
 -ms-transition:      0.75s  ;
 -o-transition:       0.75s  ;
 transition:          0.75s  ;
}

then add  $('#s-nav').css('top','0'); like this.

$(document).ready(function() {

$(window).scroll(function() {
  if ($(window).scrollTop() > 300) {
    $('#s-nav').addClass('stick');

    /*new line of code */
    $('#s-nav').css('top','0');

    $('#s-nav_placeholder').css({display: 'block'});
  }
  if ($(window).scrollTop() < 300) {
    $('#s-nav').removeClass('stick');

    /*new line of code */
    $('#s-nav').css('top','-50%');

    $('#s-nav_placeholder').css({display: 'none'});
  }
});

});

check this jsfiddle : https://jsfiddle.net/jayakrishnancn/61s0oLLs/1/


问:
unable to reset the values back to the originally selected values
I am working on bootstrap datepicker, i have a Reset and submit buttons on the datepicker.
I want to implement the Reset button functionality to one of the buttons on the datepicker.When user selects the new date range from the calendar and click on Reset button, the previously (originally) selected values should be highlighted and the newly selected values should be cleared.

Please find the code demo here

Initially when clicked in the Select Date filed, a calendar is opened and dates 04/23/2017 as start date and 06/07/2017 date as end date are selected.When user selects other date range , the newly selected dates are highlighted. When user click on Reset button, again it has to show the originally selected dates (04/23/2017 and 06/07/2017) highlighted( basically we are clearing off the newly selected values so that user can select other date range).

I have gone through the API but unable to get the expected output.

I tried something as below

```<code>$('#reportrange').daterangepicker({
  locale: { cancelLabel: 'Reset' }
});

$('#reportrange').on('cancel.daterangepicker', function(ev, picker) {
  //do something, like clearing an input
  $('#reportrange').val('');
});
</code>```

答:
I was having similar trouble and the following worked for me:

```<code>   $('#datepicker').val('').datepicker('update');
</code>```

Both method calls were needed, otherwise it didn't clear.

Body:
I am working on bootstrap datepicker, i have a Reset and submit buttons on the datepicker.
I want to implement the Reset button functionality to one of the buttons on the datepicker.When user selects the new date range from the calendar and click on Reset button, the previously (originally) selected values should be highlighted and the newly selected values should be cleared.

Please find the code demo here

Initially when clicked in the Select Date filed, a calendar is opened and dates 04/23/2017 as start date and 06/07/2017 date as end date are selected.When user selects other date range , the newly selected dates are highlighted. When user click on Reset button, again it has to show the originally selected dates (04/23/2017 and 06/07/2017) highlighted( basically we are clearing off the newly selected values so that user can select other date range).

I have gone through the API but unable to get the expected output.

I tried something as below

$('#reportrange').daterangepicker({
  locale: { cancelLabel: 'Reset' }
});

$('#reportrange').on('cancel.daterangepicker', function(ev, picker) {
  //do something, like clearing an input
  $('#reportrange').val('');
});

Body:
I was having similar trouble and the following worked for me:

   $('#datepicker').val('').datepicker('update');

Both method calls were needed, otherwise it didn't clear.