text:
Q: Javascript Split and trim delineator I have a 10 million line text file loaded stored as a string in a variable "someString".  I want to generate an array where each line is an item.  I know that to do that I would do the following:
var files = someString.split("\n");

However, this keeps the line break symbol \n after each item.  What is the most efficient way to trim this from each item?

A: Try using a regex delimiter to handle different line-ending characters for Windows (\r\n) and others (\n or \r)
someString.split(/\r\n|\r|\n/)

A: I found this answer on How to remove all line breaks from a string?.
someText = someText.replace(/(\r\n|\n|\r)/gm,"");


text:
Q: Permutations of digits with conditions I have a problem and I don'tknow how to solve it. It's just a hobby, I am not a student, I am 50 years old.
The problem is the following:
I have a string of 100 digits (this can change, it is just an example).
Digits have their own frequencies, for example:
"0" appears 3 times, "1" appears 12 times, "2" appears 21 times, "3" appears 1 time, "4" appears 1 time, "5" appears 25 times, "6" appers 2 times, "7" appears 18 times, "8" appears 10 times and "9" appears 7 times.
The condition is : two consecutive digits must not be identical.
I have 3 questions:
1 - how many permutations are there with the given codition ? otherwise the answer is simple : 100! / (3! 12! 21! 25! 2! 18! 10! 7! )
2 - if I give the number of a permutation (let's say 267.245), what is he corresponding string of digits ?
3 - if I give a string, hat is the number of the permutation ?
I tried to search the answers on the net, it seems it is impossible to find the result.
Thank you for your help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I can not visit localhost with apache on OS X 10.9 The Chrome alert me

Oops! Google Chrome could not connect to localhost

But my apache still running:
  501 80299 71841   0  2:35PM ttys003    0:00.00 grep httpd

I paste some piece of important apache configuration , please help me. Thanks.
http.conf
ServerRoot "/usr" Listen 80

ServerAdmin you@example.com

DocumentRoot "/Users/username/Sites"

<Directory />   Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride None
    Order deny,allow
    Allow from all </Directory>

<Directory "/Library/WebServer/Documents">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

Actually I don't know what file I need to show you.
If you need more configuration file detail, please tell me. I will paste later.

A: Run this command:
sudo apachectl start

That should start your standard apache server software as well as edit the system startup files to cause it to start at boot. Replace start with stop to reverse that change. Your grep shows that httpd is not actually running and there's just the grep process active. You may need to look at the logs if after asking apachectl to start things up, the httpd process doesn't stay running (or even start in the first place).


text:
Q: Flutter gradle compilation fails I have some trouble compiling my Flutter App with Gradle since I updated Flutter.
Here is my setup :
[√] Flutter (Channel stable, 2.2.2, on Microsoft Windows [version 10.0.18363.1198], locale fr-FR)
    • Flutter version 2.2.2 at C:\Users\barba\Documents\flutter
    • Framework revision d79295af24 (2 days ago), 2021-06-11 08:56:01 -0700
    • Engine revision 91c9fc8fe0
    • Dart version 2.13.3

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at C:\Users\barba\AppData\Local\Android\sdk
    • Platform android-30, build-tools 30.0.3
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
    • All Android licenses accepted.

This is the log I get when trying to compile it.
Launching lib\main.dart on HD1900 in debug mode...
e: Incompatible classes were found in dependencies. Remove them from the classpath or use '-Xskip-metadata-version-check' to suppress errors
e: C:/Users/barba/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/META-INF/kotlin-stdlib.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

[...]

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':audioplayers:compileDebugKotlin'.
> Compilation error. See log for more details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 21s
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

I tried deleting .gradle from my Android folder, and using gradlew clean.
This is what I get :
> Configure project :audio_session
WARNING: The option setting 'android.enableR8=true' is deprecated.
It will be removed in version 5.0 of the Android Gradle plugin.
You will no longer be able to disable R8

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.7/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 1s
11 actionable tasks: 11 up-to-date

However I did check my gradle.properties, there is no android.enableR8=true. This string doesn't exist in my whole project folder, there is no way to delete it from the gradle properties.
Any idea on how to solve this issue ?
Thanks

A: Generally, this type of issue comes from outdated/incompatible package versions. Try this :

*

*run flutter clean

*run flutter pub outdated to see what versions you can upgrade to

*update your pubspec.yaml accordingly
If this doesn't work, try ruling out packages one by one until you find the one causing the issue.

A: Solution I figured out myself:

*

*Go to this location: " C:\Users\yourUserName "

*Delete the folder ".gradle" completely from this directory.

*Run the code again in VS Code by "flutter run" or "F5", then it will recreate the ".gradle" folder in the same directory and fix the issue.

*Now you can run your code easily in VS Code and use your emulators.
Problem Solved, Enjoy!


text:
Q: On focus after tabbing of Excel drop down, automatically show list for selection I have some data validation drop down lists in excel, I can tab through all the lists but I have to press alt + down arrow to show the list, Is their a way it can be automatically shown as soon as I focus on the tab.
So on focus of the drop down list, I would like the list to appear So that I can select it with the arrow down key and hit enter to select it.
Any other helpful tips for drop down lists and VBA would be great!

A: edit: still using VBA send keys.
On the sheet where the data validation cell resides (assumed it is cells A1:C1 on Sheet1), put in the following code in the Microsoft Excel Sheet1 Module (the module that holds the VBA code that is related to the first sheet)
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    On Error GoTo Err1:

    If Target = Range("A1") Then
        Application.SendKeys ("%{UP}")
    End If

    If Target = Range("B1") Then
        Application.SendKeys ("%{UP}")
    End If

    If Target = Range("C1") Then
        Application.SendKeys ("%{UP}")
    End If

Err1:
    'do nothing
End Sub

A: I found this helpful but would like to pass on a couple of observations.

*

*Using
If Target.Cells.Count = 1 Then
If Target.Validation.InCellDropdown = True Then
in the event will apply this to all validation drop lists on the sheet rather than listing the individual cells.  You need the first if to avoid an error caused by selecting multiple cells.

*

*Beware of send keys being called twice in a row.  It turns your num lock off and I had to add an API call to turn it back on again.

I hope this helps others


text:
Q: Comparing date and time I want to write an alarm clock application that should display a certain message at a time set by the user.
How to compare system date and time with the time set by users in a text box?
Thanks
Furqan

A: You can convert TextBox.Text value to a DateTime value as the following:
String dateTimeFormat = "MM/dd/yyyy hh:mm:ss tt";
DateTime dateTimeValue =
    DateTime.ParseExact(textBox.Text, dateTimeFormat ,
        CultureInfo.InvariantCulture);

DateTime.ParseExact Method converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly or an exception is thrown.

A: You should use the intellisense feature ... but the hint is:
DateTime.Parse ....
and you need a timer, I called him "timEr" (you should name him better ....), and read the answer from Akram, he made it culture independent ....
Private Sub timEr_Tick(sender As System.Object, e As System.EventArgs) _
    Handles timEr.Tick

    timEr.Enabled = False
    If DateTime.Now >= DateTime.Parse("29.06.2011 17:29") Then
        MessageBox.Show("Time to leave the office ....")
    End If

End Sub

A: Your best bet would be to use System.DateTime object
Just make sure when you take a users input from a text box, that you save it in a DateTime object, then you can use the generic DateTime.Equals to compare the two.
Dim currentDateTime As New System.DateTime
Dim alarmDateTime As DateTime
currentDateTime = Date.Now
alarmDateTime =
    New DateTime(2011, Month(Date.Now), dayInput, hourInput, minuteInput, 0)
If currentDateTime.Equals(alarmDateTime) Then
  'alarm code
End If

Something to this effect shold get the job done.
EDIT: The parse method outlined in one of the other solutions would be better for creating your alarmDateTime object than manually doing it.

A: Since you're using VB.NET you can use the functionality in Microsoft.VisualBasic.DateAndTime. For example, you could use DateTime.Parse (or better, .TryParse) to get a DateTime representation of the user's value, then check whether the system time is within, say, one minute of the user's time. This way, you don't need to mess with seconds.
Dim diffInMinutes As Long =
    Microsoft.VisualBasic.DateAndTime.
        DateDiff(DateInterval.Minute, userTime, DateTime.Now)


text:
Q: How to create a proper XHR request in AJAX Here's my simple web page:
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body onload="start()">
  </body>
</html>

And here's my XMLHttpRequest:
function start(){
  //Name the function that will perform request
  var httpRequest;

  //cross browser instance
  if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
  } else if (window.ActiveXObject){ //if IE 8 and older
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
  }

  httpRequest.onreadystatechange = httpResult; //what to do after response
  httpRequest.open("GET","http://data.mtgox.com/api/2/BTCUSD/money/ticker_fast?pretty", true);
  httpRequest.send();

  function httpResult(){
    if (httpRequest.readyState === 4 && httpRequest.status === 200){
      alert(httpResult.responseText);
    } else {
      alert("problem making request");
    }
  }
}

When I load the page, it runs the code and returns the "problem making request" alert 3 times. I don't see any error pop up in the JavaScript console. Anyone have a clue as to why I'm not getting a proper response from the request?

A: You seem to be violating the same origin policy restriction that's built into browsers which prevents you from sending cross domain AJAX requests.
You can only send AJAX requests to the domain from which originated the script. In your case you are attempting to send a request to http://data.mtgox.com and this can only work if your page is hosted on this very same domain, which I suspect isn't your case.
Of course if the server supports CORS or JSONP it would be possible to perform such a request.

