问:
Calling a Python script from C# - changing the script's filepath causes the program to not work
The following code works perfectly without flaw:

```<code>    public partial class MainForm : Form
    {
        string pyInterp = File.ReadAllText(Directory.GetCurrentDirectory() + @"\config\pathToPythonInterpreter.txt");
        string pyWeather = @"C:\getWeather.py";
        public MainForm()
        {
            InitializeComponent();
            UpdateWeather();
        }

        public void UpdateWeather()
        {
            labelWeather.Text = PySharp.ExecutePy(pyInterp, pyWeather);
        }
    }
</code>```

However, when I change the path to getWeather.py to not be in an arbitrary random location, like this:

```<code>string pyWeather = Directory.GetCurrentDirectory() + @"\scripts\getWeather.py";
</code>```

Then my program no longer obtains the script's output. The script still works: I launched it using IDLE and it completed its function properly. When I call it using C#, the console opens, yet no output is obtained.

The Python script is the following:

```<code>from requests import get
from bs4 import BeautifulSoup as soup

r = get("http://www.ilmateenistus.ee/ilm/prognoosid/4-oopaeva-prognoos/")
parsed = soup(r.content, "html.parser")
container = parsed.find("div",{"class":"point kuusiku"})
print(str(container["data-title"]))
</code>```

(It webscrapes my local weather)

PySharp.ExecutePy() can be viewed here

By far the strangest bug I've ever encountered. Any ideas?

EDIT 1: It seems that C# is indeed reading something from the script. It just appears that this something is.. nothing. I gave the label a default sample text, and after running the program, the label's text is simply changed to an empty string. Hope this incredible discovery helps somehow.

EDIT 2: The program fails to call the script correctly when its filepath contains spaces. For example:

```<code>C:\foo bar\testing\pyWeather.py
</code>```

does not work!

答:
I would want you to return the answer instead of printing. Printer is an I/O based solution to display. So it will work super fine with IDLE however it may not return results as you expected. I strongly believe this will solve your problem.
instead of printing please try return. I can give more support after trying this.</p>

```<code>return(str(container["data-title"]))
</code>```

Body:
The following code works perfectly without flaw:

    public partial class MainForm : Form
    {
        string pyInterp = File.ReadAllText(Directory.GetCurrentDirectory() + @"\config\pathToPythonInterpreter.txt");
        string pyWeather = @"C:\getWeather.py";
        public MainForm()
        {
            InitializeComponent();
            UpdateWeather();
        }

        public void UpdateWeather()
        {
            labelWeather.Text = PySharp.ExecutePy(pyInterp, pyWeather);
        }
    }

However, when I change the path to getWeather.py to not be in an arbitrary random location, like this:

string pyWeather = Directory.GetCurrentDirectory() + @"\scripts\getWeather.py";

Then my program no longer obtains the script's output. The script still works: I launched it using IDLE and it completed its function properly. When I call it using C#, the console opens, yet no output is obtained.

The Python script is the following:

from requests import get
from bs4 import BeautifulSoup as soup

r = get("http://www.ilmateenistus.ee/ilm/prognoosid/4-oopaeva-prognoos/")
parsed = soup(r.content, "html.parser")
container = parsed.find("div",{"class":"point kuusiku"})
print(str(container["data-title"]))

(It webscrapes my local weather)

PySharp.ExecutePy() can be viewed here

By far the strangest bug I've ever encountered. Any ideas?

EDIT 1: It seems that C# is indeed reading something from the script. It just appears that this something is.. nothing. I gave the label a default sample text, and after running the program, the label's text is simply changed to an empty string. Hope this incredible discovery helps somehow.

EDIT 2: The program fails to call the script correctly when its filepath contains spaces. For example:

C:\foo bar\testing\pyWeather.py

does not work!

Body:
I would want you to return the answer instead of printing. Printer is an I/O based solution to display. So it will work super fine with IDLE however it may not return results as you expected. I strongly believe this will solve your problem.
instead of printing please try return. I can give more support after trying this.

return(str(container["data-title"]))


来源: stackexchange

