text:
Q: Pandas Resample Upsample last date / edge of data I'm trying to upsample weekly data to daily data, however, I'm having difficulty upsampling the last edge. How can I go about this?
import pandas as pd
import datetime
df = pd.DataFrame({'wk start': ['2018-08-12', '2018-08-12', '2018-08-19'],
    'car': [ 'tesla model 3', 'tesla model x', 'tesla model 3'],
    'sales':[38000,98000, 40000]})
df['wk start'] = df['wk start'].apply(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d'))
df.set_index('wk start').groupby('car').resample('D').pad()

This returns:
                             car            sales
car             wk start
tesla model 3   2018-08-12  tesla model 3   38000
                2018-08-13  tesla model 3   38000
                2018-08-14  tesla model 3   38000
                2018-08-15  tesla model 3   38000
                2018-08-16  tesla model 3   38000
                2018-08-17  tesla model 3   38000
                2018-08-18  tesla model 3   38000
                2018-08-19  tesla model 3   40000

tesla model x   2018-08-12  tesla model x   98000

My desired output is:
                             car            sales
car             wk start
tesla model 3   2018-08-12  tesla model 3   38000
                2018-08-13  tesla model 3   38000
                2018-08-14  tesla model 3   38000
                2018-08-15  tesla model 3   38000
                2018-08-16  tesla model 3   38000
                2018-08-17  tesla model 3   38000
                2018-08-18  tesla model 3   38000
                2018-08-19  tesla model 3   40000
                2018-08-20  tesla model 3   40000
                2018-08-21  tesla model 3   40000
                2018-08-22  tesla model 3   40000
                2018-08-23  tesla model 3   40000
                2018-08-24  tesla model 3   40000
                2018-08-25  tesla model 3   40000
tesla model x   2018-08-12  tesla model x   98000
                2018-08-13  tesla model x   98000
                2018-08-14  tesla model x   98000
                2018-08-15  tesla model x   98000
                2018-08-16  tesla model x   98000
                2018-08-17  tesla model x   98000
                2018-08-18  tesla model x   98000

I looked at this, but they're using periods and I'm looking at datetimes. Thanks in advance!

A: Assign a column for the end of each of your weeks and stack, before using your previous groupby attempt:
(df.assign(end=df['wk start'].add(pd.DateOffset(6))).set_index(
    ['car', 'sales']).stack()
    .rename('wk start').reset_index([0, 1])
    .set_index('wk start').groupby('car')
    .resample('D').pad()
)

Output:
                                    car  sales
car           wk start
tesla model 3 2018-08-12  tesla model 3  38000
              2018-08-13  tesla model 3  38000
              2018-08-14  tesla model 3  38000
              2018-08-15  tesla model 3  38000
              2018-08-16  tesla model 3  38000
              2018-08-17  tesla model 3  38000
              2018-08-18  tesla model 3  38000
              2018-08-19  tesla model 3  40000
              2018-08-20  tesla model 3  40000
              2018-08-21  tesla model 3  40000
              2018-08-22  tesla model 3  40000
              2018-08-23  tesla model 3  40000
              2018-08-24  tesla model 3  40000
              2018-08-25  tesla model 3  40000
tesla model x 2018-08-12  tesla model x  98000
              2018-08-13  tesla model x  98000
              2018-08-14  tesla model x  98000
              2018-08-15  tesla model x  98000
              2018-08-16  tesla model x  98000
              2018-08-17  tesla model x  98000
              2018-08-18  tesla model x  98000

A: Yes, you are right, last edge data are excluded. Solution is add them to input DataFrame - my solution creates a helper Dataframe using drop_duplicates, adds 6 days and concat's to original df before using your solution:
df1 = df.sort_values('wk start').drop_duplicates('car', keep='last').copy()
df1['wk start'] = df1['wk start'] + pd.Timedelta(6, unit='d')

df = pd.concat([df, df1], ignore_index=True)
df = df.set_index('wk start').groupby('car').resample('D').pad()
print (df)
                                    car  sales
car           wk start
tesla model 3 2018-08-12  tesla model 3  38000
              2018-08-13  tesla model 3  38000
              2018-08-14  tesla model 3  38000
              2018-08-15  tesla model 3  38000
              2018-08-16  tesla model 3  38000
              2018-08-17  tesla model 3  38000
              2018-08-18  tesla model 3  38000
              2018-08-19  tesla model 3  40000
              2018-08-20  tesla model 3  40000
              2018-08-21  tesla model 3  40000
              2018-08-22  tesla model 3  40000
              2018-08-23  tesla model 3  40000
              2018-08-24  tesla model 3  40000
              2018-08-25  tesla model 3  40000
tesla model x 2018-08-12  tesla model x  98000
              2018-08-13  tesla model x  98000
              2018-08-14  tesla model x  98000
              2018-08-15  tesla model x  98000
              2018-08-16  tesla model x  98000
              2018-08-17  tesla model x  98000
              2018-08-18  tesla model x  98000

A: you could also do:
(pd.melt(df.assign(w = df['wk start']+pd.DateOffset(6)),df.columns[1:],value_name =
  "wk start").drop('variable',1).set_index('wk start').groupby('car').resample('D').pad())

                                    car  sales
car           wk start
tesla model 3 2018-08-12  tesla model 3  38000
              2018-08-13  tesla model 3  38000
              2018-08-14  tesla model 3  38000
              2018-08-15  tesla model 3  38000
              2018-08-16  tesla model 3  38000
              2018-08-17  tesla model 3  38000
              2018-08-18  tesla model 3  38000
              2018-08-19  tesla model 3  40000
              2018-08-20  tesla model 3  40000
              2018-08-21  tesla model 3  40000
              2018-08-22  tesla model 3  40000
              2018-08-23  tesla model 3  40000
              2018-08-24  tesla model 3  40000
              2018-08-25  tesla model 3  40000
tesla model x 2018-08-12  tesla model x  98000
              2018-08-13  tesla model x  98000
              2018-08-14  tesla model x  98000
              2018-08-15  tesla model x  98000
              2018-08-16  tesla model x  98000
              2018-08-17  tesla model x  98000
              2018-08-18  tesla model x  98000


text:
Q: How can I simplify a definite integral raised to a power? $\bigg(\int_a^bf(t)dt\bigg)^n$ Is there a way to simplify and integral to some power into a single integral?
$$\bigg(\int_a^b{f(t)}dt\bigg)^n=\int_c^dg(t)dt$$
My first thought was to rewrite the integral as
$$\int_a^b\int_a^b...\int_a^bf(t_1)f(t_2)...f(t_n)dt_1dt_2...dt_n$$
and use the Cauchy formula for repeated integration to collapse it into
$$\frac{1}{(n-1)!}\int_a^b(b-t)^{n-1}f(t)dt$$
but I realized that only works for repeated antidifferentiation -  not definite integration.
$$$$$$$$
The problem arose because I was looking to find for what values of b
$$\sin\bigg(-b{\pi}\int_0^{\infty}\ln(t)e^{-t}dt\bigg)=0$$
I thought it might help rewrite it as a mclaurin series
$$\sum_{n=0}^{\infty}\bigg[\frac{(-1)^n}{(2n+1)!}(-b{\pi})^{2n+1}\bigg(\int_0^{\infty}\ln(t)e^{-t}dt\bigg)^{2n+1}\bigg]=0$$
and I was planning to rewrite the sum to be
$$\int_c^d\bigg[\sum_{n=0}^{\infty}\bigg(\frac{(-1)^n}{(2n+1)!}g(t)\bigg)\bigg]dt=0$$
Is there any way to do this?
Less importantly - is there a good way to evaluate the sum in the resulting integral?
edit: I'm specifically looking for integer values of b

redpajama_set_name: RedPajamaStackExchange


text:
Q: Новый стандартный эмулятор в Android Studio На I/O Extended 16 была презентована новая версия Android Studio, в которой обновился стандартный эмулятор. Как утверждают разработчики, новый эмулятор стал в 16 раз быстрее собирать проекты, требует в несколько раз меньшее количество ресурсов и т.д.
Кто-нибудь уже разбирался и сравнивал НОВЫЙ стандартный эмулятор и Genymotion? Что лучше, что быстрее, почему?

A: Новый эмулятор доступен уже давно, еще вместе с Android Studio 2.0.
Да, он быстрее старого намного. На хорошем железе быстрее некоторых средних телефонов.
В Android Studio 2.2, представленной на I/O 2016 ускорена сборка проектов и загрузка APK на устройсто/эмулятор.
В новом эмуляторе много полезных фич, динамический размер, скриншоты одним кликом, drag-n-drop и т.п.
Просто попробуйте, все это уже есть вместе с последней стабильной Android Studio 2.1.1.

A: Genymotion однозначно лучше и быстрее. В новом эмуляторе в студии бережно сохранили все старые баги. Вот тут в конце статьи можете почитать.

A: Я понимаю, что это не ответ на вопрос, но хотелось бы обратить внимание на нововведения в Android Studio 2.2 , раз уж речь зашла о последнем Google I/O и этой IDE
В представленой на Google I/O Android Studio 2.2 следующие нововведения:

*

*Новый визуальный редактор с существенными улучшениями под новый контейнер ConstraintLayout (немного описал здесь)

*Визуальный редактор для файлов разметки Menu и Preferences

*Layout Inspector для теста нагруженности разметки прямо в Android Studio

*Улучшенный Lint и инспекции

*Переработанный браузер сэмплов, теперь можно вставлять сэмплы прямо в свой код

*Улучшена поддержка С++

*Плагин Firebase

*Компилятор Jack с поддержкой Java 8

*IntelliJ IDEA 2016.1 в базе, со всеми ее основными фишками.

*APK Analyzer для решения проблем с скомпилированным приложением: размер, проблема 64K и тп
А новый эмулятор представлен еще в версии AS2.0


text:
Q: SoundCloud API Downloadable Tracks Filtering

I'm going to develop sound cloud based music app and having an issue at filtering.
What I want is to filter downloadable tracks at sound cloud.
I've seen the sound cloud developers' API guide and made the following request.

"https://api.soundcloud.com/tracks.json?offset=0&limit=10&q=最炫民族风&filter=downloadable&order=hotness&client_id=11111111111111111111111"

But this request doesn't return downloadable songs only, and there is downloadable|non-downloadable tracks in the returned track list.

Would you please tell me the correct request for this purpose?

Thanks in advance.


text:
Q: python, yaml how to parse a string containing apostrophe I am using python to parse YAML files.
One of the YAML documents contain a dictionary such as follow:
scrapers:
    results: //article[@class='story ']

This apparently causes a problem because the last apostrophe is preceded by a whitespace. If I could remove the whitespace it would solve the problem. However since it is an xpath I can't.
Anyone knows how I could escape that sequence?
I looked into other SO question, but solution like wrapping the string in "", or
using
scrapers:
  results: //article[@class='story ']

or
scrapers:>
  results: //article[@class='story ']

or
scrapers:
  results: //article[@class='story '']

did not work.
EDIT:
I am trying to open a file containing the above expression with:
import yaml
with open('/home/depot/wintergreen/yaml/scrapers.yml', 'r') as f:
    scrapers = yaml.load(f)

However i receive the error:
    ScannerError: mapping values are not allowed here
pointing at the whitespace after story.
I have been trying a suggestion offered by an answerer below, i.e. to create the yaml expression from a python dict. This works. I i save the yaml to file and load it back again it also does work.
However when i create the yaml by typing the exact same characters, then it does not work...
EDIT2:
I think the problem stemmed from the fact that i created the yaml file on a window machine and uploaded it on a unix server.

A: It's easy to find the correct YAML format for a structure: create the structure in Python then use yaml.dump to create the YAML-encoded string:
d = {'scrapers': {'results': "//article[@class='story ']"}}
print d

import yaml
print yaml.dump(d, default_flow_style=False)

The result of which is:
{'scrapers': {'results': "//article[@class='story '"}}

scrapers:
    results: //article[@class='story ']

That's the correct YAML representation, so if you're having a problem, it's with the parser, not the input text. If you use the standard yaml library it should parse fine.


text:
Q: How do nested if...else statements outperform a series of single-selection if statements in C++ I'm reading C++: How to Program, Ninth Edition by Paul and Harvey Deitel and I've found something that somewhat confuses me on page 114.
The book gives the example code:
if ( studentGrade >= 90 ) // 90 and above gets "A"
    cout << "A";
else
    if ( studentGrade >= 80 ) // 80-89 gets "B"
        cout << "B";
    else
        if ( studentGrade >= 70 ) // 70-79 gets "C"
            cout << "C";
        else
            if ( studentGrade >= 60 ) // 60-69 gets "D"
                cout << "D";
            else // less than 60 gets "F"
                cout << "F";

The book then goes on to say:

Most programmers write the preceding statement as:

if ( studentGrade >= 90 ) // 90 and above gets "A"
    cout << "A";
else if ( studentGrade >= 80 ) // 80-89 gets "B"
    cout << "B";
else if ( studentGrade >= 70 ) // 70-79 gets "C"
    cout << "C";
else if ( studentGrade >= 60 ) // 60-69 gets "D"
    cout << "D";
else // less than 60 gets "F"
    cout << "F";

The two forms are identical except for the spacing and indentation, which the compiler ignores. The latter form is popular because it
avoids deep indentation of the code to the right, which can force
lines to wrap.

Below that there is a box labelled as Performance Tip 4.1:

A nested if...else statement can perform much faster than a series of single-selection if statements because of the possibility of early exit after one of the conditions is satisfied.

I don't really understand this because (I'm assuming that a "series of single-selection if statements" means the second code example, using the if...else if on the same indentation; the style that is very popular) from what I understand about C and C++, when an if statement or one of the following else if statements is tested to be true, the rest of the else if statements aren't even tested, they're just skipped. Wouldn't that be the same as an early exit? Also, the book says that the two forms are identical as far as the compiler is concerned, why would one outperform the other?

