问:
Why is generic required when all types are already defined?
The exercise was to write my own map() function over Collection (without using any functional primitives, such as reduce()). It should handle a case such as this:

```<code>func square(_ input: Int) -> Int {
            return input * input
        }
let result = input.accumulate(square) // [1,2,3] =>  [1,4,9]
</code>```

My first attempt was:

```<code>extension Collection {
    func accumulate(_ transform: (Element) -> Element) -> [Element] {

        var array: [Element] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}
</code>```

This works fine in a playground, but fails to build against the tests, giving an error:

```<code>Value of type '[Int]' has no member 'accumulate'
</code>```

The solution is to genericize the accumulate method:

```<code>extension Collection {
    func accumulate<T>(_ transform: (Element) -> T) -> [T] {

        var array: [T] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}
</code>```

I recognize that the generic version is less restrictive (doesn't require the transform to return same type), but given that the tests don't require this generality, why does the compiler?

Out of curiousity I tried:

```<code>extension Collection {
    func accumulate<Element>(_ transform: (Element) -> Element) -> [Element] {

        var array: [Element] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}
</code>```

which throws the fascinating build error: '(Self.Element) -> Element' is not convertible to '(Element) -> Element' at the append() statement.

So the compiler (of course) knows that the first Element is Self.Element, but doesn't treat the other Element type as the same. Why?

UPDATE:

Based on the answers, it appears that the rejection of the first version was a compiler bug, fixed in XCode 9.2 (I'm on 9.1).

But still I wondered whether in

```<code>func accumulate(_ transform: (Element) -> Element) -> [Element]
</code>```

it would see two types (Self.Element and Element) or recognize that they're the same.

So I did this test:

```<code>let arr = [1,2,3]
arr.accumulate {
    return String(describing: $0)
}
</code>```

Sure enough, got the expected error: error: cannot convert value of type 'String' to closure result type 'Int'

So the correct answer is: the compiler will treat references to Element as the same, as long as there isn't a generic type that overloads the name.

Oddly, though, this succeeds:

```<code>[1,2,3].accumulate {
    return String(describing: $0)
}
</code>```

PS. Thanks to everyone for your input! The bounty was auto-awarded.

答:
About the first question, working with Xcode 9.2 and Swift 4 I didn't receive any building error such as:

Value of type '[Int]' has no member 'accumulate'

so doing this:

```<code>var mystuff:[Int] = [1,2,3]
let result = mystuff.accumulate(square)
</code>```

it's just giving me the correct result [1,4,9]

For the second question, the function prototype is wrong, you should try  Self.Element:

```<code>extension Collection {
  func accumulate<Element>(_ transform: (Self.Element) -> Element) -> [Element] {
    var array: [Element] = []
    for element in self {
      array.append(transform(element))
    }
    return array
   }
}
</code>```

Body:
The exercise was to write my own map() function over Collection (without using any functional primitives, such as reduce()). It should handle a case such as this:

func square(_ input: Int) -> Int {
            return input * input
        }
let result = input.accumulate(square) // [1,2,3] =>  [1,4,9]

My first attempt was:

extension Collection {
    func accumulate(_ transform: (Element) -> Element) -> [Element] {

        var array: [Element] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}

This works fine in a playground, but fails to build against the tests, giving an error:

Value of type '[Int]' has no member 'accumulate'

The solution is to genericize the accumulate method:

extension Collection {
    func accumulate<T>(_ transform: (Element) -> T) -> [T] {

        var array: [T] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}

I recognize that the generic version is less restrictive (doesn't require the transform to return same type), but given that the tests don't require this generality, why does the compiler?

Out of curiousity I tried:

extension Collection {
    func accumulate<Element>(_ transform: (Element) -> Element) -> [Element] {

        var array: [Element] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}

which throws the fascinating build error: '(Self.Element) -> Element' is not convertible to '(Element) -> Element' at the append() statement.

So the compiler (of course) knows that the first Element is Self.Element, but doesn't treat the other Element type as the same. Why?

UPDATE:

Based on the answers, it appears that the rejection of the first version was a compiler bug, fixed in XCode 9.2 (I'm on 9.1).

But still I wondered whether in

func accumulate(_ transform: (Element) -> Element) -> [Element]

it would see two types (Self.Element and Element) or recognize that they're the same.

So I did this test:

let arr = [1,2,3]
arr.accumulate {
    return String(describing: $0)
}

Sure enough, got the expected error: error: cannot convert value of type 'String' to closure result type 'Int'

So the correct answer is: the compiler will treat references to Element as the same, as long as there isn't a generic type that overloads the name.

Oddly, though, this succeeds:

[1,2,3].accumulate {
    return String(describing: $0)
}

PS. Thanks to everyone for your input! The bounty was auto-awarded.

Body:
About the first question, working with Xcode 9.2 and Swift 4 I didn't receive any building error such as:

Value of type '[Int]' has no member 'accumulate'

so doing this:

var mystuff:[Int] = [1,2,3]
let result = mystuff.accumulate(square)

it's just giving me the correct result [1,4,9]

For the second question, the function prototype is wrong, you should try  Self.Element:

extension Collection {
  func accumulate<Element>(_ transform: (Self.Element) -> Element) -> [Element] {
    var array: [Element] = []
    for element in self {
      array.append(transform(element))
    }
    return array
   }
}


来源: stackexchange

问:
Android app Keystore password reset
How to reset Keystore password for android. I can't update application on play store.
How to resolve this problem?
When I tried to update the application with the new key then play store rejected it.
I have the old Keystore file but the password is not accepting.

答:
One trick is here you can get your password from android studio.I windows go to

```<code>C:\Users\yourUser\.Android2.2\system\log\idea.log.1
</code>```

where Android2.2 is the studio version , you have to go to your version name folder.  The password is shown just below the first ***** part . Search in file **** or android.injected.signing.store word. you will find your password.

Hope it helps to you.

ContentLicense: CC BY-SA 3.0

Title: Android app Keystore password reset

Body:
One trick is here you can get your password from android studio.I windows go to

C:\Users\yourUser\.Android2.2\system\log\idea.log.1

where Android2.2 is the studio version , you have to go to your version name folder.  The password is shown just below the first ***** part . Search in file **** or android.injected.signing.store word. you will find your password.

Hope it helps to you.


问:
Understanding Luajit SNAP IR instruction
I am trying to trace some register coalescing too complex NYI in my luajit code. From the IR in can see that the snapshot when the NYI happens is pretty full. My attempt is to trace backwards and to find out what causes the snapshot to be filled up.

To start with I am looking to understand what information is given out by the SNAP line. for example in a SNAP line below:

```<code>> local x = 1.2 for i=1,1e3 do x = x * -3 end
---- TRACE 1 start stdin:1
0006  MULVN    0   0   1  ; -3
0007  FORL     1 => 0006
---- TRACE 1 IR
....              SNAP   #0   [ ---- ]
0001 rbp      int SLOAD  #2    CI
0002 xmm7  >  num SLOAD  #1    T
0003 xmm7   + num MUL    0002  -3
0004 rbp    + int ADD    0001  +1
....              SNAP   #1   [ ---- 0003 ]
0005       >  int LE     0004  +1000
....              SNAP   #2   [ ---- 0003 0004 ---- ---- 0004 ]
0006 ------------ LOOP ------------
0007 xmm7   + num MUL    0003  -3
0008 rbp    + int ADD    0004  +1
....              SNAP   #3   [ ---- 0007 ]
0009       >  int LE     0008  +1000
0010 rbp      int PHI    0004  0008
0011 xmm7     num PHI    0003  0007
</code>```

If my understanding is correct, in first snapshot second position is written by IR at 0003. Going by the argument of IR at 0003 I guess 0002 (is this a memory location?) is x.

What I do not understand is that in second snapshot line (after IR 0005) 3rd and 6th position is modified by IR at 0004. How is that?

Now, how can I trace which variables are present in a snapshot position in above IR? For eg: in SNAP #7 [ ---- 0007 ].

Also what does the second argument to SLOAD (flags) signify? [I, CI, CRI, T, PI, PRI, R, RI] etc... I have also seen SLOAD with second argument empty.

答:
This has been extensively answerd at luajit mail list by Peter Cawley in the following thread

https://www.freelists.org/post/luajit/Understanding-SNAP

Body:
I am trying to trace some register coalescing too complex NYI in my luajit code. From the IR in can see that the snapshot when the NYI happens is pretty full. My attempt is to trace backwards and to find out what causes the snapshot to be filled up.

To start with I am looking to understand what information is given out by the SNAP line. for example in a SNAP line below:

> local x = 1.2 for i=1,1e3 do x = x * -3 end
---- TRACE 1 start stdin:1
0006  MULVN    0   0   1  ; -3
0007  FORL     1 => 0006
---- TRACE 1 IR
....              SNAP   #0   [ ---- ]
0001 rbp      int SLOAD  #2    CI
0002 xmm7  >  num SLOAD  #1    T
0003 xmm7   + num MUL    0002  -3
0004 rbp    + int ADD    0001  +1
....              SNAP   #1   [ ---- 0003 ]
0005       >  int LE     0004  +1000
....              SNAP   #2   [ ---- 0003 0004 ---- ---- 0004 ]
0006 ------------ LOOP ------------
0007 xmm7   + num MUL    0003  -3
0008 rbp    + int ADD    0004  +1
....              SNAP   #3   [ ---- 0007 ]
0009       >  int LE     0008  +1000
0010 rbp      int PHI    0004  0008
0011 xmm7     num PHI    0003  0007

If my understanding is correct, in first snapshot second position is written by IR at 0003. Going by the argument of IR at 0003 I guess 0002 (is this a memory location?) is x.

What I do not understand is that in second snapshot line (after IR 0005) 3rd and 6th position is modified by IR at 0004. How is that?

Now, how can I trace which variables are present in a snapshot position in above IR? For eg: in SNAP #7 [ ---- 0007 ].

Also what does the second argument to SLOAD (flags) signify? [I, CI, CRI, T, PI, PRI, R, RI] etc... I have also seen SLOAD with second argument empty.


问:
Where does EMR store Spark stdout?
I am running my Spark application on EMR, and have several println() statements. Other than the console, where do these statements get logged?

My S3 aws-logs directory structure for my cluster looks like:

node
├── i-0031cd7a536a42g1e
│   ├── applications
│   ├── bootstrap-actions
│   ├── daemons
│   ├── provision-node
│   └── setup-devices
containers/
├── application_12341331455631_0001
│   ├── container_12341331455631_0001_01_000001

答:
You can find println's in a few places:

Resource Manager -> Your Application -> Logs -> stdout

Your S3 log directory -> containers/application_.../container_.../stdout (though this takes a few minutes to populate after the application)

SSH into the EMR, yarn logs -applicationId <Application ID> -log_files <log_file_type>

Title: Where does EMR store Spark stdout?


问:
Commandline to convert ISO8601 time to unix timestamp
What is the most efficient way to get a unix timestamp for a given ISO 8601 date and vice versa?

There are several third party websites to do this. However I am looking for a simple command that can be executed at the Linux prompt

答:
Convert ISO Date/Time to Unix timestamp

```<code>date -d 'date' +"%s"
</code>```

Example

```<code>   bash-# date -d 'Fri Dec  8 00:12:50 UTC 2017' +"%s"
   bash-# 1512691970
</code>```

man -a date

```<code>   -d, --date=STRING
          display time described by STRING, not 'now'

   %s     seconds since 1970-01-01 00:00:00 UTC
</code>```

Convert Unix timestamp to ISO Date/Time

```<code>date -Iseconds -d @<unix timestamp>
</code>```

Example

```<code>   bash-# date -Iseconds -d @1512711426
   bash-# 2017-12-07T21:37:06-0800
</code>```

man -a date

```<code>   -d, --date=STRING
          display time described by STRING, not 'now'

   -I[TIMESPEC], --iso-8601[=TIMESPEC]
          output  date/time  in  ISO 8601 format.
          TIMESPEC='date' for date only (the default), 'hours',
          'minutes', 'seconds', or 'ns' for date and time to the
          indicated precision.
</code>```

Body:
Convert ISO Date/Time to Unix timestamp

date -d 'date' +"%s"

Example

   bash-# date -d 'Fri Dec  8 00:12:50 UTC 2017' +"%s"
   bash-# 1512691970

man -a date

   -d, --date=STRING
          display time described by STRING, not 'now'

   %s     seconds since 1970-01-01 00:00:00 UTC

Convert Unix timestamp to ISO Date/Time

date -Iseconds -d @<unix timestamp>

Example

   bash-# date -Iseconds -d @1512711426
   bash-# 2017-12-07T21:37:06-0800

man -a date

   -d, --date=STRING
          display time described by STRING, not 'now'

   -I[TIMESPEC], --iso-8601[=TIMESPEC]
          output  date/time  in  ISO 8601 format.
          TIMESPEC='date' for date only (the default), 'hours',
          'minutes', 'seconds', or 'ns' for date and time to the
          indicated precision.

ContentLicense: CC BY-SA 4.0


问:
Should I show two validation messages for email id in web application?
I have an email address field on my web application.I have 2 cases for this

a) email should not be empty

b) email should be in proper format .

Whether user keep it empty or put improper email address in the email address
I show only one message "Please enter valid emailid".

My manager says that we should use two validation messages. but I am insisting that this one message is suffiecient.

Please suggest what should be approach for this.

UPDATED : -

Here is what I found for Yahoo.com login screen

答:
Try below if it is suitable for you, you can do it by jquery

```<code><input type="text" name="emailid" id="emailid" placeholder="Email ID">
<input type="submit" id="submit" value="Submit" />
</code>```

and use below jquery method for validation

```<code>$(document).ready(function() {
   $('#submit').click(function() {
        var EmailID = $('#emailid').val();
        if ($.trim(EmailID).length == 0) {
            alert('Please enter valid email address');
            e.preventDefault();
        }
        if (validateEmail(EmailID)) {
            alert('Email is valid');
        }
        else {
            alert('Invalid Email Address');
            e.preventDefault();
        }
    });
});

function validateEmail(EmailID ) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (filter.test(EmailID)) {
        return true;
    }
    else {
        return false;
    }
}
</code>```

Body:
Try below if it is suitable for you, you can do it by jquery

<input type="text" name="emailid" id="emailid" placeholder="Email ID">
<input type="submit" id="submit" value="Submit" />

and use below jquery method for validation

$(document).ready(function() {
   $('#submit').click(function() {
        var EmailID = $('#emailid').val();
        if ($.trim(EmailID).length == 0) {
            alert('Please enter valid email address');
            e.preventDefault();
        }
        if (validateEmail(EmailID)) {
            alert('Email is valid');
        }
        else {
            alert('Invalid Email Address');
            e.preventDefault();
        }
    });
});

function validateEmail(EmailID ) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (filter.test(EmailID)) {
        return true;
    }
    else {
        return false;
    }
}


问:
Trigger webhook when Google Sheet edited
I made a google sheet for sharing todo list with co-workers.

My hope is when that sheet is modified, send message to slack channel.

Even if tried to find api related with this, I failed to suitable one.

Is there a appropriate API or webhook?

答:
There's Drive API's Push Notifications which lets you watch for changes to resources. You can also use Apps Scripts' onEdit trigger which acts more like a real-time checker.

```<code>function onEdit(e){
  // Set a comment on the edited cell to indicate when it was changed.
  var range = e.range;
  range.setNote('Last modified: ' + new Date());
}
</code>```

This forum might also offer additional insight.

Body:
There's Drive API's Push Notifications which lets you watch for changes to resources. You can also use Apps Scripts' onEdit trigger which acts more like a real-time checker.

function onEdit(e){
  // Set a comment on the edited cell to indicate when it was changed.
  var range = e.range;
  range.setNote('Last modified: ' + new Date());
}

This forum might also offer additional insight.


问:
java.lang.ClassNotFoundException: org.hibernate.Session Exception to clear
I'm creating a log-in page and to check the login details I have connected with database using hibernate.I'm transporting data via servlets and I UserDAO dao = new UserDAO is my object here for DAO class

I got exception like this:

```<code>SEVERE: Servlet.service() for servlet [com.onlineportal.tp.servlet.LoginServlet] in context with path [/Online_Course_Learning_Portal] threw exception [Servlet execution threw an exception] with root cause
</code>```

java.lang.ClassNotFoundException: org.hibernate.Session
      at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1313)
      at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1164)
      at com.onlineportal.tp.servlet.LoginServlet.doPost(LoginServlet.java:31)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
      at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
      at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
      at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1527)
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1484)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      at java.lang.Thread.run(Unknown Source)