A: The onreadystatechange handler is fired every time the readyState property changes. This means your else part will always execute until readyState turns 4.
Problem is you're trying to access the responseText property of httpResult, which is the onreadystatechange handler. Instead use httpRequest.responseText.
if (httpRequest.readyState === 4 && httpRequest.status === 200){
            alert(httpResult.responseText);
}

This isn't a CORS-related problem, your URL allows CORS requests.
jsFiddle Demo
BTW, you must use the onerror handler for detecting XHR errors.


text:
Q: Modify expander header children when expanded I can't figure out how to do it in XAML.  I came up with workarounds that use Expanded/Collapsed events, but they just don't feel right.
I have a DataGrid, with groups, that are templated as expanders.  I have a button inside expander, that's hidden by default, and only needs to be shown when an expander is expanded.
<GroupStyle.ContainerStyle>
    <Style TargetType="{x:Type GroupItem}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type GroupItem}">
                    <Expander IsExpanded="True">
                        <Expander.Header>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="Some Text"/>
                                <Button Name="MyButton" Visibility="Collapsed" Content="Add All"/>
                            </StackPanel>
                        </Expander.Header>
                        <Expander.Content>
                            <ItemsPresenter />
                        </Expander.Content>
                    </Expander>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</GroupStyle.ContainerStyle>

So basically the code in question is right in the middle:
<Expander IsExpanded="True">
    <Expander.Header>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Some Text"/>
            <Button Name="MyButton" Visibility="Collapsed" Content="Add All"/>
        </StackPanel>
    </Expander.Header>
    <Expander.Content>
        <ItemsPresenter />
    </Expander.Content>
</Expander>

I'm trying to set Visibility of the Button to false, when the expander is expanded.  I tried using a trigger like the following:
<Expander.Style>
    <Style TargetType="Expander">
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsExpanded, RelativeSource={RelativeSource Self}}" Value="False">
                <Setter TargetProperty="MyButton" Property="Visibility" Value="Visible" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Expander.Style>

, but the compiler doesn't accept it, because it can't find MyButton (I'm guessing because it's inside a header).  Any ideas on how I can get this to work?

A: You have to move the DataTrigger in a ControlTemplate like this:
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type GroupItem}">
            <Expander Name="Expander" IsExpanded="True">
                <Expander.Header>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="Some Text" />

                        <Button Name="MyButton"
                                Visibility="Collapsed"
                                Content="Add All" />
                    </StackPanel>
                </Expander.Header>

                <Expander.Content>
                    <ItemsPresenter />
                </Expander.Content>
            </Expander>

            <ControlTemplate.Triggers>
                <DataTrigger Binding="{Binding Path=IsExpanded, ElementName=Expander}" Value="False">
                    <Setter TargetName="MyButton" Property="Visibility" Value="Visible" />
                </DataTrigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Setter.Value>
 </Setter>

Notes

*

*I explicitly set the name for the Expander, because the construction RelativeSource={RelativeSource Self} points to control himself, and there in GroupItem is no property IsExpanded.

*In Setter does not have a TargetProperty property, but there are TargetName.


text:
Q: Gremlin query is not returning any hits when using both union and choose step I used the below gremlin query to fetch records, but it returns 0 hits when records are present.
g.V().hasLabel('LABEL').
  union(hasLabel('LABEL')).as('vertex').
    select('vertex').
  choose(
    has('core.classType'),
    values('core.classType')
  ).groupCount('core.classType').
    select('vertex')

When I used the same query without the 'Union' or the 'Choose' step, then it worked fine
Ex:
Without 'Union':
g.V().hasLabel('LABEL').as('vertex').
    select('vertex').
  choose(
    has('core.classType'),
    values('core.classType')
  ).groupCount('core.classType').
    select('vertex')

Without 'Choose'
g.V().hasLabel('LABEL').
  union(hasLabel('LABEL')).as('vertex').
    select('vertex')

When I used the sideEffect instead of storing results in the 'As' step, then also it worked fine
g.V().hasLabel('LABEL').
  union(hasLabel('LABEL')).sideEffect(choose(
      has('core.classType'),
      values('core.classType')
    ).
    groupCount('core.classType'))

I want the hits using both the 'Union' and 'Choose' steps. Can someone please explain the reason for this? Should we need to use 'Barrier' steps to handle this?


text:
Q: TimeSpan ToString format Just curious, is there a format string I can use to output something like "5h 3m 30s"?
eg. (obviously wrong)
myTimeSpan.ToString("hh mm ss")

A: This little code sample should help you to parse and reverse-parse TimeSpan:
var t = TimeSpan.FromMilliseconds(450780);
double d1 = t.TotalSeconds;
string t3 = t.ToString(@"hh\:mm\:ss\.f",null);
var tt = TimeSpan.ParseExact(t3, @"hh\:mm\:ss\.f",null);
double d2 = tt.TotalSeconds;

Reference: Custom TimeSpan format strings

A: how about concactenation:
String oTime = myTimeSpan.ToString("h") + "h " +
               myTimeSpan.ToString("m") + "m " +
               myTimeSpan.ToString("s") + "s "

UPDATE 1:
You can escape it with single quote: h'h 'm'm 's's'

A: I sometimes find format strings a little like regexes, in that when I come back to the code later, I've forgotten the nuances. I've therefore gone with the following, which is less likely to send me back the documentation:
string FormatTimeSpan(TimeSpan timeSpan) =>
    $"{Math.Floor(timeSpan.TotalHours)}h {timeSpan.Minutes}m {timeSpan.Seconds}s";

String interpolation, introduced in C# 6, is making this a lot clearer than it would otherwise be.

A: Be aware of this when using the answer from Jon Skeet, with code like this:
// 12 days, 23 hours, 24 minutes, 2 seconds.
TimeSpan span = new TimeSpan(12, 23, 24, 2);
// 27 hours, 24 minutes, 2 seconds
TimeSpan span2 = new TimeSpan(27,24,2);

string format = span.ToString("h'h 'm'm 's's'");
string format2 = span2.ToString("h'h 'm'm 's's'");
Console.WriteLine(format);
Console.WriteLine(format2);
Console.ReadLine();

You get results like these:
23h 24m 2s
3h 24m 2s

The hour format can at maximum show 23 hours. It will not show 27 hours or convert the 12 days to hours, it will simply cut them off as if they never existed.
One way to fix this would be to create an extension that checks the length of the TimeSpan  and creates formatting based on if the timespan is over a year, day, ect. Or you could simply always show days as well because they never cut off:
string newFormat = span.ToString("d'd 'h'h 'm'm 's's'");

Do note I am a beginner at programming. This is only coming from observations after I was lucky enough to notice this after having assumed it would show all hours. I'm saying this because I don't know if there is a better solution, like another hour format that can display endless hours.
I do however think this format is doing its intended functionality. You just have to be aware of it. Thus this post. Jon Skeet's answer never indicated that this format is to show only the hour property of a date type format where the hours can be at most 23.

A: If you're unfortunate enough not to be using .NET4:
string.Format("{0}h{1}m{2}s",
    myTimeSpan.Hours,
    myTimeSpan.Minutes,
    myTimeSpan.Seconds);

A: Using Xamarin and .NET Portable 4.5 this was the only format I got working after trying all other answers here:
timespan.ToString("hh':'mm':'ss");

Essentially I'm putting the : in single quotes to escape them.

A: Try:
myTimeSpan.ToString("h'h 'm'm 's's'")