A: The "series of single-selection if statements" is not shown in the book. It would be the similar to the two code samples you show, but without the else keywords. However, you'd have to add some code to exclude the earlier cases.
if ( studentGrade >= 90 ) // 90 and above gets "A"
    cout << "A";
if (studentGrade < 90 && studentGrade >= 80 ) // 80-89 gets "B"
    cout << "B";
if (studentGrade < 80 && studentGrade >= 70 ) // 70-79 gets "C"
    cout << "C";
if (studentGrade < 70 && studentGrade >= 60 ) // 60-69 gets "D"
    cout << "D";
if (studentGrade < 60) // less than 60 gets "F"
    cout << "F";

Besides having to run tests that you know are going to be false (after outputting a grade), the later tests are more complicated, and it is easy to get something wrong in those expanded tests (either forgetting to exclude the earlier cases, or not typing the exclusion correctly). All that extra code also makes the code harder to comprehend when reading it.
So using an if else chain is better for performance, code readability, and code maintenance.


text:
Q: WPF TranslateTransform Im trying to use the TranslateTransform class to move a image on a Grid on Y axis. I need this movment to be smooth so i can not use SetMargin or SetCanvas. I try this in code behind:
public void MoveTo(Image target, double oldY, double newY)
{
    var trans = new TranslateTransform();
    var anim2 = new DoubleAnimation(0, newY, TimeSpan.FromSeconds(2))
                    {EasingFunction = new SineEase()};
    target.RenderTransform = trans;
    trans.BeginAnimation(TranslateTransform.YProperty, anim2);
}

