问:
Pig Latin Program Java, problems with vowel inputs
This is my attempt at a simple Pig Latin Word Translator in Java.  If the word starts with a consonant, the consonant is moved to the end of the word and "ay" is added.  If the word starts with a vowel then way is added to the end of the word.  I have difficulty understanding as to why my program is having issues with vowels.

Example:

apple is translated to ppleaay instead of appleway
Yet, van is translated to anvay as it should.

```<code>public class PigLatin
{
    public static String translate (String original) {
        String vowels = "aeiouAEIOU";
        String latin = "";
        for (int i = 0; i < vowels.length() - 1; i++) {
            if (original.charAt(0) == vowels.charAt(i)) {
                latin = original + "way";
            }else {
                latin = original.substring(1) + original.charAt(0) + "ay";
            }
        }
        return latin;
    }

    public static void main(String[] args) {

        System.out.print("What is the word to be translated: ");
        String origWord = IO.readString();
        String newWord = translate(origWord);
        System.out.print("The translated word is: " + newWord);
    }
}
</code>```

答:
Your loop will loop through every single vowel without stopping when it finds a match. Basically, the last test is the only one that will matter, and since apple does not start with U, you get the unexpected result.

There are a couple of ways of dealing with this. One is to terminate the loop early if you find a match. You can use a break, but a return would be better. The reason is that you will end up constructing a bunch of useless results along the way for non-matching characters otherwise. Here is an example using return:

```<code>public static String translate (String original) {
    String vowels = "aeiouAEIOU";
    for (int i = 0; i < vowels.length() - 1; i++) {
        if (original.charAt(0) == vowels.charAt(i)) {
            return original + "way";
        }
    }
    return original.substring(1) + original.charAt(0) + "ay";
}
</code>```

Another, probably better way would be check if the first character of your word is in the list of vowels using one of the built-in String methods instead of reinventing the wheel. A couple of obvious options are String.indexOf(int) and String.contains(CharSequence). Here are examples of how to use these methods:

```<code>public static String translate (String original) {
    String vowels = "aeiouAEIOU";
    if(vowels.contains(original.substring(0, 1))) {
        return original + "way";
    }
    return original.substring(1) + original.charAt(0) + "ay";
}
</code>```

or

```<code>public static String translate (String original) {
    String vowels = "aeiouAEIOU";
    if(vowels.indexOf(original.charAt(0)) >= 0) {
        return original + "way";
    }
    return original.substring(1) + original.charAt(0) + "ay";
}
</code>```

As @Aloso pointed out, you may want to handle the case where your original string begins with an uppercase letter a bit differently. For example, you would probably want Van to become Anvay, not anVay. I would recommend using the isUpperCase(char), toUpperCase(char) and toLowerCase(char) methods of the Character class rather than messing with ASCII codes. If you need this functionality, replace the line return original.substring(1) + original.charAt(0) + "ay"; with the following in any of the examples above:

```<code>if(Character.isUpperCase(original.charAt(0))) {
    return Character.toUpperCase(original.charAt(1)) + original.substring(2) + Character.toLowerCase(original.charAt(0)) + "ay";
}
return original.substring(1) + original.charAt(0) + "ay";
</code>```

Using the methods in Character also means that your strings will behave properly even if you enter non-Latin characters. Although is it really pig-Latin in that case?

Body:
This is my attempt at a simple Pig Latin Word Translator in Java.  If the word starts with a consonant, the consonant is moved to the end of the word and "ay" is added.  If the word starts with a vowel then way is added to the end of the word.  I have difficulty understanding as to why my program is having issues with vowels.

Example:

apple is translated to ppleaay instead of appleway
Yet, van is translated to anvay as it should.

public class PigLatin
{
    public static String translate (String original) {
        String vowels = "aeiouAEIOU";
        String latin = "";
        for (int i = 0; i < vowels.length() - 1; i++) {
            if (original.charAt(0) == vowels.charAt(i)) {
                latin = original + "way";
            }else {
                latin = original.substring(1) + original.charAt(0) + "ay";
            }
        }
        return latin;
    }

    public static void main(String[] args) {

        System.out.print("What is the word to be translated: ");
        String origWord = IO.readString();
        String newWord = translate(origWord);
        System.out.print("The translated word is: " + newWord);
    }
}

Body:
Your loop will loop through every single vowel without stopping when it finds a match. Basically, the last test is the only one that will matter, and since apple does not start with U, you get the unexpected result.

There are a couple of ways of dealing with this. One is to terminate the loop early if you find a match. You can use a break, but a return would be better. The reason is that you will end up constructing a bunch of useless results along the way for non-matching characters otherwise. Here is an example using return:

public static String translate (String original) {
    String vowels = "aeiouAEIOU";
    for (int i = 0; i < vowels.length() - 1; i++) {
        if (original.charAt(0) == vowels.charAt(i)) {
            return original + "way";
        }
    }
    return original.substring(1) + original.charAt(0) + "ay";
}

Another, probably better way would be check if the first character of your word is in the list of vowels using one of the built-in String methods instead of reinventing the wheel. A couple of obvious options are String.indexOf(int) and String.contains(CharSequence). Here are examples of how to use these methods:

public static String translate (String original) {
    String vowels = "aeiouAEIOU";
    if(vowels.contains(original.substring(0, 1))) {
        return original + "way";
    }
    return original.substring(1) + original.charAt(0) + "ay";
}

or

public static String translate (String original) {
    String vowels = "aeiouAEIOU";
    if(vowels.indexOf(original.charAt(0)) >= 0) {
        return original + "way";
    }
    return original.substring(1) + original.charAt(0) + "ay";
}

As @Aloso pointed out, you may want to handle the case where your original string begins with an uppercase letter a bit differently. For example, you would probably want Van to become Anvay, not anVay. I would recommend using the isUpperCase(char), toUpperCase(char) and toLowerCase(char) methods of the Character class rather than messing with ASCII codes. If you need this functionality, replace the line return original.substring(1) + original.charAt(0) + "ay"; with the following in any of the examples above:

if(Character.isUpperCase(original.charAt(0))) {
    return Character.toUpperCase(original.charAt(1)) + original.substring(2) + Character.toLowerCase(original.charAt(0)) + "ay";
}
return original.substring(1) + original.charAt(0) + "ay";

Using the methods in Character also means that your strings will behave properly even if you enter non-Latin characters. Although is it really pig-Latin in that case?


来源: stackexchange

问:
Moving outward a range of numbers plotted on a curve line
I was wondering how to make the numbers currently plotted on the curve line below to move a bit outward such that however a and b in my R code are changed the distance between the numbers and the curve line remain the same (i.e., constant)?

Please see my R code below the following image:

```<code> a = 0  ;  b = 1

curve( dnorm(x, mean = a, sd = b ), -4, 4, axes = F, ann = F)

xx <- -4:4

yy <- dnorm(xx, mean = a, sd = b)

text(xx, yy, paste(round(yy, 2) ), font = 2 )
</code>```

答:
```<code>a = 0
b = 1

#Draw curve
curve(dnorm(x, mean = a, sd = b ), -4, 4, axes = F, ann = F)

#Assign curve to 'cc' and determine the length of points on the curve
cc = curve(dnorm(x, mean = a, sd = b ), -4, 4, axes = F, ann = F)
l_cc = length(cc$x)

xx <- -4:4
yy <- dnorm(xx, mean = a, sd = b)

#Find indices of values in cc$x closest ot xx
slope_inds = findInterval(xx, cc$x)

#Calculate approximate slope of cc for each xx
slope = numeric(0)
for (i in 1:length(slope_inds)){
    if (slope_inds[i] == 1){
        n = 1
    }else if (slope_inds[i] == l_cc){
        n = l_cc - 1
    }else{
        n = slope_inds[i]
    }
    slope[i] = round(diff(cc$y[n:(n+1)])/diff(cc$x[n:(n+1)]), 1)
}

#Assign pos value based on slope of cc. For ~zero slope, put text on top
# For other slopes assign values accordingly
positions = integer(0)
positions[slope == 0] = 3
positions[slope > 0] = 2
positions[slope < 0] = 4

#Write text
points(xx,yy)
text(xx, yy, paste(round(yy, 2) ), font = 2, pos = positions)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was wondering how to make the numbers currently plotted on the curve line below to move a bit outward such that however a and b in my R code are changed the distance between the numbers and the curve line remain the same (i.e., constant)?

Please see my R code below the following image:

 a = 0  ;  b = 1

curve( dnorm(x, mean = a, sd = b ), -4, 4, axes = F, ann = F)

xx <- -4:4

yy <- dnorm(xx, mean = a, sd = b)

text(xx, yy, paste(round(yy, 2) ), font = 2 )


问:
Table CSS Issue
I have this in HTML:

```<code><div class="dataBurst" title="What is the Matrix?">
    <table align="center" height="100%">
        <tr>
            <td id="matrixTD">
                <span onclick="alert('Not Yet Online');" class="coredump"
                    title="How Would You Know the Difference Between the Dream World And the Real World?">
                    Click for System Core Dump
                </span>
            </td>
        </tr>
    </table>
</div>
</code>```

The CSS I'm using:

```<code>div.dataBurst
{
    vertical-align:middle;
    width:500px;
    height:321px;
    background-color:#FFF;
    margin-left:auto;
    margin-right:auto;
    border-width:1px;
    border-style:solid;
    margin-bottom:20px;
    padding:5px;
    float:left;
    cursor:pointer;
    cursor:default;
    font-weight:normal;
    font-size:9px;

    overflow:auto;
    overflow-y: scroll;
    overflow-x: hide;
    text-align:justify;

    scrollbar-base-color:#575757;
    scrollbar-3dlight-color:#a6a6a6;
    scrollbar-track-color: #a6a6a6;
}

td#matrixTD
{
    text-align:justify;
    cursor:default;
}
</code>```

The issue is when I try to create a class/id using:
, it does not work; how can I implement this?

my site is at: http://guygar.com

答:
This works. The HTML:

```<code><div class="dataBurst" title="What is the Matrix?">
    <table id="table">
        <tr>
            <td id="matrixTD">
                <span onclick="alert('Not Yet Online');" class="coredump"
                    title="How Would You Know the Difference Between the Dream World And the Real World?">
                    Click for System Core Dump
                </span>
            </td>
        </tr>
    </table>