(Note that even spaces need to be quoted - that's what was wrong with my first attempt.)
I'm assuming you're using .NET 4, of course - before that, TimeSpan didn't support custom format strings.
EDIT: As noted, this won't work beyond 24 hours. Also note that alternatives are available via Noda Time too :)


text:
Q: Why does Coldfusion occasionally throw an error? For example, I have a page. I can load this page 100 times without error. However sometimes someone gets an error because I get the email that is sent from ColdFusion in the onError method. I don't get them a lot, but I get them more than I would think I should. It's impossible to "debug" because it doesn't happen all the time. Once a day maybe on a given page.
Has anyone seen anything similar.
One exmaple:
if((StructKeyExists(ARGUMENTS.itm, 'video_code') && len(trim(ARGUMENTS.itm.video_code)) || !StructKeyExists(ARGUMENTS.itm, 'video_code')) == 0) return '#title##fileext#';
    else return '#title#';

In this page request, the item struct had video_code in there. But when the second line was processed video_code was undefined. I can run the page 100 more times, and this doesn't happen.
objectType  class coldfusion.runtime.Struct
element VIDEO_CODE
Resolvedname    ITM
Detail
ErrNumber   0
Message Element VIDEO_CODE is undefined in ITM.
Type    Expression
Trace:  Template    Line
D:\www\websites\assets\cfcs\menu.cfc    240
D:\www\websites\assets\cfcs\menu.cfc    209
D:\www\websites\assets\cfcs\menu.cfc    15
D:\www\websites\assets\templates\distance_general\campus_index_page.cfm 120
D:\www\websites\domain.com\index.cfm    1

A: It's a bug in your code.
That's the standard automatic response when anyone asks a question like the one you have, because it's almost always the case.
There is of course a chance that you've identified a flaw in ColdFusion, but the odds of finding a bug in an established product are  significantly lower than those of it being an error in your specific code/config.
Given the convoluted code provided as an example, the probably is very high that it's a bug in your code.

can programming languages mis-parse at times or anything like that.

Simply, no. There are no parse-level constructs that would make the parser behave differently, and the parsing is done once, then the same compiled code is used (until cleared or server restarted).

why this would not fail 100 times over and fail once?

Looking again at the example, it may well be a scoping issue - you are checking StructKeyExists on ARGUMENTS.itm but are then using simply itm in the code. ColdFusion has threading issues with unscoped variables that can manifest when under heavy load.
Use varscoper to check for unscoped variables.

A: It's an actual bug in your code.  The if condition is:
(StructKeyExists(ARGUMENTS.itm, 'video_code') && len(trim(ARGUMENTS.itm.video_code)) || !StructKeyExists(ARGUMENTS.itm, 'video_code')) == 0

which means that the else condition is:
(StructKeyExists(ARGUMENTS.itm, 'video_code') && len(trim(ARGUMENTS.itm.video_code)) || !StructKeyExists(ARGUMENTS.itm, 'video_code'))

So the else clause will be executed when ARGUMENTS.itm.video_code exists and is not empty, or when it doesn't exist. In the latter case, the reference to itm.video_code on the second line will fail.
I can't explain why the error happens intermittently. I think you need to look at the different callers, to see why the argument sometimes doesn't exist.


text:
Q: Why is resistance across my arm-span so much less than across my face? This sounds like a strange question (it is) but, from a purely biological standpoint, why is the measured resistance across my hands (I measured 120k\$\Omega\$) so much less than across my face? I thought to ask this because the distance across my face is much less than my arm span.
More specifically, what makes the tissue in my face so much more resistant to charge (ion) flow than my entire arm-span?
P.S. I used a standard multimeter with resistance set at 2M\$\Omega\$ to get my readings - across my face doesn't even give a reading (too much resistance)

A: Your skin surface resistance is what varies greatly.   It will be affected by things like sweat, salt, and skin oils.
edit:
Skin oils can add a more resistive layer.
edit:
Try different distances in the same parts and like distances in different parts.

A: As Skaperen says it is all about the skin resistance. With an electrode in the meat under the skin, the resistance across the body will be much lower.
My theory is that you are able to obtain more contact pressure holding the meter probes in your hands, than when pressing them to your face.
Rather have someone else poke you with the probe, in the same way, in different places.
You could also put one probe in your mouth, which would be a low resistance connection to your body, and you'd have your hands free to probe all around.
Doing this, I think you'll find it's only the skin type and pressure that matter, not the distance across the body.

A: Is it possible that since there is likely more skin oils on your face, and more sweat on your hands that the results were affected?

A: Hopefully this helps:
Because resistance is proportional to material length
and inversely proportional to cross sectional area (see below), I think
it's safe to say that because your face has significantly
lower cross-sectional area compared to your arm-span
(probably by a couple orders of magnitude) that the length
difference is negligible.
\$
    R = \rho * \frac{L}{A_c}
\$
Added to that (like what others have said before) a 'sweaty'
surface like your hands likely gives excellent probe contact,
while the less-moist (and hairier) surface of your face gives
less complete contact.
All these factors result in much higher resistance across your
face compared to your arm-span


text:
Q: run cronjob and supervisor in dockerfile I am new to docker and trying to run supervisor and corn , but in this file it is just running
supervisor.
I know the problem is with last line but how can I fix it?
FROM php:7.4-fpm

# Copy composer.lock and composer.json
COPY composer.lock composer.json /var/www/

# Set working directory
WORKDIR /var/www

# Install dependencies
RUN apt-get update && apt-get install -y \
    libonig-dev\
    build-essential \
    libpng-dev \
    libjpeg62-turbo-dev \
    libfreetype6-dev \
    locales \
    zip \
    jpegoptim optipng pngquant gifsicle \
    vim \
    unzip \
    git \
    curl \
    libzip-dev

# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install extensions
RUN docker-php-ext-install pdo_mysql mbstring zip exif pcntl
RUN docker-php-ext-configure gd --with-freetype --with-jpeg
RUN docker-php-ext-install gd
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

RUN apt-get update
RUN apt-get update && apt-get install -y cron

COPY /docker/crontab /etc/cron.d/crontab
#
# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/crontab
RUN crontab /etc/cron.d/crontab

# Create the log file to be able to run tail
RUN touch /var/log/cron.log

RUN apt-get update && apt-get install -y supervisor
COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf

CMD /usr/bin/supervisord ; cron && tail -f /var/log/cron.log

A: Because you are using ";" after the supervisord command, the command waits for supervisord to finish and after that cron will run. You can make it like:
CMD /usr/bin/supervisord & cron && tail -f /var/log/cron.log

so the supervisord will run in the back ground.
If you want the container to fail if supervisord fails, you can do it like:
CMD cron && tail -f /var/log/cron.log  & /usr/bin/supervisord


text:
Q: In ConfigParser how to get only section-local options? Consider the following MWE named foo.py:
#!/usr/bin/env python3
from configparser import ConfigParser

if __name__ == "__main__":
    cfg = ConfigParser()
    with open("foo.ini") as ini:
        cfg.read_file(ini)
    for section in cfg.sections():
        print("[%s]" % (section))
        for option, value in cfg.items(section):
            print("%s = %s" % (option, value))

... and the accompanying foo.ini:
[DEFAULT]
basedir = /foo/bar
sourcedir = %(basedir)s/baz

[task:1]
sourcedir = /usr
workdir = %(sourcedir)s/src

[task:2]
hdrdir = %(sourcedir)s/include

The script will yield the following when run:
[task:1]
basedir = /foo/bar
sourcedir = /usr
workdir = /usr/src
[task:2]
basedir = /foo/bar
sourcedir = /foo/bar/baz
hdrdir = /foo/bar/baz/include

The desired outcome is to iterate exclusively over the (interpolated) options (via ConfigParser.items()) local to the given section.
Passing raw=True to ConfigParser.items() doesn't affect the list of items other than that the values are not being interpolated (which is anyway not the desired outcome).
Now I could do something like in this modified version of the initial script:
#!/usr/bin/env python3
from configparser import ConfigParser

if __name__ == "__main__":
    cfg = ConfigParser()
    with open("foo.ini") as ini:
        cfg.read_file(ini)
    print("; sections: %s" % (cfg.sections()))
    print("; defaults: %s" % (cfg.defaults()))
    for section in cfg.sections():
        print("[%s]" % (section))
        print("; options = %s" % (cfg.options(section)))
        for option, value in cfg.items(section):
            if option in cfg.defaults():
                # can't use cfg.defaults()[option] ... that's the raw value
                if cfg[cfg.default_section][option] == value:
                    continue
            print("%s = %s" % (option, value))

... which yields:
; sections: ['task:1', 'task:2']
; defaults: OrderedDict([('basedir', '/foo/bar'), ('sourcedir', '%(basedir)s/baz')])
[task:1]
; options = ['sourcedir', 'workdir', 'basedir']
sourcedir = /usr
workdir = /usr/src
[task:2]
; options = ['hdrdir', 'basedir', 'sourcedir']
hdrdir = /foo/bar/baz/include

So it'll work at first glance, but would filter out section-local options which have a value identical to the global one of the same name.
Now this may seem only like a cosmetic issue, but in my case there is a semantic difference, still, between whether the option exists locally inside a section or whether its value was inherited from the default section (think multiple files, multiple inherited options ...). Point being that this is a naïve approach which doesn't work for me.
So the question: how can I get just the options that are really inside a section of an .ini file, without all those global inherited options?
Is there a way to do this without reaching into the guts of the configparser module and tampering with non-public methods and stuff?

A: Inspecting the code of ConfigParser I don't see a public API to do it. Indeed, any method in ConfigParser extends the given section with defaults.
The only straightfoward way I see would be to change the default section either in your config or in ConfigParser constructor (default_section argument):
if __name__ == "__main__":
    cfg = ConfigParser(default_section=None)
# (...)

However the side effect is that the automatic "default" mechanism will not work any more for this instanciated ConfigParser. However you can still do the fallback mechanism your self:
cfg = ConfigParser(default_section=None)
cfg.get(mysection, myoption, fallback=cfg.get('DEFAULT', myoption))

Also, the interpolation in values will not work from DEFAULT section. But you can use ExtendedInterpolation.
Full example:
# test.py
from configparser import ConfigParser, DEFAULTSECT, ExtendedInterpolation

if __name__ == '__main__':
    cfg = ConfigParser(default_section=None, interpolation=ExtendedInterpolation())

    with open('test.ini') as ini:
        cfg.read_file(ini)

    for section in cfg.sections():
        if section == DEFAULTSECT:
            continue

        print('[%s]' % (section))
        for key, value in cfg.items(section):
            print('%s = %s' % (key, value))

# test.ini
[DEFAULT]
foo=bar

[section]
key="value ${DEFAULT:foo}"

Edits:

*

*Rename DEFAULT section is not a good idea if the purpose of it is to configure default values. I strike this option.

*Set default_section as None instead of "whatever"

*Add a full code example

*Add details about ExtendedInterpolation


text:
Q: jQuery tooltip showing behind dropdown How can I get tooltip to disable & hide when element gets focus and not show up again for mouseover until blur event takes place.
Expected:
Tooltip has a delay on mouseover. In my jsFiddle, mouseover left dropdown, wait for tooltip to appear, click on dropdown, tooltip will disappear, you can mouseover other elements, those tooltips show, assuming left dropbox still has focus, mouse back over, tooltip still does not show.
Not Expected (Requirement to resolve):
Now hit run again, click on same dropdown before tooltip shows. Keep mouseover element, tooltip appears - I don't want it to show while element has focus.
jsFiddle: http://jsfiddle.net/x1Lveooy/9/
$(document).on({
focus: function (e) {
    $('.ui-tooltip').hide()
    tempTitle = $(this).attr("data-title");
    $(this).attr("data-title", "");
    //intent, disable tooltip for this element only:
    //$(this).tooltip().tooltip('disable');
    //This would work if I wrap init in function & call again on blur, but not what I want:
    //$(document).tooltip().tooltip('disable');
},
blur: function (e) {
    $(this).attr("data-title", tempTitle);
}
}, '.element1, .element2, #box');

UPDATE another try, using "setTimeout" instead of "delay" during initTooltip() (I read delay can't be cancelled), getting error:
http://jsfiddle.net/x1Lveooy/12/

A: *

*$('*').tooltip() instead of $(document).tooltip()

*Use $(this).tooltip().tooltip('close'); in combination with clearing title attribute and resetting it on blur

Fixed fiddle: http://jsfiddle.net/x1Lveooy/16/
$(document).ready(function () {
    //key point in fix: '*' instead of document
    initTooltip('*');
});
$(document).on({
    focus: function (e) {
        $('.ui-tooltip').hide();
        tempTitle = $(this).attr("data-title");
        $(this).attr("data-title", "");
        //key point in fix: close works even if tooltip isn't showing yet
        $(this).tooltip().tooltip('close');
    },
    blur: function (e) {
        $(this).attr("data-title", tempTitle);
    }
}, '.element1, .element2, #box');

function initTooltip(target) {
    $(target).tooltip({
        track: true,
        content: function () {
            return $(this).attr("data-title");
        },
        show: {
            delay: 1500
        },
        open: function (event, ui) {
            setTimeout(function () {
                $(ui.tooltip).fadeTo(1000, 0);
            }, 5000);
        }
    });
}


text:
Q: Does matter to match furniture built with the same kind of wood?
Possible Duplicate:
Does the kind of wood matter to build furnitures ?

will a room be more "attractive" or efficient if all furnitures are built in oak ?
Will a room with furnitures built in different kind of wood matters ?

A: The effect of materials on the dwarves is completely individual. There is no room score for that. For those effects, see my answer here.


text:
Q: Laravel Cleaner Url issue in ubuntu, How to fix it? I'm Using laravel latest version. I just added a new route but it's not working.
    Route::get('/about',function()
{
   return View::make('about');
});

When i type localhost/index.php/about it starts working.
So i checked some articles they suggest to edit .htaccess and i did the same.
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

but it again didn't work so did some changes in my config file. This is the content of my config file.
    <VirtualHost *:80>
        ServerName sar.dev
        DocumentRoot "/var/www/laravel/public"
        <Directory "/var/www/laravel/public">
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
        </Directory>
    </VirtualHost>

This method also failed. I'm working on ubuntu 13.10. Is there any other way to fix it ?

A: To go with my comment. I noticed you were using a modified .htaccess that is not the default for laravel.
Give the laravel default .htaccess file a try with the / next to the index.php part.
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ /index.php [L]
</IfModule>

This solution has helped me when coming across a similar error where the site would not work when going to /route and had to use /index.php/route as you are.


text:
Q: Finding synonyms in DFS Giving a path to a file on the network, for example:
\\server1\folder\file

I'm trying to find all the other paths (in my network) pointing to the exactly same file (not a copy of it, but a replicate or another mapping of it):
\\server2\folder2\file, \\server3\folder3\file

As far as i understand, all the information required is stored in the domain's active directory - i'm trying to figure out how to extract it, using a tool\script.

A: Have you try with powershell with something like this :
$folders=get-dfsnfolder -path "\\your_dfs\path\*"
$points=foreach ($folder in $folders){get-dfsnfoldertarget -path $folder.path }

write-host $points


text:
Q: Variable not updating after sending data to cloud servers I have been having trouble with updating this global variable that is an array of strings. This rfDataArray is supposed to be updated as the rf data is coming in from another device. Now, when I have tested this without sending anything over to the cloud servers, it works (the rfDataArray gets updated as frequently as the data is being sent) however as soon as I start sending the data, the rfDataArray array seems to be stuck at the initial array and does not get updated ever again...
import httplib, urllib
import time, sys
import serial

key = 'MY_API_KEY'
rfDataArray = []
rfWaterLevelVal = 0

ser = serial.Serial('/dev/ttyUSB0',9600)

def rfWaterLevel():
    global rfWaterLevelVal
    global rfDataArray

    rfDataArray = ser.readline().strip().split()
    print 'incoming: %s' %rfDataArray
    if len(rfDataArray) == 5:
        rfWaterLevelVal = float(rfDataArray[4])
        print 'RFWater Level1: %.3f cm' % (rfWaterLevelVal)

def sendRFWaterlevel():
    params = urllib.urlencode({'field1':rfWaterLevelVal, 'key':key})
    headers = {"Content-type": "application/x-www-form-urlencoded",
               "Accept": "text/plain"}
    conn = httplib.HTTPConnection("api.thingspeak.com:80", timeout = 5)
    conn.request("POST", "/update", params, headers)
    print 'RFWater Level2: %.3f cm' % (rfWaterLevelVal)
    response = conn.getresponse()
    print response.status, response.reason
    data = response.read()
    conn.close()

while True:
    try:
        rfWaterLevel()
        time.sleep(1)
        sendRFWaterlevel()
        time.sleep(3)
    except KeyboardInterrupt:
        print "caught keyboard interrupt"
        sys.exit()

I need to update therfDataArray variable (so the rfWaterlevelVal is updated to send over to the cloud servers).

A: You are running into a race condition. The array is trying to store values before the cloud can send it back. You need to do the operations asynchronously. One solution is to use the callback methods from Python multithreading. Alternatively, you could use some 'locking' mechanism and not execute the rest of the program till you get a response from the cloud.


text:
Q: After running git revert commitizen doesn't create new tag After running git revert cz bump doesn't create a new tag.
Output = increment detected: None
It should create a new tag.
Commitizen version 2.18.0
Python 3.8


text:
Q: Order an Array by Value of Key Here is my current code to add to the array:
foreach ($query->result() as $exp) {
    $activities[] = array('type' => 'level', 'exp' => $exp->exp, 'timestamp' => $badge->timestamp);
}

How would I go about sorting this array according to the value of the 'timestamp' key?

A: You would need to use usort which will let you sort the array using a user-defined function.
http://www.php.net/manual/en/function.usort.php
Example:
<?php
function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

A: I would use the function array-multisort for the actual sorting, also I would store the values differently:
foreach ($query->result() as $exp) {
  $activities[$badge->timestamp] = array('type' => 'level',... );
}
array_multisort($activities, SORT_ASC, $array);

http://php.net/manual/en/function.array-multisort.php


text:
Q: The following C++ Code relate to pointer and reference I have seen this code
  void path(
    const char * p);
  » more...

void path(
    const std::string & p);
  » more...

Can I do the following modification, basically reversing the * and &.
void path(
    const char & p);
  » more...

void path(
    const std::string * p);
  » more...

A: The first is passing an array of characters as a pointer to the first one. This is how strings are conventionally handled in C, and you sometimes see it in C++ due to the common heritage of the two languages. While you could pass a reference and carefully document that it's actually supposed to be an array, it would be confusing to anyone used to that convention.
The second is passing a single object by reference. While you could emulate the reference with a pointer, this would be (mildly) confusing to anyone used to the reference semantics of C++.

A: You should understand what the function is trying to do before changing.
Lets see what happens when you change void path(const char * p); to void path(const char &p);
Probably the reason a char * is passed could be that the function needs to access an array of characters. And if you change the parameter to char &p, then the function only accepts a char by reference.

A: yes you can. but you must be careful with the use of . and -> in these function
and keep in mind that the meaning compelitly changes


text:
Q: Can cURL accept connection request and verify certificates? I wonder is there any possibility that cURL to accept a connection request from the server and verify certificates, requested ports by listening on some port?. If in a case of success, receives data from the server until the server closes the connection.
Backgound : C++11
Thanks
Uma


text:
Q: Which is better ConcurrentHashMap or Synchronized Hash Map in this case? I am writing a utility class which uses map as a cache store. Now since its going to be used in multithreaded environment. I came up with usage of either synchronized hashmap while doing put operation or ConcurrentHashMap( using putIfAbsent) which I am still confused about if it is prone to override of key-value(though key-value is unique in my case)  and both have there pros and cons. So I am not able to decide. There might be some other cache store which i can use for this purpose, do suggest but I am more interested in knowing which is to be used CHM or Hashmap if this is the only option.
In Comments of program is CHM usage which I thought else I have used HashMap.
public final class DateTime {

  private static final Map<CountryLanguage, Locale> localeMap = new HashMap<>();

 /*private static final Map<CountryLanguage, Locale> localeMap = new ConcurrentHashMap<>();*/

public static String getDateTime1(String pattern, LocalDateTime localDateTime, String language,
      String country) {
    if (language == null || language.isEmpty()) {
      throw new NullPointerException("Language cannot be null or empty");
    }
    CountryLanguage countryLanguage = new CountryLanguage(language, country);
    if (!localeMap.containsKey(countryLanguage)) {
      synchronized (localeMap) {
        // Putting double lock
        if (!localeMap.containsKey(countryLanguage)) {
          for (Locale locale : Locale.getAvailableLocales()) {
            if (locale.getLanguage().equals(language) && locale.getCountry().equals(country)) {
              localeMap.put(new CountryLanguage(language, country), locale);
            }
          }
        }
      }
    }
      /*for (Locale locale : Locale.getAvailableLocales()) {
        if (locale.getLanguage().equals(language) && locale.getCountry().equals(country)) {
          localeMap.putIfAbsent(new CountryLanguage(language, country), locale);
        }
    }*/
    Locale locale = localeMap.get(countryLanguage);
    if (locale == null) {
      locale = Locale.ROOT;
    }
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern, locale);
    return localDateTime.format(dateTimeFormatter);
  }

NOTE:

*

*I have an inner class CountryLanguage which has String country,String language as member variable and both hashCode and equals methods have been overridden.

Edit1: I am not making whole map as synchronized I am just using synchronized on map while put operation. And I am using double check to make sure no two key-value exists

A:
Synchronized HashMap:

*

*Each method is synchronized using an object level lock. SO the get
  and put methods on synchMap acquire a lock.

*Locking the entire collection is a performance overhead. While one
  thread holds on to the lock, no other thread can use the collection.

  ConcurrentHashMap: (was introduced in JDK 5)

*

*There is no locking at the object level,The locking is at a much
  finer granularity. For a ConcurrentHashMap, the locks may be at a
  hashmap bucket level.

*The effect of lower level locking is that you can have concurrent
  readers and writers which is not possible for synchronized
  collections. This leads to much more scalability.

*ConcurrentHashMap does not throw a ConcurrentModificationException
  if one thread tries to modify it while another is iterating over it.

So, I recommend you ConcurrentHashMap, it won't block all the "cahce" all the time.
If you want more info HashMap vs ConcurrentHashMap
EDIT:
Some other post about this:
Is ConcurrentHashMap totally safe?

A: I would implement this using a ConcurrentHashMap:
public final class DateTime
{
    private static final ConcurrentMap<CountryLanguage, Locale> localeMap = new ConcurrentHashMap<>();

    public static String getDateTime1(String pattern, LocalDateTime localDateTime, String language, String country)
    {
        if (language == null || language.isEmpty()) {
            throw new NullPointerException("Language cannot be null or empty");
        }

        CountryLanguage countryLanguage = new CountryLanguage(language, country);

        // See if it is already there
        Locale locale = localeMap.get(countryLanguage);
        if (locale == null) {
            // It's not there (probably), so look it up
            Local candidate = null;
            for (Locale l : Locale.getAvailableLocales()) {
                if (l.getLanguage().equals(language) && l.getCountry().equals(country)) {
                    candidate = l;
                    break;
                }
            }

            // If we found it, put it in the map
            if (candidate != null) {
                // It's possible that another thread beat us here, so use putIfAbsent()
                // and check the return value
                locale = localeMap.putIfAbsent(countryLanguage, candidate);
                if (locale == null) {
                    locale = candidate;
                }
            }
        }

        if (locale == null) {
            locale = Locale.ROOT;
        }

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern, locale);
        return localDateTime.format(dateTimeFormatter);
    }
}

This is thread-safe and requires no external synchronization.


text:
Q: How to logout G+ plus sigin from different Activity? I have implemented his code working on successfully on the same activity, but how can I log out from another Activity.
To refer full code: https://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/
private void signOut() {
    Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    updateUI(false);
                }
            });
}