What should I do ?

答: Hibernate jar is missing, if using Maven then add the dependency else download Hibernate and use the proper jars which are required to work with Hibernate.</p>

Body:
I'm creating a log-in page and to check the login details I have connected with database using hibernate.I'm transporting data via servlets and I UserDAO dao = new UserDAO is my object here for DAO class

I got exception like this:

SEVERE: Servlet.service() for servlet [com.onlineportal.tp.servlet.LoginServlet] in context with path [/Online_Course_Learning_Portal] threw exception [Servlet execution threw an exception] with root cause

java.lang.ClassNotFoundException: org.hibernate.Session
      at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1313)
      at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1164)
      at com.onlineportal.tp.servlet.LoginServlet.doPost(LoginServlet.java:31)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
      at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
      at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
      at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1527)
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1484)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      at java.lang.Thread.run(Unknown Source)

What should I do ?


问:
mongos status is not showing any shard and adding shards also getting failed
Unable to list shards of replica set from Mongos client..

Mongodb Authentication is enabled in sharded cluster.. in config server, the key got changed so cluster stopped working .. I have restored same key and enabled authentication now.. hence after, i am unable to see the shards which were added earlier and also can't able to add same shard again ..

mongos> sh.status()
--- Sharding Status ---
  sharding version: {
        "_id" : 1,
        "minCompatibleVersion" : 5,
        "currentVersion" : 6,
        "clusterId" : ObjectId("58bd2f7ea00a1d1ce3806bf3")
}
  shards:
  active mongoses:
        "3.2.9" : 1
  balancer:
        Currently enabled:  yes
        Currently running:  no
        Failed balancer rounds in last 5 attempts:  0
        Migration Results for the last 24 hours:
                No recent migrations
  databases:

mongos> sh.addShard("rs01/rs01-p01:27017,rs01-s01:27017,rs01-s02:27017")
{
        "ok" : 0,
        "errmsg" : "can't add shard 'rs01/rs01-p01:27017,rs01-s01:27017,rs01-s02:27017' because a local database 'config' exists in another config",
        "code" : 96
}
mongos>

can some one please help me what went wrong and how can configserver can get shards information back..

答:
I had the same.  I just had to connect to the server I was trying to add, and drop its config database.

```<code>$ mongo rs01-p01:27017
> use config
> db.dropDatabase()
</code>```

Then on the mongos, I could add the shard as expected.

Body:
I had the same.  I just had to connect to the server I was trying to add, and drop its config database.

$ mongo rs01-p01:27017
> use config
> db.dropDatabase()

Then on the mongos, I could add the shard as expected.


问:
Update one value in parent activity from a child activity while retaining all remaining original values on the parent
I have an input form where I collect 4 values in a text field that are tied to the FirstActivity. The user enters 4 values and clicks a button which will present the user with 2 options that are tied to SecondActivity.

Upon clicking one of the options in SecondActivity, he is presented with a 3rd screen with a search option. Upon searching, he is presented with search results as a list.

When the user clicks on one of the results, I want to update one field in FirstActivity while retaining all the values that the user selected initially. I used the Intent flags to retain the state and it works except for one problem - I dont see the updated value in the first screen.

PROBLEM: While this code helps me retain the initial state in FirstActivity, it doesn't update the CopiesValue when I return to FirstActivity. I want the copies value to be updated with the value that was selected in ThirdActivity. All original values on FirstActivity are retained though...

I want the updated value from ThirdActivity to reflect on the first screen once a value is selected on the third screen.

Here is my code within the onClickListener in ThirdActivity:

```<code>lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object o = lv.getItemAtPosition(position);
        String str = (String) o;
        Globals g = Globals.getInstance();
        ((FirstActivity)g.getFirstContext()).getSettingHolder().setSelectedCopiesValue(5);
        Intent intent = new Intent(g.getFirstContext(), FirstActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivityForResult(intent, 1);
        finish();
    }
});
</code>```

Here is my AndroidManifest.xml entry:

```<code><activity
        android:name=".activity.FirstActivity"
        android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|layoutDirection|fontScale"
        android:label="@string/app_name"
        android:launchMode="singleTop">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".activity.SecondActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".activity.FirstActivity" />
    </activity>
    <activity android:name=".activity.ThirdActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".activity.FirstActivity" />
    </activity>
</code>```