</div>
</code>```

And the CSS:

```<code>div.dataBurst {
    vertical-align:middle;
    width:500px;
    height:321px;
    background-color:#FFF;
    margin-left:auto;
    margin-right:auto;
    border-width:1px;
    border-style:solid;
    margin-bottom:20px;
    padding:5px;
    float:left;
    cursor:pointer;
    cursor:default;
    font-weight:normal;
    font-size:9px;

    overflow:auto;
    overflow-y: scroll;
    overflow-x: hide;
    text-align:justify;

    scrollbar-base-color:#575757;
    scrollbar-3dlight-color:#a6a6a6;
    scrollbar-track-color: #a6a6a6;
}

table#table
{
    margin: 0 auto; height: 100%;

}

td#matrixTD
{
    text-align:justify!important;
    cursor:default;
}
</code>```

And you should delete cursor: default; take a look here (only IE 5.5 is not supporting cursor: pointer; but nobody is using it anymore.): http://www.quirksmode.org/css/cursor.html#t09

ContentLicense: CC BY-SA 2.5

Title: Table CSS Issue

Body:
I have this in HTML:

                    Click for System Core Dump

The CSS I'm using:

div.dataBurst
{
    vertical-align:middle;
    width:500px;
    height:321px;
    background-color:#FFF;
    margin-left:auto;
    margin-right:auto;
    border-width:1px;
    border-style:solid;
    margin-bottom:20px;
    padding:5px;
    float:left;
    cursor:pointer;
    cursor:default;
    font-weight:normal;
    font-size:9px;

    overflow:auto;
    overflow-y: scroll;
    overflow-x: hide;
    text-align:justify;

    scrollbar-base-color:#575757;
    scrollbar-3dlight-color:#a6a6a6;
    scrollbar-track-color: #a6a6a6;
}

td#matrixTD
{
    text-align:justify;
    cursor:default;
}

The issue is when I try to create a class/id using:
, it does not work; how can I implement this?

my site is at: http://guygar.com

Body:
This works. The HTML:

<div class="dataBurst" title="What is the Matrix?">
    <table id="table">
        <tr>
            <td id="matrixTD">
                <span onclick="alert('Not Yet Online');" class="coredump"
                    title="How Would You Know the Difference Between the Dream World And the Real World?">
                    Click for System Core Dump
                </span>
            </td>
        </tr>
    </table>
</div>

And the CSS:

div.dataBurst {
    vertical-align:middle;
    width:500px;
    height:321px;
    background-color:#FFF;
    margin-left:auto;
    margin-right:auto;
    border-width:1px;
    border-style:solid;
    margin-bottom:20px;
    padding:5px;
    float:left;
    cursor:pointer;
    cursor:default;
    font-weight:normal;
    font-size:9px;

    overflow:auto;
    overflow-y: scroll;
    overflow-x: hide;
    text-align:justify;

    scrollbar-base-color:#575757;
    scrollbar-3dlight-color:#a6a6a6;
    scrollbar-track-color: #a6a6a6;
}

table#table
{
    margin: 0 auto; height: 100%;

}

td#matrixTD
{
    text-align:justify!important;
    cursor:default;
}

And you should delete cursor: default; take a look here (only IE 5.5 is not supporting cursor: pointer; but nobody is using it anymore.): http://www.quirksmode.org/css/cursor.html#t09


问:
Javascript for loop array length
I am new to javascript and I am having this really simple problem.

```<code>    var counters = [];
    for (var i = 0; i < 3; i++) {
        counters.push[i];
    }
    alert(counters.length);