A: I did the following in one of my project...
public class MainActivity extends AppCompatActivity {

    private GoogleSignInClient mGoogleSignInClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Configure Google Sign In
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.signout) {
            //DialogUtils.getInstance().
            signOut();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void signOut() {

        // Google sign out
        mGoogleSignInClient.signOut().addOnCompleteListener(this,
                new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                       startActivity(new Intent(MainActivity.this,LoginActivity.class));
                        finish();
                    }
                });
    }
}

A: on second activity create
public GoogleActivity google_activity;

on Google Activity initialize
SecondActivity.google_activity=this;

Then you can call
google_activity.signout();


text:
Q: Location tracking by Flutter app in terminated mode We are developing Flutter application that should track geography location and post it to backend server.
Actually We're using our custom tracking plugin with native code with CoreLocation
This tracking should occur in all modes (foreground and background) and works fine
It sends received location to Flutter channel and Dart code receives it and posts to backend (this part is pure dart code).
But additional requirement is: tracking should occur when it's terminated.
For Signing&Capabilities we set Location updates, background fetch and notification.
Info.plists contains following modes
    <key>UIBackgroundModes</key>
    <array>
        <string>fetch</string>
        <string>location</string>
        <string>remote-notification</string>
    </array>

We also added text for keys
NSLocationAlwaysAndWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
NSLocationWhenInUseUsageDescription