答:
LocalBroadcastRecevier will do the trick over here...

Register receiver in you FirstActivity:

```<code>private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    // Handle data coming from thirdActivity

  }
};

@Override
public void onCreate(Bundle savedInstanceState) {
  // Register to receive messages.
  // We are registering an observer (mMessageReceiver) to receive Intents
  // with actions named "custom-event-name".
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
      new IntentFilter("custom-event-name"));
}

@Override
protected void onDestroy() {
  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
  super.onDestroy();
}
</code>```

Add these lines to you ThirdActivity(which is a sender)

```<code>private void sendMessage() {
  Intent intent = new Intent("custom-event-name");
  intent.putExtra("KEY", "Value");
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

// OnClick event of something...
@Override
public void onClick(View v) {
  sendMessage();
}
</code>```

Body:
I have an input form where I collect 4 values in a text field that are tied to the FirstActivity. The user enters 4 values and clicks a button which will present the user with 2 options that are tied to SecondActivity.

Upon clicking one of the options in SecondActivity, he is presented with a 3rd screen with a search option. Upon searching, he is presented with search results as a list.

When the user clicks on one of the results, I want to update one field in FirstActivity while retaining all the values that the user selected initially. I used the Intent flags to retain the state and it works except for one problem - I dont see the updated value in the first screen.

PROBLEM: While this code helps me retain the initial state in FirstActivity, it doesn't update the CopiesValue when I return to FirstActivity. I want the copies value to be updated with the value that was selected in ThirdActivity. All original values on FirstActivity are retained though...

I want the updated value from ThirdActivity to reflect on the first screen once a value is selected on the third screen.

Here is my code within the onClickListener in ThirdActivity:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object o = lv.getItemAtPosition(position);
        String str = (String) o;
        Globals g = Globals.getInstance();
        ((FirstActivity)g.getFirstContext()).getSettingHolder().setSelectedCopiesValue(5);
        Intent intent = new Intent(g.getFirstContext(), FirstActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivityForResult(intent, 1);
        finish();
    }
});

Here is my AndroidManifest.xml entry:

<activity
        android:name=".activity.FirstActivity"
        android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|layoutDirection|fontScale"
        android:label="@string/app_name"
        android:launchMode="singleTop">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".activity.SecondActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".activity.FirstActivity" />
    </activity>
    <activity android:name=".activity.ThirdActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".activity.FirstActivity" />
    </activity>

Body:
LocalBroadcastRecevier will do the trick over here...

Register receiver in you FirstActivity:

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    // Handle data coming from thirdActivity

  }
};

@Override
public void onCreate(Bundle savedInstanceState) {
  // Register to receive messages.
  // We are registering an observer (mMessageReceiver) to receive Intents
  // with actions named "custom-event-name".
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
      new IntentFilter("custom-event-name"));
}

@Override
protected void onDestroy() {
  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
  super.onDestroy();
}

Add these lines to you ThirdActivity(which is a sender)

private void sendMessage() {
  Intent intent = new Intent("custom-event-name");
  intent.putExtra("KEY", "Value");
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

// OnClick event of something...
@Override
public void onClick(View v) {
  sendMessage();
}


问:
how to compare date with GETDATE() in sql server 2008
I have a stored procedure, which is used to insert some kind of information to table 'demotable', in that i have a field loginTime where datatype is dateTime.
i am using GETDATE() to get the current datetime, problem is i want to compare whether this GETDATE() is lower than 9:00 AM and then make it as 9:00AM, if not lower keep the output as it is without any changes. -using microsoft sql server 2008.

below is my sample stored procedure

```<code>         //Beg Stored Procedure Contents...

            insert into dbo.demoTable([loginTime],[nStatus]) values(GETDATE(),'1')

         //End
</code>```

答:
select CASE when DATEPART(HOUR, GETDATE()) < 9 THEN dateadd(hh, 9,  DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) ELSE getdate() END

This is the solution that i have founnd myself, Thanks @CodingYoshi for your tip, Where SQL Server 2008 Does Not support IIF, Instead we can use CASE

Body:
I have a stored procedure, which is used to insert some kind of information to table 'demotable', in that i have a field loginTime where datatype is dateTime.
i am using GETDATE() to get the current datetime, problem is i want to compare whether this GETDATE() is lower than 9:00 AM and then make it as 9:00AM, if not lower keep the output as it is without any changes. -using microsoft sql server 2008.

below is my sample stored procedure

         //Beg Stored Procedure Contents...

            insert into dbo.demoTable([loginTime],[nStatus]) values(GETDATE(),'1')

         //End


问:
Generate OAuth 2.0 Access Token For PUT Request In Google Sheets API In JavaScript
GOAL

I would like to update some information in a Google Sheets document though a web service. I don't mind if the data is public, but it seems like I need to get an OAuth token in order to use PUT https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{range}as opposed to simply getting the data. However, I get back errors stating that I'm missing OAuth 2.0 credentials.

EXPECTATIONS

In order to do this, I assume that I need to first get credentials from Google's Developer Console . I currently have an OAuth 2.0 client ID and API key through that console. The API key is used to read the data and the OAuth would be used to write data.

I then need to hit an endpoint of some kind with the OAuth information to get credentials that'll be used. I'm supposed to put this info into my PUT request. This is the documentation I've found in regards to my request, but it's missing the authorization documentation.

QUESTIONS

1) Where is the endpoint that I'm hitting to get a refresh token and access token in Google's OAuth 2.0 stuffs? I've heard it's something like https://accounts.google.com/o/oauth2/token, but I'm not sure how to get the tokens. What do I need to pass? How do I pass that info? I can't find any documentation over it.

2) After getting these tokens, how do I incorporate them into the PUT request to the Google Sheets API? Do the tokens go into the Authorization header or the access_token query parameter or something?

答:
I would highly recommend to check the Javascript Quickstart for Sheets API first as it includes OAuth sign-in demo.

From the quickstart code, this is the part that calls the OAuth library:

```<code> function handleClientLoad() {
        gapi.load('client:auth2', initClient);
 }
</code>```

And here's me using the PUT request in an app I made:

```<code>function recordTimeInSheet(){

     var params = {
       "range":"Sheet1!"+A+":"+C,
       "majorDimension": "ROWS",
       "values": [
       ["bruceWayne","8:00AM", "5:00PM"]
      ],
     }
     var xhr = new XMLHttpRequest();
     xhr.open('PUT', 'https://sheets.googleapis.com/v4/spreadsheets/'+myspreadsheetId+'/'+"values/"+"Sheet1!"+A+":"+C+"?"+'valueInputOption=USER_ENTERED');
     xhr.setRequestHeader('Authorization', 'Bearer ' + myAccessToken);

    xhr.send(JSON.stringify(params));
  }
</code>```

Body:
I would highly recommend to check the Javascript Quickstart for Sheets API first as it includes OAuth sign-in demo.

From the quickstart code, this is the part that calls the OAuth library:

 function handleClientLoad() {
        gapi.load('client:auth2', initClient);
 }

And here's me using the PUT request in an app I made:

function recordTimeInSheet(){

     var params = {
       "range":"Sheet1!"+A+":"+C,
       "majorDimension": "ROWS",
       "values": [
       ["bruceWayne","8:00AM", "5:00PM"]
      ],
     }
     var xhr = new XMLHttpRequest();
     xhr.open('PUT', 'https://sheets.googleapis.com/v4/spreadsheets/'+myspreadsheetId+'/'+"values/"+"Sheet1!"+A+":"+C+"?"+'valueInputOption=USER_ENTERED');
     xhr.setRequestHeader('Authorization', 'Bearer ' + myAccessToken);

    xhr.send(JSON.stringify(params));
  }


问:
Can not transpile ES7 "includes" feature with Cloud Functions
I'm trying to use Typescript in a VueJS project which has a subdirectory functions for the Cloud Functions to execute on the server side.

I'd like to use the ES2017 feature Array.prototype.includes and I thought I'd made that happen by adding the following tsconfig.json to my functions directory:

```<code>{
  "compilerOptions": {
    "lib": ["es2016", "es2017"],
    "target": "es6",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "strict": true
  }
}
</code>```

If I go into the functions directory and run the tsc transpiler it runs without error. Also my vs-code editor does not highlight any issue with the use of "includes". However, following along with the suggested configuration on the Firebase docs I have added the following to my firebase.json config file:

```<code>"functions": {
  "predeploy": "npm --prefix functions run build"
}
</code>```

In turn, my package.json in the functions directory has the build script listed as:

```<code>"scripts": {
  "build": "tslint *.ts && tsc *.ts"
},
</code>```

But when I run firebase deploy --only functions it correctly runs the build script but it then gives the following error:

index.ts(44,31): error TS2339: Property 'includes' does not exist on type 'string[]'.

I believe this may be happening because it is incorrectly using the tsconfig.json in the root project directory (aka, the one that VueJS is using) instead of the one in the functions directory but I'm not entirely sure.

I CAN get around this by changing the build command to:

```<code>"build": "tslint *.ts && tsc *.ts --lib 'es7'"
</code>```

and this does work but it leaves me feeling I've hacked it a bit. Can anyone point to a better answer?

答:
The reason is that when you specify input files to tsc using tsc *.ts, the tsconfig.json file is ignored.

From the documentation:

When input files are specified on the command line, tsconfig.json
  files are ignored.

To fix this run tsc without any parameters. This will use your tsconfig.json file.

Body:
I'm trying to use Typescript in a VueJS project which has a subdirectory functions for the Cloud Functions to execute on the server side.

I'd like to use the ES2017 feature Array.prototype.includes and I thought I'd made that happen by adding the following tsconfig.json to my functions directory:

{
  "compilerOptions": {
    "lib": ["es2016", "es2017"],
    "target": "es6",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "strict": true
  }
}

If I go into the functions directory and run the tsc transpiler it runs without error. Also my vs-code editor does not highlight any issue with the use of "includes". However, following along with the suggested configuration on the Firebase docs I have added the following to my firebase.json config file:

"functions": {
  "predeploy": "npm --prefix functions run build"
}

In turn, my package.json in the functions directory has the build script listed as:

"scripts": {
  "build": "tslint *.ts && tsc *.ts"
},

But when I run firebase deploy --only functions it correctly runs the build script but it then gives the following error:

index.ts(44,31): error TS2339: Property 'includes' does not exist on type 'string[]'.