The object i want to use (a Image control) is placed on a Grid.
 For the first time everything works fine.
The problems comes when i try to move the object again using the same function.
The object (a Image control) first move to the start position (initial Y coordinate) then the animation begins.
Is it not suposed for the TranslateTransform to change the coordinates (in my case the Margin property) too?
Thank you.

A: The transform does not change the original values.they are your point of origin. If you want a new point of origin each time you move you can handle the animation completed event. Or from your transform you can get your current offset and make that your new start point for the animation.
In other words your start values would always be your last move to values

A: The TranslateTransform is a specific kind of render transformation. Rather that changing properties of the control (such as the Margin property), it simply affects how the control is displayed on the screen.

A: You've explicitly told the animation to start from 0. It's doing what you've told it.
Just remove the explicit zero fromvalue and everything will work.
var anim2 = new DoubleAnimation(newY, TimeSpan.FromSeconds(2))
                { EasingFunction = new SineEase() };

A: You have to use the By property of DoubleAnimation.
Try that:
//everytime you execute this anmation your object will be moved 2.0 further
double offset = 2.0
var anim2 = new DoubleAnimation(newY, TimeSpan.FromSeconds(2));
anim2.To = null;
anim2.By = offset;


text:
Q: Android UTF-8 encoding not working? I am working with a CSV file right now.
In my program i am using an OutputStreamWriter to write data the csv file.
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut, Charset.forName("UTF-8").newEncoder());

I tried printing out the encoding style of this writer and get the following:
Log.i(TAG, "BODY ENCODING: " + myOutWriter.getEncoding());
Logcat: BODY ENCODING: UTF-8

But when i try to open the csv file on my desktop it says that the file is in windows-1252 so i cant read æøå chars which i need.
Am i missing something obvious here or am i not understanding the concept of outputStreamWriter? I have tried different types of encoding, but it doesn't seem to work :)
When i try to open in Excel:

A: Your file is actually UTF-8 not CP-1252. Your text editor/viewer detected it as CP-1251 (since no multi-byte characters). You can help your editor by adding byte order mark  (BOM) in the beginning of the file. I.e.
static final byte[] UTF8_BOM = {0xEF,0xBB,0xBF};
...
fOut.write(UTF8_BOM);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut, Charset.forName("UTF-8").newEncoder());

A: Did you try opening it in EXCEL? For EXCEL to recognize the file as UTF-8 it needs to have BOM (https://en.wikipedia.org/wiki/Byte_order_mark)