We are initialise CLLocationManager and successfully requesting manager.requestAlwaysAuthorization() and do locationManager.startMonitoringSignificantLocationChanges()
Similar code on "pure" iOS application without Flutter works fine. For example on simulator I see it writing locations into file even when application is terminated.
For Flutter application it works fine in background but it stops when I terminate the application.
My understanding -- it still receives
locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) receives locations
But it can not send it to Flutter channel
So our question is:

*

*Is it possible at all? Does Flutter supports it?

*If yes -- what additional steps we need to do to re-initialise Flutter engine when receives new location in such terminated mode.

Thanks


text:
Q: Table doesn't fit to page width properly The table produced by this code always goes out off the width of my page. I want the table to fit within the width of the page. I tried giving extra \\ in between but it made it worse only.
\begin{tabular}{|l|l|}
\hline
 LocationProvider & Description \\
 \hline
 network & Uses the mobile network or WI-Fi to determine the best location.Might have a higher precision in closed rooms than GPS. \\
\hline
gps & Use the GPS receiver in the Android device to determine the best location via satellites. Usually better precision than network. \\
\hline
passive & Allows to participate in location of updates of other components to save energy \\
\hline
\end{tabular}

The result:

A: It looks like a job for package tabularx:
\documentclass{article}
\usepackage{tabularx}

\begin{document}
\noindent
\begin{tabularx}{\linewidth}{|l|X|}
\hline
 LocationProvider & Description \\
 \hline
 network & Uses the mobile network or WI-Fi to determine the best
 location.Might have a higher precision in closed rooms than GPS. \\
\hline
gps & Use the GPS receiver in the Android device to determine the best
location via satellites. Usually better precision than network. \\
\hline
passive & Allows to participate in location of updates of other components
to save energy \\
\hline
\end{tabularx}
\end{document}

A: "l" means left aligned so everything in the cell comes out in a single row and if you have a lot of material you end up exceeding the available width on your page.
Alternatives:

*

*use p{<width>} on one or more columns to have the text inside wrap the the specified <width>

*or use the package tabularx which allows you to get the column width for wrapping columns be determined automatically (see package documentation how to do this)

*in some cases using a slightly smaller font for the table might be a choice, but in general I would not recommend this.


text:
Q: HTML5 Page Structure: Section and Article correct placement I'm trying to build correct structure for HTML Page.
My question is about article and section tags implementation.
article tag inside section tag or section tag inside article tag. Which one should be correct?

Here is my structure

A: This article contains some useful information:
https://iandevlin.com/blog/2011/04/html5/html5-section-or-article/
There's no reason you can't have a section, in an article, which is itself inside a section, so long as that best describes the content on which you're working.

A: Both are correct. It depends on the incident you are going to apply it.
Read below links to understand it's usage,
Article - https://www.w3schools.com/tags/tag_article.asp
Section - https://www.w3schools.com/tags/tag_section.asp
Cheers !!!


text:
Q: How can I find memory leak in android app I'm developing an android kind-of-gallery-app with Firebase, so I will have plenty of images. I know that I need to be careful about memory management.
When I was searching how to find memory leak in android apps, I came across with LeakCanary. It looks really great, so I used in my app.
Basically my app has 3 fragments, which are Drawer, ProductGrid and ProductDetail. Sometimes LeakCanary says that I have a memory leak in ProductGrid, but I couldn't find it! Usually, adapters or static methods or listeners could cause memory leak because of Context object, but my knowledge is not sufficient to say 'aah that's because of here'
Here are the classes. Where is the leak?(If you suggest me anything that I can improve my code or approach, I would be appreciated!)
Because of body character limit, I put the link leak canary log file.
How I suspect there is a memory leak
First of all, LeakCanary shows a dialog and logs the dump. Second thing is, when I click on an item in drawer, in grid and in detail like 15 times(respectively), memory usage increases. It starts with 18M, increases 22M-23M after showing 3 images(normal). Then it heads up to 29M-30M after clicking on 15 times. If you click on around 30-40, memory usage increases 34M-35M
Edit: I've just figured out that, if I open and close drawer, memory usage increases 0.05M everytime, so one time opening and closing drawer costs 0.1M! What am i missing?
Main.java
public class Main extends ActionBarActivity implements DrawerListener {

  private Toolbar mToolbar;

  private Drawer drawerFragment;
  private HomePage homeFragment;

  private FragmentHelper fh = new FragmentHelper();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    if (homeFragment == null)
      homeFragment = new HomePage();

    if (savedInstanceState == null) {
      mToolbar = (Toolbar) findViewById(R.id.toolbar);
      setSupportActionBar(mToolbar);
      getSupportActionBar().setDisplayShowHomeEnabled(true);

      drawerFragment = (Drawer)
            getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
      drawerFragment.setUp(R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
      drawerFragment.setDrawerListener(this);
      drawerFragment.setRetainInstance(true);

      displayView(null);
    }
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_home) {
      getSupportActionBar().setTitle(getString(R.string.app_name));

      fh.replace(getSupportFragmentManager(), homeFragment, R.id.container_body);
      return true;
    }

    if (id == R.id.action_settings) {
      return true;
    }

    if (id == R.id.action_search) {
      Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
      return true;
    }

    return super.onOptionsItemSelected(item);
  }

  @Override
  public void onDrawerItemSelected(View view, int position, Category category) {
    displayView(category);
  }

  private void displayView(Category category) {
    if (category != null) {
      getSupportActionBar().setTitle(category.getName());

      ProductGrid gridFragment = new ProductGrid();
      Bundle args = new Bundle();
      args.putString(Product.CATEGORY_ID, category.getId());
      gridFragment.setArguments(args);

      fh.replace(getSupportFragmentManager(), gridFragment, R.id.container_body);
    } else {
      getSupportActionBar().setTitle(getString(R.string.app_name));

      fh.replace(getSupportFragmentManager(), homeFragment, R.id.container_body);
    }
  }
}