</code>```

This code is expected to alert 3, but the real result is 0. Can someone please this to me. I'm not really sure how to ask about this error. Thanks

Sorry for this question.. I have fixed it. Thanks for answering

I can't ask another quesition yet since not enough karma.. But My real problem is this

```<code>for (var i = 0; i < 2; i++) {
if (i == 1) {document.write(" <tr class='noBorder' onclick='alert(i)');}
if (i == 0){ document.write(" <tr class='noBorder' onclick='alert(i)');}
}
</code>```

Whenever I click on a row, the alert results in 2.
 It's basically this question, but in html
Passing parameter onclick, in a loop

答:
```<code>counters.push[i];
</code>```

is supposed to be

```<code>counters.push(i);
</code>```

or

```<code>counters[i] = i;
</code>```

() is used for method invocation. push is a method available for all objects of type array, so in this case you are supposed to use () to add values to the array.

[] is used to access a ( named dynamic ) property on a object.

```<code>var obj = {
   a : 10,
   c : function() {
       return 20;
   }
};
</code>```

In the above use case to access the values of a and b, you would use . or [] to access the properties of the object.

```<code>obj.a  || obj['a'];
obj.b()  || obj['b']();
</code>```

Because property c is a function, you would first access the property using [] and then call the function using ()

Title: Javascript for loop array length

Body:
I am new to javascript and I am having this really simple problem.

    var counters = [];
    for (var i = 0; i < 3; i++) {
        counters.push[i];
    }
    alert(counters.length);

This code is expected to alert 3, but the real result is 0. Can someone please this to me. I'm not really sure how to ask about this error. Thanks

Sorry for this question.. I have fixed it. Thanks for answering

I can't ask another quesition yet since not enough karma.. But My real problem is this

for (var i = 0; i < 2; i++) {
if (i == 1) {document.write(" <tr class='noBorder' onclick='alert(i)');}
if (i == 0){ document.write(" <tr class='noBorder' onclick='alert(i)');}
}

Whenever I click on a row, the alert results in 2.
 It's basically this question, but in html
Passing parameter onclick, in a loop

Body:
counters.push[i];

is supposed to be

counters.push(i);

or

counters[i] = i;

() is used for method invocation. push is a method available for all objects of type array, so in this case you are supposed to use () to add values to the array.

[] is used to access a ( named dynamic ) property on a object.

var obj = {
   a : 10,
   c : function() {
       return 20;
   }
};

In the above use case to access the values of a and b, you would use . or [] to access the properties of the object.

obj.a  || obj['a'];
obj.b()  || obj['b']();

Because property c is a function, you would first access the property using [] and then call the function using ()


问:
add values with one another with input field submit in php calculator
I want a calculator with my PHP code that adds values with one after one with submit button.like when I input a number then submit it and show it on the page then and input other, it should add previous number.and then enter another then submit.like these, numbers are adding with one another after submitting.

<?php
session_start();

?>

<?php
error_reporting(0);
?>

<title>adding input single values</title>

<form method="post">

    <input type="text"  name='number'  method="post"/>
    <input type="submit" />
</form>
<?php
if(!isset($_POST['number']))
{

}
else
{
$sum += $_POST['number'];
echo ++$sum;

}
?>

```

here is the output

答:
```<code><?php

if(!isset($_POST['number'])) {
    // ...
}
else {
    $_SESSION['number'] = isset($_SESSION['number']) ? $_SESSION['number'] : '';
    $_SESSION['number'] += $_POST['number'];
    echo $_SESSION['number'];
}
</code>```

Body:
I want a calculator with my PHP code that adds values with one after one with submit button.like when I input a number then submit it and show it on the page then and input other, it should add previous number.and then enter another then submit.like these, numbers are adding with one another after submitting.

<?php
session_start();

?>

<?php
error_reporting(0);
?>

<title>adding input single values</title>

<form method="post">

    <input type="text"  name='number'  method="post"/>
    <input type="submit" />
</form>
<?php
if(!isset($_POST['number']))
{

}
else
{
$sum += $_POST['number'];
echo ++$sum;

}
?>

here is the output


问:
How to find the element of this HTML link? The class_name, Xpath and css selector nothing is helping to find the element
```<code><div data-offset-key="80psj-0-0" class="_1mf _1mj"><span data-offset-key="80psj-0-0"><br data-text="true"></span></div>
</code>```

I have used these three options

driver.find_element_by_class_name("_1mf_1mj")

driver.find_element_by_xpath("//*[@id="js_1e"]/div[1]/div[1]/div[2]/div/div/div/div/div[2]/div/div/div/div")

driver.find_element_by_css_selector("#js_1e > div._i-o > div.clearfix._ikh > div._4bl9 > div > div > div > div > div._5rpb > div > div > div > div")

答:
With css selector:

```<code>driver.find_element_by_css_selector('div[data-offset-key=80psj-0-0]')
</code>```

Or as Willem Van Onsem said in comments, with xpath:

```<code>driver.find_element_by_xpath('//div[@data-offset-key="80psj-0-0"]')
</code>```

Body:
With css selector:

driver.find_element_by_css_selector('div[data-offset-key=80psj-0-0]')

Or as Willem Van Onsem said in comments, with xpath:

driver.find_element_by_xpath('//div[@data-offset-key="80psj-0-0"]')


问:
Can I call commit from one of mutations in Vuex store
I have a vuex store, like following:

```<code>import spreeApi from '../../gateways/spree-api'
// initial state
const state = {
  products: [],
  categories: []
}

// mutations
const mutations = {
 SET_PRODUCTS: (state, response) => {
   state.products = response.data.products
   commit('SET_CATEGORIES')
 },
 SET_CATEGORIES: (state) => {
   state.categories = state.products.map(function(product) { return product.category})
 }

}

const actions = {
 FETCH_PRODUCTS: (state, filters) => {
   return spreeApi.get('products').then(response => state.commit('SET_PRODUCTS', response))
 }
}

export default {
  state,
  mutations,
  actions
}
</code>```

I want to call mutation: SET_CATEGORIES from mutation: SET_PRODUCTS, But this gives me error:

projectFilter.js:22 Uncaught (in promise) ReferenceError: commit is not defined(…)

What should be correct way to do this. I tried store.commit and this.commit, but these also gave similar errors.

答:
If you absolutely must commit two mutations, why not do it from an action? Actions don't have to perform async operations. You can destructure the commit method in your action the same way you do with state like so:</p>

```<code>commitTwoThings: ({commit}, payload) => {
  commit('MUTATION_1', payload.thing)
  commit('MUTATION_2', payload.otherThing)
}
</code>```

Body:
I have a vuex store, like following:

import spreeApi from '../../gateways/spree-api'
// initial state
const state = {
  products: [],
  categories: []
}

// mutations
const mutations = {
 SET_PRODUCTS: (state, response) => {
   state.products = response.data.products
   commit('SET_CATEGORIES')
 },
 SET_CATEGORIES: (state) => {
   state.categories = state.products.map(function(product) { return product.category})
 }

}

const actions = {
 FETCH_PRODUCTS: (state, filters) => {
   return spreeApi.get('products').then(response => state.commit('SET_PRODUCTS', response))
 }
}

export default {
  state,
  mutations,
  actions
}

I want to call mutation: SET_CATEGORIES from mutation: SET_PRODUCTS, But this gives me error:

projectFilter.js:22 Uncaught (in promise) ReferenceError: commit is not defined(…)

What should be correct way to do this. I tried store.commit and this.commit, but these also gave similar errors.

Body:
If you absolutely must commit two mutations, why not do it from an action? Actions don't have to perform async operations. You can destructure the commit method in your action the same way you do with state like so:

commitTwoThings: ({commit}, payload) => {
  commit('MUTATION_1', payload.thing)
  commit('MUTATION_2', payload.otherThing)
}


问:
Get number before a specified string
Given the string

```<code>RAM Statistics: 5954 / 8174 743=InUse 746=Peak
</code>```

I need a RegEx (or three) to extract the 743, the 746, and ideally the 5954 / 8174 so each can be assigned to a specific variable.

I THINK this is what LookBehind is used for, but I am having a hell of a time actually getting a RegEx to "Get the numbers between a Space and =Peak", for example.

I have tried

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'
$string -match $regexPeak > $null
$peak = $matches[0]
Write-Host "$peak"
</code>```

But that's returning nothing.

UPDATE:
Per Joshua I have tried

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(\d+) / (\d+) (\d+)=\D+(\d+)=peak/gi'
$string -match $regexPeak
$peak = $matches[0]
Write-Host "$peak!"
</code>```

And both $matches[0] and [1] return everything before the =Peak. So

```<code>Statistics:     5954 /     8174       743=InUse      746!
</code>```

答:
Just to pull apart your trial code:

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'
</code>```

Your regex has a lookbehind for a space, which is OK. Then it has a middle bit with a grouping of (.#) and that almost certainly is not doing what you intend - a dot matches any single character, and a hash matches a hash. So it would match things like 4#, z#, ## and not 746. Then you have a positive lookahead, which looks OK. But the combined effect is to lock the inner bit down to two characters and look for space, two characters (where the second is a hash), equals peak.

Probably you want \d to mean a digit, and + to mean "match one or more times", so \d+

The second thing you're doing is mixing up lookarounds and grouping. One use of regex involves matching a string like 'number is 4' with a pattern like 'number is (\d)'. The whole pattern matches and appears in the output, and then you query the capture groups to pick out the 4 out of the whole match. $matches[0] is number is 4 and $matches[1] is 4.

Another use of regex involves matching the number with a lookbehind like (?<=number is )\d because the lookbehind matches but it doesn't appear in the output. So the output of $matches[0] is just the 4 and you don't need any groups. So you're using lookarounds to match without having the text in the output, and trying to group the number as well, which works but it's overkill / unnecessary mixed use of two different approaches.

That means your regex is very close to working:

```<code>$regexPeak = '(?<= )(.#)(?=\=Peak)'  # change to
$regexPeak = '(?<= )\d+(?=\=Peak)'   # to indicate "one or more digits"
</code>```

and:

```<code>PS C:\> $string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
PS C:\> $regexPeak = '(?<= )\d+(?=\=Peak)'
PS C:\> $string -match $regexPeak > $null
PS C:\> $peak = $matches[0]
PS C:\> $peak
746
</code>```

Title: Get number before a specified string

Body:
Given the string

RAM Statistics: 5954 / 8174 743=InUse 746=Peak

I need a RegEx (or three) to extract the 743, the 746, and ideally the 5954 / 8174 so each can be assigned to a specific variable.

I THINK this is what LookBehind is used for, but I am having a hell of a time actually getting a RegEx to "Get the numbers between a Space and =Peak", for example.

I have tried

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'
$string -match $regexPeak > $null
$peak = $matches[0]
Write-Host "$peak"

But that's returning nothing.

UPDATE:
Per Joshua I have tried

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(\d+) / (\d+) (\d+)=\D+(\d+)=peak/gi'
$string -match $regexPeak
$peak = $matches[0]
Write-Host "$peak!"

And both $matches[0] and [1] return everything before the =Peak. So

Statistics:     5954 /     8174       743=InUse      746!

Body:
Just to pull apart your trial code:

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'

Your regex has a lookbehind for a space, which is OK. Then it has a middle bit with a grouping of (.#) and that almost certainly is not doing what you intend - a dot matches any single character, and a hash matches a hash. So it would match things like 4#, z#, ## and not 746. Then you have a positive lookahead, which looks OK. But the combined effect is to lock the inner bit down to two characters and look for space, two characters (where the second is a hash), equals peak.

Probably you want \d to mean a digit, and + to mean "match one or more times", so \d+

The second thing you're doing is mixing up lookarounds and grouping. One use of regex involves matching a string like 'number is 4' with a pattern like 'number is (\d)'. The whole pattern matches and appears in the output, and then you query the capture groups to pick out the 4 out of the whole match. $matches[0] is number is 4 and $matches[1] is 4.

Another use of regex involves matching the number with a lookbehind like (?<=number is )\d because the lookbehind matches but it doesn't appear in the output. So the output of $matches[0] is just the 4 and you don't need any groups. So you're using lookarounds to match without having the text in the output, and trying to group the number as well, which works but it's overkill / unnecessary mixed use of two different approaches.

That means your regex is very close to working:

$regexPeak = '(?<= )(.#)(?=\=Peak)'  # change to
$regexPeak = '(?<= )\d+(?=\=Peak)'   # to indicate "one or more digits"

and:

PS C:\> $string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
PS C:\> $regexPeak = '(?<= )\d+(?=\=Peak)'
PS C:\> $string -match $regexPeak > $null
PS C:\> $peak = $matches[0]
PS C:\> $peak
746


问:
reStructuredText: Add credit line to an image
I have recently started a new blog, and I'm using Wikimedia images in it. I would naturally like to properly give image credits.

The conventional credit location is below the image (here, for example, in gray font).

My blog is written in Pelican and i use reStructuredText to write my posts, so an image is inserted in the following way:

```<code>.. image:: images/Steve_Jobs_and_Bill_Gates.jpg
   :target: https://commons.wikimedia.org/wiki/File:Steve_Jobs_and_Bill_Gates_(522695099).jpg
   :alt: Joi Ito from Inbamura, Japan, licensed under the Creative Commons Attribution 2.0 Generic license
</code>```

Does reStructuredText have a credit field which will appear below the image?

答:
I don't know if you're still wondering this, since this post is a year old.

However, I am using the "Better Figures and Images" python plugin by Duncan Lock (see http://duncanlock.net/blog/2013/05/29/better-figures-images-plugin-for-pelican/) to have captions below my images. I bet you can use that for credits, also.

Body:
I have recently started a new blog, and I'm using Wikimedia images in it. I would naturally like to properly give image credits.

The conventional credit location is below the image (here, for example, in gray font).

My blog is written in Pelican and i use reStructuredText to write my posts, so an image is inserted in the following way:

.. image:: images/Steve_Jobs_and_Bill_Gates.jpg
   :target: https://commons.wikimedia.org/wiki/File:Steve_Jobs_and_Bill_Gates_(522695099).jpg
   :alt: Joi Ito from Inbamura, Japan, licensed under the Creative Commons Attribution 2.0 Generic license

Does reStructuredText have a credit field which will appear below the image?


问:
Should self generated transaction ids be exchanged in HTTP synchronous requests
I am new to the HTTP world. My sincere apologies if the question is too trivial.

I created a HTTP client which send a SOAP message to a 3rd party server. My client sends a synchronous request and has a timeout value of 15 seconds. The API is used to update user balance, so it is very critical. I send the userId in the SOAP request and amount to be added/deducted from user balance to the server. The server responds with Status of 0=SUCCESS or 1=FAILURE

Now considering that multiple failures can occur at server and I might hit the server multiple times for the same user in a day, should there be a transaction id added in the message part. If yes, what would be the use cases for it. As per my understanding, client would always know which transaction it initiated, so it can do the transaction bookkeeping on its own. I would also need to reconcile the transactions with the server on daily basis (which could happen using userId).

Note: Server APIs are being developed and can change right now.

答: TCP will provide the underlying reliable connection so you are correct that each Client SOAP request does not need an additional mechanism to track its response from the server.   But, with that said, an additional message level GUID is helpful for troubleshooting purposes.  It will allow you later to track and trace  the exact client message to the server if you experience issues.  </p>


问:
Get record with maximum value and show other fields from that record
I am trying to show the important dates for a manufacturing process. There are 10 rooms performing the same process. Each time the process starts over a new cycle number is assigned. I want to show the important dates for the current (i.e. maximum) cycle in each room.

So far I have put together a query that will show the important dates for the maximum cycle number overall (my code is below), but I want to add an additional criterion so that I see the information for the maximum cycle number in each room

```<code>SELECT
     [dbo_batch_overview5].[rm],
     [dbo_batch_overview5].[cyc],
     [dbo_batch_overview5].[bpr],
     [dbo_batch_overview5].[plug_date],
     [dbo_batch_overview5].[trig_date],
     [dbo_batch_overview5].[flush_date],
     [dbo_batch_overview5].[harv_date]
FROM dbo_batch_overview5
WHERE ((([dbo_batch_overview5].[cyc])=(SELECT Max([dbo_batch_overview5].[cyc])
FROM [dbo_batch_overview5]
)));
</code>```

I think I need to add a GROUP BY statement to specify that I want to see the maximum cycle number for each unique entry in the room [rm] field, here is the code with my attempt at the statement I think I need included:

```<code>  SELECT
     [dbo_batch_overview5].[rm],
     [dbo_batch_overview5].[cyc],
     [dbo_batch_overview5].[bpr],
     [dbo_batch_overview5].[plug_date],
     [dbo_batch_overview5].[trig_date],
     [dbo_batch_overview5].[flush_date],
     [dbo_batch_overview5].[harv_date]
FROM dbo_batch_overview5
WHERE ((([dbo_batch_overview5].[cyc])=(SELECT Max([dbo_batch_overview5].[cyc])
FROM [dbo_batch_overview5]
GROUP BY [dbo_batch_overview5].[rm]
)));
</code>```

When I try the above code I get an error saying that my subquery is returning more than one value. Can anyone tell me what I'm doing wrong?

As requested, here is some sample data

```<code>rm  cyc bpr         clone_date  plug_date   trig_date   harv_date
1   13  20161031-OP 10/31/2016  11/16/2016  11/22/2016  1/12/2017
1   13  20161101-EV 11/1/2016   11/16/2016  11/22/2016  1/13/2017
1   13  20161031-CG 10/31/2016  11/16/2016  11/22/2016  1/13/2017
1   13  20161101-CB 11/1/2016   11/16/2016  11/22/2016  1/12/2017
1   13  20161031-VO 10/31/2016  11/16/2016  11/22/2016  1/13/2017
1   14  20170104-CG 1/4/2017    1/23/2017   1/28/2017
1   14  20170104-CB 1/4/2017    1/23/2017   1/28/2017
1   14  20170106-AV 1/6/2017    1/23/2017   1/28/2017
1   14  20170106-MN 1/6/2017    1/23/2017   1/28/2017
2   7   20150925-ST 9/25/2015   10/10/2015  10/19/2015  12/16/2015
2   7   20150924-AL 9/24/2015   10/10/2015  10/19/2015  12/16/2015
2   7   20150924-EA 9/24/2015   10/10/2015  10/19/2015  12/21/2015
2   7   20150928-LM 9/28/2015   10/10/2015  10/19/2015  12/22/2015
2   7   20150928-HM 9/28/2015   10/10/2015  10/19/2015  12/19/2015
2   8   20151214-CG 12/14/2015  12/30/2015  1/7/2016    3/14/2016
2   8   20151214-RM 12/14/2015  12/30/2015  1/7/2016    3/15/2016
2   8   20151215-CB 12/15/2015  12/30/2015  1/7/2016    3/8/2016
</code>```

In the above example, I would only want to see the records associated with cycle 14 in room 1 and cycle 8 in room 2

答:
Would something like this solve your problem?</p>

```<code>SELECT
 a.[rm],
 a.[cyc],
 a.[bpr],
 a.[plug_date],
 a.[trig_date],
 a.[flush_date],
 a.[harv_date]
FROM dbo_batch_overview5 a
    INNER JOIN (SELECT Max([cyc]) AS maxcyc,
                       rm as rm2
                FROM [dbo_batch_overview5]
                GROUP BY [rm])c
        ON a.rm = c.rm2 AND a.cyc = c.maxcyc
</code>```

Body:
I am trying to show the important dates for a manufacturing process. There are 10 rooms performing the same process. Each time the process starts over a new cycle number is assigned. I want to show the important dates for the current (i.e. maximum) cycle in each room.

So far I have put together a query that will show the important dates for the maximum cycle number overall (my code is below), but I want to add an additional criterion so that I see the information for the maximum cycle number in each room

SELECT
     [dbo_batch_overview5].[rm],
     [dbo_batch_overview5].[cyc],
     [dbo_batch_overview5].[bpr],
     [dbo_batch_overview5].[plug_date],
     [dbo_batch_overview5].[trig_date],
     [dbo_batch_overview5].[flush_date],
     [dbo_batch_overview5].[harv_date]
FROM dbo_batch_overview5
WHERE ((([dbo_batch_overview5].[cyc])=(SELECT Max([dbo_batch_overview5].[cyc])
FROM [dbo_batch_overview5]
)));

I think I need to add a GROUP BY statement to specify that I want to see the maximum cycle number for each unique entry in the room [rm] field, here is the code with my attempt at the statement I think I need included:

  SELECT
     [dbo_batch_overview5].[rm],
     [dbo_batch_overview5].[cyc],
     [dbo_batch_overview5].[bpr],
     [dbo_batch_overview5].[plug_date],
     [dbo_batch_overview5].[trig_date],
     [dbo_batch_overview5].[flush_date],
     [dbo_batch_overview5].[harv_date]
FROM dbo_batch_overview5
WHERE ((([dbo_batch_overview5].[cyc])=(SELECT Max([dbo_batch_overview5].[cyc])
FROM [dbo_batch_overview5]
GROUP BY [dbo_batch_overview5].[rm]
)));

When I try the above code I get an error saying that my subquery is returning more than one value. Can anyone tell me what I'm doing wrong?

As requested, here is some sample data

rm  cyc bpr         clone_date  plug_date   trig_date   harv_date
1   13  20161031-OP 10/31/2016  11/16/2016  11/22/2016  1/12/2017
1   13  20161101-EV 11/1/2016   11/16/2016  11/22/2016  1/13/2017
1   13  20161031-CG 10/31/2016  11/16/2016  11/22/2016  1/13/2017
1   13  20161101-CB 11/1/2016   11/16/2016  11/22/2016  1/12/2017
1   13  20161031-VO 10/31/2016  11/16/2016  11/22/2016  1/13/2017
1   14  20170104-CG 1/4/2017    1/23/2017   1/28/2017
1   14  20170104-CB 1/4/2017    1/23/2017   1/28/2017
1   14  20170106-AV 1/6/2017    1/23/2017   1/28/2017
1   14  20170106-MN 1/6/2017    1/23/2017   1/28/2017
2   7   20150925-ST 9/25/2015   10/10/2015  10/19/2015  12/16/2015
2   7   20150924-AL 9/24/2015   10/10/2015  10/19/2015  12/16/2015
2   7   20150924-EA 9/24/2015   10/10/2015  10/19/2015  12/21/2015
2   7   20150928-LM 9/28/2015   10/10/2015  10/19/2015  12/22/2015
2   7   20150928-HM 9/28/2015   10/10/2015  10/19/2015  12/19/2015
2   8   20151214-CG 12/14/2015  12/30/2015  1/7/2016    3/14/2016
2   8   20151214-RM 12/14/2015  12/30/2015  1/7/2016    3/15/2016
2   8   20151215-CB 12/15/2015  12/30/2015  1/7/2016    3/8/2016

In the above example, I would only want to see the records associated with cycle 14 in room 1 and cycle 8 in room 2

Body:
Would something like this solve your problem?

SELECT
 a.[rm],
 a.[cyc],
 a.[bpr],
 a.[plug_date],
 a.[trig_date],
 a.[flush_date],
 a.[harv_date]
FROM dbo_batch_overview5 a
    INNER JOIN (SELECT Max([cyc]) AS maxcyc,
                       rm as rm2
                FROM [dbo_batch_overview5]
                GROUP BY [rm])c
        ON a.rm = c.rm2 AND a.cyc = c.maxcyc


问:
Multi-threading access to MapPoint?
Good afternoon,

As I said earlier in another post, I have to calculate some 8,000,000 shortest- time/path distances between some points in the map, the coordinates of which are know. The problem is that, while straight-line distances were easy (and quick) to calculate, someone told me that a single-threaded application can have problems calculating this number of distances using MapPoint. The question is that I know nothing about multi-threading... I am currently working on a i7 - 720QM environment, so I would like to use all the 4 cores to make these calculations... Is there any easy way of doing this in C# or C++?

Thank you very much.

答:
That might have been me who said it would take a long time. MapPoint's COM API is single threaded. The way to get it to compute multiple routes in parallel is to start multiple MapPoint's, each on its own thread.

So for your quad core, you will start 2-3 threads. Each thread starts its own MapPoint, and then uses it for routing. You will NOT have one MapPoint per core. As well OS overhead and your I/O overhead, if you watch a single MapPoint compute a route, you will find that later versions are partially internally multi-threaded and can take about 1.5 cores if they are available.

There are also a lot of gotchas to watch out for. MapPoint's own garbage collection is not optimized for batch route calculation. The easiest workaround for this is to simply restart each MapPoint application at periodic intervals (at least once a day but probably more frequently).

Also, some operations (File Open seems to be the main one) cannot be called by multiple MapPoints at once. Probably because they are trying to open the same file, but I have not investigated further. You will need to implement your own locking mechanism to avoid this.

Saurabh's advice for .NET 4 sounds good: I have yet to use .NET 4's multi-threading in anger - my MapPoint/.NET threading experience is with .NET 2.

I don't know what your app is, but did you know that I sell a product that uses multi-processor MapPoint for batch route distance/time calculation...  :-)

Title: Multi-threading access to MapPoint?


问:
Basic SSH connection via JSCH on android
As the fellow user from this question and this tutorial explain, I'm trying to setup a simples ssh connection to perform a single command on a app. It dosen't even need to wait for any response.

Here is the code:

Main Activity:
    package com.example.lucas.shutdown;

```<code>import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onCLick(View v){
        new AsyncTask<Integer, Void, Void>(){
            @Override
            protected Void doInBackground(Integer... params) {
                try {
                    executeRemoteShutdown();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute(1);
    }

    public void executeRemoteShutdown(){
        String user = "ssh";
        String password = "123";
        String host = "192.168.1.4";
        int port=22;
        try{
            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            Channel channel = (ChannelExec) session.openChannel("exec");
            ((ChannelExec) channel).setCommand("shutdown /s");
            channel.connect();
            try{
               Thread.sleep(1000);
            }catch(Exception ee){}
            channel.disconnect();
            session.disconnect();
        }
        catch(Exception e){}
    }
}
</code>```

The button that performs the action:

```<code>    <Button
    android:text="Shutdown"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:id="@+id/button"
    android:onClick="onCLick" />
</code>```

This same method executeRemoteShutdown() already works on a diferent program in pure java, however the thing I'm having trouble with is that the conection and comand execution seems to never happen. I followed the recomendations from the question I linked above to run the ssh method on a diferent thread, add a delay to wait for the command be executed on the host before the method finishes and gave internet permission on the manifest file.

答:
Ok here we go,
your code is okay, but some little errors are in.. let me correct this,
you have to implement the button right and some little changes and it will work:

MainActivity:

```<code>    import android.os.AsyncTask;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.ChannelExec;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.Session;

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

    Button btn = (Button) view.findViewById(R.id.button);
            btn.setOnClickListener(new View.OnClickListener() {
                //start execution of ssh commands
                @Override
                public void onClick(View v){
                    new AsyncTask<Integer, Void, Void>(){
                        @Override
                        protected Void doInBackground(Integer... params) {
                            try {
                                executeSSHcommand();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            return null;
                        }
                    }.execute(1);
                }
            });
}

    public void executeSSHcommand(){
        String user = "xxx";
        String password = "xxx";
        String host = "192.168.xxx.xxx";
        int port=22;
        try{

            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setTimeout(10000);
            session.connect();
            ChannelExec channel = (ChannelExec)session.openChannel("exec");
            channel.setCommand("your ssh command here");
            channel.connect();
            channel.disconnect();
            // show success in UI with a snackbar alternatively use a toast
            Snackbar.make(getActivity().findViewById(android.R.id.content),
                    "Success!", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
        catch(JSchException e){
            // show the error in the UI
            Snackbar.make(getActivity().findViewById(android.R.id.content),
                     "Check WIFI or Server! Error : "+e.getMessage(),
                     Snackbar.LENGTH_LONG)
                     .setDuration(20000).setAction("Action", null).show();
        }
    }
}
</code>```

additional you can delete the line " android:onClick="onCLick" " in your layout.xml

at my project this is working just fine even without the delay. of curse you need internet permission in manifest file. but i think this permission will  grantet immediately on start of the application.

hope it helps, sometimes little things make a difference.

kind regards

chwzr

Body:
As the fellow user from this question and this tutorial explain, I'm trying to setup a simples ssh connection to perform a single command on a app. It dosen't even need to wait for any response.

Here is the code:

Main Activity:
    package com.example.lucas.shutdown;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onCLick(View v){
        new AsyncTask<Integer, Void, Void>(){
            @Override
            protected Void doInBackground(Integer... params) {
                try {
                    executeRemoteShutdown();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute(1);
    }

    public void executeRemoteShutdown(){
        String user = "ssh";
        String password = "123";
        String host = "192.168.1.4";
        int port=22;
        try{
            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            Channel channel = (ChannelExec) session.openChannel("exec");
            ((ChannelExec) channel).setCommand("shutdown /s");
            channel.connect();
            try{
               Thread.sleep(1000);
            }catch(Exception ee){}
            channel.disconnect();
            session.disconnect();
        }
        catch(Exception e){}
    }
}

The button that performs the action:

    <Button
    android:text="Shutdown"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:id="@+id/button"
    android:onClick="onCLick" />

This same method executeRemoteShutdown() already works on a diferent program in pure java, however the thing I'm having trouble with is that the conection and comand execution seems to never happen. I followed the recomendations from the question I linked above to run the ssh method on a diferent thread, add a delay to wait for the command be executed on the host before the method finishes and gave internet permission on the manifest file.

Body:
Ok here we go,
your code is okay, but some little errors are in.. let me correct this,
you have to implement the button right and some little changes and it will work:

MainActivity:

    import android.os.AsyncTask;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.ChannelExec;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.Session;

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

    Button btn = (Button) view.findViewById(R.id.button);
            btn.setOnClickListener(new View.OnClickListener() {
                //start execution of ssh commands
                @Override
                public void onClick(View v){
                    new AsyncTask<Integer, Void, Void>(){
                        @Override
                        protected Void doInBackground(Integer... params) {
                            try {
                                executeSSHcommand();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            return null;
                        }
                    }.execute(1);
                }
            });
}

    public void executeSSHcommand(){
        String user = "xxx";
        String password = "xxx";
        String host = "192.168.xxx.xxx";
        int port=22;
        try{

            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setTimeout(10000);
            session.connect();
            ChannelExec channel = (ChannelExec)session.openChannel("exec");
            channel.setCommand("your ssh command here");
            channel.connect();
            channel.disconnect();
            // show success in UI with a snackbar alternatively use a toast
            Snackbar.make(getActivity().findViewById(android.R.id.content),
                    "Success!", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
        catch(JSchException e){
            // show the error in the UI
            Snackbar.make(getActivity().findViewById(android.R.id.content),
                     "Check WIFI or Server! Error : "+e.getMessage(),
                     Snackbar.LENGTH_LONG)
                     .setDuration(20000).setAction("Action", null).show();
        }
    }
}

additional you can delete the line " android:onClick="onCLick" " in your layout.xml

at my project this is working just fine even without the delay. of curse you need internet permission in manifest file. but i think this permission will  grantet immediately on start of the application.

hope it helps, sometimes little things make a difference.

kind regards

chwzr


问:
iOS builds / ipa creation no longer works from the command line
Overview

Our command line builds (to build and create the .ipa) are no longer working.

iTunesConnect has started rejecting builds that use the CODE_SIGN_RESOURCE_RULES_PATH build setting.

If we build WITHOUT that setting the PackageApplication tool (which we use to create the signed .ipa) fails.

It seems that PackageApplication calls /usr/bin/codesign with resource-rules arguments even if the CODE_SIGN_RESOURCE_RULES_PATH build setting is excluded

I suspect the PackageApplication needs to be updated so that it does not call /usr/bin/codesign with resource-rules arguments when the CODE_SIGN_RESOURCE_RULES_PATH build setting is excluded.

Has anyone found a solution for this?

Details

We build our app on the command line like this:

```<code>xcodebuild -workspace myApp.xcworkspace -scheme myApp -sdk iphoneos -configuration AppStoreDistribution OBJROOT=$PWD/build SYMROOT=$PWD/build ONLY_ACTIVE_ARCH=NO 'CODE_SIGN_RESOURCE_RULES_PATH=$(SDKROOT)/ResourceRules.plist'
</code>```

We create the signed .ipa on the command line like this:

```<code>xcrun -log -sdk iphoneos PackageApplication "/Users/mpv/dev/myApp/build/AppStoreDistribution-iphoneos/myApp.app" -o "/Users/mpv/dev/myApp/build/AppStoreDistribution-iphoneos/myApp.ipa" -sign "iPhone Distribution: MyTeam (XXXXXXXXXX)" -embed /Users/mpv/Library/MobileDevice/Provisioning\ Profiles/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.mobileprovision
</code>```

iTunesConnect is now rejecting our builds with the following error:

"This bundle is invalid. The Info.plist contains an invalid key
  'CFBundleResourceSpecification' in bundle myApp [myApp.app]"

If we remove the 'CODE_SIGN_RESOURCE_RULES_PATH=$(SDKROOT)/ResourceRules.plist' bit from the build command then the app is built without the CFBundleResourceSpecification plist key (which I presume is what we want). The new build command looks like this:

```<code>xcodebuild -workspace myApp.xcworkspace -scheme myApp -sdk iphoneos -configuration AppStoreDistribution OBJROOT=$PWD/build SYMROOT=$PWD/build ONLY_ACTIVE_ARCH=NO
</code>```

The problem now is that the command to build the .ipa fails with the following error:

error: /usr/bin/codesign --force
  --preserve-metadata=identifier,entitlements,resource-rules --sign iPhone Distribution: MyTeam (XXXXXXXXXX)
  --resource-rules=/var/folders/2b/7hylk7nn13dgrl9yyh2wp0lm0000gn/T/zDRRJMkKtQ/Payload/myApp.app/ResourceRules.plist
  --entitlements /var/folders/2b/7hylk7nn13dgrl9yyh2wp0lm0000gn/T/zDRRJMkKtQ/entitlements_plistIUdGWLYe
  /var/folders/2b/7hylk7nn13dgrl9yyh2wp0lm0000gn/T/zDRRJMkKtQ/Payload/myApp.app
  failed with error 1. Output: Warning: usage of --preserve-metadata
  with option "resource-rules" (deprecated in Mac OS X >= 10.10)!

Warning: --resource-rules has been deprecated in Mac OS X >= 10.10!
  /var/folders/2b/7hylk7nn13dgrl9yyh2wp0lm0000gn/T/zDRRJMkKtQ/Payload/myApp.app/ResourceRules.plist:
  cannot read resources

It seems that PackageApplication calls /usr/bin/codesign with resource-rules arguments even if the CODE_SIGN_RESOURCE_RULES_PATH argument / build setting is excluded.

I think PackageApplication needs to be updated so that it does not call /usr/bin/codesign with resource-rules arguments when the CODE_SIGN_RESOURCE_RULES_PATH argument / build setting is excluded.

答:
Here's a quick tip in case you need to create the exportOptions.plist file as part of your build process (maybe Jenkins).

You can use the plutil tool to turn JSON into a plist. Example:

```<code>echo "{\"method\":\"app-store\"}" | plutil -convert xml1 -o /tmp/exportOptions.plist -- -
</code>```

Enjoy!

Body:
Overview

Our command line builds (to build and create the .ipa) are no longer working.

iTunesConnect has started rejecting builds that use the CODE_SIGN_RESOURCE_RULES_PATH build setting.

If we build WITHOUT that setting the PackageApplication tool (which we use to create the signed .ipa) fails.

It seems that PackageApplication calls /usr/bin/codesign with resource-rules arguments even if the CODE_SIGN_RESOURCE_RULES_PATH build setting is excluded

I suspect the PackageApplication needs to be updated so that it does not call /usr/bin/codesign with resource-rules arguments when the CODE_SIGN_RESOURCE_RULES_PATH build setting is excluded.

Has anyone found a solution for this?

Details

We build our app on the command line like this:

xcodebuild -workspace myApp.xcworkspace -scheme myApp -sdk iphoneos -configuration AppStoreDistribution OBJROOT=$PWD/build SYMROOT=$PWD/build ONLY_ACTIVE_ARCH=NO 'CODE_SIGN_RESOURCE_RULES_PATH=$(SDKROOT)/ResourceRules.plist'

We create the signed .ipa on the command line like this:

xcrun -log -sdk iphoneos PackageApplication "/Users/mpv/dev/myApp/build/AppStoreDistribution-iphoneos/myApp.app" -o "/Users/mpv/dev/myApp/build/AppStoreDistribution-iphoneos/myApp.ipa" -sign "iPhone Distribution: MyTeam (XXXXXXXXXX)" -embed /Users/mpv/Library/MobileDevice/Provisioning\ Profiles/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.mobileprovision

iTunesConnect is now rejecting our builds with the following error:

"This bundle is invalid. The Info.plist contains an invalid key
  'CFBundleResourceSpecification' in bundle myApp [myApp.app]"

If we remove the 'CODE_SIGN_RESOURCE_RULES_PATH=$(SDKROOT)/ResourceRules.plist' bit from the build command then the app is built without the CFBundleResourceSpecification plist key (which I presume is what we want). The new build command looks like this:

xcodebuild -workspace myApp.xcworkspace -scheme myApp -sdk iphoneos -configuration AppStoreDistribution OBJROOT=$PWD/build SYMROOT=$PWD/build ONLY_ACTIVE_ARCH=NO

The problem now is that the command to build the .ipa fails with the following error:

error: /usr/bin/codesign --force
  --preserve-metadata=identifier,entitlements,resource-rules --sign iPhone Distribution: MyTeam (XXXXXXXXXX)
  --resource-rules=/var/folders/2b/7hylk7nn13dgrl9yyh2wp0lm0000gn/T/zDRRJMkKtQ/Payload/myApp.app/ResourceRules.plist
  --entitlements /var/folders/2b/7hylk7nn13dgrl9yyh2wp0lm0000gn/T/zDRRJMkKtQ/entitlements_plistIUdGWLYe
  /var/folders/2b/7hylk7nn13dgrl9yyh2wp0lm0000gn/T/zDRRJMkKtQ/Payload/myApp.app
  failed with error 1. Output: Warning: usage of --preserve-metadata
  with option "resource-rules" (deprecated in Mac OS X >= 10.10)!

Warning: --resource-rules has been deprecated in Mac OS X >= 10.10!
  /var/folders/2b/7hylk7nn13dgrl9yyh2wp0lm0000gn/T/zDRRJMkKtQ/Payload/myApp.app/ResourceRules.plist:
  cannot read resources

It seems that PackageApplication calls /usr/bin/codesign with resource-rules arguments even if the CODE_SIGN_RESOURCE_RULES_PATH argument / build setting is excluded.

I think PackageApplication needs to be updated so that it does not call /usr/bin/codesign with resource-rules arguments when the CODE_SIGN_RESOURCE_RULES_PATH argument / build setting is excluded.

Body:
Here's a quick tip in case you need to create the exportOptions.plist file as part of your build process (maybe Jenkins).

You can use the plutil tool to turn JSON into a plist. Example:

echo "{\"method\":\"app-store\"}" | plutil -convert xml1 -o /tmp/exportOptions.plist -- -

Enjoy!


问:
Webpack Dev Server: Unknown argument: NODE_ENV
I have setup my angular js project with webpack. I am getting below error whenever I try to run in development mode:

"Unknown argument: NODE_ENV".

Below is my package.json. I am already using latest version of webpack-dev-server. Please let me know what went wrong here.

Package.json:

```<code>{
"name": "My project",
"version": "0.0.1",
"description": "",
"main": "/",
"author": "",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --config webpack/webpack.dev.js --watch --NODE_ENV=dev",
"test": "karma start --NODE_ENV=test",
"build": "webpack --config webpack/webpack.build.js --NODE_ENV=production"
},
"dependencies": {
"angular": "1.6.3",
"angular-datepicker": "^1.0.5",
"angular-file-upload": "^2.2.0",
"angular-flash-alert": "^2.2.4",
"angular-messages": "^1.5.0",
"angular-repository": "^0.1.8",
"angular-resource": "^1.5.0",
"angular-sanitize": "^1.5.5",
"angular-symfony-acl": "^1.0.9",
"angular-symfony-form": "^3.0.0",
"angular-translate": "^2.11.0",
"angular-ui-bootstrap": "^1.3.2",
"angular-ui-router": "^0.2.18",
"angular-voauth2": "^0.1.16",
"angular-youtube-embed": "^1.2.0",
"angularjs-datepicker": "^2.1.3",
"bootstrap": "^3.3.6",
"bootstrap-sass": "3.3.6",
"dotenv": "^4.0.0",
"font-awesome": "4.5.0",
"jquery": "2.2.0",
"lodash": "^4.0.1",
"moment": "^2.12.0",
"ng-file-upload": "^12.0.4",
"ng-infinite-scroll": "^1.2.1",
"postcss-loader": "^0.9.1",
"ui-select": "^0.19.4"
},
"devDependencies": {
"angular-mocks": "1.5.0-rc.2",
"angular-module-mocks": "1.2.19",
"babel-core": "^6.4.5",
"babel-istanbul": "0.6.0",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.3.13",
"compression-webpack-plugin": "0.3.0",
"connect-history-api-fallback": "^1.2.0",
"css-loader": "^0.18.0",
"file-loader": "0.8.5",
"html-webpack-plugin": "2.7.2",
"webpack-dev-server": "2.4.2",
"istanbul": "0.4.2",
"istanbul-instrumenter-loader": "0.1.3",
"jasmine": "2.4.1",
"karma": "0.13.19",
"karma-coverage": "0.5.3",
"karma-jasmine": "0.3.6",
"karma-phantomjs-launcher": "1.0.0",
"karma-sourcemap-loader": "0.3.7",
"karma-spec-reporter": "0.0.23",
"karma-typescript-preprocessor": "0.0.21",
"karma-webpack": "1.7.0",
"lodash": "4.0.1",
"node-sass": "3.4.2",
"phantomjs-polyfill": "0.0.1",
"phantomjs-prebuilt": "2.1.3",
"raw-loader": "0.5.1",
"sass-loader": "3.1.2",
"style-loader": "0.13.0",
"url-loader": "0.5.7",
"webpack": "1.12.12"
}
}
</code>```

webpack.dev.js:

```<code>var loaders = require("./loaders");
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: {
        build: './src/app.js',
        vendors: ['angular', 'bootstrap', 'angular-ui-router', 'ng-file-upload']
    },
    output: {
        filename: '[name].min.js',
        path: 'dist'
    },
    resolve: {
        root: __dirname,
        extensions: ['', '.js', '.json']
    },
    resolveLoader: {
        modulesDirectories: ["node_modules"]
    },
    devtool: "source-map",
    devServer: {
        port: 8080,
        historyApiFallback: true
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html',
            inject: 'body',
            hash: true
        }),
        new webpack.ProvidePlugin({
            moment: 'moment',
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            'window.jquery': 'jquery'
        })
    ],
    module:{
        loaders: loaders
    }
};
</code>```

答:
In addition to what @Emre has provided, I had to change the npm start command in package.json to run application in DEV MODE. Then only it worked for me. My package.json now looks as below:

```<code>"scripts": {
    "start": "NODE_ENV=dev webpack-dev-server --config ./webpack/webpack.dev.js --",
    "test": "karma start --NODE_ENV=test",
    "build": "webpack --config webpack/webpack.build.js --NODE_ENV=production"
},
</code>```

Thanks.

Body:
I have setup my angular js project with webpack. I am getting below error whenever I try to run in development mode:

"Unknown argument: NODE_ENV".

Below is my package.json. I am already using latest version of webpack-dev-server. Please let me know what went wrong here.

Package.json:

{
"name": "My project",
"version": "0.0.1",
"description": "",
"main": "/",
"author": "",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --config webpack/webpack.dev.js --watch --NODE_ENV=dev",
"test": "karma start --NODE_ENV=test",
"build": "webpack --config webpack/webpack.build.js --NODE_ENV=production"
},
"dependencies": {
"angular": "1.6.3",
"angular-datepicker": "^1.0.5",
"angular-file-upload": "^2.2.0",
"angular-flash-alert": "^2.2.4",
"angular-messages": "^1.5.0",
"angular-repository": "^0.1.8",
"angular-resource": "^1.5.0",
"angular-sanitize": "^1.5.5",
"angular-symfony-acl": "^1.0.9",
"angular-symfony-form": "^3.0.0",
"angular-translate": "^2.11.0",
"angular-ui-bootstrap": "^1.3.2",
"angular-ui-router": "^0.2.18",
"angular-voauth2": "^0.1.16",
"angular-youtube-embed": "^1.2.0",
"angularjs-datepicker": "^2.1.3",
"bootstrap": "^3.3.6",
"bootstrap-sass": "3.3.6",
"dotenv": "^4.0.0",
"font-awesome": "4.5.0",
"jquery": "2.2.0",
"lodash": "^4.0.1",
"moment": "^2.12.0",
"ng-file-upload": "^12.0.4",
"ng-infinite-scroll": "^1.2.1",
"postcss-loader": "^0.9.1",
"ui-select": "^0.19.4"
},
"devDependencies": {
"angular-mocks": "1.5.0-rc.2",
"angular-module-mocks": "1.2.19",
"babel-core": "^6.4.5",
"babel-istanbul": "0.6.0",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.3.13",
"compression-webpack-plugin": "0.3.0",
"connect-history-api-fallback": "^1.2.0",
"css-loader": "^0.18.0",
"file-loader": "0.8.5",
"html-webpack-plugin": "2.7.2",
"webpack-dev-server": "2.4.2",
"istanbul": "0.4.2",
"istanbul-instrumenter-loader": "0.1.3",
"jasmine": "2.4.1",
"karma": "0.13.19",
"karma-coverage": "0.5.3",
"karma-jasmine": "0.3.6",
"karma-phantomjs-launcher": "1.0.0",
"karma-sourcemap-loader": "0.3.7",
"karma-spec-reporter": "0.0.23",
"karma-typescript-preprocessor": "0.0.21",
"karma-webpack": "1.7.0",
"lodash": "4.0.1",
"node-sass": "3.4.2",
"phantomjs-polyfill": "0.0.1",
"phantomjs-prebuilt": "2.1.3",
"raw-loader": "0.5.1",
"sass-loader": "3.1.2",
"style-loader": "0.13.0",
"url-loader": "0.5.7",
"webpack": "1.12.12"
}
}

webpack.dev.js:

var loaders = require("./loaders");
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: {
        build: './src/app.js',
        vendors: ['angular', 'bootstrap', 'angular-ui-router', 'ng-file-upload']
    },
    output: {
        filename: '[name].min.js',
        path: 'dist'
    },
    resolve: {
        root: __dirname,
        extensions: ['', '.js', '.json']
    },
    resolveLoader: {
        modulesDirectories: ["node_modules"]
    },
    devtool: "source-map",
    devServer: {
        port: 8080,
        historyApiFallback: true
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html',
            inject: 'body',
            hash: true
        }),
        new webpack.ProvidePlugin({
            moment: 'moment',
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            'window.jquery': 'jquery'
        })
    ],
    module:{
        loaders: loaders
    }
};

Body:
In addition to what @Emre has provided, I had to change the npm start command in package.json to run application in DEV MODE. Then only it worked for me. My package.json now looks as below:

"scripts": {
    "start": "NODE_ENV=dev webpack-dev-server --config ./webpack/webpack.dev.js --",
    "test": "karma start --NODE_ENV=test",
    "build": "webpack --config webpack/webpack.build.js --NODE_ENV=production"
},

Thanks.


问:
ReactJS - Unknown prop `activeClassName` on  tag. Remove this prop from the element
I am using react 15.4.2 and react-router4.0.0 and This project was bootstrapped with Create React App.

Here is my Code.

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import {BrowserRouter as Router,Route,Link} from 'react-router-dom'

 const AboutPage = () => {
 return(
    <section>
        <h2>This is About page</h2>
        <Link activeClassName="active" to="/about/nestedone">Nestedone</Link>
        {' '}
        <Link activeClassName="active" to="/about/nestedtwo">Nested two</Link>
    </section>
)
}

const HomePage = () => {
return(
    <section>
        <h2>This is Home page</h2>
        <Link to="/about">About</Link>
    </section>
)
}

const NestedOne = () => {
return (
    <section>
        <h2>Nested page 1</h2>
    </section>
)
}

const NestedTwo = () => {
return (
    <section>
        <h2>Nested page 2</h2>
    </section>
)
}

 ReactDOM.render(
 <Router>
  <section>
    <Route exact path="/" component={HomePage} />
    <Route path="/about" component={AboutPage} />
    <Route path="/about/nestedone" component={NestedOne} />
    <Route path="/about/nestedtwo" component={NestedTwo} />
 </section>
 </Router>,
  document.getElementById('root')
);
</code>```

When I browse /about, I am getting this error:

"Warning: Unknown prop activeClassName on  tag. Remove this prop from the element.

What am I doing wrong here?

Thanks!

答:
activeClassName is not a property of Link but of NavLink.

Since react-router v4 beta8, the property is active by default. Verify which version is installed in your node modules folder

Title: ReactJS - Unknown prop `activeClassName` on <a> tag. Remove this prop from the element

Body:
I am using react 15.4.2 and react-router4.0.0 and This project was bootstrapped with Create React App.

Here is my Code.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import {BrowserRouter as Router,Route,Link} from 'react-router-dom'

 const AboutPage = () => {
 return(

This is About page

        <Link activeClassName="active" to="/about/nestedone">Nestedone</Link>
        {' '}
        <Link activeClassName="active" to="/about/nestedtwo">Nested two</Link>

)
}

const HomePage = () => {
return(

This is Home page

        <Link to="/about">About</Link>

)
}

const NestedOne = () => {
return (

Nested page 1

)
}

const NestedTwo = () => {
return (

Nested page 2

)
}

 ReactDOM.render(
 <Router>

    <Route exact path="/" component={HomePage} />
    <Route path="/about" component={AboutPage} />
    <Route path="/about/nestedone" component={NestedOne} />
    <Route path="/about/nestedtwo" component={NestedTwo} />

 </Router>,
  document.getElementById('root')
);

When I browse /about, I am getting this error:

"Warning: Unknown prop activeClassName on  tag. Remove this prop from the element.

What am I doing wrong here?

Thanks!


问:
SQL Server - Sorting by category
I have a sorting question. I am using SQL Server 2012. I have the following dataset. The empty lines are for display purposes.

```<code>Country        CountryUser        State        StateUser
---------------------------------------------------------
Canada         User1              null         null
Canada         User2              null         null
USA            User2              null         null
USA            User3              null         null

Canada         User1              BC           User4
Canada         User1              BC           User5
Canada         User1              ON           User4
Canada         User1              ON           User8

Canada         User2              BC           User4
Canada         User2              BC           User5
Canada         User2              ON           User4
Canada         User2              ON           User8
total rows: 12
</code>```

I want to sort the rows such that all the rows that contain a state are shown below their country(row with null as state). Example,

```<code>Country        CountryUser        State        StateUser
---------------------------------------------------------
Canada         User1              null         null
Canada         User1              BC           User4
Canada         User1              BC           User5
Canada         User1              ON           User4
Canada         User1              ON           User8

Canada         User2              null         null
Canada         User2              BC           User4
Canada         User2              BC           User5
Canada         User2              ON           User4
Canada         User2              ON           User8

USA            User2              null         null
USA            User3              null         null
total rows: 12
</code>```

The first sort category is Country. The row with an empty state is shown first, then all the states are non null are shown afterwards. These rows have a secondary sort of state

答:
You can use case in the order by:

```<code>select *
from #yourCountry
order by CountryUser, case when state is null then '00000000' else 'zzzzz' end
                    , case when stateUser is null then '00000000' else 'zzzzz' end
</code>```

Your table:

```<code>create table #yourCountry ( Country varchar(15), CountryUser varchar(10), State varchar(5), StateUser varchar(10))

insert into #yourCountry (
Country    ,    CountryUser ,       State    ,    StateUser  ) values
---------------------------------------------------------
 ('Canada','User1',null , null )
,('Canada','User2',null , null )
,('USA   ','User2',null , null )
,('USA   ','User3',null , null )
,('Canada','User1','BC','User4')
,('Canada','User1','BC','User5')
,('Canada','User1','ON','User4')
,('Canada','User1','ON','User8')
,('Canada','User2','BC','User4')
,('Canada','User2','BC','User5')
,('Canada','User2','ON','User4')
,('Canada','User2','ON','User8')
</code>```

Title: SQL Server - Sorting by category

Body:
I have a sorting question. I am using SQL Server 2012. I have the following dataset. The empty lines are for display purposes.

Country        CountryUser        State        StateUser
---------------------------------------------------------
Canada         User1              null         null
Canada         User2              null         null
USA            User2              null         null
USA            User3              null         null

Canada         User1              BC           User4
Canada         User1              BC           User5
Canada         User1              ON           User4
Canada         User1              ON           User8

Canada         User2              BC           User4
Canada         User2              BC           User5
Canada         User2              ON           User4
Canada         User2              ON           User8
total rows: 12

I want to sort the rows such that all the rows that contain a state are shown below their country(row with null as state). Example,

Country        CountryUser        State        StateUser
---------------------------------------------------------
Canada         User1              null         null
Canada         User1              BC           User4
Canada         User1              BC           User5
Canada         User1              ON           User4
Canada         User1              ON           User8

Canada         User2              null         null
Canada         User2              BC           User4
Canada         User2              BC           User5
Canada         User2              ON           User4
Canada         User2              ON           User8

USA            User2              null         null
USA            User3              null         null
total rows: 12

The first sort category is Country. The row with an empty state is shown first, then all the states are non null are shown afterwards. These rows have a secondary sort of state

Body:
You can use case in the order by:

select *
from #yourCountry
order by CountryUser, case when state is null then '00000000' else 'zzzzz' end
                    , case when stateUser is null then '00000000' else 'zzzzz' end

Your table:

create table #yourCountry ( Country varchar(15), CountryUser varchar(10), State varchar(5), StateUser varchar(10))

insert into #yourCountry (
Country    ,    CountryUser ,       State    ,    StateUser  ) values
---------------------------------------------------------
 ('Canada','User1',null , null )
,('Canada','User2',null , null )
,('USA   ','User2',null , null )
,('USA   ','User3',null , null )
,('Canada','User1','BC','User4')
,('Canada','User1','BC','User5')
,('Canada','User1','ON','User4')
,('Canada','User1','ON','User8')
,('Canada','User2','BC','User4')
,('Canada','User2','BC','User5')
,('Canada','User2','ON','User4')
,('Canada','User2','ON','User8')


问:
Alternative to `sed -i` on Solaris
On Linux sed -i will modify the input files in place. It doesn't work on Solaris, though.

```<code>sed -i '$ s/OLD/NEW/g' test
sed: illegal option -- i
</code>```

What can I use in place of sed -i on Solaris?

答:
It isn't exactly the same as sed -i, but i had a similar issue. You can do this using perl:

```<code>perl -pi -e 's/find/replace/g' file
</code>```

doing the copy/move only works for single files. if you want to replace some text across every file in a directory and sub-directories, you need something which does it in place. you can do this with perl and find:

```<code>find . -exec perl -pi -e 's/find/replace/g' '{}' \;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Alternative to `sed -i` on Solaris

Body:
On Linux sed -i will modify the input files in place. It doesn't work on Solaris, though.

sed -i '$ s/OLD/NEW/g' test
sed: illegal option -- i

What can I use in place of sed -i on Solaris?

Body:
It isn't exactly the same as sed -i, but i had a similar issue. You can do this using perl:

perl -pi -e 's/find/replace/g' file

doing the copy/move only works for single files. if you want to replace some text across every file in a directory and sub-directories, you need something which does it in place. you can do this with perl and find:

find . -exec perl -pi -e 's/find/replace/g' '{}' \;


问:
Referer sub array?
I have an array orig[].
Now I want to create another array ref[] that refer to only specific elements in orig[].
By implying it is referrer I mean any change in element of ref[] will change the corresponding element of orig[].

F.e. pseudo code :

```<code>orig = [ 1,2,3,4,5 ]
ref[0] ==> orig[2]
ref[1] ==> orig[4]
</code>```

now if I do :

```<code> ref[0] = 11
 ref[1] = 22
</code>```

orig will become :

```<code>[ 1,2,11,4,22 ]
</code>```

also when I ca do : for x in ref : ....

答:
we will need to use an addition dictionary for mapping and set, get via function as follows:</p>

```<code>orig = [1, 2, 3, 4, 5]

ref = []

mapper = {}  # dictionary mapping ref index againt orig index

def fill_lst(lst, index):
    for _ in range(index-len(lst)+1):
        lst.append(None)

def populate_lst(target_index, source_index):
    try:
        ref[target_index] = orig[source_index]
    except IndexError:
        fill_lst(ref, target_index)
        ref[target_index] = orig[source_index]
    mapper[target_index] = source_index

def set_lst_val(target_index, val):
    try:
        ref[target_index] = val
    except IndexError:
        fill_lst(ref, target_index)
        ref[target_index] = val
    orig[mapper[target_index]] = val

populate_lst(0, 2)
populate_lst(1, 4)

print ref  # [3, 5]

set_lst_val(0, 11)
set_lst_val(1, 22)

print orig  # [1, 2, 11, 4, 22]
</code>```

Title: Referer sub array?

Body:
I have an array orig[].
Now I want to create another array ref[] that refer to only specific elements in orig[].
By implying it is referrer I mean any change in element of ref[] will change the corresponding element of orig[].

F.e. pseudo code :

orig = [ 1,2,3,4,5 ]
ref[0] ==> orig[2]
ref[1] ==> orig[4]

now if I do :

 ref[0] = 11
 ref[1] = 22

orig will become :

[ 1,2,11,4,22 ]

also when I ca do : for x in ref : ....

Body:
we will need to use an addition dictionary for mapping and set, get via function as follows:

orig = [1, 2, 3, 4, 5]

ref = []

mapper = {}  # dictionary mapping ref index againt orig index

def fill_lst(lst, index):
    for _ in range(index-len(lst)+1):
        lst.append(None)

def populate_lst(target_index, source_index):
    try:
        ref[target_index] = orig[source_index]
    except IndexError:
        fill_lst(ref, target_index)
        ref[target_index] = orig[source_index]
    mapper[target_index] = source_index

def set_lst_val(target_index, val):
    try:
        ref[target_index] = val
    except IndexError:
        fill_lst(ref, target_index)
        ref[target_index] = val
    orig[mapper[target_index]] = val

populate_lst(0, 2)
populate_lst(1, 4)

print ref  # [3, 5]

set_lst_val(0, 11)
set_lst_val(1, 22)

print orig  # [1, 2, 11, 4, 22]


问:
DDMS files not found: SDK_HOME/tools/traceview : Eclipse
I'm newly configured Android Eclipse neon in Ubuntu. When I try to open the eclipse it throws error As
 "Failed to get the required ADT version number from the SDK. The Android Development Toolkit may not work properly"

I have tried many references but i am unable to solve the issue as given in references to reinstall ADT plugin.Which i have tried many times and does not solve the issue.

The Message shown in dialog box

答:
Finally i got an answer.

You first restart your eclipse and check it.

If again throws same error please try this steps:

 1. Download latest SDK tools package package from google.Download here end of the page.

2. Extract the tools package.

3. Replace Exract folder(ToolsPackage) to ANDROID_SDK_DIRECTORY/tools folder.

4. Now fixed the issue. works fine for me.


问:
Adding a property to a function
You can assign a property to a function, but is that a good idea?
In this example, I'm showing that you can't create a property to a function inside the function, but you can outside it.

Q: Is a.questionable considered an ok JavaScript programming practice?

function a() {
a.bad = 1
}
a.questionable = 2

function d() {
  console.log(a.bad)
  console.log(a.questionable)
}
d()```

This question was inspired by JavaScript: Understanding the Weird Parts

答:
It’s fine to put properties on functions. In fact, that’s exactly what static methods are on ES6 classes, which is the only use of static; consider it explicit language support.

```<code>class Foo {
    static bar() {}
}

'bar' in Foo  // true
typeof Foo    // 'function'
</code>```

In this example, I'm showing that you can't create a property to a function inside the function, but you can outside it.

You can create a property on a function inside that function, but it’s unreasonable to expect the body of a function to run without calling it.

Title: Adding a property to a function

Body:
You can assign a property to a function, but is that a good idea?
In this example, I'm showing that you can't create a property to a function inside the function, but you can outside it.

Q: Is a.questionable considered an ok JavaScript programming practice?

function a() {
a.bad = 1
}
a.questionable = 2

function d() {
  console.log(a.bad)
  console.log(a.questionable)
}
d()

This question was inspired by JavaScript: Understanding the Weird Parts

Body:
It’s fine to put properties on functions. In fact, that’s exactly what static methods are on ES6 classes, which is the only use of static; consider it explicit language support.

class Foo {
    static bar() {}
}

'bar' in Foo  // true
typeof Foo    // 'function'

In this example, I'm showing that you can't create a property to a function inside the function, but you can outside it.

You can create a property on a function inside that function, but it’s unreasonable to expect the body of a function to run without calling it.


问:
How do I get the server uptime in Node.js?
How do I get a server uptime in Node.js so I can output it by a command like;

```<code>if(commandCheck("/uptime")){
  Give server uptime;
}
</code>```

Now I don't know how to calculate the uptime from the server's startup.

答:
To get process's uptime in seconds

```<code>    console.log(process.uptime())
</code>```

To get OS uptime in seconds

```<code>    console.log(require('os').uptime())
</code>```

Body:
How do I get a server uptime in Node.js so I can output it by a command like;

if(commandCheck("/uptime")){
  Give server uptime;
}

Now I don't know how to calculate the uptime from the server's startup.

Body:
To get process's uptime in seconds

    console.log(process.uptime())

To get OS uptime in seconds

    console.log(require('os').uptime())


问:
Unable to use iOS framework which is internally using .xib file
I am trying to make a universal framework, for iOS by following steps specified in this URL: Universal-framework-iOS

I have a viewController class within, that framework which internally loads a .xib file.

Below is a part of code which shows, how I am initializing that viewController and showing related view:

```<code>/*** Part of implementation of SomeViewController class, which is outside the framework ***/

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.viewControllerWithinFramework = [[ViewControllerWithinFramework alloc] initWithTitle:@"My custom view"];
}
- (IBAction)showSomeView:(id)sender {
    [self.viewControllerWithinFramework showRelatedView];
}

/*** Part of implementation of ViewControllerWithinFramework class, which is inside the framework ***/

- (id)initWithTitle:(NSString *)aTitle
{
   self = [super initWithNibName:@"ViewControllerWithinFramework" bundle:nil]; // ViewControllerWithinFramework.xib is within the framework

   if (self)
   {
       _viewControllerTitle = aTitle;
   }

   return self;
}
</code>```

While creating the framework, I included all .xib files, including ViewControllerWithinFramework.xib within its Copy Bundle Resources build phase.

Now my problem is when I try to integrate that framework within other project, it crashes with below stack trace:

```<code>Sample[3616:a0b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </Users/miraaj/Library/Application Support/iPhone Simulator/7.0/Applications/78CB9BC5-0FCE-40FC-8BCB-721EBA031296/Sample.app> (loaded)' with name 'ViewControllerWithinFramework''
*** First throw call stack:
(
    0   CoreFoundation                      0x017365e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x014b98b6 objc_exception_throw + 44
    2   CoreFoundation                      0x017363bb +[NSException raise:format:] + 139
    3   UIKit                               0x004cc65c -[UINib instantiateWithOwner:options:] + 951
    4   UIKit                               0x0033ec95 -[UIViewController _loadViewFromNibNamed:bundle:] + 280
    5   UIKit                               0x0033f43d -[UIViewController loadView] + 302
    6   UIKit                               0x0033f73e -[UIViewController loadViewIfRequired] + 78
    7   UIKit                               0x0033fc44 -[UIViewController view] + 35
</code>```

Any ideas, how could I resolve this problem?

Note: It works fine if there is no any xib within the framework.

答:
As an another option you can directly put your xib file into your framework project and can get your nib with calling

Swift 3 and Swift 4

```<code>let bundleIdentifier = "YOUR_FRAMEWORK_BUNDLE_ID"
let bundle = Bundle(identifier: bundleIdentifier)
let view = bundle?.loadNibNamed("YOUR_XIB_FILE_NAME", owner: nil, options: nil)?.first as! UIView
</code>```

Objective-C

```<code>NSString *bundleIdentifier = @"YOUR_FRAMEWORK_BUNDLE_ID";
NSBundle *bundle = [NSBundle bundleWithIdentifier:bundleIdentifier];
UIView *view =  [bundle loadNibNamed:@"YOUR_XIB_FILE_NAME" owner:nil options:nil];
</code>```

Body:
I am trying to make a universal framework, for iOS by following steps specified in this URL: Universal-framework-iOS

I have a viewController class within, that framework which internally loads a .xib file.

Below is a part of code which shows, how I am initializing that viewController and showing related view:

/*** Part of implementation of SomeViewController class, which is outside the framework ***/

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.viewControllerWithinFramework = [[ViewControllerWithinFramework alloc] initWithTitle:@"My custom view"];
}
- (IBAction)showSomeView:(id)sender {
    [self.viewControllerWithinFramework showRelatedView];
}

/*** Part of implementation of ViewControllerWithinFramework class, which is inside the framework ***/

- (id)initWithTitle:(NSString *)aTitle
{
   self = [super initWithNibName:@"ViewControllerWithinFramework" bundle:nil]; // ViewControllerWithinFramework.xib is within the framework

   if (self)
   {
       _viewControllerTitle = aTitle;
   }

   return self;
}

While creating the framework, I included all .xib files, including ViewControllerWithinFramework.xib within its Copy Bundle Resources build phase.

Now my problem is when I try to integrate that framework within other project, it crashes with below stack trace:

Sample[3616:a0b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </Users/miraaj/Library/Application Support/iPhone Simulator/7.0/Applications/78CB9BC5-0FCE-40FC-8BCB-721EBA031296/Sample.app> (loaded)' with name 'ViewControllerWithinFramework''
*** First throw call stack:
(
    0   CoreFoundation                      0x017365e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x014b98b6 objc_exception_throw + 44
    2   CoreFoundation                      0x017363bb +[NSException raise:format:] + 139
    3   UIKit                               0x004cc65c -[UINib instantiateWithOwner:options:] + 951
    4   UIKit                               0x0033ec95 -[UIViewController _loadViewFromNibNamed:bundle:] + 280
    5   UIKit                               0x0033f43d -[UIViewController loadView] + 302
    6   UIKit                               0x0033f73e -[UIViewController loadViewIfRequired] + 78
    7   UIKit                               0x0033fc44 -[UIViewController view] + 35

Any ideas, how could I resolve this problem?

Note: It works fine if there is no any xib within the framework.

Body:
As an another option you can directly put your xib file into your framework project and can get your nib with calling

Swift 3 and Swift 4

let bundleIdentifier = "YOUR_FRAMEWORK_BUNDLE_ID"
let bundle = Bundle(identifier: bundleIdentifier)
let view = bundle?.loadNibNamed("YOUR_XIB_FILE_NAME", owner: nil, options: nil)?.first as! UIView

Objective-C

NSString *bundleIdentifier = @"YOUR_FRAMEWORK_BUNDLE_ID";
NSBundle *bundle = [NSBundle bundleWithIdentifier:bundleIdentifier];
UIView *view =  [bundle loadNibNamed:@"YOUR_XIB_FILE_NAME" owner:nil options:nil];