问:
Self Join issue, not receiving any result
I am trying to run query where I would compare same accounts with different time stamps, I have run this query (similar, with real accounts but I am not getting any result back. Please help.</p>

```<code>    select  t1.number , t1.created, t1.comment, t2.number , t2.created,
    t2.comment from [aaa].[dbo].[t_table]  t1 inner join
    (select number , created, comment from [aaa].[dbo].[table]
where created > '2017-07-06 12:00:00.000'
    and number in (1,2,3,4,5)) t2
    on t1.number = t2.number
    where t1.created >= '2017-07-06 11:00:00.000' and
    t1.created < '2017-07-06 12:00:00.000' and t1.number in (1,2,3,4,5);
</code>```

答:
This

```<code>t1 inner join
    (select number , created, comment from [aaa].[dbo].[table]
where created > '2017-07-06 12:00:00.000'
</code>```

gets rows after noon but this condition:

```<code>t1.created < '2017-07-06 12:00:00.000'
</code>```

gets rows before noon.  They are mutually exclusive.  No rows were created both before and after noon.

Based on what you entered in the other part of the query, perhaps you mean:

```<code>t1 inner join
    (select number , created, comment from [aaa].[dbo].[table]
where created > '2017-07-06 11:00:00.000'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run query where I would compare same accounts with different time stamps, I have run this query (similar, with real accounts but I am not getting any result back. Please help.

    select  t1.number , t1.created, t1.comment, t2.number , t2.created,
    t2.comment from [aaa].[dbo].[t_table]  t1 inner join
    (select number , created, comment from [aaa].[dbo].[table]
where created > '2017-07-06 12:00:00.000'
    and number in (1,2,3,4,5)) t2
    on t1.number = t2.number
    where t1.created >= '2017-07-06 11:00:00.000' and
    t1.created < '2017-07-06 12:00:00.000' and t1.number in (1,2,3,4,5);

Body:
This

t1 inner join
    (select number , created, comment from [aaa].[dbo].[table]
where created > '2017-07-06 12:00:00.000'

gets rows after noon but this condition:

t1.created < '2017-07-06 12:00:00.000'

gets rows before noon.  They are mutually exclusive.  No rows were created both before and after noon.

Based on what you entered in the other part of the query, perhaps you mean:

t1 inner join
    (select number , created, comment from [aaa].[dbo].[table]
where created > '2017-07-06 11:00:00.000'


问:
Problems with refreshing a draggable MFC window
Greetings.

I have to make a draggable MFC dialog window, which has a background  - used that: http://www.codeproject.com/KB/graphics/picturewindow.aspx - and has several picturebox controls. I have tried two approaches, and while they do work, they have some problems.

First approach is "Manual" - on the LBUTTONDOWN message I check if it;s on a clean area of my window, and set a flag variable. On MOUSEMOVE, the flag is checked and if it's set, a MoveWindow function is called, and then, Invalidate(1). On LBUTTONUP, flag is unset.
This approach works correctly and redraws as needed, but is somehow very slow - if I'm moving the cursor too fast, the window falls behing and isn't dragged, as cursor's not over the window anymore.

The second approach is "Automatic" - I just call

DefWindowProc(WM_SYSCOMMAND, SC_MOVE+2,MAKELPARAM(point.x,point.y));

on LBUTTONDOWN, and it handles the rest, it's quick and never fall behind, but when I drag it over screen's edge ( so that some part of the window gets invisible), when I drag it back, all the controls get invisible and are not refreshed, background is okay.  I suppose that's because Invalidate() isn't called during movement that way, as I actually call it after calling DefWindowProc() and so, everything is refreshed properly when I depress the button.

What should I do to improve either of those solutions? I need it both fast and correct. I may have not provided some required information, I'll add it is need arise.

Thanks in advance.

答: Solved the problem, by modifying the second way. I added a total redraw to the OnPaint(), and to get rid of flicker, I only redraw durng dragging, by using a flag variable.</p>

ContentLicense: CC BY-SA 2.5


问:
Custom Javascript scrolling plugin not working
Documentation: http://idiotwu.github.io/smooth-scrollbar/

Github: https://github.com/idiotWu/smooth-scrollbar

My JSFiddle attempt

What am I missing or not doing correctly?

```<code><div class="box" data-scrollbar="true">
<p>
 This is some sample text to input into the textbox on this Fiddle. This is some sample text to input into the textbox on this Fiddle......
 </p>
</div>
</code>```

答:
You tried to use the plugin before it was even declared.
I moved the usage part down and it worked.

See here: https://jsfiddle.net/8vw2pexa/2.

```<code>/* SMOOTH SCROLLING PLUGIN */
... plugin code ...

const { Scrollbar } = window;
Scrollbar.initAll({ speed: 0.15 });
</code>```

Body:
Documentation: http://idiotwu.github.io/smooth-scrollbar/

Github: https://github.com/idiotWu/smooth-scrollbar

My JSFiddle attempt

What am I missing or not doing correctly?

 This is some sample text to input into the textbox on this Fiddle. This is some sample text to input into the textbox on this Fiddle......

Body:
You tried to use the plugin before it was even declared.
I moved the usage part down and it worked.

See here: https://jsfiddle.net/8vw2pexa/2.

/* SMOOTH SCROLLING PLUGIN */
... plugin code ...

const { Scrollbar } = window;
Scrollbar.initAll({ speed: 0.15 });


问:
Why is my pandas dataframe not updating its values as I change them?
I am trying to make changes to each string in my Series object 'tweet_text', but for some reason when I print the series object after making changes to the tweets in my for loop, I get the same strings as I had before the for loop. How can I fix this?  </p>

```<code>import pandas as pd
import re
import string

df = pd.read_csv('sample-tweets.csv',
                 names=['Tweet_Date', 'User_ID', 'Tweet_Text', 'Favorites', 'Retweets', 'Tweet_ID'])

sum_df = df[['User_ID', 'Tweet_ID', 'Tweet_Text']].copy()
sum_df.set_index(['User_ID'])
# print sum_df

tweet_text = df.ix[:, 2]
print type(tweet_text)

# efficiency could be im proved by using translate method
# regex = re.compile('[%s]' % re.escape(string.punctuation))

for tweet in tweet_text:
    tweet = re.sub('https://t.co/[a-zA-Z0-9]*', "", tweet)
    tweet = re.sub('@[a-zA-Z0-9]*', '', tweet)
    tweet = re.sub('#[a-zA-Z0-9]*', '', tweet)
    tweet = re.sub('$[a-zA-Z0-9]*', '', tweet)
    tweet = ''.join(i for i in tweet if not i.isdigit())
    tweet = tweet.replace('"', '')
    tweet = re.sub(r'[\(\[].*?[\)\]]', '', tweet)  # takes out everything between parentheses also, fix this

    # gets rid of all punctuation and emoji's
    tweet = "".join(l for l in tweet if l not in string.punctuation)
    tweet = re.sub(r'[^\x00-\x7F]+',' ', tweet)

    # gets ride of all extra spacing
    tweet = tweet.lower()
    tweet = tweet.strip()
    tweet = " ".join(tweet.split())

    count = count + 1
    # print tweet

print tweet_text
</code>```

答:
It is happening like that because tweet_text is a copy of a column df.ix[:, 2] for starters. Secondly, this is not pandas way to iterate over Series - you should use apply().

To update your code, everything that goes into the loop, change into function:

```<code>def parse_tweet(tweet):
    ## everything from loop goes here
    return tweet
</code>```

Then, instead of:

```<code>tweet_text = df.ix[:, 2]
</code>```

do:

```<code>df.iloc[:, 2] = df.iloc[:, 2].apply(parse_tweet)
</code>```

BTW, do not use ix indexer as it is depreciated and going to be removed in the future versions of pandas.

Body:
I am trying to make changes to each string in my Series object 'tweet_text', but for some reason when I print the series object after making changes to the tweets in my for loop, I get the same strings as I had before the for loop. How can I fix this?

import pandas as pd
import re
import string

df = pd.read_csv('sample-tweets.csv',
                 names=['Tweet_Date', 'User_ID', 'Tweet_Text', 'Favorites', 'Retweets', 'Tweet_ID'])

sum_df = df[['User_ID', 'Tweet_ID', 'Tweet_Text']].copy()
sum_df.set_index(['User_ID'])
# print sum_df

tweet_text = df.ix[:, 2]
print type(tweet_text)

# efficiency could be im proved by using translate method
# regex = re.compile('[%s]' % re.escape(string.punctuation))

for tweet in tweet_text:
    tweet = re.sub('https://t.co/[a-zA-Z0-9]*', "", tweet)
    tweet = re.sub('@[a-zA-Z0-9]*', '', tweet)
    tweet = re.sub('#[a-zA-Z0-9]*', '', tweet)
    tweet = re.sub('$[a-zA-Z0-9]*', '', tweet)
    tweet = ''.join(i for i in tweet if not i.isdigit())
    tweet = tweet.replace('"', '')
    tweet = re.sub(r'[\(\[].*?[\)\]]', '', tweet)  # takes out everything between parentheses also, fix this

    # gets rid of all punctuation and emoji's
    tweet = "".join(l for l in tweet if l not in string.punctuation)
    tweet = re.sub(r'[^\x00-\x7F]+',' ', tweet)

    # gets ride of all extra spacing
    tweet = tweet.lower()
    tweet = tweet.strip()
    tweet = " ".join(tweet.split())

    count = count + 1
    # print tweet

print tweet_text

Body:
It is happening like that because tweet_text is a copy of a column df.ix[:, 2] for starters. Secondly, this is not pandas way to iterate over Series - you should use apply().

To update your code, everything that goes into the loop, change into function:

def parse_tweet(tweet):
    ## everything from loop goes here
    return tweet

Then, instead of:

tweet_text = df.ix[:, 2]

do:

df.iloc[:, 2] = df.iloc[:, 2].apply(parse_tweet)

BTW, do not use ix indexer as it is depreciated and going to be removed in the future versions of pandas.


问:
How to make clickable listview in android using kotlin
I am new in android development with kotlin  . I am trying to make clickable listview items but not getting good resource.</p>

答: It's really not much different from how you'd do it in Java since Kotlin uses Java's frameworks/libraries and its JVM. Just apply the necessary Kotlin plugins and configurations in Android Studio, convert the Java code to Kotlin, and then refer to the Kotlin docs for potential bug fixes and whatnot.</p>


问:
Prebuilt MIPS cross compiler with toolchain for MS-Windows
I'm using a MIPS cross compiler on my Linux machine which works great.
Now I need to compile the same application on Windows.

I'm searching the web for some prebuilt MIPS cross compiler (with toolchain) for MS-Windows, but without success.

Since I'm not sure how to do so, I'm asking if someone knows such prebuilt toolchain? or some guide how to convert my Linux toolchain for windows if it's possible?

Thanks.

答: It looks like Mentor has taken away the free MIPS toolchain from the CodeSourcery distribution.  Maybe one of these might still work: https://www.linux-mips.org/wiki/Toolchains.</p>


问:
Paypal NVP API - Keep getting error 81002
I am new to PayPal API, and I'm having trouble calling SetExpressCheckout using CURL in PHP.
I have set everything correctly, as far as I'm concerned, but I kept getting an 81002 error "Method Specified is not Supported".

The code snippet is below. I got the CA Root certificates file from here.

```<code><?php

$paypal_data = array(
    'USER' => urlencode('andree_1272823561_biz_api1.gmail.com'),
    'PWD' => urlencode('1272823576'),
    'SIGNATURE' => urlencode('Am1t0wiu2tv7VwZ5ebdeY9zv1GF6Ad0PFz-qTGFFf7vbWU6ee4bxy8KL'),
    'VERSION' => urlencode('52.0'),
    'PAYMENTACTION' => urlencode('Sale'),
    'METHOD' => urlencode('SetExpressCheckout'),
    'AMT' => urlencode('52.00'),
    'RETURNURL' => urlencode('get_express_checkout_details.php'),
    'CANCELURL' => urlencode('index.php')
);

$url = 'https://api-3t.sandbox.paypal.com/nvp?' . http_build_query($paypal_data);
$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');

$result = curl_exec($curl);
curl_close($curl);
parse_str($result, $result);
?>

```Data sent: <?php print_r($paypal_data); ?>```
```Result: <?php print_r($result); ?>```
</code>```

When I run the code, the output is the following:

```<code>Data sent: Array
(
    [USER] => andree_1272823561_biz_api1.gmail.com
    [PWD] => 1272823576
    [SIGNATURE] => Am1t0wiu2tv7VwZ5ebdeY9zv1GF6Ad0PFz-qTGFFf7vbWU6ee4bxy8KL
    [VERSION] => 52.0
    [PAYMENTACTION] => Sale
    [METHOD] => SetExpressCheckout
    [AMT] => 52.00
    [RETURNURL] => get_express_checkout_details.php
    [CANCELURL] => index.php
)

Result: Array
(
    [ACK] => Failure
    [L_ERRORCODE0] => 81002
    [L_SHORTMESSAGE0] => Unspecified Method
    [L_LONGMESSAGE0] => Method Specified is not Supported
    [L_SEVERITYCODE0] => Error
)
</code>```

Anyone knows what could be the problem?

Regards, Andree.

答:
I am not using the PHP API, but I ran into the same 81002 error using the Callback API (java) and I got this when some of the parameters were either missing or badly formated.

I don't know if you solved the issue, but my advice would be checking which of the parameters are requred for the SetExpressCheckout (API Reference). And than if you have set those, check if the limitations part of the description of the parameter is satisfied.

Sadly but they sometimes throw inappropriate errors (or errors that the developer can't quite understand). On the other side I usually get most of my responses answered on their forum. If in "trouble" you can also write a private message to the paypal team member on shift (or to a person that has already solved your problem).

Hope that helped!

Despot

Body:
I am new to PayPal API, and I'm having trouble calling SetExpressCheckout using CURL in PHP.
I have set everything correctly, as far as I'm concerned, but I kept getting an 81002 error "Method Specified is not Supported".

The code snippet is below. I got the CA Root certificates file from here.

<?php

$paypal_data = array(
    'USER' => urlencode('andree_1272823561_biz_api1.gmail.com'),
    'PWD' => urlencode('1272823576'),
    'SIGNATURE' => urlencode('Am1t0wiu2tv7VwZ5ebdeY9zv1GF6Ad0PFz-qTGFFf7vbWU6ee4bxy8KL'),
    'VERSION' => urlencode('52.0'),
    'PAYMENTACTION' => urlencode('Sale'),
    'METHOD' => urlencode('SetExpressCheckout'),
    'AMT' => urlencode('52.00'),
    'RETURNURL' => urlencode('get_express_checkout_details.php'),
    'CANCELURL' => urlencode('index.php')
);

$url = 'https://api-3t.sandbox.paypal.com/nvp?' . http_build_query($paypal_data);
$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');

$result = curl_exec($curl);
curl_close($curl);
parse_str($result, $result);
?>

Data sent: <?php print_r($paypal_data); ?>

Result: <?php print_r($result); ?>

When I run the code, the output is the following:

Data sent: Array
(
    [USER] => andree_1272823561_biz_api1.gmail.com
    [PWD] => 1272823576
    [SIGNATURE] => Am1t0wiu2tv7VwZ5ebdeY9zv1GF6Ad0PFz-qTGFFf7vbWU6ee4bxy8KL
    [VERSION] => 52.0
    [PAYMENTACTION] => Sale
    [METHOD] => SetExpressCheckout
    [AMT] => 52.00
    [RETURNURL] => get_express_checkout_details.php
    [CANCELURL] => index.php
)

Result: Array
(
    [ACK] => Failure
    [L_ERRORCODE0] => 81002
    [L_SHORTMESSAGE0] => Unspecified Method
    [L_LONGMESSAGE0] => Method Specified is not Supported
    [L_SEVERITYCODE0] => Error
)

Anyone knows what could be the problem?

Regards, Andree.


问:
How to write junit for this code?
How do I call populateMapWithFormattedDates method in JUnit and how to write JUnit populateMapWithFormattedDates for this method. I dont know how to write JUnit for nested methods so kindly help. </p>

```<code>protected Map<String, String> populateDispatch(final RequestDispatchData requestDispatchData)
    {
        final Map<String, String> map = getDispatchFieldMapper().populateMapper(requestDispatchData);
        populateMapWithFormattedDates(requestDispatchData, map);
 }

private void populateMapWithFormattedDates(final RequestDispatchData requestDispatchData, final Map<String, String> map)
    {
        String dateFormatted = map.get("ticket_date");
        Date date = null;
        try
        {
            date = new SimpleDateFormat("MM/dd/yy").parse(dateFormatted);
        }
        catch (ParseException parseException)
        {
            customLogger.logMessage(diagnosticMethodSignature, DiagnosticType.EXCEPTION,
                    "Exception in parsing start date of ticket " + parseException);
        }
        map.put("startDateDDMMYY", DateEnum.DDMMYY.getFormattor().format(date));
        map.put("startDateDDMMMYY", DateEnum.DDMMMYY.getFormattor().format(date));
        map.put("startDateDMY", DateEnum.DMY.getFormattor().format(date));
        map.put("startDateYYMMDD", DateEnum.YYMMDD.getFormattor().format(date));
    }
</code>```

答:
You should decouple the populateMapWithFormattedDates method like this:

```<code>// I created an utility class but it's a suggestion.
// I'm using an util class because you don't use requestDispatchData for
// anything. But if you do, maybe it's a good idea to implement this code
// on RequestDispatchData class
class DispatchMapUtils {
    // Note that I took of the requestDispatchData
    public static Map<String, String> populateMapWithFormattedDates(final Map<String, String> map) throws ParseException {
         // Your code without try-catch.
         // Throw the exception to the caller of this method
         // and try-catch there to use the customLogger
    }
}
</code>```

With this code, your test would be something like this:

```<code>@Test
public void shouldFormatTicketDateInVariousFormat() {
     Map<String, String> map;
     // Instantiate and put some initial datas
     map = new ...
     map.put('ticket_date') = ..
     // Call the method!
     DispatchMapUtils.populateMapWithFormattedDates(map);
     // Do the assertions!
     Assert.assertTrue(map.get("startDateDDMMYY").equals(...));
}

@Test
public void shouldThrowExceptionWhenTicketDateIsInvalid() {
    // More testing code
}
</code>```

Title: How to write junit for this code?

Body:
How do I call populateMapWithFormattedDates method in JUnit and how to write JUnit populateMapWithFormattedDates for this method. I dont know how to write JUnit for nested methods so kindly help.

protected Map<String, String> populateDispatch(final RequestDispatchData requestDispatchData)
    {
        final Map<String, String> map = getDispatchFieldMapper().populateMapper(requestDispatchData);
        populateMapWithFormattedDates(requestDispatchData, map);
 }

private void populateMapWithFormattedDates(final RequestDispatchData requestDispatchData, final Map<String, String> map)
    {
        String dateFormatted = map.get("ticket_date");
        Date date = null;
        try
        {
            date = new SimpleDateFormat("MM/dd/yy").parse(dateFormatted);
        }
        catch (ParseException parseException)
        {
            customLogger.logMessage(diagnosticMethodSignature, DiagnosticType.EXCEPTION,
                    "Exception in parsing start date of ticket " + parseException);
        }
        map.put("startDateDDMMYY", DateEnum.DDMMYY.getFormattor().format(date));
        map.put("startDateDDMMMYY", DateEnum.DDMMMYY.getFormattor().format(date));
        map.put("startDateDMY", DateEnum.DMY.getFormattor().format(date));
        map.put("startDateYYMMDD", DateEnum.YYMMDD.getFormattor().format(date));
    }

Body:
You should decouple the populateMapWithFormattedDates method like this:

// I created an utility class but it's a suggestion.
// I'm using an util class because you don't use requestDispatchData for
// anything. But if you do, maybe it's a good idea to implement this code
// on RequestDispatchData class
class DispatchMapUtils {
    // Note that I took of the requestDispatchData
    public static Map<String, String> populateMapWithFormattedDates(final Map<String, String> map) throws ParseException {
         // Your code without try-catch.
         // Throw the exception to the caller of this method
         // and try-catch there to use the customLogger
    }
}

With this code, your test would be something like this:

@Test
public void shouldFormatTicketDateInVariousFormat() {
     Map<String, String> map;
     // Instantiate and put some initial datas
     map = new ...
     map.put('ticket_date') = ..
     // Call the method!
     DispatchMapUtils.populateMapWithFormattedDates(map);
     // Do the assertions!
     Assert.assertTrue(map.get("startDateDDMMYY").equals(...));
}

@Test
public void shouldThrowExceptionWhenTicketDateIsInvalid() {
    // More testing code
}


问:
Slice data.frame and join back old data.frame without slice
I am slicing a data.frame by removing 50% of rows with lowest revenue, now I want to join back old data.frame so I can compare result with slice against result before slice.

I have a solution but looking for a more elegant.

```<code>require(dplyr)

> #creating my data.frame with revenue for id and subid
> df <- data.frame(id = gl(n = 2, k= 5, length = 10),
+                   subid = gl(n = 6, k = 2, length = 10),
+                   rev = rnorm(10, 100, 15))
> df
   id subid       rev
1   1     1 102.80694
2   1     1  77.88691
3   1     2 122.71019
4   1     2  67.13475
5   1     3  93.21146
6   2     3  91.48368
7   2     4 103.05535
8   2     4  82.27343
9   2     5 106.03651
10  2     5  81.14182
>
> #keep only subid with 50% highest turnover within each id
> df_sliced <-  df %>%
+     arrange(id, desc(rev)) %>%
+     group_by(id) %>%
+     slice(seq(n()*0.5)) %>%
+     group_by(id) %>%
+     summarise(rev_sliced = sum(rev))
>
> df_sliced
Source: local data frame [2 x 2]

      id rev_sliced
  (fctr)      (dbl)
1      1   225.5171
2      2   209.0919
>
> #now I want to join back and compare my sliced result with result before slice.
> df_desired <- df %>%
+   group_by(id) %>%
+   summarise(rev = sum(rev)) %>%
+   cbind(df_sliced) #this will obviously also give me two columns with id. Desired result is with only one column for id.
>
> df_desired
  id      rev id rev_sliced
1  1 463.7503  1   225.5171
2  2 463.9908  2   209.0919
</code>```

I have not solved how to use join and not how to have everything in one chain.

答:
For the sliced sum, you can calculate the sum of rev that is above the 50% quantile as follows; then you can calculate both in the same summarize expression without the need of a join:

```<code>df %>%
    group_by(id) %>%
    summarise(rev_sliced = sum(rev[rev > quantile(rev, 0.5)]),
              rev = sum(rev))

# A tibble: 2 x 3
#     id rev_sliced      rev
#  <int>      <dbl>    <dbl>
#1     1   225.5171 463.7502
#2     2   209.0919 463.9908
</code>```

Body:
I am slicing a data.frame by removing 50% of rows with lowest revenue, now I want to join back old data.frame so I can compare result with slice against result before slice.

I have a solution but looking for a more elegant.

require(dplyr)

> #creating my data.frame with revenue for id and subid
> df <- data.frame(id = gl(n = 2, k= 5, length = 10),
+                   subid = gl(n = 6, k = 2, length = 10),
+                   rev = rnorm(10, 100, 15))
> df
   id subid       rev
1   1     1 102.80694
2   1     1  77.88691
3   1     2 122.71019
4   1     2  67.13475
5   1     3  93.21146
6   2     3  91.48368
7   2     4 103.05535
8   2     4  82.27343
9   2     5 106.03651
10  2     5  81.14182
>
> #keep only subid with 50% highest turnover within each id
> df_sliced <-  df %>%
+     arrange(id, desc(rev)) %>%
+     group_by(id) %>%
+     slice(seq(n()*0.5)) %>%
+     group_by(id) %>%
+     summarise(rev_sliced = sum(rev))
>
> df_sliced
Source: local data frame [2 x 2]

      id rev_sliced
  (fctr)      (dbl)
1      1   225.5171
2      2   209.0919
>
> #now I want to join back and compare my sliced result with result before slice.
> df_desired <- df %>%
+   group_by(id) %>%
+   summarise(rev = sum(rev)) %>%
+   cbind(df_sliced) #this will obviously also give me two columns with id. Desired result is with only one column for id.
>
> df_desired
  id      rev id rev_sliced
1  1 463.7503  1   225.5171
2  2 463.9908  2   209.0919

I have not solved how to use join and not how to have everything in one chain.

Body:
For the sliced sum, you can calculate the sum of rev that is above the 50% quantile as follows; then you can calculate both in the same summarize expression without the need of a join:

df %>%
    group_by(id) %>%
    summarise(rev_sliced = sum(rev[rev > quantile(rev, 0.5)]),
              rev = sum(rev))

# A tibble: 2 x 3
#     id rev_sliced      rev
#  <int>      <dbl>    <dbl>
#1     1   225.5171 463.7502
#2     2   209.0919 463.9908


问:
Upgrade / Uninstall NodeJS on Windows
Somehow node version v0.12.2 got installed on my Windows machine and I'd like to upgrade to a newer version, however, it is not in the "Add or Remove Programs" menu.

When I try to install node from the Windows MSI, I get the standard windows 1603 error (below), which I am assuming means windows thinks that this application is already installed.

MSI (s) (64:84): Windows Installer installed the
  product. Product Name: Node.js. Product Version: 6.11.0. Product
  Language: 1033. Manufacturer: Node.js Foundation. Installation success
  or error status: 1603.

Any ideas?  I've tried lots of things like this and this with no luck.

I am trying to install an npm package that depends on a higher version of node and striking out.

答:
Man, I had this same issue a long time ago and it was really a pain to discover what I should do. Just download the .msi related to the version installed on your machine from here:

https://nodejs.org/en/download/releases/

Execute the downloaded .msi, and from there, choose to uninstall.

Title: Upgrade / Uninstall NodeJS on Windows


问:
How to map assosiative array in React/ES6? Starts an infinite loop
The array is generated following way:

```<code>for(var i = start; i <= end;i+=step) {
    arr[i] = i + 'is the number';
}
</code>```

Array structure looks like this

```<code>arr = [
1100: "1100 is the number",
1101: "1101 is the number",
1102: "1102 is the number",
1103: "1103 is the number",
1104: "1104 is the number",
1105: "1105 is the number",
];
</code>```

and so on.

This array will be mapped into a list element in React.

```<code>render() {
    const list = this.arr;
    const timeList = list.map((element) =>
        <li>{element}</li>
        );

    return (
      <div className="App" >
        {timeList}
      </div>
    );
</code>```

It works fine with the regular arrays, but using this one gives me an infinite loop.

Why is this happening and what are the possibilities to solve this ?

Thank you

UPDATE:
Found out that
"If you use named indexes, JavaScript will redefine the array to a standard object.
After that, some array methods and properties will produce incorrect results."

But still no solution to the problem

答:
I am assuming you have arr variable inside your render function. Your issue is 'this.arr'. Remove 'this' from here and use 'arr'.

Here is the working code, I have checked on my local react setup it prints the array:

```<code>render() {
    const arr = [
         1100: "1100 is the number",
         1101: "1101 is the number",
         1102: "1102 is the number",
         1103: "1103 is the number",
         1104: "1104 is the number",
         1105: "1105 is the number",
     ];
    const list = arr;
    const timeList = list.map((element, idx) =>
        <li key={idx}>{element}</li>
        );

    return (
      <div className="App" >
        {timeList}
      </div>
    );
}
</code>```

Body:
The array is generated following way:

for(var i = start; i <= end;i+=step) {
    arr[i] = i + 'is the number';
}

Array structure looks like this

arr = [
1100: "1100 is the number",
1101: "1101 is the number",
1102: "1102 is the number",
1103: "1103 is the number",
1104: "1104 is the number",
1105: "1105 is the number",
];

and so on.

This array will be mapped into a list element in React.

render() {
    const list = this.arr;
    const timeList = list.map((element) =>

{element}

        );

    return (

        {timeList}

    );

It works fine with the regular arrays, but using this one gives me an infinite loop.

Why is this happening and what are the possibilities to solve this ?

Thank you

UPDATE:
Found out that
"If you use named indexes, JavaScript will redefine the array to a standard object.
After that, some array methods and properties will produce incorrect results."

But still no solution to the problem

Body:
I am assuming you have arr variable inside your render function. Your issue is 'this.arr'. Remove 'this' from here and use 'arr'.

Here is the working code, I have checked on my local react setup it prints the array:

render() {
    const arr = [
         1100: "1100 is the number",
         1101: "1101 is the number",
         1102: "1102 is the number",
         1103: "1103 is the number",
         1104: "1104 is the number",
         1105: "1105 is the number",
     ];
    const list = arr;
    const timeList = list.map((element, idx) =>
        <li key={idx}>{element}</li>
        );

    return (
      <div className="App" >
        {timeList}
      </div>
    );
}


问:
Is that possible to replay events via RabbitMQ with Axon 3
I have an application built with the framework Axon 3.

There are 2 instances (jvm)

The first one handles commands and notifies the second one with RabbitMQ to construct a read model database.

There is an event store for this application (MongoDB)

Now I want to build a third instance and Is that possible to replay all historic events of the first instance via RabbitMQ to construct the initial state of the third instance ? and how to configure it ?

I tried the doc Axons for an answer, it seems that I should use TrackingEventProcessor instead of the default one SubscribingEventProcessor, but it does not allow to use with SpringAMQPMessageSource (mentioned in the doc)

答:
Axon has two modes: Tracking and Subscribing. Depending on the source of your events, you can chose either one or sometimes both styles.

AMQP is a specification for a message broker. Once a message is delivered, it is removed from the Queue it was placed on. Therefore, conceptually, it is impossible to replay those events, since they don't exist in the broker anymore.

If replays are important, make sure you use a messaging mechanism that stores the messages. In Axon, the EventStore does exactly that. For now, Axon only has the EmbeddedEventStore, but you could have an Event Store in the receiving node point to the same database as the sending node.

At the moment, at AxonIQ, we are working on an Event Store Server, that deals with this in a cleaner way (no need to share datasources between instances).


问:
Write an executable .sh file via fs.writeFileSync
Is there a way to write an executable shell script file using fs.writeFileSync

Fundamentally i'm trying to output a .sh file via a CLI and i want that .sh file to be executable so i do not need to manually run a chmod +x "filename" once the file gets outputted from CLI.

答:
You can create the script file and set the permissions within Node using the filesystem (fs) module.

```<code>var fs = require('fs');

var script_name = "myscript.sh";
var script_content = "echo Hello world!";

fs.writeFileSync(script_name, script_content);
fs.chmodSync(script_name, "755");
</code>```

Consider looking here for more information on understanding rights

Body:
You can create the script file and set the permissions within Node using the filesystem (fs) module.

var fs = require('fs');

var script_name = "myscript.sh";
var script_content = "echo Hello world!";

fs.writeFileSync(script_name, script_content);
fs.chmodSync(script_name, "755");

Consider looking here for more information on understanding rights


问:
JavaScript works no wrap but not onLoad with jsfiddle
So, I have code that works with no wrap, but doesn't work onLoad. Could somebody explain to me why this doesn't work?
I am trying to get this to work for my web app, but the JavaScript isn't working. However, when I plug it into fiddle, it works when I change from onLoad to no wrap.

function zoomIn(event) {
  var element = document.getElementById("overlay0");
  element.className = "overlay";
  element.style.display = "inline-block";
  var img = document.getElementById("imgZoom0");
  var posX = event.offsetX ? (event.offsetX) : event.pageX - img.offsetLeft;
  var posY = event.offsetY ? (event.offsetY) : event.pageY - img.offsetTop;
  element.style.backgroundPosition=(-posX*2)+"px "+(-posY*4)+"px";

}

function zoomOut() {
  var element = document.getElementById("overlay0");
  element.style.display = "none";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.overlay{
  border:1px solid black;
  width:350px;
  height:200px;
  display:none;
  background-image:url('http://ginger-mum.com/wp-content/uploads/2015/10/3633-1269758855-0da5042c33400a811a5d766be4579cb8.jpg');
  background-repeat:no-repeat;

}</code>```

```

答:
Because when you use onLoad option the code is wrapped in a load event handler.....something like:

```<code>window.onload = function(){
  // your code  ends up here
}
</code>```

So the scope of your functions are not in global window space where they need to be to be able to call them from the dom

Body:
So, I have code that works with no wrap, but doesn't work onLoad. Could somebody explain to me why this doesn't work?
I am trying to get this to work for my web app, but the JavaScript isn't working. However, when I plug it into fiddle, it works when I change from onLoad to no wrap.

function zoomIn(event) {
  var element = document.getElementById("overlay0");
  element.className = "overlay";
  element.style.display = "inline-block";
  var img = document.getElementById("imgZoom0");
  var posX = event.offsetX ? (event.offsetX) : event.pageX - img.offsetLeft;
  var posY = event.offsetY ? (event.offsetY) : event.pageY - img.offsetTop;
  element.style.backgroundPosition=(-posX*2)+"px "+(-posY*4)+"px";

}

function zoomOut() {
  var element = document.getElementById("overlay0");
  element.style.display = "none";
}

.overlay{
  border:1px solid black;
  width:350px;
  height:200px;
  display:none;
  background-image:url('http://ginger-mum.com/wp-content/uploads/2015/10/3633-1269758855-0da5042c33400a811a5d766be4579cb8.jpg');
  background-repeat:no-repeat;

}

Body:
Because when you use onLoad option the code is wrapped in a load event handler.....something like:

window.onload = function(){
  // your code  ends up here
}

So the scope of your functions are not in global window space where they need to be to be able to call them from the dom


问:
Ansible check if key/value pair exists in list of dictionaries
I am trying to check if a certain key/value pair exists in a list of dictionaries in Ansible.

I found this question, however I am not sure if the syntax differs from python to ansible (I have never seen an if statement in ansible!)
Check if value already exists within list of dictionaries?

I have already tried the when condition:

```<code>  when: '"value" not in list'
</code>```

however I have not had any luck with that.

For example, list looks something like:

```<code>list: [
   {
   "key1" : "value1",
   "key2" : "value2",
   "key3" : "value3"
   },
   {
   "key1" : "value4",
   "key2" : "value5",
   "key3" : "value6"
   },
   and so on
</code>```

And I am trying to find out, for example, whether the pair "key2":"value5" exists within any of the dictionaries in the list. Hopefully there is a way to do this that just gives true if the pair exists, false if not?

Any tips would be greatly appreciated! Thanks.

答:
Here you go:</p>

```<code>- hosts: localhost
  gather_facts: no
  vars:
    list_of_dicts: [
     {
     "key1" : "value1",
     "key2" : "value2",
     "key3" : "value3"
     },
     {
     "key1" : "value4",
     "key2" : "value5",
     "key3" : "value3"
     }]
  tasks:
    - debug:
        msg: found
      when: list_of_dicts | selectattr(search_key,'equalto',search_val) | list | count > 0
      vars:
        search_key: key3
        search_val: value3
</code>```

Body:
I am trying to check if a certain key/value pair exists in a list of dictionaries in Ansible.

I found this question, however I am not sure if the syntax differs from python to ansible (I have never seen an if statement in ansible!)
Check if value already exists within list of dictionaries?

I have already tried the when condition:

  when: '"value" not in list'

however I have not had any luck with that.

For example, list looks something like:

list: [
   {
   "key1" : "value1",
   "key2" : "value2",
   "key3" : "value3"
   },
   {
   "key1" : "value4",
   "key2" : "value5",
   "key3" : "value6"
   },
   and so on

And I am trying to find out, for example, whether the pair "key2":"value5" exists within any of the dictionaries in the list. Hopefully there is a way to do this that just gives true if the pair exists, false if not?

Any tips would be greatly appreciated! Thanks.

Body:
Here you go:

- hosts: localhost
  gather_facts: no
  vars:
    list_of_dicts: [
     {
     "key1" : "value1",
     "key2" : "value2",
     "key3" : "value3"
     },
     {
     "key1" : "value4",
     "key2" : "value5",
     "key3" : "value3"
     }]
  tasks:
    - debug:
        msg: found
      when: list_of_dicts | selectattr(search_key,'equalto',search_val) | list | count > 0
      vars:
        search_key: key3
        search_val: value3


问:
Merge multiple dataframes into a single column
Hello guys I'm here again to ask  you some questions.

I've "n" separated csv with only two columns temperature and date in format dmy HM, these documents are from a single digital Thermometer which only can store 4 months at time.
I would like to read all these documents and put their variable temperature into a new df (Union)just in a single column.

In order to make a single document,  I created a df named "date" with a date-time sequence bigger than any other csv to union this "n" documents with the column "Date" to paste the value when the dates are the same.

My inputs are like this:

```<code>Date<- seq(as.POSIXlt("2017-01-01 00:00:00", tz="UTC"),
     as.POSIXlt("2017-03-01 00:00:00", tz="UTC"),
     by="60 min")
temp = runif(1417, min = 32, max = 100)
df1 <- data.frame(Date,temp)

Date<- seq(as.POSIXlt("2017-03-01 00:00:00", tz="UTC"),
     as.POSIXlt("2017-06-01 00:00:00", tz="UTC"),
     by="60 min")
temp = runif(2209, min = 32, max = 100)
df2 <- data.frame(Date,temp)
</code>```

So, it's the big sequence which I made to union my df's with.

```<code>Date <- seq(as.POSIXlt("2017-01-01 00:00:00", tz="UTC"),
       as.POSIXlt("2017-07-01 00:00:00", tz="UTC"),
       by="60 min")
date <- data.frame(Date)
</code>```

I was trying with the library data.table as follow:

```<code>setDT(date)
setDT(df1)
Union<-df1[date, on="Date"])
</code>```

This worked just with 1 df, but, How can I  get a way to automate the multiple merge from my 2 df just into that single column which was made in Union.

I hope you can help me.
Thanks

答:
I'm not entirely sure what you are asking without a sample data set and desired solution.  You can use stack() to set columns on top of each other like so:

```<code>> x <- data.frame(x = seq(1,3), y = seq(11,13), z = seq(21,23))
> x
  x  y  z
1 1 11 21
2 2 12 22
3 3 13 23
> stack(x)
  values ind
1      1   x
2      2   x
3      3   x
4     11   y
5     12   y
6     13   y
7     21   z
8     22   z
9     23   z
</code>```

I'm making the assumption that x,y,z would be different weather stations in your example and this is after you have created one single large table and want to have a two column dataset from that master table.

Body:
Hello guys I'm here again to ask  you some questions.

I've "n" separated csv with only two columns temperature and date in format dmy HM, these documents are from a single digital Thermometer which only can store 4 months at time.
I would like to read all these documents and put their variable temperature into a new df (Union)just in a single column.

In order to make a single document,  I created a df named "date" with a date-time sequence bigger than any other csv to union this "n" documents with the column "Date" to paste the value when the dates are the same.

My inputs are like this:

Date<- seq(as.POSIXlt("2017-01-01 00:00:00", tz="UTC"),
     as.POSIXlt("2017-03-01 00:00:00", tz="UTC"),
     by="60 min")
temp = runif(1417, min = 32, max = 100)
df1 <- data.frame(Date,temp)

Date<- seq(as.POSIXlt("2017-03-01 00:00:00", tz="UTC"),
     as.POSIXlt("2017-06-01 00:00:00", tz="UTC"),
     by="60 min")
temp = runif(2209, min = 32, max = 100)
df2 <- data.frame(Date,temp)

So, it's the big sequence which I made to union my df's with.

Date <- seq(as.POSIXlt("2017-01-01 00:00:00", tz="UTC"),
       as.POSIXlt("2017-07-01 00:00:00", tz="UTC"),
       by="60 min")
date <- data.frame(Date)

I was trying with the library data.table as follow:

setDT(date)
setDT(df1)
Union<-df1[date, on="Date"])

This worked just with 1 df, but, How can I  get a way to automate the multiple merge from my 2 df just into that single column which was made in Union.

I hope you can help me.
Thanks

Body:
I'm not entirely sure what you are asking without a sample data set and desired solution.  You can use stack() to set columns on top of each other like so:

> x <- data.frame(x = seq(1,3), y = seq(11,13), z = seq(21,23))
> x
  x  y  z
1 1 11 21
2 2 12 22
3 3 13 23
> stack(x)
  values ind
1      1   x
2      2   x
3      3   x
4     11   y
5     12   y
6     13   y
7     21   z
8     22   z
9     23   z

I'm making the assumption that x,y,z would be different weather stations in your example and this is after you have created one single large table and want to have a two column dataset from that master table.


问:
How to write logs in a diff file for multiples instances in mfp
I have multiple instances of MFP running, but my problem is that all the instances are writing logs to a single log file. How can I write logs to diff location for diff instances? </p>

答:
Assuming that by "multiple instances of MFP" you are referring to multiple MFP runtimes deployed on the same JVM,it is normal to see all logging appearing in the same log - SystemOut.log for WAS , messages.log for WebSphere Liberty etc.

This is because MFP is a layer that is deployed on top of the Application server and all logging from MFP is directed to the standard logging of the JVM. As such, if you deploy multiple runtime wars on the same JVM, it is normal to expect all logging from all the runtimes appear in the same log. This is not different from different EAR/WARs deployed on the same Application server, logging into the same log file.

If you wish to have different logs for different runtimes, deploy them in different JVM instances.


问:
nodejs include required packages in all route files using require() function
Hi I'm new to nodeJs and currently developing a Rest API using node.I'm planning to develop it with a good folder structure, so I can scale it up easily. There I'm using several route files according to the business logic.

ex :- authRoutes,profileRoutes,orderRoutes ......

Currently in every single route file I had to include following codes

```<code>var express    = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var passport = require('passport');
</code>```

My problem is , Is it totally fine to use above code segments in all the route files( I'm concerning about the code optimisation/coding standards and execution speed ) or is there any better way to do this.

It's better if you can explain the functionality of require() function.

Thanks

答:
In my experience, this is very standard to do. I suggest reading this question and answer to learn more about the way it affects the speed of your programs.

TL;DR of require()

When your lines of code are ran that include a variable that exists because of a require(), for instance

```<code>var https = require('https');
https.get(url, function(response) {...});
</code>```

The compiler reads it and goes into the https module folder, and looks for the .get function.

However, if you are trying to require() a certain JavaScript file, such as analysis.js, you must navigate to that file from the file you are currently in. For instance, if the file you want is on the same level as the file you are in, you can access it like this:

```<code>var analysis = require('./analysis.js');
//Let analysis have a function called analyzeWeather
analysis.analyzeWeather(weather_data);
</code>```

These lines of code are a little different from above. In this require() statement, we are saying grab the .js file with this name, analysis. Once you require it, you can access any public function inside of that analysis.js file.

Edits

Added require() example for .js file.

Body:
Hi I'm new to nodeJs and currently developing a Rest API using node.I'm planning to develop it with a good folder structure, so I can scale it up easily. There I'm using several route files according to the business logic.

ex :- authRoutes,profileRoutes,orderRoutes ......

Currently in every single route file I had to include following codes

var express    = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var passport = require('passport');

My problem is , Is it totally fine to use above code segments in all the route files( I'm concerning about the code optimisation/coding standards and execution speed ) or is there any better way to do this.

It's better if you can explain the functionality of require() function.

Thanks

Body:
In my experience, this is very standard to do. I suggest reading this question and answer to learn more about the way it affects the speed of your programs.

TL;DR of require()

When your lines of code are ran that include a variable that exists because of a require(), for instance

var https = require('https');
https.get(url, function(response) {...});

The compiler reads it and goes into the https module folder, and looks for the .get function.

However, if you are trying to require() a certain JavaScript file, such as analysis.js, you must navigate to that file from the file you are currently in. For instance, if the file you want is on the same level as the file you are in, you can access it like this:

var analysis = require('./analysis.js');
//Let analysis have a function called analyzeWeather
analysis.analyzeWeather(weather_data);

These lines of code are a little different from above. In this require() statement, we are saying grab the .js file with this name, analysis. Once you require it, you can access any public function inside of that analysis.js file.

Edits

Added require() example for .js file.


问:
How to print an array in descending order?
Basically this is my code and it works fine. I just don't know how to print it in descending order. This code basically shows the odd numbers:1,3,5,7. I want it to be printed 7,5,3,1. I know I need use the sort function but I dont know how. </p>

```<code>#include <iostream>

using namespace std;

void fillArray(int arr[], int &n);
void printArray(int arr[], int n);
void findSum(int arr[], int &n);

int main()
{
    int n;
    cin>>n;
    int arr[n];
    fillArray(arr,n);
    printArray(arr,n);
    findSum(arr,n);

    return 0;
}

void fillArray(int arr[], int &n)
{
    int j=1;
    for(int i=0;i<n;i++)
    {
        if(j%2==1)
            arr[i]=j;
        else
            i--;
        j++;
    }
}

void printArray(int arr[], int n)
{
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<", ";
    }
}

void findSum(int arr[], int &n)
{
    int sum=0;
    for(int i=0;i<n;i++)
    {
        sum=sum+arr[i];
    }
}
</code>```

Body:
Basically this is my code and it works fine. I just don't know how to print it in descending order. This code basically shows the odd numbers:1,3,5,7. I want it to be printed 7,5,3,1. I know I need use the sort function but I dont know how.

#include <iostream>

using namespace std;

void fillArray(int arr[], int &n);
void printArray(int arr[], int n);
void findSum(int arr[], int &n);

int main()
{
    int n;
    cin>>n;
    int arr[n];
    fillArray(arr,n);
    printArray(arr,n);
    findSum(arr,n);

    return 0;
}

void fillArray(int arr[], int &n)
{
    int j=1;
    for(int i=0;i<n;i++)
    {
        if(j%2==1)
            arr[i]=j;
        else
            i--;
        j++;
    }
}

void printArray(int arr[], int n)
{
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<", ";
    }
}

void findSum(int arr[], int &n)
{
    int sum=0;
    for(int i=0;i<n;i++)
    {
        sum=sum+arr[i];
    }
}

Body:
for(int i = n-1; i >= 0; i--)
{
    cout << arr[i] << ", ";
}


问:
How does Java know which class to use in this example?
I am beginning to learn the principles of OOP and inheritance, and I came across this question while writing some code:

Suppose there is a package which contains a class called ClassA. Then, in a separate folder, I have another class called MyClass. Inside the same folder as MyClass, I have another class called ClassA, which is unrelated to the ClassA in the package. When I write the code for MyClass, I make it extend ClassA.

Which ClassA does MyClass extend from? Does MyClass inherit the ClassA which is in the imported package, or does MyClass inherit the ClassA which is in the same folder as MyClass? Would the code even compile?

I am trying to understand this from a theory perspective before diving into examples.

答:
Packages in Java is a mechanism to encapsulate a group of classes,
  interfaces and sub packages. Many implementations of Java use a
  hierarchical file system to manage source and class files. It is easy
  to organize class files into packages. All we need to do is put
  related class files in the same directory, give the directory a name
  that relates to the purpose of the classes, and add a line to the top
  of each class file that declares the package name, which is the same
  as the directory name where they reside.

in the top of java files, you have import that you can choose what class from what package you mean of course as @Jason said too if the class you want its in your package you don't need to tell it explicitly and compiler know that but if its in another package you have to tell him explicitly.

assume you have FirstClass.java in src folder and another in mycodes folder when in your class you import FirstClass you mean FirstClass.java that exist in src folder and when you import mycodes.FirstClass you mean FirstClass in mycodes folder.

your class can be member of packag.when you extend class that you class are in package A when you extend SomeClass you mean SomeClass that is in package A and if you want extend other class that is in other package like B you must extend B.SomClass

Here is another information about packages in java


问:
Artist's most popular city on spotify api
is it possible, through the spotify api, to access an artist's most popular city? it allows you to view it on the mobile app and on the desktop app, but not the web app. example below:

example:

答: this is currently not available, there is an enhancement request for this feature</p>


问:
Are technologies like LINQ, WPF, WF just libraries or development changing methodologies
Lately, Microsoft keeps coming out with new technologies Linq, WF, WPF, etc... Seems to me that they are presented like technology inovations that completely change the way your applications are designed and coded.

Yet,they are based on the same underlying framework (2.0) If I look at Java, there are a lot of libraries that provide critical functionality (Hibernate, Spring for example), yet they are considered to be still just libraries.

So my question is, Do people think that these technologies are really changing the way we write windows code? Is it worth learning every development methodology that Microsoft is putting out with Visual Studio releases.

Or is this just hype. As libraries, they are important, however, not critical to get job done. Will they make as big of an impact and ss I learn it, it will considerably effect my future as a developer?

EDIT: The same goes for some of the language futures that are implemented. Some are changing the way we program (Generics) Others, are much less critical (Partial Classes) That makes learning Generics a critical part of learning .NET, unlike learning to use Partial Classes

答:
New libraries and technologies come out all the time. Taking GUI development as an example there are literally dozens of ways you could develop a GUI application. Some cross platform some not. Some more "designer friendly" some not. These things are constantly shifting though and I think, at least for a while more, they will continue to shift. You can call these different approaches whatever you want but that is really marketing. Is it an API? A new methodology? Does it matter? It's a different way to do things that may be convenient for some people in some situations.

Ultimately these APIs or methodologies or whatever you want to call them are just tools. You learn a new tool and you apply it to your craft, and when a better too becomes available you learn to use it or you let your skills fade. So do new tools change the way we write code? Sure. But do they change our craft? Absolutely not.

OwnerDisplayName: Timur Fanshteyn

LastEditorDisplayName: Timur Fanshteyn

OwnerDisplayName: John Conrad


问:
What is the best way in PHP or JS to expand shortened URLs like Bitly, Tinyurl to find the original URL?
I am using the Twitter and Facewbook API to pull posts that potentially contain shortened URLs using bit.ly or TinyURL like services. I need to do a real-time expansion to get the original URL then pull content from that URL into my app.</p>

答:
You can use CURL to expand a short URL.

Try this:

```<code>    function traceUrl($url, $hops = 0)
    {
        if ($hops == MAX_URL_HOPS)
        {
            throw new Exception('TOO_MANY_HOPS');
        }

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $r = curl_exec($ch);

        if (preg_match('/Location: (?P<url>.*)/i', $r, $match))
        {
            return traceUrl($match['url'], $hops + 1);
        }

        return rtrim($url);
    }
</code>```

You can use this function as so traceUrl('http://bit.ly/example'). This function is recursive in the sense that it will even find short urls that are shortened (if it ever happens). Make sure you set the MAX_URL_HOPS constant. I use define('MAX_URL_HOPS', 5);.

Christian

Body:
You can use CURL to expand a short URL.

Try this:

    function traceUrl($url, $hops = 0)
    {
        if ($hops == MAX_URL_HOPS)
        {
            throw new Exception('TOO_MANY_HOPS');
        }

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $r = curl_exec($ch);

        if (preg_match('/Location: (?P<url>.*)/i', $r, $match))
        {
            return traceUrl($match['url'], $hops + 1);
        }

        return rtrim($url);
    }

You can use this function as so traceUrl('http://bit.ly/example'). This function is recursive in the sense that it will even find short urls that are shortened (if it ever happens). Make sure you set the MAX_URL_HOPS constant. I use define('MAX_URL_HOPS', 5);.

Christian


问:
HTML: Picture/Image height percentage
Again me with one of my weird questions: What have I done wrong?!

Ok, seriously now, I somehow just got stuck while i was casually designing my webpage and then suddenly something weird happend.

I had a picture (background-image of a div) with a height percentage of 90%. For security reasons, so that it will display at least a bit appropriate on all display-sized devices, i used a fallback min-height from 300px. When i now started that same webpage again, suddenly it wouldn´t go to 90% of the webbrowsers site height, and instead, use the "fallback" of 300px. What has changed? After removing the fallback, the image didn´t show at all (and i´m using a pretty big gaming monitor), as if I would have a browser size of 0. What happened?

I can understand your need of a code, but that webpage is almost done and has some important information I can´t show. Therefore, please try to answer my question theoretically with the information given above. If you´d need more explanation because of my poor information, feel free to ask in a comment!

Thank you for all help I can get,

VicStudio

答:
I just made it by simply replacing the 90% with 90vh. I bet there was something with the parent elements and stuff.

I hope this can help anybody in the future with the same problem.

VicStudio

Thanks for everybody who tried solving it :)

Title: HTML: Picture/Image height percentage


问:
In between doesn't work with multiple AND's - MYSQL
```<code>SELECT price from items Where categoryId = 11724 AND price BETWEEN 10 AND 20
</code>```

Result:

 price

17.99
18.95
20.0
17.99
18.95

Above query works fine but adding another clause doesn't show desired results

```<code>SELECT price from items
Where categoryId = 11724
    AND ( brand = 'Akaso' OR brand = 'Andoer')
    and price BETWEEN 10 AND 20
</code>```

Result: 0 rows found

```<code>SELECT price from items
Where categoryId = 11724
    AND brand = 'Akaso' OR brand = 'Andoer'
    and price BETWEEN 10 AND 20
</code>```

Result:
 price

17.99
78.95
77.0
80.99
102.95

Have tried with and (column and column) for each clause. price type is VARCHAR
 CHANGED TO Decimal(10,2)
Where am i doing wrong?

答:
I don't have your data, but I feel like everything is working properly and your last query is trying to do this:</p>

```<code>SELECT price from items
Where (categoryId = 11724
AND brand = 'Akaso') OR (brand = 'Andoer'
and price BETWEEN 10 AND 20)
</code>```

Body:
SELECT price from items Where categoryId = 11724 AND price BETWEEN 10 AND 20

Result:

 price

17.99
18.95
20.0
17.99
18.95

Above query works fine but adding another clause doesn't show desired results

SELECT price from items
Where categoryId = 11724
    AND ( brand = 'Akaso' OR brand = 'Andoer')
    and price BETWEEN 10 AND 20

Result: 0 rows found

SELECT price from items
Where categoryId = 11724
    AND brand = 'Akaso' OR brand = 'Andoer'
    and price BETWEEN 10 AND 20

Result:
 price

17.99
78.95
77.0
80.99
102.95

Have tried with and (column and column) for each clause. price type is VARCHAR
 CHANGED TO Decimal(10,2)
Where am i doing wrong?

Body:
I don't have your data, but I feel like everything is working properly and your last query is trying to do this:

SELECT price from items
Where (categoryId = 11724
AND brand = 'Akaso') OR (brand = 'Andoer'
and price BETWEEN 10 AND 20)


问:
java.lang.ClassCastException: org.springframework.cache.interceptor.SimpleKey cannot be cast to java.lang.String
Using spring-data-redis,there is a exception like this question title.
My spring config xml file is:

And use the annotation follow:

```<code>@Cacheable(cacheNames = "data")
</code>```

framework version :

```<code><spring.version>4.3.8.RELEASE</spring.version>
<spring-data-redis.version>1.6.0.RELEASE</spring-data-redis.version>
<jedis.version>2.8.1</jedis.version>
</code>```

any help will be appreciated..

答:
StringRedisSerializer is only capable of converting String to byte [] and back. Its usage as keySerializer for the template passed into the CacheManager is causing the issue. Maybe JdkSerializationRedisSerializer would be a better choice here.
Find more about RedisSerializer in the Reference Manual.

Body:
Using spring-data-redis,there is a exception like this question title.
My spring config xml file is:

And use the annotation follow:

@Cacheable(cacheNames = "data")

framework version :

<spring.version>4.3.8.RELEASE</spring.version>
<spring-data-redis.version>1.6.0.RELEASE</spring-data-redis.version>
<jedis.version>2.8.1</jedis.version>

any help will be appreciated..


问:
Rails inserting multiple records for single model
How shall I set the form fields to be able to insert multiple rows in the database for a single model.

I am updating a div with another link and cannot use the form helper. So I need to set the field names manually.

I have a post model and it has a title field.
  I want to insert i posts to db like post[0][title] But when I name the form field like this It gets 0 as string and does not record.

Also I tried to set the Array my self from Rails Console like

```<code>post = Array.new
post << [:title => "title 1"]
post << [:title => "title 2"]
sav = Post.new(post)
sav.save
</code>```

And still nothing is saved.

答:
is this what you're trying to do?</p>

```<code>posts = []
posts << Post.new(:title => "title 1")
posts << Post.new(:title => "title 2")

posts.each do |post|
  post.save
end
</code>```

Body:
How shall I set the form fields to be able to insert multiple rows in the database for a single model.

I am updating a div with another link and cannot use the form helper. So I need to set the field names manually.

I have a post model and it has a title field.
  I want to insert i posts to db like post[0][title] But when I name the form field like this It gets 0 as string and does not record.

Also I tried to set the Array my self from Rails Console like

post = Array.new
post << [:title => "title 1"]
post << [:title => "title 2"]
sav = Post.new(post)
sav.save

And still nothing is saved.

Body:
is this what you're trying to do?

posts = []
posts << Post.new(:title => "title 1")
posts << Post.new(:title => "title 2")

posts.each do |post|
  post.save
end


问:
Sorting Listview in Android Studio By Time(HH:mm)

I have the "questTime" column in the sqlite database that contains hour and minute.I want to sort the ListView objects in my Android app by this hour and minute.

Database

```<code>db.execSQL("create table questions(_id integer primary key autoincrement," +
            "stuId integer," +
            "lesson text not null," +
            "subject text not null," +
            "questPhoto blob," +
            "answer text not null," +
            "questTime text," +
            "point integer not null)");
</code>```

Item Class

```<code>public class ItemQuestions {

String strkonu,strpuan,strgonderen,strtime;
Bitmap imgsoru,imguserinquest;

public ItemQuestions(){

}

public ItemQuestions(String strkonu, String strpuan, String strgonderen, String strtime,
                     Bitmap imgsoru, Bitmap imguserinquest){
    this.strkonu=strkonu;
    this.strpuan=strpuan;
    this.strgonderen=strgonderen;
    this.strtime=strtime;
    this.imgsoru=imgsoru;
    this.imguserinquest=imguserinquest;
}

public String getStrtime() {
    return strtime;
}

public void setStrtime(String strtime) {
    this.strtime = strtime;
}

public String getStrkonu() {
    return strkonu;
}

public void setStrkonu(String strkonu) {
    this.strkonu = strkonu;
}

public String getStrpuan() {
    return strpuan;
}

public void setStrpuan(String strpuan) {
    this.strpuan = strpuan;
}

public String getStrgonderen() {
    return strgonderen;
}

public void setStrgonderen(String strgonderen) {
    this.strgonderen = strgonderen;
}

public Bitmap getImgsoru() {
    return imgsoru;
}

public void setImgsoru(Bitmap imgsoru) {
    this.imgsoru = imgsoru;
}

public Bitmap getImguserinquest() {
    return imguserinquest;
}

public void setImguserinquest(Bitmap imguserinquest) {
    this.imguserinquest = imguserinquest;
}
</code>```

}

Adapter Class

```<code>public class AdapterQuestions extends ArrayAdapter<ItemQuestions> {

Context context;
ArrayList<ItemQuestions> listarrayforQuest=new ArrayList<ItemQuestions>();
private int resource;

public AdapterQuestions(Context context, int resource, ArrayList<ItemQuestions> listarrayforQuest) {
    super(context, resource, listarrayforQuest);
    this.context=context;
    this.resource=resource;
    this.listarrayforQuest=listarrayforQuest;
}

class ViewYerTutucu{
    TextView tvholder_strkonu, tvholder_strpuan, tvholder_strgonderen, tvholder_strtime;
    ImageView imgholder_seen, imgholder_imgsoru, imgholder_comment;
    CircleImageView crcimgholder_imguserinquestions;

    ViewYerTutucu(View v){
        imgholder_imgsoru= (ImageView) v.findViewById(R.id.imgviewinquestions);
        imgholder_seen= (ImageView) v.findViewById(R.id.imgviewseeninquest);
        imgholder_comment= (ImageView) v.findViewById(R.id.imgviewcommentinquest);
        tvholder_strkonu= (TextView) v.findViewById(R.id.txtkonuinquest);
        tvholder_strpuan= (TextView) v.findViewById(R.id.txtpuaninquest);
        tvholder_strgonderen= (TextView) v.findViewById(R.id.txtgondereninquest);
        tvholder_strtime= (TextView) v.findViewById(R.id.txtquestiondate);
        crcimgholder_imguserinquestions= (CircleImageView) v.findViewById(R.id.crcimguserfotoinquest);
    }
}

@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View viewquest=convertView;
    ViewYerTutucu tutucu=null;

    if(viewquest==null){
        LayoutInflater inflater= (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        viewquest=inflater.inflate(resource,null);
        tutucu=new ViewYerTutucu(viewquest);
        viewquest.setTag(tutucu);
    }
    else {
        tutucu= (ViewYerTutucu) viewquest.getTag();
    }

    ItemQuestions itemQuestions=listarrayforQuest.get(position);

    tutucu.tvholder_strkonu.setText(itemQuestions.getStrkonu());
    tutucu.tvholder_strpuan.setText(itemQuestions.getStrpuan());
    tutucu.tvholder_strgonderen.setText(itemQuestions.getStrgonderen());
    tutucu.tvholder_strtime.setText(itemQuestions.getStrtime());

    tutucu.imgholder_imgsoru.setImageBitmap(itemQuestions.getImgsoru());
    tutucu.crcimgholder_imguserinquestions.setImageBitmap(itemQuestions.getImguserinquest());

    return viewquest;

}
</code>```

}

View in ListView
  enter image description here

I searched many examples of ListView sorting, buy I want to sort according to time(HH:mm).So, how can I ensure that the object with the most current time is at the top of the ListView?

答:
I recommend you using the combination of RecyclerView, an Adapter and SortedList which keeps elements in order. You can also get notification about changes in that list through a Callback object.

I'd loved to write an article about this, but someone already did a good job explaining it well.

If you still want to use a ListView, I think you will have to manually sort objects after any change (and before calling notifyDatasetChanged). I mean by sorting, select * order by xxx again or sorting your collection with Java, whatever you need.

Body:
I have the "questTime" column in the sqlite database that contains hour and minute.I want to sort the ListView objects in my Android app by this hour and minute.

Database

db.execSQL("create table questions(_id integer primary key autoincrement," +
            "stuId integer," +
            "lesson text not null," +
            "subject text not null," +
            "questPhoto blob," +
            "answer text not null," +
            "questTime text," +
            "point integer not null)");

Item Class

public class ItemQuestions {

String strkonu,strpuan,strgonderen,strtime;
Bitmap imgsoru,imguserinquest;

public ItemQuestions(){

}

public ItemQuestions(String strkonu, String strpuan, String strgonderen, String strtime,
                     Bitmap imgsoru, Bitmap imguserinquest){
    this.strkonu=strkonu;
    this.strpuan=strpuan;
    this.strgonderen=strgonderen;
    this.strtime=strtime;
    this.imgsoru=imgsoru;
    this.imguserinquest=imguserinquest;
}

public String getStrtime() {
    return strtime;
}

public void setStrtime(String strtime) {
    this.strtime = strtime;
}

public String getStrkonu() {
    return strkonu;
}

public void setStrkonu(String strkonu) {
    this.strkonu = strkonu;
}

public String getStrpuan() {
    return strpuan;
}

public void setStrpuan(String strpuan) {
    this.strpuan = strpuan;
}

public String getStrgonderen() {
    return strgonderen;
}

public void setStrgonderen(String strgonderen) {
    this.strgonderen = strgonderen;
}

public Bitmap getImgsoru() {
    return imgsoru;
}

public void setImgsoru(Bitmap imgsoru) {
    this.imgsoru = imgsoru;
}

public Bitmap getImguserinquest() {
    return imguserinquest;
}

public void setImguserinquest(Bitmap imguserinquest) {
    this.imguserinquest = imguserinquest;
}

}

Adapter Class

public class AdapterQuestions extends ArrayAdapter<ItemQuestions> {

Context context;
ArrayList<ItemQuestions> listarrayforQuest=new ArrayList<ItemQuestions>();
private int resource;

public AdapterQuestions(Context context, int resource, ArrayList<ItemQuestions> listarrayforQuest) {
    super(context, resource, listarrayforQuest);
    this.context=context;
    this.resource=resource;
    this.listarrayforQuest=listarrayforQuest;
}

class ViewYerTutucu{
    TextView tvholder_strkonu, tvholder_strpuan, tvholder_strgonderen, tvholder_strtime;
    ImageView imgholder_seen, imgholder_imgsoru, imgholder_comment;
    CircleImageView crcimgholder_imguserinquestions;

    ViewYerTutucu(View v){
        imgholder_imgsoru= (ImageView) v.findViewById(R.id.imgviewinquestions);
        imgholder_seen= (ImageView) v.findViewById(R.id.imgviewseeninquest);
        imgholder_comment= (ImageView) v.findViewById(R.id.imgviewcommentinquest);
        tvholder_strkonu= (TextView) v.findViewById(R.id.txtkonuinquest);
        tvholder_strpuan= (TextView) v.findViewById(R.id.txtpuaninquest);
        tvholder_strgonderen= (TextView) v.findViewById(R.id.txtgondereninquest);
        tvholder_strtime= (TextView) v.findViewById(R.id.txtquestiondate);
        crcimgholder_imguserinquestions= (CircleImageView) v.findViewById(R.id.crcimguserfotoinquest);
    }
}

@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View viewquest=convertView;
    ViewYerTutucu tutucu=null;

    if(viewquest==null){
        LayoutInflater inflater= (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        viewquest=inflater.inflate(resource,null);
        tutucu=new ViewYerTutucu(viewquest);
        viewquest.setTag(tutucu);
    }
    else {
        tutucu= (ViewYerTutucu) viewquest.getTag();
    }

    ItemQuestions itemQuestions=listarrayforQuest.get(position);

    tutucu.tvholder_strkonu.setText(itemQuestions.getStrkonu());
    tutucu.tvholder_strpuan.setText(itemQuestions.getStrpuan());
    tutucu.tvholder_strgonderen.setText(itemQuestions.getStrgonderen());
    tutucu.tvholder_strtime.setText(itemQuestions.getStrtime());

    tutucu.imgholder_imgsoru.setImageBitmap(itemQuestions.getImgsoru());
    tutucu.crcimgholder_imguserinquestions.setImageBitmap(itemQuestions.getImguserinquest());

    return viewquest;

}

}

View in ListView
  enter image description here

I searched many examples of ListView sorting, buy I want to sort according to time(HH:mm).So, how can I ensure that the object with the most current time is at the top of the ListView?


问:
Er diagram one-to-many relationship - Participation constraints
When drawing ER diagram with Chen notation. Do all 1:N relationship be drawn with Total participation constraints double lines?
For example: one Invoice can have multiple payments. And a payment must have a invoice number as a payment is done for an invoice. This has 1:n relationship so how do i put this in a diagram?
erd example

答:
No, all 1:N relationships don't require full participation of the entity set on the many side. A person can be in one building, while a building can hold multiple persons, but a building can be empty, and people can be outside.

In your example, must every Payment necessarily be related to an Invoice? If so, then indicate total participation of Payment in the Received relationship by using a double association line.

A double-bordered diamond indicates an identifying relationship. Using that would indicate that a Payment isn't identified by its own attributes, but by its Invoice and a weak key. A weak key is usually an ordinal or role that isn't unique by itself, but serves to subdivide the parent entity. For example, consider a model where Invoices have numbers, and Payments are identified by an Invoice number together with a sequence number to indicate the 1st, 2nd or 3rd payment on that Invoice.

Weak entity sets necessarily participate totally in their identifying relationships, but keep in mind that total participation doesn't imply an identifying relationship.

See also my answer to Is optionality (mandatory, optional) and participation (total, partial) are same?


答: In that situation, to make it perfectly clear to the compiler you would probably want to do something like extends otherPackage.ClassA, and use the full reference name to extend the classA from the other package. If you want to use the one from the package MyClass is in, then just don't import the other ClassA and do extends ClassA

Title: How does Java know which class to use in this example?

Body:
I am beginning to learn the principles of OOP and inheritance, and I came across this question while writing some code:

Suppose there is a package which contains a class called ClassA. Then, in a separate folder, I have another class called MyClass. Inside the same folder as MyClass, I have another class called ClassA, which is unrelated to the ClassA in the package. When I write the code for MyClass, I make it extend ClassA.

Which ClassA does MyClass extend from? Does MyClass inherit the ClassA which is in the imported package, or does MyClass inherit the ClassA which is in the same folder as MyClass? Would the code even compile?

I am trying to understand this from a theory perspective before diving into examples.


问:
SQL Query to return new column based on first two columns
I have a table that looks like this:

```<code>username    manager
emp001      emp006
emp002      emp006
emp003      emp006
emp004      emp007
emp005      emp007
emp006      emp009
emp007      emp010
emp008      emp010
emp009      emp011
emp010      null
emp011      null
</code>```

I would like to create a select query that returns a third column like this - where the new column is based taking the manager item and referring back to the first column and getting manager of that row.

```<code>username    manager    director
emp001      emp006     emp009
emp002      emp006     emp009
emp003      emp006     emp009
emp004      emp007     emp010
emp005      emp007     emp010
emp006      emp009     emp011
emp007      emp010     null
emp008      emp010     null
emp009      emp011     null
emp010      null       null
emp011      null       null
</code>```

I'm lost on this one.

Thanks for any advise. I've tried various combinations of selects and joins but nothing seems to do what I want.

Thank you!

答:
This should do what you want:</p>

```<code>Select      E.UserName, E.Manager, M.Manager As Director
From        YourTable   E
Left Join   YourTable   M   On  E.Manager = M.UserName
</code>```

Body:
I have a table that looks like this:

username    manager
emp001      emp006
emp002      emp006
emp003      emp006
emp004      emp007
emp005      emp007
emp006      emp009
emp007      emp010
emp008      emp010
emp009      emp011
emp010      null
emp011      null

I would like to create a select query that returns a third column like this - where the new column is based taking the manager item and referring back to the first column and getting manager of that row.

username    manager    director
emp001      emp006     emp009
emp002      emp006     emp009
emp003      emp006     emp009
emp004      emp007     emp010
emp005      emp007     emp010
emp006      emp009     emp011
emp007      emp010     null
emp008      emp010     null
emp009      emp011     null
emp010      null       null
emp011      null       null

I'm lost on this one.

Thanks for any advise. I've tried various combinations of selects and joins but nothing seems to do what I want.

Thank you!

Body:
This should do what you want:

Select      E.UserName, E.Manager, M.Manager As Director
From        YourTable   E
Left Join   YourTable   M   On  E.Manager = M.UserName


问:
Python - Beautiful Soup, how to get first value of tag
I have this tag:

```<code><span class="companyName">Actua Corp <acronym title="Central Index Key">CIK</acronym>#: <a href="/cgi-bin/browse-edgar?action=getcompany&CIK=0001085621&owner=include&count=40">0001085621 (see all company filings)</a></span>
</code>```

How would I obtain the value after .

Which in this case is Actua Corp.

I'm open to all methods.

答:
If you just want Actua Corp, you can use next

```<code>r = '<span class="companyName">Actua Corp <acronym title="Central Index Key">CIK</acronym>#: <a href="/cgi-bin/browse-edgar?action=getcompany&CIK=0001085621&owner=include&count=40">0001085621 (see all company filings)</a></span>'

from bs4 import BeautifulSoup
soup = BeautifulSoup(r)

span = soup.find('span', {'class': 'companyName'})
print(span.next)
>>> Actua Corp
</code>```

If you want all of the text within the span, you can use text

```<code>print(span.text)
>>> Actua Corp CIK#: 0001085621 (see all company filings)
</code>```

Body:
I have this tag:

Actua Corp <acronym title="Central Index Key">CIK</acronym>#: 0001085621 (see all company filings)

How would I obtain the value after .

Which in this case is Actua Corp.

I'm open to all methods.

Body:
If you just want Actua Corp, you can use next

r = '<span class="companyName">Actua Corp <acronym title="Central Index Key">CIK</acronym>#: <a href="/cgi-bin/browse-edgar?action=getcompany&amp;CIK=0001085621&amp;owner=include&amp;count=40">0001085621 (see all company filings)</a></span>'

from bs4 import BeautifulSoup
soup = BeautifulSoup(r)

span = soup.find('span', {'class': 'companyName'})
print(span.next)
>>> Actua Corp

If you want all of the text within the span, you can use text

print(span.text)
>>> Actua Corp CIK#: 0001085621 (see all company filings)


问:
How to use an outer variable in an anonymous inner class
How I can access an outer variable from inside an implicit object created inside a method?

```<code>public void insertMaterial() {

new Thread(){

  public void run(){
    com.ssn.acx.api.configuration.ParameterSet ps = com.ssn.acx.api.ACXObjectFactory.getConfigurationFactory().getLocalConfiguration().getParameterSet(com.ssn.acx.api.persistence.ACXPersistenceFactory.CFG_DEFAULT);
    com.ssn.acx.api.persistence.ACXPersistenceFactory factory = com.ssn.acx.api.ACXObjectFactory.getPersistenceFactory(ps);
    com.ssn.acx.api.persistence.ACXPersistenceSession session = factory.openSession();
    com.ssn.acx.api.common.transaction.ACXTransaction tx = null;
    WMSMaterial mat = null;

    try {
      tx = session.beginTransaction("InsertMaterial");

      mat = new WMSMaterial("101", "Baby Lotion");
      session.getPersistenceSession().insert(mat);

      mat = new WMSMaterial("102", "Bubble Gum");
      session.getPersistenceSession().insert(mat);

      mat = new WMSMaterial("103", "Soda");
      session.getPersistenceSession().insert(mat);

      tx.commit();

    } finally { if (tx != null && !tx.closed()) { tx.rollback(); } session.close(); }//end of try-catch-finally block

  }//end of run method

}.start(); //end of Thread Object creation

}   //end of insertMaterial method
</code>```

For example, I need to have access to Material object if it was passed to insertMaterial() method args from within the run() method which belongs to implicit thread object, instead of creating Material object inside the thread object.

答:
In JLS 8.1.3. Inner Classes and Enclosing Instances:

When an inner class (whose declaration does not occur in a static
  context) refers to an instance variable that is a member of a
  lexically enclosing class, the variable of the corresponding lexically
  enclosing instance is used.

Any local variable, formal parameter, or exception parameter used but
  not declared in an inner class must be declared final.

It means you can only use an outside final variable or an enclosing class member in an anonymous inner class.

```<code>/*
 * I suggest this solution, but not this approach,
 * please be careful with multi-threading programming. :)
 */

// [...]
// private List<WMSMaterial> listMaterials; // or using a class member
// [...]
public void insertMaterial(final List<WMSMaterial> listMaterials) {

new Thread(){

  public void run(){
    com.ssn.acx.api.configuration.ParameterSet ps = com.ssn.acx.api.ACXObjectFactory.getConfigurationFactory().getLocalConfiguration().getParameterSet(com.ssn.acx.api.persistence.ACXPersistenceFactory.CFG_DEFAULT);
    com.ssn.acx.api.persistence.ACXPersistenceFactory factory = com.ssn.acx.api.ACXObjectFactory.getPersistenceFactory(ps);
    com.ssn.acx.api.persistence.ACXPersistenceSession session = factory.openSession();
    com.ssn.acx.api.common.transaction.ACXTransaction tx = null;

    try {
      tx = session.beginTransaction("InsertMaterial");

      for (WMSMaterial material : listMaterials) {
          session.getPersistenceSession().insert(material);
      }

      tx.commit();

    } finally { if (tx != null && !tx.closed()) { tx.rollback(); } session.close(); }//end of try-catch-finally block

  }//end of run method

}.start(); //end of Thread Object creation

}   //end of insertMaterial method
</code>```

[Update]

As @AndyThomas points out in the comment, Java 8 has effectively final variable that you do not need to explicitly mark a variable as final:

Certain variables that are not declared final are instead considered effectively final:

It is not declared final.

It never occurs as the left hand side in an assignment expression
  . (Note that the local variable declarator containing the
  initializer is not an assignment expression.)

It never occurs as the operand of a prefix or postfix increment or
  decrement operator.

JLS 4.12.4. final Variables

Body:
How I can access an outer variable from inside an implicit object created inside a method?

public void insertMaterial() {

new Thread(){

  public void run(){
    com.ssn.acx.api.configuration.ParameterSet ps = com.ssn.acx.api.ACXObjectFactory.getConfigurationFactory().getLocalConfiguration().getParameterSet(com.ssn.acx.api.persistence.ACXPersistenceFactory.CFG_DEFAULT);
    com.ssn.acx.api.persistence.ACXPersistenceFactory factory = com.ssn.acx.api.ACXObjectFactory.getPersistenceFactory(ps);
    com.ssn.acx.api.persistence.ACXPersistenceSession session = factory.openSession();
    com.ssn.acx.api.common.transaction.ACXTransaction tx = null;
    WMSMaterial mat = null;

    try {
      tx = session.beginTransaction("InsertMaterial");

      mat = new WMSMaterial("101", "Baby Lotion");
      session.getPersistenceSession().insert(mat);

      mat = new WMSMaterial("102", "Bubble Gum");
      session.getPersistenceSession().insert(mat);

      mat = new WMSMaterial("103", "Soda");
      session.getPersistenceSession().insert(mat);

      tx.commit();

    } finally { if (tx != null && !tx.closed()) { tx.rollback(); } session.close(); }//end of try-catch-finally block

  }//end of run method

}.start(); //end of Thread Object creation

}   //end of insertMaterial method

For example, I need to have access to Material object if it was passed to insertMaterial() method args from within the run() method which belongs to implicit thread object, instead of creating Material object inside the thread object.

Body:
In JLS 8.1.3. Inner Classes and Enclosing Instances:

When an inner class (whose declaration does not occur in a static
  context) refers to an instance variable that is a member of a
  lexically enclosing class, the variable of the corresponding lexically
  enclosing instance is used.

Any local variable, formal parameter, or exception parameter used but
  not declared in an inner class must be declared final.

It means you can only use an outside final variable or an enclosing class member in an anonymous inner class.

/*
 * I suggest this solution, but not this approach,
 * please be careful with multi-threading programming. :)
 */

// [...]
// private List<WMSMaterial> listMaterials; // or using a class member
// [...]
public void insertMaterial(final List<WMSMaterial> listMaterials) {

new Thread(){

  public void run(){
    com.ssn.acx.api.configuration.ParameterSet ps = com.ssn.acx.api.ACXObjectFactory.getConfigurationFactory().getLocalConfiguration().getParameterSet(com.ssn.acx.api.persistence.ACXPersistenceFactory.CFG_DEFAULT);
    com.ssn.acx.api.persistence.ACXPersistenceFactory factory = com.ssn.acx.api.ACXObjectFactory.getPersistenceFactory(ps);
    com.ssn.acx.api.persistence.ACXPersistenceSession session = factory.openSession();
    com.ssn.acx.api.common.transaction.ACXTransaction tx = null;

    try {
      tx = session.beginTransaction("InsertMaterial");

      for (WMSMaterial material : listMaterials) {
          session.getPersistenceSession().insert(material);
      }

      tx.commit();

    } finally { if (tx != null && !tx.closed()) { tx.rollback(); } session.close(); }//end of try-catch-finally block

  }//end of run method

}.start(); //end of Thread Object creation

}   //end of insertMaterial method

[Update]

As @AndyThomas points out in the comment, Java 8 has effectively final variable that you do not need to explicitly mark a variable as final:

Certain variables that are not declared final are instead considered effectively final:

It is not declared final.

It never occurs as the left hand side in an assignment expression
  . (Note that the local variable declarator containing the
  initializer is not an assignment expression.)

It never occurs as the operand of a prefix or postfix increment or
  decrement operator.

JLS 4.12.4. final Variables


问:
Hadoop NoSuchMethodError apache.commons.cli
I'm using hadoop-2.7.2 and I did a MapReduceJob with IntelliJ. In my job, I'm using apache.commons.cli-1.3.1 and I put the lib in the jar.

When I use the MapReduceJob on my Hadoop cluster I have a NoSuchMethodError:

Exception in thread "main" java.lang.NoSuchMethodError:
  org.apache.commons.cli.Option.builder(Ljava/lang/String;)Lorg/apache/commons/cli/Option$Builder;

I don't understand because the method exist in the class Option and the class Option is extracted from the commons-cli.jar to my application jar. Moreover, I don't have this issue with my others libraries.

Thank you for your time.

答:
The problem seems to be related to how the classloader is loading the classes. Because the static Builder class was in common-cli 1.4, while some of the hadoop dependencies were still referring to older version - the issue occurred.

In my case, the issue resolved by changing the sequence of jar file addition into the classpath in the shell script responsible for setting up environment before program execution. Earlier, I was adding the jar into classpath like

```<code>CLASSPATH=<Hadoop Jars>:<Common CLI jar>:$CLASSPATH
</code>```

is changed to

```<code>CLASSPATH=<Common CLI jar>:<Hadoop Jars>:$CLASSPATH
</code>```

and it fixed the problem.

Body:
The problem seems to be related to how the classloader is loading the classes. Because the static Builder class was in common-cli 1.4, while some of the hadoop dependencies were still referring to older version - the issue occurred.

In my case, the issue resolved by changing the sequence of jar file addition into the classpath in the shell script responsible for setting up environment before program execution. Earlier, I was adding the jar into classpath like

CLASSPATH=<Hadoop Jars>:<Common CLI jar>:$CLASSPATH

is changed to

CLASSPATH=<Common CLI jar>:<Hadoop Jars>:$CLASSPATH

and it fixed the problem.


问:
Ruby RegEx to Match between . and :
I have this string: "51. some thing:"
 and would like to extract just "some thing" using reg ex in ruby. Can anyone point me in the right direction to match between a . and a : and discard everything else?

Title: Ruby RegEx to Match between . and :

Body:
'51. some thing:'.sub /.*\. *([^:]*).*/, '\1'
=> "some thing"


答:
example:

```<code>void printArray(int *tab, int size)
{
    for (int i = size - 1; i >= 0; i--)
        std::cout << tab[i] << std::endl;
}
int main() {
    int tab[3] = { 1,2,3 };
    printArray(tab, 3);

}
</code>```

You should begin from last element array, and decrement iterator (i) to i == 0

Title: How to print an array in descending order?

Body:
Basically this is my code and it works fine. I just don't know how to print it in descending order. This code basically shows the odd numbers:1,3,5,7. I want it to be printed 7,5,3,1. I know I need use the sort function but I dont know how.

#include <iostream>

using namespace std;

void fillArray(int arr[], int &n);
void printArray(int arr[], int n);
void findSum(int arr[], int &n);

int main()
{
    int n;
    cin>>n;
    int arr[n];
    fillArray(arr,n);
    printArray(arr,n);
    findSum(arr,n);

    return 0;
}

void fillArray(int arr[], int &n)
{
    int j=1;
    for(int i=0;i<n;i++)
    {
        if(j%2==1)
            arr[i]=j;
        else
            i--;
        j++;
    }
}

void printArray(int arr[], int n)
{
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<", ";
    }
}

void findSum(int arr[], int &n)
{
    int sum=0;
    for(int i=0;i<n;i++)
    {
        sum=sum+arr[i];
    }
}

Body:
example:

void printArray(int *tab, int size)
{
    for (int i = size - 1; i >= 0; i--)
        std::cout << tab[i] << std::endl;
}
int main() {
    int tab[3] = { 1,2,3 };
    printArray(tab, 3);

}

You should begin from last element array, and decrement iterator (i) to i == 0


答:
```<code>select e1.id, e1.managerId, e2.managerId
from employees e1
left join employees e2 on (e1.manager = e2.employee)
</code>```

Title: SQL Query to return new column based on first two columns