Drawer.java
public class Drawer extends Fragment {

  private Firebase mFirebase;
  private Alert alert;

  private RecyclerView recyclerView;
  private View containerView;
  private DrawerLayout mDrawerLayout;
  private ActionBarDrawerToggle mDrawerToggle;
  private DrawerListener drawerListener;

  private DrawerAdapter mAdapter;

  private List<Category> mCategories;

  public Drawer() {
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    alert = new Alert(getActivity().getApplicationContext());
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View layout = inflater.inflate(R.layout.drawer, container, false);

    mCategories = new ArrayList<>();

    mAdapter = new DrawerAdapter(mCategories);

    recyclerView = (RecyclerView) layout.findViewById(R.id.drawer_list);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
    recyclerView.setItemAnimator(new SlideInOutLeftItemAnimator(recyclerView));
    recyclerView.setAdapter(mAdapter);

    mFirebase = new Firebase(getActivity().getResources().getString(R.string.firebase_ref))
          .child(FirebaseRoots.CATEGORY);

    Query query = mFirebase.orderByChild(Category.PRIO);

    query.addChildEventListener(new ChildEventListener() {
      @Override
      public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        Category model = dataSnapshot.getValue(Category.class);
        model.setId(dataSnapshot.getKey());
        mCategories.add(model);

        recyclerView.scrollToPosition(mCategories.size() - 1);
        mAdapter.notifyItemInserted(mCategories.size() - 1);
      }

      @Override
      public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        Category model = dataSnapshot.getValue(Category.class);
        model.setId(dataSnapshot.getKey());

        int index = -1;
        for (int i = 0; i < mCategories.size(); i++) {
          if (mCategories.get(i).getId().equals(model.getId())) {
            index = i;
            break;
          }
        }
        mCategories.set(index, model);

        recyclerView.scrollToPosition(0);
        mAdapter.notifyItemChanged(index);
      }

      @Override
      public void onChildRemoved(DataSnapshot dataSnapshot) {
        Category model = dataSnapshot.getValue(Category.class);
        model.setId(dataSnapshot.getKey());

        int index = -1;
        for (int i = 0; i < mCategories.size(); i++) {
          if (mCategories.get(i).getId().equals(model.getId())) {
            index = i;
            break;
          }
        }
        mCategories.remove(index);

        recyclerView.scrollToPosition(0);
        mAdapter.notifyItemRemoved(index);
      }

      @Override
      public void onChildMoved(DataSnapshot dataSnapshot, String s) {

      }

      @Override
      public void onCancelled(FirebaseError firebaseError) {
        alert.show(firebaseError.toString());
      }
    });

    recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity().getApplicationContext(),
          recyclerView, new ClickListener() {
      @Override
      public void onClick(View view, int position) {
        Category category = mCategories.get(position);
        drawerListener.onDrawerItemSelected(view, position, category);
        mDrawerLayout.closeDrawer(containerView);
      }

      @Override
      public void onLongClick(View view, int position) {

      }
    }));

    return layout;
  }

  public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
    containerView = getActivity().findViewById(fragmentId);
    mDrawerLayout = drawerLayout;
    mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
      @Override
      public void onDrawerOpened(View drawerView) {
        super.onDrawerOpened(drawerView);
        getActivity().invalidateOptionsMenu();
      }

      @Override
      public void onDrawerClosed(View drawerView) {
        super.onDrawerClosed(drawerView);
        getActivity().invalidateOptionsMenu();
      }

      @Override
      public void onDrawerSlide(View drawerView, float slideOffset) {
        super.onDrawerSlide(drawerView, slideOffset);
        toolbar.setAlpha(1 - slideOffset / 2);
      }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);
    mDrawerLayout.post(new Runnable() {
      @Override
      public void run() {
        mDrawerToggle.syncState();
      }
    });
  }

  public void setDrawerListener(DrawerListener listener) {
    this.drawerListener = listener;
  }

}

ProductGrid.java
public class ProductGrid extends Fragment implements ChildEventListener{

  private Firebase mFirebaseRef;
  private Alert alert;

  private RecyclerView recyclerView;
  private GridAdapter mAdapter;

  private String categoryId;
  private ArrayList<Product> mProducts;

  private FileSystem fs;

  public ProductGrid() {
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.categoryId = getArguments().getString(Product.CATEGORY_ID);

    this.alert = new Alert(getActivity().getApplicationContext());
    this.fs = new FileSystem(getActivity().getApplicationContext());
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View layout = inflater.inflate(R.layout.grid, container, false);
    fieldInitialize(layout);

    mProducts = new ArrayList<>();
    mAdapter = new GridAdapter(mProducts, getActivity().getApplicationContext());

    recyclerView.addItemDecoration(new MarginDecoration(getActivity()));
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
    recyclerView.setAdapter(mAdapter);

    mFirebaseRef = new Firebase(getActivity().getResources().getString(R.string.firebase_ref))
          .child(FirebaseRoots.PRODUCT);

    Query query = mFirebaseRef.orderByChild(Product.CATEGORY_ID).equalTo(categoryId);
    query.addChildEventListener(this);

    recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
      @Override
      public void onClick(View view, int position) {
        ProductDetail detailFragment = new ProductDetail();

        Bundle args = new Bundle();
        args.putSerializable("product", mProducts);
        args.putInt("position", position);
        detailFragment.setArguments(args);

        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.container_body, detailFragment);
        transaction.addToBackStack(null);
        transaction.commit();
      }

      @Override
      public void onLongClick(View view, int position) {

      }
    }));

    return layout;
  }

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
  }

  @Override
  public void onDetach() {
    super.onDetach();
  }

  public void fieldInitialize(View layout) {
    recyclerView = (RecyclerView) layout.findViewById(R.id.product_grid_layout);
  }

  @Override
  public void onChildAdded(DataSnapshot dataSnapshot, String s) {
    Product model = dataSnapshot.getValue(Product.class);
    model.setId(dataSnapshot.getKey());
    mProducts.add(model);

    if (!fs.getFileNames().contains(model.getName() + FileExt.JPG.get())) {
      fs.writeImage(model.getName(), ImageUtil.base64ToBitmap(
            StringUtil.getBase64FromUrl(model.getImageData().getDataUrl())));
    }

    Collections.sort(mProducts);

    recyclerView.scrollToPosition(0);
    mAdapter.notifyItemInserted(mProducts.size() - 1);
  }

  @Override
  public void onChildChanged(DataSnapshot dataSnapshot, String s) {
    Product model = dataSnapshot.getValue(Product.class);
    model.setId(dataSnapshot.getKey());

    fs.writeImage(model.getName(), ImageUtil.base64ToBitmap(
          StringUtil.getBase64FromUrl(model.getImageData().getDataUrl())));

    int index = -1;
    for (int i = 0; i < mProducts.size(); i++) {
      if (mProducts.get(i).getId().equals(model.getId())) {
        index = i;
        break;
      }
    }
    mProducts.set(index, model);

    recyclerView.scrollToPosition(0);
    mAdapter.notifyItemChanged(index);
  }

  @Override
  public void onChildRemoved(DataSnapshot dataSnapshot) {
    Product model = dataSnapshot.getValue(Product.class);
    model.setId(dataSnapshot.getKey());

    fs.deleteImage(model.getName());

    int index = -1;
    for (int i = 0; i < mProducts.size(); i++) {
      if (mProducts.get(i).getId().equals(model.getId())) {
        index = i;
        break;
      }
    }
    mProducts.remove(index);

    recyclerView.scrollToPosition(0);
    mAdapter.notifyItemRemoved(index);
  }

  @Override
  public void onChildMoved(DataSnapshot dataSnapshot, String s) {
  }

  @Override
  public void onCancelled(FirebaseError firebaseError) {
    alert.show(firebaseError.toString());
  }

  @Override public void onDestroy() {
    super.onDestroy();
    RefWatcher refWatcher = AcarsanApp.getRefWatcher(getActivity());
    refWatcher.watch(this);
  }
}

ProductDetail.java
public class ProductDetail extends Fragment {

  private FullScreenImageAdapter adapter;
  private ViewPager viewPager;

  private ArrayList<Product> products;
  private int position;

  public ProductDetail() {
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    products = (ArrayList<Product>) getArguments().getSerializable("product");
    position = getArguments().getInt("position");
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.product_detail, container, false);

    viewPager = (ViewPager) view.findViewById(R.id.product_gallery);
    adapter = new FullScreenImageAdapter(getActivity().getApplicationContext(), products);

    viewPager.setAdapter(adapter);
    viewPager.setCurrentItem(position);

    return view;
  }

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
  }

  @Override
  public void onDetach() {
    super.onDetach();
  }
}

FileSystem
public class FileSystem {

  private Context mContext;

  public static final String PHOTOS_FOLDER = "photos";

  public FileSystem(Context mContext) {
    this.mContext = mContext;
  }