I believe this may be happening because it is incorrectly using the tsconfig.json in the root project directory (aka, the one that VueJS is using) instead of the one in the functions directory but I'm not entirely sure.

I CAN get around this by changing the build command to:

"build": "tslint *.ts && tsc *.ts --lib 'es7'"

and this does work but it leaves me feeling I've hacked it a bit. Can anyone point to a better answer?


问:
Cron Scheduling bad username
My crontab isn't running. After checking the syslog I am getting the following errors:

```<code>Dec  7 18:57:01 raspberrypi cron[334]: Error: bad username; while reading /etc/cron.d/crontab
Dec  7 18:57:01 raspberrypi cron[334]: (*system*crontab) ERROR (Syntax error, this crontab file will be ignored)
</code>```

I'm trying to schedule a cron task, and it keeps giving me a bad username error... i've tried both:

```<code>57 13 * * * pi /home/pi/Desktop/shell.sh
</code>```

and

```<code>57 13 * * * root /home/pi/Desktop/shell.sh
</code>```

and they're both coming back invalid, what am i missing?

答: You might have gotten some unintended control characters when editing your crontab. cat -v on your crontab to check. Always make sure to edit your crontab with crontab -e.

Title: Cron Scheduling bad username

Body:
My crontab isn't running. After checking the syslog I am getting the following errors:

Dec  7 18:57:01 raspberrypi cron[334]: Error: bad username; while reading /etc/cron.d/crontab
Dec  7 18:57:01 raspberrypi cron[334]: (*system*crontab) ERROR (Syntax error, this crontab file will be ignored)

I'm trying to schedule a cron task, and it keeps giving me a bad username error... i've tried both:

57 13 * * * pi /home/pi/Desktop/shell.sh

and

57 13 * * * root /home/pi/Desktop/shell.sh

and they're both coming back invalid, what am i missing?


问:
Unable to deploy rails application using capistrano, bundle not found
I am trying to deploy my rails application using capistrano but it is giving me "bundle stdout: /home/deploy/.rvm/scripts/set: line 19: exec: bundle: not found" error. I have installed bundler gem on the server still capistrano unable to find bundle.

Capfile content:

```<code>require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/bundler'
require 'capistrano/rvm'
require 'capistrano/rails/assets' # for asset handling add
require 'capistrano/rails/migrations' # for running migrations
require 'capistrano/puma'
require 'capistrano/rake'

install_plugin Capistrano::Puma
# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }
</code>```

Deploy.rb content :

```<code>lock '3.10.0'

set :application, 'app_name'
set :repo_url, 'my-repo-url' # Edit this to match your repository
set :branch, :branch_name
set :deploy_to, '/home/deploy/app_name'
set :pty, true
set :linked_files, %w{config/database.yml config/application.yml}
set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system public/uploads}
set :keep_releases, 3
set :rvm_type, :user
set :rvm_ruby_version, 'ruby-2.3.1' # Edit this if you are using MRI Ruby

set :puma_rackup, -> { File.join(current_path, 'config.ru') }
set :puma_state, "#{shared_path}/tmp/pids/puma.state"
set :puma_pid, "#{shared_path}/tmp/pids/puma.pid"
set :puma_bind, "unix://#{shared_path}/tmp/sockets/puma.sock"    #accept array for multi-bind
set :puma_conf, "#{shared_path}/puma.rb"
set :puma_access_log, "#{shared_path}/log/puma_error.log"
set :puma_error_log, "#{shared_path}/log/puma_access.log"
set :puma_role, :app
set :puma_threads, [0, 16]
set :puma_workers, 0
set :puma_worker_timeout, nil
set :puma_init_active_record, true
set :puma_preload_app, false
set :puma_prune_bundler, true

namespace :deploy do
    desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      invoke 'puma:restart'
    end
  end

  after  :finishing,    :compile_assets
  after  :finishing,    :cleanup
  after  :finishing,    :restart
end
</code>```

Production.rb content :

```<code>server 'My-IP', user: 'deploy', roles: %w{web app db}
set :puma_env, fetch(:rack_env, fetch(:rails_env, 'production'))
</code>```

答:
When deploying a Rails app using capistrano with rvm, you have to be careful that capistrano will switch the ruby version, and it might not the same ruby version as you see.

You can ssh to the remote server and check yourself

```<code>ssh deploy@My-IP
ruby -v        # It's probably not 2.3.1
which bundle
rvm use 2.3.1  # This is the actual version that will be used by capistrano
which bundle
</code>```

If you cannot see the bundle installed within ruby-2.3.1, you can manually install it by

```<code>rvm use 2.3.1
gem install bundler
</code>```

After that, the capistrano deployment should work as expected.

Body:
I am trying to deploy my rails application using capistrano but it is giving me "bundle stdout: /home/deploy/.rvm/scripts/set: line 19: exec: bundle: not found" error. I have installed bundler gem on the server still capistrano unable to find bundle.

Capfile content:

require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/bundler'
require 'capistrano/rvm'
require 'capistrano/rails/assets' # for asset handling add
require 'capistrano/rails/migrations' # for running migrations
require 'capistrano/puma'
require 'capistrano/rake'

install_plugin Capistrano::Puma
# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }

Deploy.rb content :

lock '3.10.0'

set :application, 'app_name'
set :repo_url, 'my-repo-url' # Edit this to match your repository
set :branch, :branch_name
set :deploy_to, '/home/deploy/app_name'
set :pty, true
set :linked_files, %w{config/database.yml config/application.yml}
set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system public/uploads}
set :keep_releases, 3
set :rvm_type, :user
set :rvm_ruby_version, 'ruby-2.3.1' # Edit this if you are using MRI Ruby

set :puma_rackup, -> { File.join(current_path, 'config.ru') }
set :puma_state, "#{shared_path}/tmp/pids/puma.state"
set :puma_pid, "#{shared_path}/tmp/pids/puma.pid"
set :puma_bind, "unix://#{shared_path}/tmp/sockets/puma.sock"    #accept array for multi-bind
set :puma_conf, "#{shared_path}/puma.rb"
set :puma_access_log, "#{shared_path}/log/puma_error.log"
set :puma_error_log, "#{shared_path}/log/puma_access.log"
set :puma_role, :app
set :puma_threads, [0, 16]
set :puma_workers, 0
set :puma_worker_timeout, nil
set :puma_init_active_record, true
set :puma_preload_app, false
set :puma_prune_bundler, true

namespace :deploy do
    desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      invoke 'puma:restart'
    end
  end

  after  :finishing,    :compile_assets
  after  :finishing,    :cleanup
  after  :finishing,    :restart
end

Production.rb content :

server 'My-IP', user: 'deploy', roles: %w{web app db}
set :puma_env, fetch(:rack_env, fetch(:rails_env, 'production'))

Body:
When deploying a Rails app using capistrano with rvm, you have to be careful that capistrano will switch the ruby version, and it might not the same ruby version as you see.

You can ssh to the remote server and check yourself

ssh deploy@My-IP
ruby -v        # It's probably not 2.3.1
which bundle
rvm use 2.3.1  # This is the actual version that will be used by capistrano
which bundle

If you cannot see the bundle installed within ruby-2.3.1, you can manually install it by

rvm use 2.3.1
gem install bundler

After that, the capistrano deployment should work as expected.


问:
jQuery autocomplete special character (Norwegian) problems
I'm using jQuery's autocomplete function on my Norwegian site. When typing in the Norwegian characters æ, ø and å, the autocomplete function suggests words with the respective character, but not words starting with the respective character. It seems like I've to manage to character encode Norwegian characters in the middle of the words, but not characters starting with it.

I'm using a PHP script with my own function for encoding Norwegian characters to UTF-8 and generating the autocomplete list.

This is really frustrating!

Code:

PHP code:

```<code>$q = strtolower($_REQUEST["q"]);
if (!$q) return;

function rewrite($string){

 $to = array('%E6','%F8','%E5','%F6','%EB','%E4','%C6','%D8','%C5','%C4','%D6','%CB', '%FC', '+', ' ');
 $from = array('æ', 'ø', 'å', 'ä', 'ö', 'ë', 'æ', 'ø', 'å', 'ä', 'ö', 'ë', '-', '-');

 $string = str_replace($from, $to, $string);

 return $string;
}
</code>```

$items is an array containg suggestion-words.

```<code>foreach ($items as $key=>$value) {
  if (strpos(strtolower(rewrite($key)), $q) !== false) {
    echo utf8_encode($key)."\n";
  }
}
</code>```

jQuery code:

```<code>$(document).ready(function(){
$("#autocomplete").autocomplete("/search_words.php", {
        position: 'after',
        selectFirst: false,
        minChars: 3,
        width: 240,
        cacheLength: 100,
        delay: 0
        }
    )
}
);
</code>```

答: I had similar problem. solution in my case was urldecode() php function to convert string back to it's original and than send query to db. </p>

ContentLicense: CC BY-SA 2.5

Body:
I'm using jQuery's autocomplete function on my Norwegian site. When typing in the Norwegian characters æ, ø and å, the autocomplete function suggests words with the respective character, but not words starting with the respective character. It seems like I've to manage to character encode Norwegian characters in the middle of the words, but not characters starting with it.

I'm using a PHP script with my own function for encoding Norwegian characters to UTF-8 and generating the autocomplete list.

This is really frustrating!

Code:

PHP code:

$q = strtolower($_REQUEST["q"]);
if (!$q) return;

function rewrite($string){

 $to = array('%E6','%F8','%E5','%F6','%EB','%E4','%C6','%D8','%C5','%C4','%D6','%CB', '%FC', '+', ' ');
 $from = array('æ', 'ø', 'å', 'ä', 'ö', 'ë', 'æ', 'ø', 'å', 'ä', 'ö', 'ë', '-', '-');

 $string = str_replace($from, $to, $string);

 return $string;
}

$items is an array containg suggestion-words.

foreach ($items as $key=>$value) {
  if (strpos(strtolower(rewrite($key)), $q) !== false) {
    echo utf8_encode($key)."\n";
  }
}

jQuery code:

$(document).ready(function(){
$("#autocomplete").autocomplete("/search_words.php", {
        position: 'after',
        selectFirst: false,
        minChars: 3,
        width: 240,
        cacheLength: 100,
        delay: 0
        }
    )
}
);


问:
Creating a dictionary with string,string, string,int and string,object
I am just getting started with C# and I'm a little stuck.

How do I create a dictionary that contains a mix of string,string, string,int, and string,object?

this is what it would look like:

```<code>var values = new Dictionary<????>
{
    "key0":
         {
         "key1": "stringValue1",
         "key2": "stringValue2",
         "key3": "stringValue3",
         "key4": 10000
         },
    "key5": "stringValue4",
    "key6": "stringValue5"
};
</code>```

I am using this as the body for a POST request. Sample code from here

```<code>var body = new FormUrlEncodedContent(values);

var url = "http://url.com/endpoint"

var resp = await client.PostAsync(url, body);

var respString = await response.Content.ReadAsStringAsync();
</code>```

答:
This is what you said in your comment:

please note that I come from a JavaScript background where you can do whatever you want with a dictionary.

Yes you can do that in JavaScript but you need to learn and understand that C# is a strongly typed language. That does not mean you have to be strong to type it, but it means the types are known at compile time (mostly). Please read into that.

Anyhow, to do what you want to do, you can do it with a Dictionary but it will not be pretty and your fellow C# developers will not be happy with you. So how about you give your keys and values some context by creating a class (OOP). Something like below:

```<code>public class Rootobject // Give it a better name
{
    public Key0 key0 { get; set; }
    public string key5 { get; set; }
    public string key6 { get; set; }
}

public class Key0
{
    public string key1 { get; set; }
    public string key2 { get; set; }
    public string key3 { get; set; }
    public int key4 { get; set; }
}
</code>```

Now you have your class so you can create one or more instances of it:

```<code>var ro = new Rootobject();
ro.key5 = "stringValue4";
ro.key6 = "stringValue5";
var key0 = new Key0();
key0.key1 = "stringValue1";
key0.key2 = "stringValue2";
key0.key3 = "stringValue3";
key0.key4 = 1000; // See we cannot put a string here. Different than JavaScript

ro.key0 = key0;
</code>```

Now you want to POST this and send it over the wire so you need to serialize it. But in your case you need to serialize it to JSON. Therefore, get NewtonSoft so it can do all the heavy lifting for you--again not saying you are not strong. Then all you need to do is this:

```<code>var json = JsonConvert.SerializeObject(ro);
</code>```

Now json will be exactly like this and you can POST it to wherever:

```<code>{
  "key0": {
    "key1": "stringValue1",
    "key2": "stringValue2",
    "key3": "stringValue3",
    "key4": 1000
  },
  "key5": "stringValue4",
  "key6": "stringValue5"
}
</code>```

How did I create the class?

The class above named RootObject, you can either create it manually or ask Visual Studio to do it for you. I am lazy so I asked Visual Studio to do it. If you are lazy then see my answer here.

Body:
I am just getting started with C# and I'm a little stuck.

How do I create a dictionary that contains a mix of string,string, string,int, and string,object?

this is what it would look like:

var values = new Dictionary<????>
{
    "key0":
         {
         "key1": "stringValue1",
         "key2": "stringValue2",
         "key3": "stringValue3",
         "key4": 10000
         },
    "key5": "stringValue4",
    "key6": "stringValue5"
};

I am using this as the body for a POST request. Sample code from here

var body = new FormUrlEncodedContent(values);

var url = "http://url.com/endpoint"

var resp = await client.PostAsync(url, body);

var respString = await response.Content.ReadAsStringAsync();

Body:
This is what you said in your comment:

please note that I come from a JavaScript background where you can do whatever you want with a dictionary.

Yes you can do that in JavaScript but you need to learn and understand that C# is a strongly typed language. That does not mean you have to be strong to type it, but it means the types are known at compile time (mostly). Please read into that.

Anyhow, to do what you want to do, you can do it with a Dictionary but it will not be pretty and your fellow C# developers will not be happy with you. So how about you give your keys and values some context by creating a class (OOP). Something like below:

public class Rootobject // Give it a better name
{
    public Key0 key0 { get; set; }
    public string key5 { get; set; }
    public string key6 { get; set; }
}

public class Key0
{
    public string key1 { get; set; }
    public string key2 { get; set; }
    public string key3 { get; set; }
    public int key4 { get; set; }
}

Now you have your class so you can create one or more instances of it:

var ro = new Rootobject();
ro.key5 = "stringValue4";
ro.key6 = "stringValue5";
var key0 = new Key0();
key0.key1 = "stringValue1";
key0.key2 = "stringValue2";
key0.key3 = "stringValue3";
key0.key4 = 1000; // See we cannot put a string here. Different than JavaScript

ro.key0 = key0;

Now you want to POST this and send it over the wire so you need to serialize it. But in your case you need to serialize it to JSON. Therefore, get NewtonSoft so it can do all the heavy lifting for you--again not saying you are not strong. Then all you need to do is this:

var json = JsonConvert.SerializeObject(ro);

Now json will be exactly like this and you can POST it to wherever:

{
  "key0": {
    "key1": "stringValue1",
    "key2": "stringValue2",
    "key3": "stringValue3",
    "key4": 1000
  },
  "key5": "stringValue4",
  "key6": "stringValue5"
}

How did I create the class?

The class above named RootObject, you can either create it manually or ask Visual Studio to do it for you. I am lazy so I asked Visual Studio to do it. If you are lazy then see my answer here.


问:
Quality Points always returning 0. Python script
So I've been given the assignment to create a GPA calculator that asks me to enter a # of courses, class names, credits, and GPA. Along with this, I'm supposed to write in a line of code that takes the GPA and multiplies it with the credits for that class in order to return a value for the quality points. Problem is that it always returns a value of zero. Any help would be greatly appreciated.</p>

```<code>classes = []
grades= []
cr = []
className = ""
num_credits = 0
quality = []
totalQP = []
total = 0
sumtotalQP = 0

Quit = 'N'
print("Welcome to the GPA calculator")
choice = str(input("\nDo you want to calculate your GPA?\nEnter Y to
calculate or N to exit the program: "))
if choice == 'N':
    exit(0)
num_classes = int(input("How many courses did you take this term?: "))
def collect():
    counter = 0
    i = 0
    x = 0
    y = 0
    z = 0
    sumtotalQP = 0
    while (counter < num_classes) and (z < num_classes) and (y <
num_classes):
        className = input("Enter name of course: ")
        classes.append(className)
        i = i +1

        num_credits = int(input("Enter the number of credits associated with
that course: "))
        cr.append(num_credits)
        cr_final = sum(cr)
        z = z +1

        grade = input("Enter Your Grade For This Class(Letter Form): ")
        grade = grade.upper()
        grades.append(grade)
        y = y +1

    for variable in quality:
        if grade == "A+":
            point = num_credits * 4.0
        elif grade == "A":
            point = num_credits * 4.0
        elif grade == "A-":
            point = num_credits * 3.7
        elif grade == "B+":
            point = num_credits * 3.3
        elif grade == "B":
            point = num_credits * 3.0
        elif grade == "B-":
            point = num_credits * 2.7
        elif grade == "C+":
            point = num_credits * 2.3
        elif grade == "C":
            point = num_credits * 2.0
        elif grade == "C-":
            point = num_credits * 1.7
        elif grade == "D+":
            point = num_credits * 1.3
        elif grade == "D":
            point = num_credits * 1.0
        elif grade == "D-":
            point = num_credits * 0.7
        totalQP.append(point)
        sumtotalQP = sum(totalQP)

    print("Courses: " + str(classes))
    print("Grades: " + str(grades))
    print("Credits: " + str(cr))
    print("Quality Points: " + str(sumtotalQP))
    print()
    print ("Total Earned Credits This Term: " + str(cr_final))
    calculate()
    choice = str(input("\nDo you want to calculate another terms GPA?\nEnter
Y to calculate or N to exit the program: "))
    if choice == 'Y':
        collect()
    elif choice == 'N':
        print ("You earned", cr_final, "overall and")
        calculate()
        qual_calc()
        exit(0)

def calculate():
    total= 0
    for element in grades:
        if element == "A+":
            total = total + 4.0
        elif element == "A":
            total = total + 4.0
        elif element == "A-":
            total = total + 3.7
        elif element == "B+":
            total = total + 3.3
        elif element == "B":
            total = total + 3.0
        elif element == "B-":
            total = total + 2.7
        elif element == "C+":
            total = total + 2.3
        elif element == "C":
            total = total + 2.0
        elif element == "C-":
            total = total + 1.7
        elif element == "D":
            total = total + 1.0
    gpa = total / num_classes
    print("you earned a GPA of", + gpa)

collect()
</code>```

答: Because you defined num_credits variable as a global value. When it's trying to calculate the "point" it's just going to top and taking the primal value (zero) of the num_credits and returning the zero value because of this. You need to define num_credits locally , not as global.</p>

Body:
So I've been given the assignment to create a GPA calculator that asks me to enter a # of courses, class names, credits, and GPA. Along with this, I'm supposed to write in a line of code that takes the GPA and multiplies it with the credits for that class in order to return a value for the quality points. Problem is that it always returns a value of zero. Any help would be greatly appreciated.

classes = []
grades= []
cr = []
className = ""
num_credits = 0
quality = []
totalQP = []
total = 0
sumtotalQP = 0