  public void writeImage(String name, Bitmap bitmap) {
    String filename = name + FileExt.JPG.get();

    File dir = mContext.getDir(PHOTOS_FOLDER, Context.MODE_PRIVATE);
    File fileWithinDir = new File(dir, filename);
    FileOutputStream outputStream;

    try {

      outputStream = new FileOutputStream(fileWithinDir);
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
      outputStream.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public List<String> getFileNames() {
    List<String> fileNames = new ArrayList<>();

    File file = mContext.getDir(PHOTOS_FOLDER, Context.MODE_PRIVATE);
    File[] files = file.listFiles();
    for (File f : files) {
      fileNames.add(f.getName());
    }
    return fileNames;
  }

}

ImageUtil
public class ImageUtil {

  public static Bitmap base64ToBitmap(String encodedImage) {
    if (encodedImage == null)
      return null;

    byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
    return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
  }
}


text:
Q: Target negated selectors using .on() for swipe events in jQM Background:
I am developing a navigation class for swipe events in jquery-mobile. The class reads a tree-like sitemap from a JSON structure and assigns swipeleft and swiperight events to navigate through a top level nodes in the tree. It assigns swipedown and swipeup event handlers to children of each node, and swipeleft and swiperight handlers to siblings of those children and so on for infinite levels. I'm only attaching these handlers to the currently loaded page, identified by $.mobile.activePage and I'm using $(document).one() function to ensure these handlers are never bound twice. The class reads the pageMap structure during the $(document).bind('pagebeforeshow') hook.
Below is some draft sample code for handling swipeleft and swiperight in a single level of the tree:
/** @todo
 *  tidy up the next 2 conditionals into a single function and a mapping object
 *  that can handle left, right, up and down
 */
//if this isn't the first page
if(page.prev !== undefined) {
    //attach the swipe handler to the previous page
    Utils.logger('log', 'Binding a swiperight to ' + page.id);
    $(page.id).one('swiperight', 'div.content', function(event) {
        Utils.logger('log', 'Navigating to previous slide: ' + page.prev.url); //debug
        $.mobile.changePage(
            page.prev.url, {
                transition: 'slide',
                direction: 'reverse'
            }
        );
    });
    //debugging
    Utils.logger('log', 'Route: ' + page.prev.url + ' <== ' + page.url);
}

//if this isn't the last page
if(page.next !== undefined) {
    //attach the swipe handler to the previous page
    Utils.logger('log', 'Binding a swiperight to ' + page.id);
    $(page.id).one('swipeleft', 'div.content', function(event) {
        Utils.logger('log', 'Navigating to next slide: ' + page.next.url); //debug
        $.mobile.changePage(
            page.next.url, {
                transition: 'slide'
            }
        );
    });
    //debugging
    Utils.logger('log', 'Route: ' + page.url + ' ==> ' + page.next.url);
}

 In case you're wondering, Utils.logger is just a simple wrapper class for console
The Problem:
My problem is that the pages in this tree can contain many different types of elements. Some are simple and look much like a photo gallery slide show. I have no problems with those kind of pages. Other pages contain forms and nested slideshows. So there might be a DIV in my page which handles swipe events to create a slideshow inside of a slideshow - let's ignore that for now and focus on somethinge even more trivial: I have in my form things like slider controls. Sliding a slider on a touch screen is equivalent to swiping a touch screen... I think you know where this is going...! If I slide my slider in the form, I trigger a swipe event which changes the page in my navigation system... DOH!
How can I ensure that my page navigation swipes only target my div.content, and ignores all the things mentioned above? I've tried using the selectors parameter of .on(), but I think what I am looking for is a way to negate/not those selectors?
Here is an example of my markup (for this example it is stripped down to the essentials - but please imagine a large form with multiple fieldsets):

        <form action="#" method="get">

                Would you like more info?
                <select name="slider2" id="more-info" data-role="slider">
                    <option value="off">No</option>
                    <option value="on">Yes</option>
                </select>

                Please rate this presentation out of 10:
                <input type="range" name="slider" id="slider" value="5" min="0" max="10" data-highlight="true"  />

                <fieldset class="ui-grid-a">

<button type="reset" id="reset" data-theme="d" data-icon="delete" data-iconpos="left">Cancel</button>

<button type="submit" data-theme="b" data-icon="check" data-iconpos="right" >Submit</button>

                </fieldset>

        </form>

So, to clarify and summarise:
I'm looking for a way to target div.content with swipe events, but to ignore any swipe event that occurs on a child node of <form> (not the <form> itself) plus any swipe event on a collection of divs which have their own swipe events - all of which I can add easily add a class to like: .ignorePageSwipe. Oh, and of course it should not be a performance hog!!!


text:
Q: Reverse string recursive function loop Where is the break criteria in this recursive function? Why doesn't this go on endlessly reversive characters of the string?
print('Enter your input:')
n = input()

def reverse(s):
    if len(s) == 0:
        return s
    else:
        return reverse(s[1:]) + s[0]

print (reverse(n))

Enter your input:
Something
gnihtemoS

A: When the String is of length 0, you make a non-recursive return, causing the recursive calls on the stack to return until you get all the way to the bottom of them.

A: A recursive function terminates if it satisfies two properties:

*

*There must be a "base case" which is solved without any recursive calls, and

*Each recursive call must be on an input which is "closer" to the base case than before.

In this recursive function, the base case is the empty string; it is handled by return s without making any recursive calls. The recursive call is on the string s[1:] which is one character shorter than s, so it is "closer" to the empty string. Therefore the function satisfies both of these properties, so it always terminates.


text:
Q: Conserved quantity for system of Stochastic Differential Equations I'm considering the set of SDEs (in the sense of Ito)
$\begin{align*} \mathrm d x &= -yx \mathrm d t+ x^2 \mathrm d B_t \\ \mathrm d y &= -y^2 \mathrm d t + xy \mathrm d B_t\end{align*}$
where the two Brownian motions are identical (i.e there is just one noise driving the dynamics).
Now as can be seen easily,
$y\cdot \mathrm d x  - x\cdot \mathrm d y = 0$ and then by Ito's formula, after defining $w = \frac{x}{ y}$,
$\mathrm d w = \frac{\mathrm d x}{y} - \frac{x\mathrm d y}{y^2} + \frac{1}{2} \cdot (-\frac{1}{y^2})(2\mathrm d x\cdot \mathrm d y) + \frac{1}{2} \frac{2x}{y^3}(\mathrm d y) = 0$
This means that the ratio of the processes $x$ and $y$ is a constant.
Now the problem I actually have is modified by a factor of 2:
$\begin{align*} \mathrm d x &= -\tilde yx \mathrm d t+ x^2 \mathrm d B_t \\ \mathrm d \tilde y &= - 2 \tilde y^2 \mathrm d t + 2x\tilde y \mathrm d B_t\end{align*}$
Structurally, this new set of SDEs looks very similar to the one above, but I can't find a process like in the case above which has a similar "good" property (like the ratio being constant). Is there a trick to this I'm missing?

A: Actually, I got it: The quantity $\frac{x}{\sqrt{y}}$ is not constant, but at least
$$\mathrm d (x y^{-1/2}) = \frac{1}{2}x^3y^{-1/2} \mathrm d t$$ which is a nice smooth quantity.


text:
Q: I don't see my implicit casting I have the following method:
def unify_np_array(A):
    '''Set every nonzero element in a numpy array to 1'''
    nonzero = A > 0
    A[nonzero] /= A[nonzero]
    return A

Which I call with the following test code:
def test_small_np(self):
    r = np.array([[3, 0], [0, 2]])
    DataConverter.unify_np_array(r)
    e = np.array([[1, 0], [0, 1]])
    np.testing.assert_array_equal(r, e)

The unit test succeeds, but I receive the following Warning:
DeprecationWarning: Implicitly casting between incompatible kinds.
In a future numpy release, this will raise an error.
Use casting="unsafe" if this is intentional.
  A[nonzero] /= A[nonzero]

However, I don't see which incompatible kinds I am casting. I divide a subsection of a numpy array with itself. Can anyone pinpoint the cast I am implicitly making?


text:
Q: How to turn off anti-aliasing on an embedded font I have a pixel font from www.fontsforflash.com. I have embedded it using flex then loaded the swf in flash CS4 to make it available. But its very blurry and I can find a way to turn off anti-aliasing in as3.
Its the right size and placed with whole numbers. The reason I have embedded this method is because I don't want to load an entire font library.
Is there a way I can turn off anti-aliasing or is there a better way to embed my font?
Thanks

A: when you embed your font make sure you select the "bitmap text" check box in the Font Symbol Properties panel (in Flash) to insure the font has no anti-alias.
i don't recall if CS4 had this option, but in Flash CS5 you can select View > Snapping > Snap To Pixels so that all of your placed assets will have rounded x and y coordinates.  it will do the same thing as the code posted by PatrickS.

A: If it's a pixel font , don't forget that the x & y values must be integers. You'll probably need to do something like this.
textfield.x = Math.round( whateverX );
textfield.y = Math.round( whateverY );

and probably the same thing for the parent!


text:
Q: Using KDE Wallet in fluxbox /openbox or other "light" window managers I have stored chromium passwords in kwalled5, from KDE.
I'd like to continue using wallet in fluxbox.
I tried while in fluxbox to start kwalletd5 then run chromium – the same way as it was started in KDE, but that's not enough as passwords are not loaded.
kwalletd5 &
chromium --password-store=detect &

Any idea what next needs to be started in order to use kwallet from fluxbox / openbox?


text:
Q: Pandas dataframe hierarchical index columns - Scale slice of dataframe I have a pandas dataframe in which I have both continuous and discrete data. I'm separating the continous from the discrete data by using an hierarchical column index to process them in a different way.
Let's assume the following dataframe:
At first I'm building an hierarchical index, that I can use when I then initialize the empty dataframe. Then I'm filling the sample dataframe with continous and discrete data.
my_multiindex = pd.MultiIndex(levels=[['discrete', 'continuous'],[]],
                              labels=[[],[]],
                              names=['Datatype', 'Data'])

df = pd.DataFrame(columns=my_multiindex,index=pd.date_range('20180101 9:01:00',freq='s',periods=50))

df.loc[:,('continuous', 'data1')] = np.random.uniform(-50, 100, 50)
df.loc[:,('continuous', 'data2')] = np.random.uniform(-500, 800, 50)
df.loc[:,('continuous', 'data3')] = np.random.uniform(-300, 200, 50)

df.loc[:,('discrete', 'data4')] = np.random.randint(0, 2, 50)
df.loc[:,('discrete', 'data5')] = np.random.randint(0, 2, 50)
df.loc[:,('discrete', 'data6')] = np.random.randint(0, 2, 50)

The resulting dataframe looks like this:
Datatype            continuous                         discrete
Data                     data1       data2       data3    data4 data5 data6
2018-01-01 09:01:00  -6.406635  208.992257    1.845863        0     1     0
2018-01-01 09:01:01  80.084693  264.907285  190.628975        0     0     0
2018-01-01 09:01:02  74.734951  -39.456532 -132.749219        0     1     0
2018-01-01 09:01:03  55.703297  413.700692  147.826342        1     0     0
2018-01-01 09:01:04  25.797465 -290.116077 -250.018855        0     0     1

Then I want to use StandardScaler to scale the continous data in the dataframe. The discrete data I'm just trying to copy to the new dataframe df_scaled.
df_scaled = pd.DataFrame(columns=my_multiindex, index=df.index)
scaler = StandardScaler()
scaler.fit(df.loc[:,'continuous'])

df_scaled.loc[:,'discrete'] = df.loc[:,'discrete']
df_scaled.loc[:,'continuous'] = pd.DataFrame(scaler.transform(df.loc[:,'continuous']))

However, this is not working. The new dataframe df_scaled is still empty after running this. What am I doing wrong?

A: I'm not really sure why your approach is not working. I guess Multiindexes are still kind of experimental in pandas.
However there is a simple workaraound:
df_scaled = df.copy()
df_scaled.loc[:,'continuous'] = scaler.transform(df.loc[:,'continuous'])

If you want to know in more detail why your approach is not working maybe you should consider to post this on pandas github issue tracking and ask if this is a bug or feature.


text:
Q: Abnormal main.m crash In my iOS app, I keep getting crash reports like this one.
0   libsystem_kernel.dylib 0x000000018d805014 __pthread_kill + 4
1   libsystem_c.dylib 0x000000018d7799c4 abort + 136
2   libc++abi.dylib 0x000000018d2451b0 abort_message + 128
3   libc++abi.dylib 0x000000018d25ec04 default_terminate_handler() + 300
4   libobjc.A.dylib 0x000000018d26c820 objc_terminate() + 120
5   libc++abi.dylib 0x000000018d25b5d4 std::__terminate() + 12
6   libc++abi.dylib 0x000000018d25b640 std::terminate() + 56
7   libdispatch.dylib 0x000000018d6c29b4 _dispatch_client_callout + 32
8   libdispatch.dylib 0x000000018d6c75e8 _dispatch_main_queue_callback_4CF + 992
9   CoreFoundation 0x000000018e7b90c0 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 8
10  CoreFoundation 0x000000018e7b6cdc __CFRunLoopRun + 1568
11  CoreFoundation 0x000000018e6e6d94 CFRunLoopRunSpecific + 420
12  GraphicsServices 0x0000000190150074 GSEventRunModal + 96
13  UIKit 0x000000019499f44c UIApplicationMain + 204
!   14  MyAppNameHere 0x000000010007b090 main (main.m:33)
15  libdyld.dylib 0x000000018d6f559c start + 0

The strange thing is that none of this exists within my code except for the main.m. All other threads in my application don't have anything related to either. This crash appears to only happen for a fraction of a percent of my users, so I am not sure where to even start looking.

A: The question as it is formulated right now is not answerable, because it is missing necessary information. See e.g. this tutorial for an explanation of how to obtain a real backtrace and how to obtain a "crash reason". Without following the recommended steps for debugging crashes every crash of an iOS-app looks exactly the same as the crash you just provided.
In order to get a real/useful backtrace, you need to set an exception breakpoint in Xcode.


text:
Q: Accordion wont work when i delete accordion__content div from my HTML. Any suggestions? I made this nested accordion, and if i dont have the parent, the accordion doesnt work at all. Its not really accordion, its more of a multilevel navbar of a sort. I need help, but in pure JAVASCRIPT, please dont post answers in jQuery, thank you very much. Also, if you could help me refactor my html so that i can delete the accordion__content class, that would mean a world, thank you.

const accordionItem = document.getElementsByClassName("accordion--item");

const parent = document.getElementsByClassName("accordion");

const accordionContent = document.getElementsByClassName("accordion__content");

for (let i = 0; i < accordionItem.length; i++) {

  if (innerWidth > '1000') {
    accordionItem[i].addEventListener("mouseover", (e) => {
      e.stopPropagation();
      for (let j = 0; j < accordionItem.length; j++) {
        accordionItem[j].classList.remove("accordion--open");
        accordionContent[j].style.display = "none";
      }
      let parentEl = accordionItem[i].parentElement.parentElement;
     ;
      while (parentEl && parentEl.classList.contains("accordion--item")) {
        parentEl.classList.add("accordion--open");
        parentEl.children[1].style.display = "block";
        parentEl = parentEl.parentElement.parentElement;
        if (accordionContent[i].parentElement.parentElement.innerHTML === "") {
          accordionContent[i].parentElement.classList.remove("accordion--open");
        }
      }
      accordionItem[i].classList.add("accordion--open");
      accordionContent[i].style.display = "block";
    });
    accordionItem[i].addEventListener("mouseout", (e) => {
      e.stopPropagation();
      accordionContent[i].style.display = "none";
      accordionItem[i].classList.remove("accordion--open");
    });
  } else {
    accordionItem[i].addEventListener("click", (e) => {
      e.stopPropagation();
      for (let j = 0; j < accordionItem.length; j++) {
        accordionItem[j].classList.remove("accordion--open");
        accordionContent[j].style.display = "none";
      }
      let parentEl = accordionItem[i].parentElement.parentElement;
      c
      while (parentEl && parentEl.classList.contains("accordion--item")) {
        parentEl.classList.add("accordion--open");
        parentEl.children[1].style.display = "block";
        parentEl = parentEl.parentElement.parentElement;
        if (accordionContent[i].textContent === "") {
          accordionContent[i].style.display = "none";
        }
      }
      accordionItem[i].classList.add("accordion--open");
      accordionContent[i].style.display = "block";
    });
  }
}
/**
 * Required CSS
 */
 .accordion__title {
    cursor: pointer;
    margin: 0;
    position: relative;
  }

  .accordion__icon {
    position: absolute;
    top: 50%;
    right: 24px;
    transform: translateY(-50%);
  }

  .accordion__icon .line-01,
  .accordion__icon .line-02 {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 16px;
    height: 2px;
    background-color: #272343;
    transition: 0.3s;
  }

  .accordion__icon .line-02 {
    transform: rotate(90deg);
  }

  .accordion__content {
    display: none;
  }

  .accordion--open > .accordion__title .line-02 {
    transform: rotate(0deg);
  }
  /* end Required CSS */

  /**
   * Now let's make it look pretty!
   */
  body {
    font-family: "Rubik", sans-serif;
    max-width: 768px;
    margin: 0 auto;
    color: #111;
    overflow-y: scroll;
  }

  h1 {
    text-align: center;
    margin: 0 0 40px;
  }

  .accordion {
    display: flex;
  }

  .accordion__title {
    padding: 20px 16px;
    font-size: 16px;
    transition: 0.2s;
  }

  .accordion__content {
    padding: 24px 16px;
  }

  .accordion__content p {
    margin: 0 0 16px;
  }

  .accordion__title:hover {
    background-color: #433d6f;
    color: #fff;
  }

  .accordion__title:hover .line-01,
  .accordion__title:hover .line-02 {
    background-color: #fff;
  }

  .accordion--open > .accordion__title {
    background-color: #272343;
    color: #fff;
  }

  .accordion--open > .accordion__title .line-01,
  .accordion--open > .accordion__title .line-02 {
    background-color: #fff;
  }

  .accordion--nested .accordion__title {
    padding: 16px;
    font-size: 14px;
  }

  .accordion--nested .accordion__content {
    padding: 24px 16px 16px;
  }
  .slideUp {
    height: 0;
  }
  .slideDown {
    height: 200px;
  }

                Parent

                        Child

                        Child of child

                        Child

                        Child 2

                                Child of child 2

                                Child of child 2

                        Child


text:
Q: SQL query about selecting the highest value I have these two tables
create table Employee2(eid char(3), ename char(10), salary number(7,2),
mid char(3),primary key
(eid), foreign key (mid) references Employee2);

create table MakesD2 (aoid char(3), eid char(3), cid char(3), prices
number, dates date, primary key
(aoid,CID), foreign key (aoid) references ArtObject2, foreign key (CID)
references Customer2,foreign key (eid) references Employee2);

I need to find the employees who sold the most paintings.
I have this so far.
SELECT e.ename, MAX(md.eid)
FROM Employee2 e inner join MakesD2 md on md.eid=e.eid
GROUP BY e.ename;

A: WITH emp_total_sales AS
(
    SELECT eid, sum(prices) total_price FROM MakesD2 GROUP BY eid
)
SELECT e.ename FROM Employee2 e, emp_total_sales es
WHERE e.eid = es.eid AND es.total_price IN (SELECT MAX(total_price) FROM emp_total_sales);