Quit = 'N'
print("Welcome to the GPA calculator")
choice = str(input("\nDo you want to calculate your GPA?\nEnter Y to
calculate or N to exit the program: "))
if choice == 'N':
    exit(0)
num_classes = int(input("How many courses did you take this term?: "))
def collect():
    counter = 0
    i = 0
    x = 0
    y = 0
    z = 0
    sumtotalQP = 0
    while (counter < num_classes) and (z < num_classes) and (y <
num_classes):
        className = input("Enter name of course: ")
        classes.append(className)
        i = i +1

        num_credits = int(input("Enter the number of credits associated with
that course: "))
        cr.append(num_credits)
        cr_final = sum(cr)
        z = z +1

        grade = input("Enter Your Grade For This Class(Letter Form): ")
        grade = grade.upper()
        grades.append(grade)
        y = y +1

    for variable in quality:
        if grade == "A+":
            point = num_credits * 4.0
        elif grade == "A":
            point = num_credits * 4.0
        elif grade == "A-":
            point = num_credits * 3.7
        elif grade == "B+":
            point = num_credits * 3.3
        elif grade == "B":
            point = num_credits * 3.0
        elif grade == "B-":
            point = num_credits * 2.7
        elif grade == "C+":
            point = num_credits * 2.3
        elif grade == "C":
            point = num_credits * 2.0
        elif grade == "C-":
            point = num_credits * 1.7
        elif grade == "D+":
            point = num_credits * 1.3
        elif grade == "D":
            point = num_credits * 1.0
        elif grade == "D-":
            point = num_credits * 0.7
        totalQP.append(point)
        sumtotalQP = sum(totalQP)

    print("Courses: " + str(classes))
    print("Grades: " + str(grades))
    print("Credits: " + str(cr))
    print("Quality Points: " + str(sumtotalQP))
    print()
    print ("Total Earned Credits This Term: " + str(cr_final))
    calculate()
    choice = str(input("\nDo you want to calculate another terms GPA?\nEnter
Y to calculate or N to exit the program: "))
    if choice == 'Y':
        collect()
    elif choice == 'N':
        print ("You earned", cr_final, "overall and")
        calculate()
        qual_calc()
        exit(0)

def calculate():
    total= 0
    for element in grades:
        if element == "A+":
            total = total + 4.0
        elif element == "A":
            total = total + 4.0
        elif element == "A-":
            total = total + 3.7
        elif element == "B+":
            total = total + 3.3
        elif element == "B":
            total = total + 3.0
        elif element == "B-":
            total = total + 2.7
        elif element == "C+":
            total = total + 2.3
        elif element == "C":
            total = total + 2.0
        elif element == "C-":
            total = total + 1.7
        elif element == "D":
            total = total + 1.0
    gpa = total / num_classes
    print("you earned a GPA of", + gpa)

collect()


问:
inserting a new node on a linked list creates a new one
i'm trying to create a linked list, which creates fine but when i try to insert new nodes to the already non-empty list and display it, only the new inserted node exist. here's the code:

```<code>struct patient{
  char name[NAME];
  int ttime;
  int atime;
  int priority;
  struct patient *next;
};

struct wr{
  struct patient *fnode;
  struct patient *lnode;
}*wr;

void wr_insert(struct patient *node){
  if(wr->fnode == NULL){
    wr->fnode = node;
    wr->lnode = node;
  }

  else{

    wr->lnode->next = node;

    wr->lnode = node;

  }

}
void display(){
  struct patient *tmp = wr->fnode;
  while(tmp != NULL){
    printf("%s %d %d %d\n",tmp->name,tmp->ttime,tmp->atime,tmp->priority);
    tmp = tmp->next;
  }
}
    void new_patient(char *line){
      int i,check;
      listsem = sem_open(lISTSEM, 0);
      char *token;
      token = strtok(line," ");
      check = atoi(token);
      if(check == 0){
        struct patient *node = malloc(sizeof(struct patient));
        strcpy(node->name,token);
        node->ttime = atoi(strtok(NULL," "));
        node->atime = atoi(strtok(NULL," "));
        node->priority = atoi(strtok(NULL," "));
        node->next = NULL;
        sem_wait(listsem);
        wr_insert(node);
        sem_post(listsem);
      }
      else{
        struct patient *group = malloc(sizeof(struct patient));
        sprintf(group->name,"20171201-%d",groupnum);
        group->ttime = atoi(strtok(NULL," "));
        group->atime = atoi(strtok(NULL," "));
        group->priority = atoi(strtok(NULL," "));
        group->next = NULL;
        groupnum++;
        sem_wait(listsem);
        wr_insert(group);
        sem_post(listsem);
        for(i=1;i<check;i++){
          struct patient *node = malloc(sizeof(struct patient));
          sprintf(node->name,"20171201-%d",groupnum);
          node->ttime = group->ttime;
          node->atime = group->atime;
          node->priority = group->priority;
          node->next = NULL;
          groupnum++;
          sem_wait(listsem);
          wr_insert(node);
          sem_post(listsem);
        }
        display();
      }
      get_patient();
    }
</code>```

So for example, if i input through the pipe "3 10 20 30" it rightfully displays the 3 nodes i've created. However if i do it again, when it should print 6 nodes, it only prints 3 again, but the new ones.

答:
this struct definition/instance:

```<code>struct wr
{
    struct patient *fnode;
    struct patient *lnode;
} *wr;
</code>```

is not correct, because the root pointers are fine, but the the instance of wr needs to be an instance of the struct, not a pointer to an instance of the struct.

Suggest:

```<code>struct wr
{
    struct patient *fnode;
    struct patient *lnode;
} wr;
</code>```

then the rest of the code needs to treat wr as an instance of the struct and not a pointer to the struct  So this:

```<code>void wr_insert(struct patient *node)
{
     if(wr->fnode == NULL)
     {
         wr->fnode = node;
         wr->lnode = node;
     }

     else
     {
         wr->lnode->next = node;
         wr->lnode = node;
     }
</code>```

should be:

```<code>void wr_insert(struct patient *node)
{
     if(wr.fnode == NULL)
     {
         wr.fnode = node;
         wr.lnode = node;
     }

     else
     {
         wr.lnode->next = node;
         wr.lnode = node;
     }
</code>```

Body:
i'm trying to create a linked list, which creates fine but when i try to insert new nodes to the already non-empty list and display it, only the new inserted node exist. here's the code:

struct patient{
  char name[NAME];
  int ttime;
  int atime;
  int priority;
  struct patient *next;
};

struct wr{
  struct patient *fnode;
  struct patient *lnode;
}*wr;

void wr_insert(struct patient *node){
  if(wr->fnode == NULL){
    wr->fnode = node;
    wr->lnode = node;
  }

  else{

    wr->lnode->next = node;

    wr->lnode = node;

  }

}
void display(){
  struct patient *tmp = wr->fnode;
  while(tmp != NULL){
    printf("%s %d %d %d\n",tmp->name,tmp->ttime,tmp->atime,tmp->priority);
    tmp = tmp->next;
  }
}
    void new_patient(char *line){
      int i,check;
      listsem = sem_open(lISTSEM, 0);
      char *token;
      token = strtok(line," ");
      check = atoi(token);
      if(check == 0){
        struct patient *node = malloc(sizeof(struct patient));
        strcpy(node->name,token);
        node->ttime = atoi(strtok(NULL," "));
        node->atime = atoi(strtok(NULL," "));
        node->priority = atoi(strtok(NULL," "));
        node->next = NULL;
        sem_wait(listsem);
        wr_insert(node);
        sem_post(listsem);
      }
      else{
        struct patient *group = malloc(sizeof(struct patient));
        sprintf(group->name,"20171201-%d",groupnum);
        group->ttime = atoi(strtok(NULL," "));
        group->atime = atoi(strtok(NULL," "));
        group->priority = atoi(strtok(NULL," "));
        group->next = NULL;
        groupnum++;
        sem_wait(listsem);
        wr_insert(group);
        sem_post(listsem);
        for(i=1;i<check;i++){
          struct patient *node = malloc(sizeof(struct patient));
          sprintf(node->name,"20171201-%d",groupnum);
          node->ttime = group->ttime;
          node->atime = group->atime;
          node->priority = group->priority;
          node->next = NULL;
          groupnum++;
          sem_wait(listsem);
          wr_insert(node);
          sem_post(listsem);
        }
        display();
      }
      get_patient();
    }

So for example, if i input through the pipe "3 10 20 30" it rightfully displays the 3 nodes i've created. However if i do it again, when it should print 6 nodes, it only prints 3 again, but the new ones.

Body:
this struct definition/instance:

struct wr
{
    struct patient *fnode;
    struct patient *lnode;
} *wr;

is not correct, because the root pointers are fine, but the the instance of wr needs to be an instance of the struct, not a pointer to an instance of the struct.

Suggest:

struct wr
{
    struct patient *fnode;
    struct patient *lnode;
} wr;

then the rest of the code needs to treat wr as an instance of the struct and not a pointer to the struct  So this:

void wr_insert(struct patient *node)
{
     if(wr->fnode == NULL)
     {
         wr->fnode = node;
         wr->lnode = node;
     }

     else
     {
         wr->lnode->next = node;
         wr->lnode = node;
     }

should be:

void wr_insert(struct patient *node)
{
     if(wr.fnode == NULL)
     {
         wr.fnode = node;
         wr.lnode = node;
     }

     else
     {
         wr.lnode->next = node;
         wr.lnode = node;
     }


问:
iCloud can't share data between two apps
I'm using the NSUbiquitousKeyValueStore to store data to iCloud from an iOS app A but I can't get any object on my iOS app B. However I can get the object on my iOS app A.
Both apps have the same team ID and both have the same Ubiquity Container Identifiers.
I have added the iCloud capability thru XCode 5, which created automatically the entitlements files.
I've also turned the iCloud option on for both App IDs.

Here is how I set data from App A:

```<code>[[NSUbiquitousKeyValueStore defaultStore] setObject:value forKey:key];
[[NSUbiquitousKeyValueStore defaultStore] synchronize];
</code>```

Here is how I get data on App B:

```<code>[[NSUbiquitousKeyValueStore defaultStore] synchronize];
[[NSUbiquitousKeyValueStore defaultStore] objectForKey:key];
</code>```

I don't know if that matters but I am running both apps in Debug mode. Do I have to create both Apps on iTunes with iCloud enabled?

Thanks!

答: Idk if this is a new thing in Xcode 9, but if you go to the Capabilities tab and after you turn on iCloud there, you can pick a container or create one. If all of your apps have the same container as specified here, you can back up your data via file system or Core Data and they can all access the same data in iCloud. I know this is 100% true because I have done it and it works really well.</p>

Body:
I'm using the NSUbiquitousKeyValueStore to store data to iCloud from an iOS app A but I can't get any object on my iOS app B. However I can get the object on my iOS app A.
Both apps have the same team ID and both have the same Ubiquity Container Identifiers.
I have added the iCloud capability thru XCode 5, which created automatically the entitlements files.
I've also turned the iCloud option on for both App IDs.

Here is how I set data from App A:

[[NSUbiquitousKeyValueStore defaultStore] setObject:value forKey:key];
[[NSUbiquitousKeyValueStore defaultStore] synchronize];

Here is how I get data on App B:

[[NSUbiquitousKeyValueStore defaultStore] synchronize];
[[NSUbiquitousKeyValueStore defaultStore] objectForKey:key];

I don't know if that matters but I am running both apps in Debug mode. Do I have to create both Apps on iTunes with iCloud enabled?

Thanks!


问:
Check if span contains value but value is after another nestled span
Trying to check if span .woocommerce-Price-amount contains 19.76. I don't think it's working since there is $  before the value I'm trying to target.

How can I ignore the currencySymbol span?

jQuery(document).ready(function($) {
  $(".ivpa_term").click(function() {
    setTimeout(function() {
      $(".woocommerce-Price-amount").each(function() {
        var inner = $(this).text();
        if (!isNaN(inner) && 19.75 < inner && inner <= 19.76) {
          console.log("Exists!");
        }
      });
    }, 0001);
  });
});```
<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>

<span class="quantity">2 ×
  <del>
    <span class="woocommerce-Price-amount amount">
      <span class="woocommerce-Price-currencySymbol">$</span> 21.95
    </span>
  </del>
  <span class="woocommerce-Price-amount amount">
    <span class="woocommerce-Price-currencySymbol">$</span>19.76
  </span>
</span></code>```

答:
I am no regex expert but you could try this if you just want to remove the dollar and get the digits</p>

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

$( ".ivpa_term" ).click(function() {
     setTimeout(function() {

  $(".woocommerce-Price-amount").each(function () {
        var inner = $(this).text();
        var numb = inner.match(/\d+\.+\d+/g); //CHECK FOR NUMBERS AND DECIMALS
        numb = numb.join("");
        if (!isNaN(numb) && 19.75 < numb && numb <= 19.76){
                            console.log("Exists!");
        }
        });
                }, 0001);
});
});
</code>```

Body:
Trying to check if span .woocommerce-Price-amount contains 19.76. I don't think it's working since there is $  before the value I'm trying to target.

How can I ignore the currencySymbol span?

jQuery(document).ready(function($) {
  $(".ivpa_term").click(function() {
    setTimeout(function() {
      $(".woocommerce-Price-amount").each(function() {
        var inner = $(this).text();
        if (!isNaN(inner) && 19.75 < inner && inner <= 19.76) {
          console.log("Exists!");
        }
      });
    }, 0001);
  });
});

2 ×

      $ 21.95

    $19.76

Body:
I am no regex expert but you could try this if you just want to remove the dollar and get the digits

jQuery(document).ready(function( $ ) {

$( ".ivpa_term" ).click(function() {
     setTimeout(function() {

  $(".woocommerce-Price-amount").each(function () {
        var inner = $(this).text();
        var numb = inner.match(/\d+\.+\d+/g); //CHECK FOR NUMBERS AND DECIMALS
        numb = numb.join("");
        if (!isNaN(numb) && 19.75 < numb && numb <= 19.76){
                            console.log("Exists!");
        }
        });
                }, 0001);
});
});


问:
What are the advantages of developing applications in C++ as compared to managed languages?
Hi I want to know why people develop library applications and employee management applications in C++ (this application, for example), when clearly the same thing can be done in C# and VB.NET in a much prettier way. Even banking applications are mostly in C++. Is there a good reason why, apart from the fact that compiled C++ code executes faster?

Can anyone shed some light on this?

答: C++ is usable on other types of systems, whereas c# and vb.net are not.</p>


问:
Get first few elements of tuples from list of list of tuples
I have a structure of list of list of tuples like:-

```<code>[[(1, 1, 96),
  (1, 2, 95),
  (0, 5, 23),
  (0, 6, 22)],
 [(2, 1, 145),
  (1, 2, 144),
  (10, 3, 143),
  (2, 4, 142)]]
</code>```

I basically want to obtain 2 list of list of tuples from this. One tuple for the first 2 columns, and the other tuple for the third column.
Desired output:-

```<code>[[(1, 1),
  (1, 2),
  (0, 5),
  (0, 6)],
 [(2, 1),
  (1, 2),
  (10, 3),
  (2, 4)]]
</code>```

&&

```<code>[[(96,),
  (95,),
  (23,),
  (22,)],
 [(145,),
  (144,),
  (143,),
  (142,)]]
</code>```

How can this be done in python?

Body:
I have a structure of list of list of tuples like:-

[[(1, 1, 96),
  (1, 2, 95),
  (0, 5, 23),
  (0, 6, 22)],
 [(2, 1, 145),
  (1, 2, 144),
  (10, 3, 143),
  (2, 4, 142)]]

I basically want to obtain 2 list of list of tuples from this. One tuple for the first 2 columns, and the other tuple for the third column.
Desired output:-

[[(1, 1),
  (1, 2),
  (0, 5),
  (0, 6)],
 [(2, 1),
  (1, 2),
  (10, 3),
  (2, 4)]]

&&

[[(96,),
  (95,),
  (23,),
  (22,)],
 [(145,),
  (144,),
  (143,),
  (142,)]]

How can this be done in python?

Body:
[[(a, b) for a, b, *c in r] for r in arr]
# => [[(1, 1), (1, 2), (0, 5), (0, 6)], [(2, 1), (1, 2), (10, 3), (2, 4)]]

[[tuple(c) for a, b, *c in r] for r in arr]
# => [[(96,), (95,), (23,), (22,)], [(145,), (144,), (143,), (142,)]]

In response to comments:

def slice_nested_array(arr, start, stop=None, step=1):
    if stop is None:
        stop = len(arr[0][0])
    return [[tuple(l[start:stop:step]) for l in r] for r in arr]

slice_nested_array(arr, 0, 2)
# => [[(1, 1), (1, 2), (0, 5), (0, 6)], [(2, 1), (1, 2), (10, 3), (2, 4)]]
slice_nested_array(arr, 2)
# => [[(96,), (95,), (23,), (22,)], [(145,), (144,), (143,), (142,)]]


问:
In TestFlight app build not showing?
I released app, now i'm releasing new version of that app. I uploaded successfully, it's build showing in activity.

But it's build not showing in test flight.

My app updated yesterday.

答:
To create .ipa file i'm using Ad Hoc option. But for testing apple send an email like this ....

```<code>Missing beta entitlement - Your app does not include the beta-reports-active entitlement. If you intend to distribute this build via TestFlight for beta testing, please re-build this app with an App Store Distribution provisioning profile. Do not use ad-hoc profiles.

After you’ve corrected the issues, you can use Xcode or Application Loader to upload a new binary to iTunes Connect.

Regards,
The App Store team
</code>```

Now i selected App Store option to create .ipa file. Now i uploaded the .ipa through application builder. Then only i'm getting my build in TestFlight.

Title: In TestFlight app build not showing?

Body:
To create .ipa file i'm using Ad Hoc option. But for testing apple send an email like this ....

Missing beta entitlement - Your app does not include the beta-reports-active entitlement. If you intend to distribute this build via TestFlight for beta testing, please re-build this app with an App Store Distribution provisioning profile. Do not use ad-hoc profiles.

After you’ve corrected the issues, you can use Xcode or Application Loader to upload a new binary to iTunes Connect.

Regards,
The App Store team

Now i selected App Store option to create .ipa file. Now i uploaded the .ipa through application builder. Then only i'm getting my build in TestFlight.


问:
How to return 403 Forbidden response as IActionResult in ASP.NET Core
I would like to return a 403 Forbidden to the client when trying to perform a restricted operation. What is the method I need to use?

I searched over the internet but I found only these for MVC 5:

If the return type for your web api method is HttpResponseMessage then
you need to use the below code:

```<code>return Request.CreateErrorResponse(HttpStatusCode.Forbidden, "RFID is disabled for this site.");
Or  if the return type for your web api method is IHttpActionResult then you need to use the below code

return StatusCode(HttpStatusCode.Forbidden,"RFID is disabled for this site.");
</code>```

How to return 403 for IActionResult type:

```<code>public IActionResult Put(string userid, [FromBody]Setting setting)
 {
    var result = _SettingsRepository.Update(userid, setting);
    if (result == true)
    {
       return Ok(201);
    }
    else
    {
       return BadRequest();
    }
 }
</code>```

答:
When you want to respond with a HTTP 403 status and allow ASP.NET Core's authentication logic to handle the response with its forbidden handling logic (can be configured in your Startup class, and may cause a redirect to another page), use:

```<code>return Forbid();
</code>```

(same applies to Unauthorized())

When you want to respond with a HTTP 403 status code from an API and do not want the ASP.NET Core authentication logic to perform any redirect or other action, use:

```<code>return StatusCode(403);

// or with developer-friendly type
return StatusCode(StatusCodes.Status403Forbidden);

// or as an api-friendly error response
return Problem(
    type: "/docs/errors/forbidden",
    title: "Authenticated user is not authorized.",
    detail: $"User '{user}' must have the Admin role.",
    statusCode: StatusCodes.Status403Forbidden,
    instance: HttpContext.Request.Path
);
</code>```

The latter example produces a client error response.

Body:
I would like to return a 403 Forbidden to the client when trying to perform a restricted operation. What is the method I need to use?

I searched over the internet but I found only these for MVC 5:

If the return type for your web api method is HttpResponseMessage then
you need to use the below code:

return Request.CreateErrorResponse(HttpStatusCode.Forbidden, "RFID is disabled for this site.");
Or  if the return type for your web api method is IHttpActionResult then you need to use the below code

return StatusCode(HttpStatusCode.Forbidden,"RFID is disabled for this site.");

How to return 403 for IActionResult type:

public IActionResult Put(string userid, [FromBody]Setting setting)
 {
    var result = _SettingsRepository.Update(userid, setting);
    if (result == true)
    {
       return Ok(201);
    }
    else
    {
       return BadRequest();
    }
 }

Body:
When you want to respond with a HTTP 403 status and allow ASP.NET Core's authentication logic to handle the response with its forbidden handling logic (can be configured in your Startup class, and may cause a redirect to another page), use:

return Forbid();

(same applies to Unauthorized())

When you want to respond with a HTTP 403 status code from an API and do not want the ASP.NET Core authentication logic to perform any redirect or other action, use:

return StatusCode(403);

// or with developer-friendly type
return StatusCode(StatusCodes.Status403Forbidden);

// or as an api-friendly error response
return Problem(
    type: "/docs/errors/forbidden",
    title: "Authenticated user is not authorized.",
    detail: $"User '{user}' must have the Admin role.",
    statusCode: StatusCodes.Status403Forbidden,
    instance: HttpContext.Request.Path
);

The latter example produces a client error response.


问:
Android Calendar View change text color
I have a CalendarView in my app. But I would like to have the background of the CalendarView black and the text inside the CalendarView white. But in xml there is no TextColor= in the CalendarView. So how can I change the text of the CalendarView?

I have tried every solution on StackOverflow and the internet so far. I've managed to change the color of the days in the CalendarView but not the month and year.

I've tried both methods in this post: Set the text color of calendar view month name

And I've tried this method:
Change CalendarView style

And some other I found on the internet but nothing was succesfull.

答:
Set style in your CalendarView

```<code><CalendarView
    android:id="@+id/calendarView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:theme="@style/CalenderViewCustom"
    android:dateTextAppearance="@style/CalenderViewDateCustomText"
    android:weekDayTextAppearance="@style/CalenderViewWeekCustomText" />
</code>```

Inside Style.xml

```<code>    <style name="CalenderViewCustom" parent="Theme.AppCompat">
        <item name="colorAccent">@color/red</item>
        <item name="colorPrimary">@color/white</item>
    </style>

    <style name="CalenderViewDateCustomText" parent="android:TextAppearance.DeviceDefault.Small">
        <item name="android:textColor">@color/white</item>
        <item name="android:weekNumberColor">@color/red</item>
    </style>

    <style name="CalenderViewWeekCustomText" parent="android:TextAppearance.DeviceDefault.Small">
        <item name="android:textColor">@color/white</item>
    </style>
</code>```

Title: Android Calendar View change text color

Body:
Set style in your CalendarView

<CalendarView
    android:id="@+id/calendarView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:theme="@style/CalenderViewCustom"
    android:dateTextAppearance="@style/CalenderViewDateCustomText"
    android:weekDayTextAppearance="@style/CalenderViewWeekCustomText" />

Inside Style.xml

    <style name="CalenderViewCustom" parent="Theme.AppCompat">
        <item name="colorAccent">@color/red</item>
        <item name="colorPrimary">@color/white</item>
    </style>

    <style name="CalenderViewDateCustomText" parent="android:TextAppearance.DeviceDefault.Small">
        <item name="android:textColor">@color/white</item>
        <item name="android:weekNumberColor">@color/red</item>
    </style>

    <style name="CalenderViewWeekCustomText" parent="android:TextAppearance.DeviceDefault.Small">
        <item name="android:textColor">@color/white</item>
    </style>


问:
How to create tag fileds in iOS
How can I create a tag fields like the below attached screenshot in iOS.

tag text shall be taken from the user input.

答:
I recommend UICollectionView to implement Tags. It's less code, less overhead and easy to implement.

Follow this link for guidance :

https://codentrick.com/create-a-tag-flow-layout-with-uicollectionview/

This is how it looks like. Please note it is flexible too.

Hope this will help you

Title: How to create tag fileds in iOS


问:
Sliding window solution for min length substring with all distinct characters of the original string
Could anyone please tell where am I going wrong. Below is my code.
Here I am using sliding window solution with left and right as pointers to String.
"dist_count" contains the count for unique characters in string.</p>

```<code>public class Solution {
    public String findSubstring(String s) {
        if (s == null || s.length() == 0)
            return "";
        int dist_count = 0;
        int[] hash = new int[256]; // character hash
        boolean[] visited = new boolean[256];
        // record each character in s to hash
        for (char c : s.toCharArray()) {
            hash[c]++;
        }
        for (char c : s.toCharArray()) {
            if (visited[c] == false) {
                dist_count++;
                visited[c] = true;
            }
        }
        System.out.println(dist_count);
        int left = 0, right = 0, count = 0;
        int min_window = Integer.MAX_VALUE;
        int startIndex = -1;
        while (right < s.length()) {
            if (hash[s.charAt(right)] >= 1) {
                count++;
            }
            hash[s.charAt(right)]--;
            right++;

            if (count == dist_count) {
                while (hash[s.charAt(left)] > 1) {
                    if (hash[s.charAt(left)] > 1)
                        hash[s.charAt(left)]--;
                    left++;
                }
                int window = right - left + 1;
                if (min_window > window) {
                    min_window = window;
                    startIndex = left;
                }
            }
        }
        return s.substring(startIndex, startIndex + min_window);
    }

    public static void main(String args[]) {
        Solution ob = new Solution();
        String str = ob.findSubstring("abdacbfcabegbdfcadcefa");
        System.out.println(str);
    }
}
</code>```

答:
Your algorithm is right but there are some issues in implementation.
You should not use the hash leftover from original string. Look at the following code:

```<code>for(int i = 0; i < 256; ++i) hash[i] = 0;  // Before entering while reset hash
                                           // counters for sliding window
while (right < s.length()) {
    if (hash[s.charAt(right)] == 0) {  // Use hash here for counting frequency
        count++;
}
hash[s.charAt(right)]--;  // Consistently increment for right and decrement for left
</code>```

Working code with above changes

Body:
Could anyone please tell where am I going wrong. Below is my code.
Here I am using sliding window solution with left and right as pointers to String.
"dist_count" contains the count for unique characters in string.

public class Solution {
    public String findSubstring(String s) {
        if (s == null || s.length() == 0)
            return "";
        int dist_count = 0;
        int[] hash = new int[256]; // character hash
        boolean[] visited = new boolean[256];
        // record each character in s to hash
        for (char c : s.toCharArray()) {
            hash[c]++;
        }
        for (char c : s.toCharArray()) {
            if (visited[c] == false) {
                dist_count++;
                visited[c] = true;
            }
        }
        System.out.println(dist_count);
        int left = 0, right = 0, count = 0;
        int min_window = Integer.MAX_VALUE;
        int startIndex = -1;
        while (right < s.length()) {
            if (hash[s.charAt(right)] >= 1) {
                count++;
            }
            hash[s.charAt(right)]--;
            right++;

            if (count == dist_count) {
                while (hash[s.charAt(left)] > 1) {
                    if (hash[s.charAt(left)] > 1)
                        hash[s.charAt(left)]--;
                    left++;
                }
                int window = right - left + 1;
                if (min_window > window) {
                    min_window = window;
                    startIndex = left;
                }
            }
        }
        return s.substring(startIndex, startIndex + min_window);
    }

    public static void main(String args[]) {
        Solution ob = new Solution();
        String str = ob.findSubstring("abdacbfcabegbdfcadcefa");
        System.out.println(str);
    }
}

Body:
Your algorithm is right but there are some issues in implementation.
You should not use the hash leftover from original string. Look at the following code:

for(int i = 0; i < 256; ++i) hash[i] = 0;  // Before entering while reset hash
                                           // counters for sliding window
while (right < s.length()) {
    if (hash[s.charAt(right)] == 0) {  // Use hash here for counting frequency
        count++;
}
hash[s.charAt(right)]--;  // Consistently increment for right and decrement for left

Working code with above changes


答:
You can reach that value in multiple ways, one of them could be

```<code> var textNode = Array.from(this.childNodes).filter(el => el.nodeType == 3 && Number(el.nodeValue) > 0 );
 var inner = $(textNode[0]).text().trim();
</code>```

Explanation

Get all the childNodes of element .woocommerce-Price-amount

Filter textnodes whose numerical value is greater than 0

Demo

      $(".woocommerce-Price-amount").each(function() {
        var textNode = Array.from(this.childNodes).filter(el => el.nodeType == 3 && Number(el.nodeValue) > 0 );
        //console.log(textNode);
        var inner = $(textNode[0]).text().trim();
        console.log(inner);
        if (!isNaN(inner) && 19.75 < inner && inner <= 19.76) {
          console.log("Exists!");
        }
      });```
<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>
<span class="quantity">2 ×
 <del>
   <span class="woocommerce-Price-amount amount">
     <span class="woocommerce-Price-currencySymbol">$</span> 21.95
</span>
</del>
<span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">$</span>19.76</span><span class="my-price"></span></span></code>```

Title: Check if span contains value but value is after another nestled span

Body:
You can reach that value in multiple ways, one of them could be

 var textNode = Array.from(this.childNodes).filter(el => el.nodeType == 3 && Number(el.nodeValue) > 0 );
 var inner = $(textNode[0]).text().trim();

Explanation

Get all the childNodes of element .woocommerce-Price-amount

Filter textnodes whose numerical value is greater than 0

Demo

      $(".woocommerce-Price-amount").each(function() {
        var textNode = Array.from(this.childNodes).filter(el => el.nodeType == 3 && Number(el.nodeValue) > 0 );
        //console.log(textNode);
        var inner = $(textNode[0]).text().trim();
        console.log(inner);
        if (!isNaN(inner) && 19.75 < inner && inner <= 19.76) {
          console.log("Exists!");
        }
      });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="quantity">2 ×
 <del>
   <span class="woocommerce-Price-amount amount">
     <span class="woocommerce-Price-currencySymbol">$</span> 21.95
</span>
</del>
<span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">$</span>19.76</span><span class="my-price"></span></span>


问:
Compiling a .java file with incorrect package name
In the book "OCA Oracle Certified Associate Java SE 8 Programmer I Study Guide Exam 1Z0-808" by Boyarsky and Selikoff I encountered a confusing question in the review exam for Chapter I:

14. Given the following class in the file /my/directory/named/A/Bird.java:

INSERT CODE HERE
public class Bird { }

Which of the following replaces INSERT CODE HERE if we compile from /my/directory? (Choose all that apply)

A. package my.directory.named.a;

B. package my.directory.named.A;

C. package named.a;

D. package named.A;

E. package a;

F. package A;

G. Does not compile

The book states that the correct answer is just D. (we'll ignore the fact that they wrote "Choose all that apply" despite stating that they would only do so if there were more than 1 answer, earlier in the book), with the explanation:

D. The package name represents any folders underneath the current path, which is
named.A in this case. Option B is incorrect because package names are case sensitive,
just like variable names and other identifiers.

I'm totally confused with this on various levels:

I tried to compile the file from /my/directory using javac /named/A/Bird.java and the code compiles successfully with any of the answers above. Furthermore, the code compiles no matter what I write after package in the first line of the class.

Let's assume I completely missed the point in (no pun intended) point 1 and that's not how we compile from /my/directory, then I've got these questions:

How do we compile from /my/directory?

Why is the option B. incorrect? The explanation they provided for B.  makes no sense, obviously.

Can someone shed some light on this matter?

答:
The short answer is the question is wrong.

A single class can be compiled from anywhere, without considering the package hierarchy if it has no references to other custom classes (so you can use String etc.). This is because it doesn't need to do any lookups for other classes, so there's no need for anything special in the compile-time classpath. As soon as you add a reference to let's say class named.A.Rock the compilation will no longer work, because the directory hierarchy doesn't match the package hierarchy (unless you put Bird in named.A package as well).

So the example in the question is just bad. As soon as you add a reference to another class and the package hierarchy starts to matter, D is the correct answer. The question is a bit poor since you can set the compile time classpath explicitly, at which point the concept of "current directory" doesn't matter one bit and all of the answers would be valid.