text:
Q: Issues with Task Scheduler on Windows from .NET I am using the Task Scheduler Managed Wrapper from https://taskscheduler.codeplex.com/ to build an app targeting .NET 4 on windows 7, that creates several tasks after deleting any old ones it created itself.
Task registration seems to succeed but the tasks do not launch and have somehow corrupted the Task Scheduler as follows:

The error dialog box in the image pops up six times which is how many tasks my app deleted then recreated. This happens when the Task Scheduler MMC Console if first launched and also when the House of Synergy folder is selected.
The code is a bit lengthy but necessary and ready to compile:
namespace TaskSchedulerHelper
{
    using System;
    using System.Diagnostics;
    using System.Linq;
    using System.Security.Principal;
    using System.Windows.Forms;
    using Microsoft.Win32.TaskScheduler;

    internal static class Program
    {
        [STAThread]
        private static void Main (string [] args)
        {
            var now = DateTime.Now;
            var folderName = @"House of Synergy";
            var taskNamePrefix = @"ShutDown Power Outage";
            var applicationName = @"Task Scheduler Helper";

            var times = new TimeSpan []
            {
                TimeSpan.FromHours(02), // 02:00 AM
                TimeSpan.FromHours(06), // 06:00 AM
                TimeSpan.FromHours(11), // 11:00 AM
                TimeSpan.FromHours(15), // 03:00 PM
                TimeSpan.FromHours(19), // 07:00 PM
                TimeSpan.FromHours(23), // 11:00 PM
            };

            try
            {
                Console.Title = applicationName;

                Console.WriteLine(applicationName);
                Console.WriteLine();

                // Uses the Task Scheduler Managed Wrapper
                //  from https://taskscheduler.codeplex.com/.
                //  Release: 2.3.0. Status: Stable.
                //  Date: Thu Dec 18, 2014 at 12:00 PM.
                using (TaskService service = new TaskService())
                {
                    var folder = service
                        .RootFolder
                        .SubFolders
                        .FirstOrDefault(f => (string.Compare(f.Name, folderName, StringComparison.InvariantCultureIgnoreCase) == 0));

                    if (folder == null) { folder = service.RootFolder.CreateFolder(folderName); }

                    var tasks = folder
                        .Tasks
                        //.Where(t => t.Name.StartsWith(taskNamePrefix, StringComparison.InvariantCultureIgnoreCase))
                        .ToList();

                    if (tasks.Any())
                    {
                        // Delete existing tasks.
                        Console.WriteLine("Deleting existing tasks.");
                        foreach (var task in tasks)
                        {
                            Console.Write(" - Deleting Task: {0}: ", task.Name);

                            try
                            {
                                task.Stop();

                                //task.Enabled = false; // Throws ComException: Element not found. (Exception from HRESULT: 0x80070490).
                                //Console.WriteLine(task.State); // Throws ComException: Element not found. (Exception from HRESULT: 0x80070490).

                                task.RegisterChanges();
                                folder.DeleteTask(task.Name, false);
                                task.Dispose();

                                Console.WriteLine("Done.");
                            }
                            catch (Exception exception)
                            {
                                Console.WriteLine("Exception: {0}.", exception);
                            }
                        }
                    }

                    Console.WriteLine();
                    Console.WriteLine("Creating new Tasks.");

                    foreach (var time in times)
                    {
                        var dateTimeNow = now.Date;
                        var definition = service.NewTask();
                        var dateTimeTrigger = now.Date.Add(time);
                        var taskName = taskNamePrefix + " " + dateTimeTrigger.ToString(@"hh-mm tt");

                        Console.Write(" - Creating Task: {0}: ", taskName);

                        try
                        {
                            definition.RegistrationInfo.Author = WindowsIdentity.GetCurrent().Name;
                            definition.RegistrationInfo.Date = DateTime.Now;
                            definition.RegistrationInfo.Description = "ShutDown event due to power outage at [" + dateTimeTrigger.ToLongTimeString() + "].";
                            definition.RegistrationInfo.Source = applicationName;
                            definition.RegistrationInfo.Version = new Version(1, 0, 0, 0);

                            definition.Settings.AllowDemandStart = true;
                            definition.Settings.AllowHardTerminate = false;
                            definition.Settings.Compatibility = TaskCompatibility.V2_1; // Windows 7 and above.
                            definition.Settings.DisallowStartIfOnBatteries = false;
                            definition.Settings.DisallowStartOnRemoteAppSession = false;
                            definition.Settings.Enabled = true;
                            definition.Settings.Hidden = false;
                            definition.Settings.MultipleInstances = TaskInstancesPolicy.IgnoreNew;
                            definition.Settings.Priority = ProcessPriorityClass.High;
                            definition.Settings.RestartCount = 10;
                            definition.Settings.RestartInterval = TimeSpan.FromMinutes(1);
                            definition.Settings.RunOnlyIfIdle = false;
                            definition.Settings.RunOnlyIfNetworkAvailable = false;
                            definition.Settings.StartWhenAvailable = true;
                            definition.Settings.StopIfGoingOnBatteries = false;
                            definition.Settings.UseUnifiedSchedulingEngine = true;
                            definition.Settings.WakeToRun = false;

                            definition.Actions.Add(new ShowMessageAction("Message Body", "Message Title"));
                            definition.Triggers.Add(new DailyTrigger() { StartBoundary = dateTimeTrigger.Subtract(TimeSpan.FromMinutes(10)), });

                            var task = folder.RegisterTaskDefinition(taskName, definition);

                            task.Enabled = true;
                            task.RegisterChanges();
                            // Always succeeds.
                            Console.WriteLine("Done.");

                            try
                            {
                                Console.WriteLine("   - Task Validation: ", task.Definition.Validate(throwException : true) ? "Succeeded." : "Failed.");
                            }
                            catch (Exception exception)
                            {
                                // Validation always fails.
                                Console.WriteLine("   - Task Validation Exception: {0}.", exception);
                            }
                        }
                        catch (Exception exception)
                        {
                            Console.WriteLine("Exception: {0}.", exception.Message);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Console.Write(exception);
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Press any key to continue...");
            Console.ReadKey(true);
        }
    }
}

A: Commenting out task.RegisterChanges(); and the two subsequent lines seems to fix the issue.


text:
Q: Analytic continuation of a periodic function on the real line Suppose $f(x+1)=f(x)$ is real analytic for $x\in \mathbb{R}\setminus \mathbb{Z}$. Moreover, it is once-differentiable at $x\in \mathbb{Z}$.
In addition, suppose that on the interval $(0,1)$, we know the analytic continuation into the complex plane. Let us call this function $g(z)$, where $0<\mathrm{Re}(z)<1$. Finally, we also know that $g(z+n)=g(z)$ for some integer $n>1$. So really, we know the analytic continuation of $f(x)$ for $\mathrm{Re}(z)\in (mn,mn+1)$ for $m\in\mathbb{Z}$.
I want to find the analytic continuation valid for any $\mathrm{Re}(z)\in \mathbb{R}\setminus \mathbb{Z}$.
An obvious continuation is that one takes $g([z])$, where the fractional part is defined as: $$[z]=z+k \quad, k\in\mathbb{Z}\quad \text{such that}\quad 0<z+k<1.$$
This function agrees with $f(x)$ on $\mathbb{R}\setminus \mathbb{Z}$. For the specific function at hand, it turns out that $g(z)$ at $z=0,1$ is once differentiable, even though the fractional part is not defined there. This matches with the behaviour of $f(x)$.
My question: is this continuation unique?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem with newcommand subscrip doubleprime Some time ago I wrote a command that I used many times, today I realize that it could be written correctly. in particular, the command is selected as "not in a mathematical environment".
I looked for other solutions but I do not like them.
I see writing pleasant, but can this command create problems? could you give me a suggestion to write it correctly? Thank you
\documentclass[a4paper]{article}

\usepackage[T1]{fontenc}
\usepackage[italian]{babel}
\usepackage{amsmath}
\usepackage{mwe}

\usepackage{scalerel}
\newcommand\scale[2]{\vstretch{#1}{\hstretch{#1}{#2}}}
\newcommand\ssp[1]{#1^{\scale{.8}{\scriptstyle{\prime}}}}
\newcommand\sspp[1]{#1^{\scale{.8}{\scriptstyle{\prime\prime}}}}

\begin{document}

\begin{minipage}[t]{.5\textwidth}
    \begin{align}
    \ssp{z_G}\\
    \sspp{z_{G}}
    \end{align}
\end{minipage}
\begin{minipage}[t]{.5\textwidth}
    \begin{align}
    \ssp{G}\\
    \sspp{G}
    \end{align}
\end{minipage}\\

\end{document}

A: I asked in a comment: "Wouldn't it be easier just to redefine your math alphabet with smaller scripts, rather than trying to scale each invocation of a script?"  The OP asked how.
\DeclareMathSizes is the command that you can define math script sizes, etc.  Take this basic code and look at the output:
\documentclass{article}
\usepackage{lmodern}
\begin{document}
\centering
\[
z'_G\quad z''_{G_G}\quad G'\quad G''
\]
Inline: $\frac{x}{y}$
\end{document}

Now (I'm not sure I am setting all the parameters correctly), compare:
\documentclass{article}
\usepackage{lmodern}
\makeatletter
\DeclareMathSizes{\@xpt}{\@xpt}{5}{4}
\DeclareMathSizes{\@xipt}{\@xipt}{6}{5}
\DeclareMathSizes{\@xiipt}{\@xiipt}{6}{5}
\DeclareMathSizes{\@xivpt}{\@xivpt}{\@xpt}{6}
\makeatother
\begin{document}
\centering
\[
z'_G\quad z''_{G_G}\quad G'\quad G''
\]
Inline: $\frac{x}{y}$
\end{document}

The script sizes are smaller.  Also, the lmodern package allows for the rendering of the very small math sizes, so you will need that.


text:
Q: Do I need to specify every selector to style a nested element? What is the proper way style a specific element that is deeply nested.
For example:

John Doe

If I want to make the name "John Doe" bold, do I name every selector:
.wrapper .content .main .profile .description .name { font-weight:bold; }

or do I just specify the selector directly like this:
.name { font-weight:bold; }

I am confused on what is the proper coding method. Thanks for your time!

A: No, you do not need to reference every parent element to target a nested element; you can simply target the element itself (such as with .name):

.name {
  font-weight: bold;
}

John Doe

Also, note that you can simply target any of the ancestor elements directly as well, where the rule will cascade down (targetting .profile will target .profile as well as everything nested within .profile, but not any of the ancestors or siblings of .profile):

.profile {
  font-weight: bold;
}

Main (not bold)

Profile

John Doe

When you specify additional parent elements such as with .wrapper .content .main .profile .description .name, you're increasing what's known as the specificity.
This can play an important part when you have two rules that both target the same element, where the most specific rule will be applied (in the following, .name is a valid selector, but .description .name targets the same element and is more specific, so .description .name overrides .name):

/* This gets applied */
.name {
  color: red;
}

/* This gets applied and takes priority, as it is more specific */
.description .name {
  color: blue;
}

John Doe

And this increased specificity also be used to denote when you have two elements with the same class or selector, where you only want the rule to apply to a particular element (the second .name here doesn't have the parent .description, so although .name would be a valid selector for it, .description .name is not):

.description .name {
  font-weight: bold;
}

Name One -- targetted

Name Two - not targetted

A: It depends if the only hierarchy you want to be selected is the one in your example. If the hierarchy does not matter, use only one class name (.name). If you want to limit your selection to a specific hierarchy (how specific depends on your situation), go for more. It's not entirely uncommon for selectors to consist of many class names, each of them going even deeper into the hierarchy.
However, looking at your code, I want to suggest giving some of your tags IDs instead of class names. IDs are like class names, but they are unique across the whole document (there can/should be only one element with the same ID per document). In your example, is there more than one .wrapper, .content, and .main? Probably not. You'll judge for yourself, but those kinds of structures are typically unique and exist only once in a document.
If you give them IDs, they are #wrapper, #content, and #main respectively.

John Doe

If you choose to do so, you can then get rid of the first three class names in your selector.
.profile .description .name

would be the same as:
#wrapper #content #main .profile .description .name

Except if there were elements in the document that had the same class names, but were outside of your #wrapper, #content, and #main.
The decision is yours, but it is commonplace to give such global structures (like main) IDs instead of class names, because they tend to be unique.


text:
Q: Is it possible to freeze part of a spreadsheet I would like to do do the following thing:
I know how to use "freeze pane" that allow me to have a fixed part of a spreadsheet (the upper part) and another part that I can scroll.
Is it possible to do this on 2 axes (vertical and horizontal)
Something like this :

A: If I think I understand what you're looking to do, you could hit the Freeze Panes button on the "some" that is just below and to the right of the yellow limits you have set (Cell H5 ?).
If that isn't what you're looking for, use the Split button located near the Freeze Panes tool.


text:
Q: C++ Find maximum element of an array USING ONLY POINTERS I have an assignment where I have to find the max and min element of an array using only pointers. The directions say you have to use pointers for everything but didn't make it clear if you can make variables then just not use them and make pointers pointing to them or if there literally cant be one regular variable declaration in the program.
I already did the whole assignment by declaring variables then making pointers point to them but just to be safe I'm redoing it with no variables.
The only thing I'm having trouble with is making a for loop with only pointers because there is no variable set to 0 that I can make a pointer point to and get the memory address of 0 to start the counter.
I would just do this:
int i = 0;

int *counterptr = &i;

cout << "Please input the array values" << endl;

for (*counterptr ; *counterptr < 10; *counterptr += 1)
{

}

But since I cant make variable i to point to I don't know how to get the memory address of 0 to use for the pointer. This is what I have right now but I don't know what to make counterptr equal to.
float nums[10];
int *counterptr = ;
float *maxptr, *minptr, *difference;
maxptr = &nums[0];
minptr = &nums[0];

cout << "Please input the array values" << endl;

for (*counterptr ; *counterptr < 10; *counterptr += 1)
{
    cin >> nums[*counterptr];
    if (nums[*counterptr] > *maxptr)
    {
        maxptr = &nums[*counterptr];
    }
    if (nums[*counterptr] < *minptr)
    {
        minptr = &nums[*counterptr];
    }

}

Any help would be appreciated thank you.

A: corrected program snippet given below. It can be written better, but I modified for your understanding from your code changed to work now. counterptr is a pointer within the array elements (as an iterator), *counterptr will be one of the elements, similarly *minptr and *maxptr are minimum and maximum elements whereas, minptr and maxptr are respective pointers to minimum and maximum elements within the array of floating point numbers. Hope this helps.
float nums[10];
float *counterptr;
float *maxptr, *minptr, *difference;
maxptr = &nums[0];
minptr = &nums[0];

cout << "Please input the array values" << endl;

for (counterptr = nums, counterptr < nums + 10; counterptr++)
{
    cin >> *counterptr;
    if (*counterptr > *maxptr)
    {
        maxptr = counterptr;
    }
    if (*counterptr < *minptr)
    {
        minptr = counterptr;
    }

}


text:
Q: Calling a method from another class - NSTextView not loading data I have 3 classes:
LocalRoom.m
- (void) handleNewConnection:(Connection*)connection {
    NSString* number = @"10";
    AppDelegate *theAppDelegate = [[NSApplication sharedApplication] delegate];
    [theAppDelegate connectionNumber:number currentZoneName:@"Zone1";
}

Triggers ----->
AppDelegate.h
MyTableController *tableController;

AppDelegate.m
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    tableController = [[MyTableController alloc] init];
}

- (void)connectionNumber:(NSString *)number zoneName:(NSString *)currentZoneName {
    if ([currentZoneName isEqualToString:zoneName1]) {
        [tableController changeConnections:number withRowNumber:0];
    }
}

Triggers ----->
MyTableController.h
@interface MyTableController : NSControl {
IBOutlet NSTextField *zoneNameTextField;
}
@property (retain) NSTableView * idTableView;
- (void) changeConnections:(NSString *)number withRowNumber:(int)rowNumber;

MyTableController.m
- (void) changeConnections:(NSString *) number withRowNumber:(int) rowNumber{

    NSRunAlertPanel([NSString stringWithFormat:@"%d", rowNumber], number, @"", @"", @"");

    NSTableColumn *tableColumn = [[NSTableColumn alloc] initWithIdentifier: @"Connections"];

    [self tableView:idTableView setObjectValue:number forTableColumn:tableColumn row:rowNumber];

    [idTableView reloadData];

}

My NSRunAlertPanel is coming up with the correct values, but my NSTextView is not changing. When I put the "edit" code for the NSTableView in an IBAction of MyTableController.m, it works. I checked if idTableView was NULL, and it was. Which is weird. So, I have a feeling something odd is happening when changeConnections is run by the AppDelegate. I had a similar problem with a nstextfield not returning data. The fix was to initialize it by AppDelegate *theAppDelegate = [[NSApplication sharedApplication] delegate]; Is there something similar in this case?
You might wonder why I'm just not calling MyTableController from LocalRoom, but "zoneName1" is set and found in the app delegate.
Thanks in advance!

A: You haven't shown all the code, but idTableView is declared as a @property of MyTableController, but not as an IBOutlet.
That is idTableView being NULL strongly suggests that the idTableView property is never set to the appropriate table view. No IBOutlet for it means it can't be connected in the NIB/XIB. So the fix is probably to make it an outlet and connect it in the NIB.
Obviously, [idTableView reloadData] has no effect if idTableView is NULL.
I assume that your NIB does set MyTableController as its table data delegate, which is why the direct editing would work.
Further, although I don't think this is related to your problem, for best practice it doesn't make sense to manufacture a new NSTableColumn to work on your existing table -- you should be using [idTableView tableColumnWithIdentifier: @"Connections"] instead.


text:
Q: Toggle menu do bootstrap não está se expandindo Meu menu com toggle-icon, sendo usado exatamente como o da documentação exemplo do bootstrap4 simplesmente não se expande.
Tentei essa solução mas não mudou nada. Atualmente o código está assim:
<!DOCTYPE html>
{% load staticfiles %}

    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"/>

    <link rel="stylesheet" href="{% static 'css/giositeapp.css' %}"/>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>G M</title>

            Home
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogg" aria-controls="navbarTogg" aria-expanded="false" aria-label="Alterna navegação">

            </button>

                            P

                            B

                            C

        {% block content %}
        {% endblock %}

As tags com {%%} são por conta do Django, e, aparentemente, não são o problema pois o meu arquivo de css personalizado esta funcionando normalmente.

A: Para deixar registrado, o d-none era o problema. Funciona perfeitamente da seguinte forma (removendo-o):

    Home
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogg" aria-controls="navbarTogg" aria-expanded="false" aria-label="Alterna navegação">

    </button>

                    P

                    B

                    C


text:
Q: Bash and Test-Driven Development When writing more than a trivial script in bash, I often wonder how to make the code testable.
It is typically hard to write tests for bash code, due to the fact that it is low on functions that take a value and return a value, and high on functions that check and set some aspect in the environment, modify the file-system, invoke a program, etc. - functions that depend on the environment or have side effects. Thus the setup and test code become much more complicated than the code they test.

For example, consider a simple function to test:
function add_to_file() {
  local f=$1
  cat >> $f
  sort -u $f -o $f
}

Test code for this function might consist of:
add_to_file.before:
foo
bar
baz

add_to_file.after:
bar
baz
foo
qux

And test code:
function test_add_to_file() {
   cp add_to_file.{before,tmp}
   add_to_file add_to_file.tmp
   cmp add_to_file.{tmp,after} && echo pass || echo fail
   rm add_to_file.tmp
}

Here 5 lines of code are tested by 6 lines of test code and 7 lines of data.

Now consider a slightly more complicated case:
function distribute() {
   local file=$1 ; shift
   local hosts=( "$@" )
   for host in "${hosts[@]}" ; do
     rsync -ae ssh $file $host:$file
   done
}

I can't even say how to start write a test for that...

So, is there a good way to do TDD in bash scripts, or should I give up and put my efforts elsewhere?

A: So here is what I learned:

*

*There are some testing frameworks written in bash and for bash,
however...

*It is not so much that Bash is not suitable for TDD (although some
other languages come to mind that are a better fit), but the
typical tasks that Bash is used for (Installation, System
configuration), that are hard to write tests for, and in
particularly hard to setup the test.

*The poor data structure support in Bash makes it hard to separate
logic from side-effect, and indeed there is typically little logic
in Bash scripts. That makes it hard to break scripts into
testable chunks. There are some functions that can be tested, but
that is the exception, not the rule.

*Function are a good thing (tm), but they can only go so far.

*Nested functions can be even better, but they are also limited.

*At the end of the day, with major effort some coverage can be
obtained, but it will test the less interesting part of the code,
and will keep the bulk of the testing as a good (or bad) old manual
testing.
Meta: I decided to answer (and accept) my own question, because I was unable to choose between Sinan Ünür's (voted up) and mouviciel's (voted up) answers that where equally useful and insightful. I want to note Stefano Borini's answer, that although not impressed me initially, I learned to appreciate it over time. Also his design patterns or best practices for shell scripts answer (voted up) referred above was useful.

A: If you code a bash program large enough to require TDD, you are using the wrong language.
I suggest you to read my previous post on best practices in bash programming, you will probably find something useful to make your bash program testable, but my statement above stays.
Design patterns or best practices for shell scripts

A: Writing what Meszaros calls consumer tests is hard in any language. Another approach is to verify the behavior of commands such as rsync manually, then write unit tests to prove specific functionality without hitting the network. In this slightly-modified example, $run is used to print the side-effects if the script is run with the keyword "test"
function distribute {
    local file=$1 ; shift
    for host in $@ ; do
        $run rsync -ae ssh $file $host:$file
    done
}

if [[ $1 == "test" ]]; then
    run="echo"
else
    distribute schedule.txt $*
    exit 0
fi

#
# Built-in self-tests
#

output=$(mktemp)
expected=$(mktemp)
set -e
trap "rm $got $expected" EXIT

distribute schedule.txt login1 login2 > $output
cat << EOF > $expected
rsync -ae ssh schedule.txt login1:schedule.txt
rsync -ae ssh schedule.txt login2:schedule.txt
EOF
diff $output $expected
echo -n '.'

echo; echo "PASS"

A: You might want to take a look at cucumber/aruba. Did quite a nice job for me.
Additionally, you can stub just about everything you want by doing something like this:
#
# code.sh
#
some_function_calling_some_external_binary()
{
    if ! external_binary action_1; then
        # ...
    fi

    if ! external_binary action_2; then
        # ...
    fi
}

#
# test.sh
#

# now for the test, simply stub your external binary:
external_binary()
{
    if [ "$@" = "action_1" ]; then
        # stub action_1

    elif [ "$@" = "action_2" ]; then
        # stub action_2

    else
        external_binary $@
    fi
}

A: If you are writing code at the same time with tests, try to make it high on functions that don't use anything besides their parameters and don't modify environment. That is, if your function might as well run in a subshell, then it will be easy to test. It takes some arguments and outputs something to stdout, or to a file, or maybe it does something on the system, but caller does not feel side effects.
Yes, you will end up with big chain of functions passing down some WORKING_DIR variable that might as well be global, but this is minor inconvenience comparing to the task of tracking what does each function read and modify. Enabling unit tests is just a free bonus too.
Try to minimize cases where you need output. A little subshell abuse will go long way to keeping things nicely separated (at the expense of performance).
Instead of linear structure, where functions are called, set some environment, then other ones are called, all pretty much on one level, try to go for deep call tree with minimum data going back. Returning stuff in bash is inconvenient if you adopt self-imposed abstinence from global vars...

A: From an implementation point of view, I suggest shUnit2 or bats.
From a practical point of view, I suggest not to give up. I use TDD on bash scripts and I confirm that it is worth the effort.
Of course, I get about twice as many lines of test than of code but with complex scripts, efforts in testing are a good investment. This is true in particular when your client changes its mind near the end of the project and modifies some requirements. Having a regression test suite is a big aid in changing complex bash code.

A: The advanced bash scripting guide has an example of an assert function but here is a simpler and more flexible assert function - just use eval of $* to test any condition.
assert() {
  if ! eval $* ; then
      echo
      echo "===== Assertion failed:  \"$*\" ====="
      echo "File \"$0\", line:$LINENO line:${BASH_LINENO[*]}"
      echo line:$(caller 0)
      exit 99
  fi
}

# e.g. USAGE:
assert [[ $r == 42 ]]
assert "((r==42))"

BASH_LINENO and caller bash builtin are bash shell specific.

A: take a look at Outthentic framework - it is designed to create scenarios which runs any Bash code and then analyze the stdout using formal DSL, it's pretty easy to build any Tdd/blackbox tests suite upon this tool.


text:
Q: Look at a hash, find the first key where value is nil, do something with that key/value pair I'm writing this complex loop structure and would love to make filling my hash a little easier.
At the beginning of my method, I make something that looks like this:
thing_array = [{
animals: nil,
fruit: nil,
cars: nil
},
{
animals: nil,
fruit: nil,
cars: nil
},
{
animals: nil,
fruit: nil,
cars: nil
}]

My goal is to loop through the array, and then each hash, find the first element that's nil and set that key/value pair based on the value of the loop that runs outside of this.
Any suggestions on how to do this?

A: Like Tin Man said you'll need to make your question clearer. The method below gets you to the first nil value in the array. I wasn't sure what you wanted to do once you got to that point, but hopefully this helps!
def getFirstNil(array)
   array.each do |hash|
      hash.each do |key,value|
         if value == nil
            #here's your first nil, do something!
            return key
         end
      end
   end
   return nil
end


text:
Q: /lib/udev/write_net_rules: No such file or directory My Linux is suffering from the network configuration, the 70-persistent-rules file is never generated. I am trying to follow this post:
https://access.redhat.com/discussions/1240213, but the udev program seems to be broken on my machine?
$ cd /lib/udev/ && ls
ata_id                    hpljP1006              pcmcia-check-broken-cis
cdrom_id                  hpljP1007              pcmcia-socket-startup
collect                   hpljP1008              rules.d
console-setup-tty         hpljP1505n             scsi_id
hdparm                    hwclock-set            snappy-app-dev
hid2hci                   hwdb.d                 udev-add-printer
hplj1000                  ifupdown-hotplug       udev-configure-printer
hplj1005                  iphone-set-info        usb_modeswitch
hplj1018                  ipod-set-info          v4l_id
hplj1020                  mtd_probe
hpljP1005                 mtp-probe
$ /lib/udev/write_net_rule
bash: /lib/udev/write_net_rule: No such file or directory
$ /lib/udev/write_net_rules
bash: /lib/udev/write_net_rules: No such file or directory
At this moment I am totally lost. I tried to upgrade udev but doesn't seem to do anything. Any thoughts could be helpful.


text:
Q: Use async with tornado and motor Newbie to Python 3.5 and the new async and await features
The following code only returns a future object. How do I get the actual book item from database and write it to json? And what is the best practice for using async await along with motor-tornado?
async def get(self, book_id=None):
    if book_id:
        book = await self.get_book(book_id)
        self.write(json_util.dumps(book.result()))
    else:
        self.write("Need a book id")

async def get_book(self, book_id):
    book = self.db.books.find_one({"_id":ObjectId(book_id)})
    return book

A: No need for "result()". Since your "get" method is a native coroutine (it's defined with "async def"), then using it with "await" means that a result is already returned to you:
async def get(self, book_id=None):
    if book_id:
        # Correct: "await" resolves the Future.
        book = await self.get_book(book_id)
        # No resolve(): "book" is already resolved to a dict.
        self.write(json_util.dumps(book))
    else:
        self.write("Need a book id")

However you must also "await" the future in "get_book" in order to resolve it before returning:
async def get_book(self, book_id):
    book = await self.db.books.find_one({"_id":ObjectId(book_id)})
    return book


text:
Q: Identifying file type in Java Please help me to find out the type of the file which is being uploaded.
I wanted to distinguish between excel type and csv.
MIMEType returns same for both of these file. Please help.

A: I hope this will help. Taken from an example not from mine:
import javax.activation.MimetypesFileTypeMap;
import java.io.File;

class GetMimeType {
  public static void main(String args[]) {
    File f = new File("test.gif");
    System.out.println("Mime Type of " + f.getName() + " is " +
                         new MimetypesFileTypeMap().getContentType(f));
    // expected output :
    // "Mime Type of test.gif is image/gif"
  }

}
Same may be true for excel and csv types. Not tested.

A: I figured out a cheaper way of doing this with java.nio.file.Files
public String getContentType(File file) throws IOException {
        return Files.probeContentType(file.toPath());
}

- or -
public String getContentType(Path filePath) throws IOException {
        return Files.probeContentType(filePath);
}

Hope that helps.
Cheers.

A: A better way without using javax.activation.*:
 URLConnection.guessContentTypeFromName(f.getAbsolutePath()));

A: If you are already using Spring this works for csv and excel:

import org.springframework.mail.javamail.ConfigurableMimeFileTypeMap;

import javax.activation.FileTypeMap;
import java.io.IOException;

public class ContentTypeResolver {

    private FileTypeMap fileTypeMap;

    public ContentTypeResolver() {
        fileTypeMap = new ConfigurableMimeFileTypeMap();
    }

    public String getContentType(String fileName) throws IOException {
        if (fileName == null) {
            return null;
        }
        return fileTypeMap.getContentType(fileName.toLowerCase());
    }

}

or with javax.activation you can update the mime.types file.

A: I use Apache Tika which identifies the filetype using magic byte patterns and globbing hints (the file extension) to detect the MIME type. It also supports additional parsing of file contents (which I don't really use).
Here is a quick and dirty example on how Tika can be used to detect the file type without performing any additional parsing on the file:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;

import org.apache.tika.metadata.HttpHeaders;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaMetadataKeys;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.xml.sax.helpers.DefaultHandler;

public class Detector {

    public static void main(String[] args) throws Exception {
        File file = new File("/pats/to/file.xls");

        AutoDetectParser parser = new AutoDetectParser();
        parser.setParsers(new HashMap<MediaType, Parser>());

        Metadata metadata = new Metadata();
        metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, file.getName());

        InputStream stream = new FileInputStream(file);
        parser.parse(stream, new DefaultHandler(), metadata, new ParseContext());
        stream.close();

        String mimeType = metadata.get(HttpHeaders.CONTENT_TYPE);
        System.out.println(mimeType);
    }

}

A: The CSV will start with text and the excel type is most likely binary.
However the simplest approach is to try to load the excel document using POI. If this fails try to load the file as a CSV, if that fails its possibly neither type.


text:
Q: Lists, Dict and Lists of Dict - CS50 and Python This is for the CS50 course an assignment called DNA in python, Ive struggled for days researching and trying to work out how to get the final section to work. I'm a newbie.
I've uploaded a database of people and their DNA into memory into a list of dict's.
I've then read a test sample of DNA into memory as a string and then searched and filtered it looking for DNA sequences.
So what I now have is a dict called str_test AND the list of dict's called data holding everyone's DNA, I need to somehow compare str_test  with data to see if anyone matched and return the persons name.
Like I said I'm struggling with this, I have worked out how to loop and address the values in  data - the list of dict and also str_test the dict of results but I can't blend them together.
I apologies for the amount of #d out areas but they are for me for testing, any guidance would be appreciated. The last 5 to 7 lines are me trying to loop through but that's wrong there has to be a simple better way, thanks
import csv
import sys

def main():

    # Ensure correct usage
    if len(sys.argv) != 3:
        sys.exit("Usage: python dna.py data.csv sequence.txt")

    data = []

    with open(sys.argv[1], "r")  as csvfile:                     #open the file in the command line argument
        reader = csv.DictReader(csvfile)

        for row in reader:  #lets go loopy
            row = (row)
            data.append(row)

            #print(row)
            #print(data)
            #print(reader.fieldnames)
            #print(data)

    with open(sys.argv[2], "r")  as file:  #open the sample file in the command line argument

        sequence = file.read()  #read it to array/memory

        print(reader.fieldnames)  #test print
        print(sequence)  #test print

#two files now opened
#sequence is the test DNA sequence

#we want to loop through the STR's here and take the first and then loop that through the sequence

    str_test = {}           # a dictionary for the counts

    for i in range (1, (len(reader.fieldnames ))):  #read the header field names ie STR, count them starting after name field
        sample = (reader.fieldnames[i])
        print(reader.fieldnames)
        print(sample)  #DNA type to compare to test string called SEQUENCE
        str_test[sample] = 0

        for j in range(len(sequence)):  # this will loop through the long string to be tested for the STR DNA (sample)

            step = 0
            max_count = 0

            while sequence[j + step:j+step+len(sample)]  == sample:
                step = step + len(sample)
                max_count += 1
                print(max_count)

            j = j + step
                                                                #test = (str_test.get(sample))
            if max_count > (str_test.get(sample)):  #get the existing value of the sample and compare
                str_test[sample] = max_count  #if count is larger then update field if not continue

    print(str_test)  #test print to see whats in the dictionary
    print(str_test.values())
    #print(key.values())
    #print(data)
    #print(len(data))
    #print(type(str_test))

    for d in data:  #data is a list of dictionaries - so this is cycle through the list  [1:] to start at first
        for values in (str_test):  #start to loop through the dictionary for the test string dna results

            for key in d:  #this is cycling through the dictionary  thats part of the list of dictionaries

                strvalue = str_test.get(values)
                datavalue = int(d.get(values)

main()

the information contained in str_test looks like this -
{'AGATC': 4, 'TTTTTTCT': 0, 'AATG': 1, 'TCTAG': 0, 'GATA': 1, 'TATC': 5, 'GAAA': 1, 'TCTG': 0}

the information in the list of dict Ive got to search for a match against the str_test above looks like this:
[
  {
    'name': 'Albus',
    'AGATC': '15',
    'TTTTTTCT': '49',
    'AATG': '38',
    'TCTAG': '5',
    'GATA': '14',
    'TATC': '44',
    'GAAA': '14',
    'TCTG': '12'
  },
  {
    'name': 'Cedric',
    'AGATC': '31',
    'TTTTTTCT': '21',
    'AATG': '41',
    'TCTAG': '28',
    'GATA': '30',
    'TATC': '9',
    'GAAA': '36',
    'TCTG': '44'
  },
  {
    'name': 'Draco',
    'AGATC': '9',
    'TTTTTTCT': '13',
    'AATG': '8',
    'TCTAG': '26',
    'GATA': '15',
    'TATC': '25',
    'GAAA': '41',
    'TCTG': '39'
  },
  {
    'name': 'Fred',
    'AGATC': '37',
    'TTTTTTCT': '40',
    'AATG': '10',
    'TCTAG': '6',
    'GATA': '5',
    'TATC': '10',
    'GAAA': '28',
    'TCTG': '8'
  },
  {
    'name': 'Ginny',
    'AGATC': '37',
    'TTTTTTCT': '47',
    'AATG': '10',
    'TCTAG': '23',
    'GATA': '5',
    'TATC': '48',
    'GAAA': '28',
    'TCTG': '23'
  },
  {
    'name': 'Hagrid',
    'AGATC': '25',
    'TTTTTTCT': '38',
    'AATG': '45',
    ... # this is a short extract

A: This does what you asked, but I'm 100% certain what you asked is not the problem you were asked to solve.  As I mentioned, every name in your name list contains every sequence in your search list.  It's pretty easy to process, because the keys in your database are the exact sequences, so you don't even have to do string searches.
searches = {'AGATC': 4, 'TTTTTTCT': 0, 'AATG': 1, 'TCTAG': 0, 'GATA': 1, 'TATC': 5, 'GAAA': 1, 'TCTG': 0}

database = [
    {'name': 'Albus', 'AGATC': '15', 'TTTTTTCT': '49', 'AATG': '38', 'TCTAG': '5', 'GATA': '14', 'TATC': '44', 'GAAA': '14', 'TCTG': '12'},
    {'name': 'Cedric', 'AGATC': '31', 'TTTTTTCT': '21', 'AATG': '41', 'TCTAG': '28', 'GATA': '30', 'TATC': '9', 'GAAA': '36', 'TCTG': '44'},
    {'name': 'Draco', 'AGATC': '9', 'TTTTTTCT': '13', 'AATG': '8', 'TCTAG': '26', 'GATA': '15', 'TATC': '25', 'GAAA': '41', 'TCTG': '39'},
    {'name': 'Fred', 'AGATC': '37', 'TTTTTTCT': '40', 'AATG': '10', 'TCTAG': '6', 'GATA': '5', 'TATC': '10', 'GAAA': '28', 'TCTG': '8'},
    {'name': 'Ginny', 'AGATC': '37', 'TTTTTTCT': '47', 'AATG': '10', 'TCTAG': '23', 'GATA': '5', 'TATC': '48', 'GAAA': '28', 'TCTG': '23'},
    {'name': 'Hagrid', 'AGATC': '25', 'TTTTTTCT': '38', 'AATG': '45'}]

for row in database:
    for search in searches.keys():
        if  search in row:
            print( row['name'], 'matches', search )

Output:
Albus matches AGATC
Albus matches TTTTTTCT
Albus matches AATG
Albus matches TCTAG
Albus matches GATA
Albus matches TATC
Albus matches GAAA
Albus matches TCTG
Cedric matches AGATC
Cedric matches TTTTTTCT
Cedric matches AATG
Cedric matches TCTAG
Cedric matches GATA
Cedric matches TATC
Cedric matches GAAA
Cedric matches TCTG
Draco matches AGATC
Draco matches TTTTTTCT
Draco matches AATG
Draco matches TCTAG
Draco matches GATA
Draco matches TATC
Draco matches GAAA
Draco matches TCTG
Fred matches AGATC
Fred matches TTTTTTCT
Fred matches AATG
Fred matches TCTAG
Fred matches GATA
Fred matches TATC
Fred matches GAAA
Fred matches TCTG
Ginny matches AGATC
Ginny matches TTTTTTCT
Ginny matches AATG
Ginny matches TCTAG
Ginny matches GATA
Ginny matches TATC
Ginny matches GAAA
Ginny matches TCTG
Hagrid matches AGATC
Hagrid matches TTTTTTCT
Hagrid matches AATG


text:
Q: Customise Folder in Windows 10 Not Working I recently noticed that my customise folder options are not working anymore and i have to manually change the columns of each folder instead of applying the settings to the folders i want via the customise tab.
For example instead of size, date modified etc i want to make folders for music but nothing changes when i apply via the customise tab so i have to go into the folder and manually select contributing artist, album, title etc
Worse yet this also resets so in my music folder it defaults back to date modified, size etc when i want the columns for music, very annoying especially when you have loads of folders full of music
This is with

*

*Windows 10 Pro, Version: 1903, Build: 18362.239

*PC has i7 6700k, M.2, 16 GB Ram. GTX 1080

Please check pictures for examples:

A: This was solved on another forum but for anyone having the same issue I was told to simply reset folder view settings in windows (google how to) and it totally worked, I am now able to change and keep columns and apply to sub-folders like before, I think the latest windows update borked something but all seems fine now, many thanks.


text:
Q: apache redirect in https from none www to www domain Edit:
Redirect permanent "/" "https://%{HTTP_HOST}/" actually doesn't work in the first redirect. It appeared to work because my CDN automatically redirected http to https:, not because of my settings. Sorry for the confusion.

I am trying to write Apache httpd config file to redirect all http traffic to https, and also need to redirect none www domain to www.
for example
http://example.com   http://www.example.com   https://example.com
should all be redirected to
https://www.example.com
Here is what I did:
<VirtualHost ipaddress:80>
  ServerName example.com
  ServerAlias www.example.com

  Redirect permanent "/" "https://%{HTTP_HOST}/"
</VirtualHost>

This part works. All http is redirect to https. Note, the %{HTTP_HOST} is resolved and replaced.
Now I need to redirect none www to www
<VirtualHost ipaddress:443>
  SSLEngine on
  ServerName www.example.com
  ServerAlias example.com

  <If "%{HTTP_HOST} !~ /www/">
     Redirect permanent "/" "https://www.%{HTTP_HOST}/"
  </If>

  ...
</VirtualHost>

When I visit https://example.com it redirects but this time it is redirected to
https://www.%{HTTP_HOST}/ instead of https://www.example.com/.
Now if I use
Redirect permanent "/" "https://www.example.com/"
then https://example.com will be redirected to https://www.example.com
So it appears that the %{HTTP_HOST} was not replaced in the second VirtualHost block.
How to make it correct?

A: You could try using a rewrite rule
 RewriteEngine On
 RewriteCond %{HTTP_HOST} ^https://example.com [NC]
 RewriteRule ^(.*)$ https://www.example.com/$1


text:
Q: Why im getting this error tho the cmd is fine? Cannot read properties of undefined (reading 'get') DiscordJS context menu problem, like it says the cmd is running fine but when it does it shows the error of Cannot read properties of undefined (reading 'get') don't know why
Im getting this error on my events folder in discordjs v14 my content.js event
the error kept showing up though the context is still executed/working
I know i should be ignoring this error as long as the command is running good but it just annoying to my console and it doesn't look clean haha...
my context events:
module.exports = {
    name: 'interactionCreate',
    execute: async (interaction, client) => {
        if (interaction.isContextMenuCommand()) {
            const { command } = client;
            const { commandName } = interaction;
            const contextCommand = command.get(commandName);
            if (!contextCommand) return;

            try {
                await contextCommand.execute(client, interaction)
            } catch (e) {
                console.log(e)
            }
        }
    }
}

simple wave context
const { ApplicationCommandType, EmbedBuilder } = require("discord.js"); // packages
const superagent = require('superagent');
const ee = require('../../Config/embed.json');

module.exports = {
    name: 'wave', // name of the command
    // description: '', description of the command
    developer: false, // false if the command is for public
    type: ApplicationCommandType.User, // chatinput
    cooldown: 3000, // cooldown of the commands
    default_member_permissions: 'SendMessages', // discord perms
    // options: [], options string
    execute: async (client, interaction) => {
        try {
            let { body } = await superagent.get(`https://api.waifu.pics/sfw/wave`);
            const embed = new EmbedBuilder()
                .setColor(ee.color)
                .setDescription(`Hey <@${interaction.targetUser.id}>!, <@${interaction.user.id}> just wave at you!`)
                .setImage(body.url)
                .setTimestamp()
                .setFooter({ text: `${client.user.username} | waifumusic.ml` })
            interaction.reply({ embeds: [embed] })
        } catch (e) {
            console.log(e)
        }
    }
}


text:
Q: Bootstrap burger menu toggle not working I used bootstrap for all of my project. but in my latest project, the Burger menu in mobile view is showing but even i click it, its not toggling.
it used to work but now isn't, and i can't seem to find whats the error.
please help me guys, thanks in advance
heres my code:
<!doctype html>

   <meta charset="utf-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
   <title>The Curated</title>
   <meta name="description" content="">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
   <link rel="shortcut icon" href="<?php the_field('favicon','options'); ?>">

                            <?php if(get_locale() == "de_DE") { ?>

FOLGE UNS

<a href="<?php the_field('linkedin_link', 'options') ?>" target="_blank">

                            <?php } else { ?>

Follow us

<a href="<?php the_field('linkedin_link', 'options') ?>" target="_blank">

                            <?php } ?>

                        <?php
                            // get the post ID in en
                            $en_post_id = icl_object_id($post->ID, 'post', FALSE,'en');
                            $ed_post_id = icl_object_id($post->ID, 'post', FALSE,'de');
                            // get the post object
                            $en_post_obj = get_post( $en_post_id);
                            $ed_post_obj = get_post( $ed_post_id);
                            // get the name
                            $en_post_name = $en_post_obj->post_name;
                            $ed_post_name = $ed_post_obj->post_name;
                        ?>

<a href="<?php global $post; echo $en_post_name; ?>">EN<img src="<?php bloginfo('template_url') ?>/img/flag-en.png">

<a href="<?php global $post; echo $ed_post_name; ?>">DE<img src="<?php bloginfo('template_url') ?>/img/flag-ed.png">

                        <button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle">
                            Toggle navigation

                        </button>
                        <a href="<?php echo esc_url( home_url( '/') ); ?>" class="navbar-brand">
                            <img src="<?php the_field('logo', 'options') ?>">

                    <?php if(get_locale() == "de_DE") { ?>
                        <?php wp_nav_menu( array( 'theme_location' => 'header-german-menu', 'container' => 'false', 'items_wrap' => '
%3$s
' ) ); ?>
                    <?php } else { ?>
                       <?php wp_nav_menu( array( 'theme_location' => 'header-menu', 'container' => 'false', 'items_wrap' => '
%3$s
' ) ); ?>
                    <?php } ?>

        <?php wp_head(); ?>

here's my website for reference: https://www.thecurated.ch


text:
Q: Upgraded to 17.04 and now spacebar wont work I've found that the problem only happens on lightdm as I was able to see it working on the text tty.
Here's what xev says:
KeymapNotify event, serial 37, synthetic NO, window 0x0,
    keys:  2   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
           0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

xinput reports the key as:
 key press   65
 key release 65

So far I'm using Ctrl + V and Ctrl +C to make it work
Also I've found that some actions that use the key, like Alt +Space , work just fine but not when using the key by itself; all it does is just clears the text selection (or the cursor on the command line) when pressed and returns to what it was on key release, if that makes any sense.
Any idea what this could be?
In the meantime I'll be using .Xmopmap to use the right-control as a space:
keysym Control_R = space

A: I've found a workaround.

*

*Boot the machine as always

*Switch to text mode console, CTRL+ALT+F1

*Login as your user

*Execute: unity --reset
Not really sure why but when unity reset itself the spacebar is working as always.
Update: Oct 2018: So the workaround wont work anymore and after some debugging I've found that ibus-ui-gtk3 was the one breaking the spacebar. Simply killing the process will make the spacebar actually work again. I've removed the package since I no need multiple language input methods.
sudo apt remove ibus-gtk3


text:
Q: Render using GLSurfaceView.Renderer without any layout I have been struggling to implement a way to rendering opengl.
I have a GLSurfaceView.Renderer class and I want to use it inside an Android Service to generate images.
I want it to render images on a scheduled basis, like in every second. But it doesn't trigger onDrawFrame method whatever I try.
So far, I tried many things;

*

*Calling requestRender

*Inflating layout then calling layout.draw(canvas)

*Using GLWallpaperService https://github.com/markfguerra/GLWallpaperService


text:
Q: Duplicated Onedrive icon in explorer I've installed windows 10 on a new pc, with a secondary hard disk containing my onedrive folder, taken from my old pc. I've configured onedrive in order to use that folder, and it's working fine.
The problem is that when I open Explorer I can see two onedrive icons on the sidebar, both of them pointing at the same folder.
How can I remove the duplicated onedrive entry from the sidebar?

A: According to Microsoft Forum Moderator Ruizell Rey:

To resolve your concern regarding duplicated OneDrive entry, follow
  the steps below:

*

*Search for regedit, and then press Enter.

*Open HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace

*Check if you have several folders under NameSpace.

*If there are several folders, highlight each folder, and then check the name of the Data on the right hand side.

*If you see multiple folders with OneDrive as the Data, right click on it, and then select Delete.

Important: This section, method, or task contains steps that tell you how to modify the registry. However, serious problems might occur
  if you modify the registry incorrectly. Therefore, make sure that you
  follow these steps carefully. For added protection, back up the
  registry before you modify it. Then, you can restore the registry if a
  problem occurs. For more information about how to back up and restore
  the registry, refer to the following Microsoft Knowledge Base article.
How to back up and restore registry and Creating a system
  restore point.

A: I have another solution, since i didn't find the folder ...\Desktop\NameSpace in my registry.
I searched the registry, using the following settings: Search only by Data, text "OneDrive", comparing the whole string. The fourth entry i found was something like this:
HKEY_USERS\[User-ID]\Software\Classes\CLSID\[XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX]
The only thing i had to change was setting System.IsPinnedToNameSpaceTree to 0, then the wrong entry disappeared.
If you try this, make sure you copy the key and store it before you make any changes. You can set the key value to 1 again, if you picked the wrong entry.


text:
Q: Android save data files to app-specific directory I have put together a small app which will take a picture and then Save the Image file out to the External Storage.
I have the permissions set in the Manifest.
And it is working (sort of...).
BUT it is saving the files to the 'root' of the MyFiles directory
( /storage/emulated/0 )
not to my app-specific directory
( /storage/emulated/0/Android/data/com.my.app )
and I don't want to go to an SD card location.
Currently I am using
private File mLocation = new File(Environment.getExternalStorageDirectory(),"test.jpg");

to establish the pathed file name.
And, as I said, that is working - only going to the wrong directory location.
Obviously I should be doing something different, but I don't know what to change and the other postings on the general topic I have found are not clearly presented such that I can 'interpret' from them what I need to change.
Your advice/suggestions would be greatly appreciated.
Thanks

A: private File mLocation  = new File(getExternalFilesDir(null), "test.jpg");

read this article

A: Well I saw where I was not specifically following your suggestions and therefore I changed the code from:
(Environment.getExternalFilesDir(null), "test.jpg")

to
(getExternalFilesDir(null), "test.jpg")

And the error message went away.
BUT now the app crashes immediately before getting up and running.


text:
Q: Magento 2 custom customer attribute data not saved We are working on Magento 2.2 create custom attribute seller_id for customer,this attribute is created successfully.
But we can not display this attribute when loading the customer data.
<?php
namespace Kh\Hello\Setup;

use Magento\Customer\Model\Customer;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;

class InstallData implements InstallDataInterface
{

    private $customerSetupFactory;

    /**
     * Constructor
     *
     * @param \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
     */
    public function __construct(
        CustomerSetupFactory $customerSetupFactory
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        $customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'seller_id', [
            'type' => 'varchar',
            'label' => 'Seller Id',
            'input' => 'text',
            'source' => '',
            'required' => false,
            'visible' => true,
            'position' => 333,
            'system' => false,
            'backend' => ''
        ]);

        $attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'seller_id')
        ->addData(['used_in_forms' => [
                'adminhtml_customer'
            ]
        ]);
        $attribute->save();

    }
}

when load customer collection this attribute is not display.
$collection = $this->_customerFactory->create()->getCollection()
                   ->addAttributeToSelect("*")
                   ->addAttributeToFilter("email", array("eq" => "gg@gmail.com"));

Also loading customer and accessing this attribute data not display.

A: Check to make sure that the attribute is in the customer_form_attribute table.
Additionally, check that the is_system attribute value is set to 0.
Also, you have assigned that attribute to "adminhtml_customer" form only. Might be it will not load attribute on the frontend.

A: Try also to add attribute to Default attribute set something like this:
$customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY);
$attributeSetId = $customerEntity->getDefaultAttributeSetId();

$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

$attribute->addData([
    'attribute_set_id' => $attributeSetId,
    'attribute_group_id' => $attributeGroupId,
    'used_in_forms' => ['customer_account_edit']
]);
$attribute->save();


text:
Q: Is "laic" an alternative word to the word "layperson"? Can laic be used interchangeably with layperson as a gender-neutral alternative to layman and laywoman?
Example 1

The site is more suitable for the laics.

vs

The site is more suitable for laypersons.

Example 2

Laics are not allowed here.

vs

Laypersons are not allowed here.

Example 3

I am a laic to this subject.

vs

I am a layperson to this subject.

A: No, not if you want anyone to know what you're talking about.
Laic is a very rare, formal, ecclesiastic term that virtually no one outside the extremely well educated have ever even heard of, let alone used. Laic is to laity as cleric is clergy.  Most people don't know who the laity even are, not to mention their laic representatives. Almost anyone who does probably knows the original Latin laicus, and just how many do you reckon know that word?
Laic is one hundred times less frequent than layman in Google ngrams, and the plural laics is thrice rarer still.

If the intent is communication, you should not use these terms outside the exceedingly narrow context of papal bulls and other equivalently religious epistles.


text:
Q: Errors using rspec, missing libraries after installing Homebrew and uninstalling MacPorts I may have taken one step too far beyond my knowledge. I installed Homebrew and after it continued to give me warnings about having MacPorts installed I uninstalled that. But now my rspec tests don't run.
These are the errors I get:
/Users/mark/.rvm/gems/ruby-1.9.2-p180/gems/nokogiri-1.4.4/lib/nokogiri.rb:13:in `require': dlopen(/Users/mark/.rvm/gems/ruby-1.9.2-p180/gems/nokogiri-1.4.4/lib/nokogiri/nokogiri.bundle, 9): Library not loaded: /opt/local/lib/libiconv.2.dylib (LoadError)
  Referenced from: /Users/mark/.rvm/gems/ruby-1.9.2-p180/gems/nokogiri-1.4.4/lib/nokogiri/nokogiri.bundle
  Reason: Incompatible library version: nokogiri.bundle requires version 8.0.0 or later, but libiconv.2.dylib provides version 7.0.0 - /Users/mark/.rvm/gems/ruby-1.9.2-p180/gems/nokogiri-1.4.4/lib/nokogiri/nokogiri.bundle
.....
.....

I've installed libiconv through Homebrew, but that didn't fix it. It's complaining about libiconv version numbers. Is this the problem?
What is going on here and what do I need to do?

A: I got things working again for anyone interested. I removed and re-installed nokogiri gem and everything seems to be working again.

A: Generally, this problem is caused by being unable to find the right libiconv. Here is how I solve my problem:
Check output of otool -L /usr/lib/libiconv.2.dylib. I got the following output:
/usr/lib/libiconv.2.dylib (compatibility version 7.0.0, current version 7.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 169.3.0)

Then I install libiconv with Homebrew, brew install libiconv, and show where it was installed using brew list libiconv. I got the following output:
/usr/local/Cellar/libiconv/1.14/bin/iconv
/usr/local/Cellar/libiconv/1.14/include/ (3 files)
/usr/local/Cellar/libiconv/1.14/lib/libcharset.1.dylib
/usr/local/Cellar/libiconv/1.14/lib/libiconv.2.dylib
/usr/local/Cellar/libiconv/1.14/lib/ (3 other files)
/usr/local/Cellar/libiconv/1.14/share/doc/ (6 files)
/usr/local/Cellar/libiconv/1.14/share/man/ (6 files)

the libiconv is installed in /usr/local/Cellar/libiconv/1.14/lib/libiconv.2.dylib. Then I check verion of newly installed libiconv,
otool -L /usr/local/Cellar/libiconv/1.14/lib/libiconv.2.dylib, and I got the following output:
/usr/local/Cellar/libiconv/1.14/lib/libiconv.2.dylib:
/usr/local/opt/libiconv/lib/libiconv.2.dylib (compatibility version 8.0.0, current version 8.1.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 169.3.0)

The version is correct, and we need to make this library available for Ruby. Creating a symbol link is a quick solution:
sudo ln -s /usr/local/opt/libiconv/lib/libiconv.2.dylib /opt/local/lib/libiconv.2.dylib

A: I had to re-install libxml-ruby in addition to nokogiri to get things working again.

A: FWIW, I ran into the same issue and if you are vendorizing your gems, you will have to remove the offending gem from vendor/ruby as a gem uninstall + reinstall is not always efficient. I'm guessing bundler leaves cache remnants of gems and their respective libs even when running a fresh install.


text:
Q: Problem to write long lines in terminal I have defined a PS1 prompt multi-line in my server with Ubuntu 11.04.
The problem occurs when I write a long command, the line cuts before the end of terminal and it continues at beginning the same line:

But if I continue writing the line ends at the end of window and it continues in next line, as expected:

And if I press Home key the cursor goes to the line above the first line.
I connect to server with SSH in a gnome-terminal.
The PS1 line in /etc/bash.bashrc is:
[ $UID -eq "0" ] && PS1="\e[31m┏━\e[42m┅◉ \e[37m\d ⌚ \t \e[31m┅\e[0m\e[31m━━\e[42m┅◈ \e[37m\H \e[0m\n\e[31m┣\e[0m \w (\e[36m\$(ls -1 | wc -l) fichero/s\e[0m) \n\e[31m┗\e[45m┅◉\e[1;37m \u \e[0m\e[31m━► " || PS1="┏━\e[44m┅◉ \e[37m\d ⌚ \t ┅\e[0m━━\e[44m┅◈ \e[37m \e[0m\n┣━━\e[42m┅◉ kernel: \e[37m$(uname -r) ┅\e[0m━━\e[42m┅◈ uptime: \e[37m$(date -d "`cut -f1 -d. /proc/uptime` seconds ago" +"%a %d %b %R") \e[0m\n┣ \w (\e[36m\$(ls -1 | wc -l) fichero/s\e[0m) \n┗\e[46m┅◉\e[1;37m \u \e[0m━► "

Some of the environment variables:
$ env
TERM=xterm
SHELL=/bin/bash
SSH_TTY=/dev/pts/0
LC_ALL=
LC_MESSAGES=POSIX
LC_COLLATE=C
LANG=es_ES.UTF-8
HISTCONTROL=ignoreboth
SHLVL=1
LESS=-Rsw
LESSOPEN=| /usr/bin/lesspipe %s
LESSCLOSE=/usr/bin/lesspipe %s %s
_=/usr/bin/env

Any idea?

A: Here I fixed it for you :
Here the first one :
PS1='\[\e[0;31m\]┏━\[\e[42m\]┅◉ \[\e[0;37m\]\[\e[42m\]\d ⌚ \t \[\e[0;31m\]┅\[\e[0m\]\[\e[0;31m\]━━\[\e[42m\]┅◈ \[\e[0;37m\]\[\e[42m\]\H \[\e[0m\]\n\[\e[0;31m\]┣\[\e[0m\] \w (\[\e[36m\]$(ls -1 | wc -l) fichero/s\[\e[0m\]) \n\[\e[0;31m\]┗\[\e[45m\]┅◉\[\e[1;37m\]\[\e[45m\] \u \[\e[0m\]\[\e[0;31m\]━► '

And the second one :
PS1='┏━\[\e[44m\]┅◉ \[\e[0;37m\]\[\e[44m\]\d ⌚ \t ┅\[\e[0m\]━━\[\e[44m\]┅◈ \[\e[0;37m\]\[\e[44m\] \[\e[0m\]\n┣━━\[\e[42m\]┅◉ kernel: \[\e[0;37m\]\[\e[42m\]$(uname -r) ┅\[\e[0m\]━━\[\e[42m\]┅◈ uptime: \[\e[0;37m\]\[\e[42m\]$(date -d "`cut -f1 -d. /proc/uptime` seconds ago" +"%a %d %b %R") \[\e[0m\]\n┣ \w (\[\e[0;36m\]$(ls -1 | wc -l) fichero/s\[\e[0m\]) \n┗\[\e[46m\]┅◉\[\e[1;37m\] \u \[\e[0m\]━► '


text:
Q: How to check all groups in an OU have enabled members I need to separate all the groups in an OU into two group. one that has enabled members and one that has no enabled members. Is there any easy way to do this?
I currently use:
$results = foreach ($OU in $OUs) {
    get-adgroup -SearchBase $OU -filter {Name -like '*'} -properties CanonicalName,CN,Description,ManagedBy,member,memberof,members |
        select CanonicalName,CN,Description,ManagedBy,member,memberof,members
}

to grab everything but I dont know how to then segregate them by their members.


text:
Q: PostgreSQL: Possible to create a function with a TYPE and modify the TYPE after Hi I want to create a function which returns a user defined type. After the function is created I want to be able to update the type to something else, so that the function uses the new type eg.
CREATE TYPE my_type AS ("Column1" text, "Column2" text);

CREATE OR REPLACE FUNCTION my_fucntion()
RETURNS SETOF my_type
bla
bla
blah

ALTER TYPE my_type AS ("Name" text, "Address" text)

Is this possible? the alterations will always only be the name of the column not the actual data format, that will always be the same.
EDIT: Well the thing is I have 2 scripts one which is generic and must be installed as is with no changes. It has to be installed in multiple places. The second is a sort of config script.
In the generic script I create a function which returns a type of what I wanted to define in the config script.
I thought to install the config script first but I can't as I need to perform some Inserts based on the functions which are in generic script.
Thanks

A: I tried with PostgreSQL 9.1, and it seems to just work.
Example:
CREATE TYPE my_type as (col1 text, col2 text);
CREATE TABLE my_table (a my_type);
INSERT INTO my_table values(('ab','cd'));
CREATE FUNCTION my_function() returns setof my_type as
    'begin return query select (a).* from my_table; end;'
language plpgsql;

select * from my_function();

Output is:
 col1 | col2
------+------
 ab   | cd

Now let's rename columns in my_type:
alter type my_type rename attribute col1 to address;
alter type my_type rename attribute col2 to name;

=> No error
Now call again the function:
select * from my_function();

No error, output is:
 address | name
---------+------
 ab      | cd

Looks like the expected result, doesn't it?

A: Can't see how you could get this to work. Anything depending on "my_type" would break when you changed its definition.
Perhaps post another question with the actual problem you are trying to solve.
EDIT (after question clarification): OK - so you want renamed columns for specific customers or sites or some such. Either wrap your original function in a view:
CREATE VIEW local_columns AS
SELECT column1 AS foo, column2 as bar FROM my_function()

If you need to pass parameters, wrap your function in another type and function:
SELECT * FROM my_outer_function('some','params')

Your config file will have to set up the outer type + function or view.

A: This is generally impossible in PostgreSQL. I quote the manual on CREATE FUNCTION:

Also, CREATE OR REPLACE FUNCTION will not let you change the return
  type of an existing function. To do that, you must drop and recreate
  the function. (When using OUT parameters, that means you cannot change
  the types of any OUT parameters except by dropping the function.)

Bold emphasis mine. To facilitate the process (and remove the tie between type and function) you might consider using OUT parameters or RETURNS TABLE instead of RETURNS SETOF my_type. Like this:
CREATE OR REPLACE FUNCTION my_function()
 RETURNS TABLE (column1 text, column2 text) AS
$BODY$
 -- do something
$BODY$ language xyz;

As an aside: My personal advise is to always user lower case identifiers in PostgreSQL. I renamed the OUT columns accordingly in the example.


text:
Q: How do you create an iterator using a closure in rust? I naively tried to do this:
struct Foo<'a, S: Send, T:Send> {
    next_:Box<Fn<(&'a mut S,), Option<T>> + Send>,
    state:S
}

impl<'a, S: Send, T: Send> Iterator<T> for Foo<'a, S, T> {
    fn next(&mut self) -> Option<T> {
        return self.next_.call((&mut self.state,));
    }
}

To create an iterator I could send to a task easily using a closure.
However, it generates the dreaded lifetime mismatch error:
<anon>:8:33: 8:48 error: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
<anon>:8         return self.next_.call((&mut self.state,));
                                         ^~~~~~~~~~~~~~~
<anon>:7:5: 9:6 help: consider using an explicit lifetime parameter as shown: fn next(&'a mut self) -> Option<T>
<anon>:7     fn next(&mut self) -> Option<T> {
<anon>:8         return self.next_.call((&mut self.state,));
<anon>:9     }
error: aborting due to previous error
playpen: application terminated with error code 101

I don't understand the error.
The closure should take an argument with the lifetime 'a, which is the lifetime of the struct.
The state is owned by the struct, so it has a lifetime of 'a.
Using next_.call((&mut self.state,)) doesn't invoke a task; it should only be for the duration of the call(), which as far as I can tell should be valid.
So the mismatch here is between the lifetime on self in next(), and the 'a in call... but I don't see why it would not be 'a.
What's the right way to fix the code above?
Is there a better approach to take to do this?
playpen: http://is.gd/hyNi0S

A: This requires higher-rank lifetimes, since the lifetime in the closure should not be part of the type signature: the closure just wants to take &'a mut S for any lifetime 'a (since it needs to call the function with data that is only guaranteed to last for the interior of the next method: nothing nameable externally), not the lifetime exposed (and somewhat controllable) externally in the type signature. This isn't possible, but I've seen Niko Matsakis talking about working on it on IRC, and there are preparatory pull requests like #18837 so this will hopefully appear soon.
To be clear: the code fails because next_ can only be called with a reference that lives for at least 'a, but &mut self.state only lives for as long as &mut self, which is not 'a unless it is declared as &'a mut self (which is why the compiler suggests it). Adding this lifetime is illegal since it does not satisfy the requirements of the trait declaration.
You can work around this using the old closures for now (this is essentially what a Fn trait object is anyway), and there's even a standard library type that does this for you: Unfold.

A: This is an unfortunate limitation of current Rust's trait system which will be lifted very soon. It is a lack of higher-kinded lifetimes. As far as I know, its implementation is currently being worked on.
Let's examine your struct definition closer (I've removed mut to allow further reasoning with 'static, this does not make it less general):
struct Foo<'a, S: Send, T:Send> {
    next_: Box<Fn<(&'a S,), Option<T>> + Send>,  // '
    state: S
}

'a lifetime parameter is an input parameter here. It means that it is provided by the user of the structure, not by its implementor.
(BTW, it is not the lifetime of the structure instance - you can't specify such lifetime with type parameters only; it must be a lifetime on self reference, which you also can't use because Iterator trait method does not have a lifetime parameter. This is just a side note, however, and it is unrelated to the actual problem)
This means that the user of your structure may choose 'a arbitrarily, including choosing some lifetime which is greater than the lifetime of your struct, for example, 'static. Now observe how such selection transforms the structure (just substituting 'static for 'a):
struct FooStatic<S: Send, T: Send> {
    next_: Box<Fn<(&'static S,), Option<T>> + Send>,  // '
    state: S
}

And suddenly, the closure only can accept 'static references, which is obviously not your case - lifetime of self in the next() method may be shorter, so you can't just pass it into the closure. This could only work if self lifetime did correspond to 'a (as suggested by the compiler):
fn next(&'a mut self) -> Option<T>

However, as I said earlier, you can't write this because it would violate trait contract.
With higher-kinded lifetimes it will be possible to specify lifetime parameter on the closure itself:
struct Foo<S: Send, T: Send> {
    next_: Box<for<'a> Fn<(&'a mut S,), Option<T>> + Send>,
    state: S
}

This way the lifetime parameter of the closure is chosen by the caller of the closure, in this case, it's the implementor of the Iterator trait (i.e. you :)), so it will be possible to call next_ with any reference, including a reference into Foo internals.

A: You can use iterate from itertools that do exactly what you need.
Otherwise if you want to enclose all the logic in a closure without use a
state concept you can implement it by:
struct IterClosure<T, C>(C) where C: FnMut() -> Option<T>;

impl<T, C> Iterator for IterClosure<T, C> where C: FnMut() -> Option<T>
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        (self.0)()
    }
}

fn iter<T>(f: impl FnMut() -> Option<T>) -> impl Iterator<Item=T> {
    IterClosure(f)
}

fn main() {
    let mut it = (0..10).into_iter();
    let mut closure = || it.next();
    println!("{}", iter(closure).sum::<i32>());

    let mut it = (0..10).into_iter();
    iter(|| it.next()).for_each(
        |i| println!("{}", i)
    )
}


text:
Q: Difference between requests.request('POST' and request.post what would it be the difference between these two sentences:
res = requests.request('POST', url)

and
res = requests.request.post(url)

A: They are pretty much the same thing: https://github.com/psf/requests/blob/177dd90f18a8f4dc79a7d2049f0a3f4fcc5932a0/requests/api.py#L103-L115
requests.post(…) is just a wrapper around requests.request('POST', …). As long as you're using standards methods, the former helps readability and reduces the risk of easily avoidable mistakes, while writing the verb.
Edit: updated the source reference, since the domain docs.python-requests.org has expired, and the previous link (http://docs.python-requests.org/en/master/_modules/requests/api/#post) is now invalid.


text:
Q: JavaFX, Maven and SceneBuilder - image doesn't load The image shows in SceneBuilder, but as you can see at the picture below, in java application it doesn't load (even though the Intellij detects image's presence). My bet is that it has something to do with Maven, but I have no idea how to fix it...

A: I guess I was right about Maven, since it messes with the resource path.
All I had to do was change <Image url="@../../../resources/logo.png" />
to <Image url="@/logo.png" />
in .fxml file


text:
Q: Query subdocuments without knowing the keys I have a collection like this:
{
"_id" : ObjectId("5a7c49b02d2bbb28a4b2e6a2"),
    "phone" : "Pinheiro",
    "email" : "Pinheiro",
    "variableParameters" : {
        "loremIpsum" : "Do you see a little Asian child with a blank expression on his face sitting outside on a mechanical helicopter that shakes when you put quarters in it?",
        "uf" : "Rio de Janeiro",
        "city" : "Rio de Janeiro",
        "end" : "RUA JARDIM BOTÂNICO 1060",
        "tel" : "5521999999999",
        "eml" : "teste@gmail.com",
        "nome" : "Usuario de Teste"
    }
}

And i want to query the "variableParameters" object, but like the name said, this properties are variable. So in some cases it will have "uf", but in other cases won't.
I'm actually doing a query that only matches the constant field from a mongoose schema:
{ 'phone': { $regex: filter, $options: 'i' } }

Is there any way that I can query "variableParameters" without knowing his child properties?

A: If you are unsure about the keys(since they are variable), then try using $text search
To use text search we need to index the variableParameters.
Case sensitive text search can also be performed but it comes with the impact on performance.
Please read https://docs.mongodb.com/manual/reference/operator/query/text/ for more information on text search

A: [SOLVED]
Thanks @Clement Amarnath for the help.
The solution is something like this:
_Events.find({ $text: { $search: 'searchText' } }, (err, events) => {
    if (err) return Exceptions.HandleApiException(err, res);
    res.send(events);
});

The $text parameter can have this properties:
{
  $text: {
      $search: <string>,
      $language: <string>,
      $caseSensitive: <boolean>,
      $diacriticSensitive: <boolean>
  }
}

$search A string of terms that MongoDB parses and uses to query the text index. MongoDB performs a logical OR search of the terms unless specified as a phrase. See Behavior for more information on the field.
$language Optional. The language that determines the list of stop words for the search and the rules for the stemmer and tokenizer. If not specified, the search uses the default language of the index. For supported languages, see Text Search Languages.
If you specify a language value of "none", then the text search uses simple tokenization with no list of stop words and no stemming.
$caseSensitive  Optional. A boolean flag to enable or disable case sensitive search. Defaults to false; i.e. the search defers to the case insensitivity of the text index.
$diacriticSensitive Optional. A boolean flag to enable or disable diacritic sensitive search against version 3 text indexes. Defaults to false; i.e. the search defers to the diacritic insensitivity of the text index.
For more information, see MongoDB Documentation.

A: You can use $where to build your own matching function.
An example for a full-text match would be:
db.col.find({$where: function(){
  return Object.values(this.variableParameters).includes("Rio de Janeiro")
}})


text:
Q: how to add close button in swiper? I want to add close butotn on the left side of swiper,
So i use this code line,
<button onclick="hide();">Click to hide!</button>

<script>
hide = function(){
document.getElementsByClassName('swipe')[0].style.display="none";
}
</script>

it written and tested on swiper demo.
I can see the button, but when i clike it, it doesnt work
how to add?
I make another button and script on the code.
And I expect that when i clik the button, the whole code about the swiper will be dissmissed.
because the style " style.display="none " would addaped.
but it doesnt work


text:
Q: Configure MySQL so it doesn't automatically change values in NOT NULL columns Surprisingly (at least to me), the following queries will insert records.
CREATE TABLE null_1 (
  id INT NOT NULL,
  text1 VARCHAR(32) NOT NULL,
  text2 VARCHAR(32) NOT NULL DEFAULT 'foo'
);

INSERT INTO null_1 (id) VALUES(1);
INSERT INTO null_1 (text1) VALUES('test');

mysql> SELECT * FROM null_1;
+----+-------+-------+
| id | text1 | text2 |
+----+-------+-------+
|  1 |       | foo   |
|  0 | test  | foo   |
+----+-------+-------+
2 rows in set (0.00 sec)

I couldn't find this behavior described in the official MySQL documentation, but it is described by http://sql-info.de/mysql/gotchas.html#1_1

Here MySQL has inserted an empty string into column text1 on the first
  row, and zero into column id on the second row, even though each
  column is defined as NOT NULL with no default value. As no value was
  provided in the INSERT statements, these can be considered an attempt
  to insert implicit NULLs into theses columns, which should normally
  cause the statements to fail.
... If no DEFAULT value is specified for a column, MySQL automatically assigns one, as follows. If the column may take NULL as
  a value, the default value is NULL. If the column is declared as NOT
  NULL, the default value depends on the column type: ...

Is it possible to configure MySQL to prevent doing so, and reject the query based on the NOT NULL constraint?  My my.cnf file is shown below.
##  _______________________________________________________________________
## / Rackspace MySQL 5.5 Terse Configuration File                          \
## |                                                                       |
## | This is a base configuration file containing the most frequently used |
## | settings with reasonably defined default values for configuring and   |
## | tuning MySQL. Note that these settings can likely be further tuned in |
## | order to get optimum performance from MySQL based upon the database   |
## | configuration and hardware platform.                                  |
## |                                                                       |
## | While the settings provided are likely sufficient for most            |
## | situations, an exhaustive list of settings (with descriptions) can be |
## | found at:                                                             |
## | http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html   |
## |                                                                       |
## | Take care to only add/remove/change a setting if you are comfortable  |
## | doing so! For Rackspace customers, if you have any questions or       |
## | concerns, please contact the MySQL Database Services Team. Be aware   |
## | that some work performed by this team can involve additional billable |
## \ fees.                                                                 /
##  -----------------------------------------------------------------------
##         \   ^__^
##          \  (oo)\_______
##             (__)\       )\/\
##                 ||----w |
##                 ||     ||

[mysqld]

## General
datadir                         = /var/lib/mysql
tmpdir                          = /var/lib/mysqltmp
socket                          = /var/lib/mysql/mysql.sock
skip-name-resolve
sql-mode                        = NO_ENGINE_SUBSTITUTION
#event-scheduler                = 1

## Cache
thread-cache-size               = 16
table-open-cache                = 4096
table-definition-cache          = 2048
query-cache-size                = 32M
query-cache-limit               = 1M

## Per-thread Buffers
sort-buffer-size                = 1M
read-buffer-size                = 1M
read-rnd-buffer-size            = 1M
join-buffer-size                = 1M

## Temp Tables
tmp-table-size                  = 32M
max-heap-table-size             = 64M

## Networking
back-log                        = 100
#max-connections                = 200
max-connect-errors              = 10000
max-allowed-packet              = 16M
interactive-timeout             = 3600
wait-timeout                    = 600

### Storage Engines
#default-storage-engine         = InnoDB
innodb                          = FORCE

## MyISAM
key-buffer-size                 = 64M
myisam-sort-buffer-size         = 128M

## InnoDB
#innodb-buffer-pool-size        = 128M
#innodb-log-file-size           = 100M
#innodb-log-buffer-size         = 8M
#innodb-file-per-table          = 1
#innodb-open-files              = 300

## Replication
server-id                       = 1
#log-bin                        = /var/log/mysql/bin-log
#relay-log                      = /var/log/mysql/relay-log
relay-log-space-limit           = 16G
expire-logs-days                = 7
#read-only                      = 1
#sync-binlog                    = 1
#log-slave-updates              = 1
#binlog-format                  = STATEMENT
#auto-increment-offset          = 1
#auto-increment-increment       = 2

## Logging
#log-output                      = FILE
#slow-query-log                  = 1
#slow-query-log-file             = /var/log/mysql/slow-log
#log-slow-slave-statements
#long-query-time                 = 2

#log                              = /home/mysql_log/allqueries.log
general_log = on
general_log_file=/home/mysql_log/allqueries.log

symbolic-links=0

[mysqld_safe]
log-error                       = /var/log/mysqld.log
open-files-limit                = 65535

innodb_flush_log_at_trx_commit = 0
innodb_strict_mode=on
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_DATE,NO_ZERO_IN_DATE

[mysql]
no-auto-rehash

A:
I couldn't find this behavior described in the official MySQL documentation

A few minutes of looking in the MySQL docs found this:
Column values can be given in several ways:

If you are not running in strict SQL mode, any column
not explicitly given a value is set to its default
(explicit or implicit) value. For example, if you specify a
column list that does not name all the columns in the
table, unnamed columns are set to their default values.
Default value assignment is described in Section 11.6,
"Data Type Default Values". See also Section 1.8.3.3,
"Constraints on Invalid Data".

If you want an INSERT statement to generate an error unless
you explicitly specify values for all columns that do not
have a default value, you should use strict mode. See
Section 5.1.7, "Server SQL Modes".

A: Use SQL mode STRICT_ALL_TABLES per http://dev.mysql.com/doc/refman/5.6/en/sql-mode.html#sqlmode_strict_all_tables.


text:
Q: add library on makefile I execute the guide of "Using a "Real" Cross-Compiler" descript on the link. In the botton of the guide there is a standard makefile. I write a simple program write in C and with the comand make it run. Now I would to write a program with the library "ev3c.h". How can I add this library in the makefile?

A: If you're using gcc or clang, pass -I  /home/daniele/ev3c/include to it in your recipe.
That'll allow you to #include from that path with #include "someheader".
As far as Make-treatment of include files is concerned, they're usually implicit dependencies—that is you usually don't want to mention them in your dependencies explicitly, because compilers such as clang or gcc can detect them and add them to the appropriate Makefile rules for you.
-MMD -MF somefile allows you to do this kind of #include dependency detection with gcc or clang:
For example:
%.o: %.c
    $(COMPILE.c) -I /home/daniele/ev3c/include $(OUTPUT_OPTION) $< -MMD -MF $(patsubst %.o,%.o.d,$@)

-include $(wildcard *.o.d)

This will have the compiler detect include dependencies for each compiled c file and the -include line will add these dependencies to your Makefile so that if your C file includes "foo.h" and foo.h changes, make will trigger a recompile even if you don't mention foo.h  as an explicit dependency.

A: Your .h file is header. Headers are included in the source code, not at compile time like libraries:
#include "ev3c.h"

for example.
A library has a different extension, like .a for example. You would add libev3c.a with:
-lev3c

in your makefile on the line that calls your compiler. However, you have a header, so simply add #include "ev3c.h" to the top of your source code (the .c file)


text:
Q: How do we describe the relationship of balloon size and related lift? We know that hydrogen and helium are lighter that air.
Therefore it is certain that they would create a lifting force when enclosed in a balloon.
How do we describe the relationship of balloon size and related lift?

A: The force is given by Archimedes' principle. For a balloon of mass $m$ containing a volume $V$ of some gas of density $rho_g$, immersed in air of density $\rho_a$, the net upward force is
$$F=-mg+V(\rho_a-\rho_g)g.$$
Some show of an attempt to research the question before posting it here would be quite welcome, though.


text:
Q: Is it possible to view the list of file names of a zip file which is inside another zip file? I know I can use unzip -l file.zip to view the file list of a zip file.
But a got a zip file inside another zip file. I tried unzip -l file.zip/sub_file.zip, but failed.
Is it possible to view the file list of the sub_file.zip  without extract it out?

A: You can use less with Wolfgang Friebel's lesspipe script: less file.zip:sub_file.zip

A: unzip -l file.zip/sub_file.zip doesn't work because file.zip isn't a directory: it's a regular file that happens to be in an archive format. But you can create a directory that mirrors the content of the zip file, by mounting a filesystem that presents a view of the content of the zip file. There are several choices, pick whichever is easiest to install on your distribution:

*

*AVFS

*fuse-zip

*archivemount
For example, with archivemount:
mkdir file.d
archivemount file.zip file.d
unzip -l file.d/sub_file.zip
fusermount -u file.d

or even
mkdir file.d sub_file.d
archivemount file.zip file.d
archivemount file.d/sub_file.zip sub_file.d
ls -lR sub_file.d
fusermount -u sub_file.d
fusermount -u file.d

See Extract only a specific file from a zipped archive to a given directory, How do I recursively grep through compressed archives? and Search for files with a specific size inside recursive zipped archives for examples of AVFS and fuse-zip in similar situations.

A: With zsh:
$ unzip -l a.zip.zip
Archive:  a.zip.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
      195  2014-08-18 09:38   a.zip
---------                     -------
      195                     1 file

$ unzip -l =(unzip -p a.zip.zip a.zip)
Archive:  /tmp/zsh0i0JyZ
  Length      Date    Time    Name
---------  ---------- -----   ----
       55  2014-08-15 15:24   a
---------                     -------
       55                     1 file

=(...) is a third form of process substitution that  uses a temporary file instead of a pipe (unzip only works with  seekable files).


text:
Q: Algorithmic Toolbox : Maximize Arithmetic expression using parentheses? Failed Test Case #5/19 The problem was in week 6 of algorithmic toolbox course on Coursera. The problem is to find out the maximum value of an arithmetic expression consisting of + , - and * only.
I coded a solution, have run it with test cases and also incurred a stress test with other solutions available online. Everywhere my code seems to run fine. But whenever I am trying to submit it is failing the 5th test case. First I thought it was due to value overflow in long long, so submitted the solution with double data type. Still the problem remains.
The maximum and minimum functions
long long maximum(long long a,long long b,long long c,long long d)
{
    int a1 = a>b?a:b;
    int a2 = c>d?c:d;
    return a1>a2?a1:a2;
}

long long minimum(long long a,long long b,long long c,long long d)
{
    int a1 = a<b?a:b;
    int a2 = c<d?c:d;
    return a1<a2?a1:a2;
}

The eval function
long long eval(long long a, long long b, char op) {
  if (op == '*') {
    return a * b;
  } else if (op == '+') {
    return a + b;
  } else if (op == '-') {
    return a - b;
  } else {
    assert(0);
  }
}

The algorithm implementation
long long get_maximum_value(char *str) {
  int len = strlen(str);
  int n = (len+1)/2,i,j,k;
  long long a,b,c,d,a1,b1;
  long long **max = (long long **)malloc(n*sizeof(long long*));
  long long **min = (long long **)malloc(n*sizeof(long long*));
  for(i=0;i<n;i++)
  {
      max[i] = (long long*)malloc(n*sizeof(long long));
      min[i] = (long long*)malloc(n*sizeof(long long));
  }
  for(i=0;i<n;i++){
    max[i][i] = str[i*2] - '0';
    min[i][i] = str[i*2] - '0';
  }
  for(i=1;i<n;i++)
    for(j=0;i+j<n;j++)
    {
        max[j][i+j] = LLONG_MIN;
        min[j][i+j] = LLONG_MAX;
        for(k=j;k<i+j;k++)
        {
            a = eval(max[j][k],max[k+1][i+j],str[2*k+1]);
            b = eval(max[j][k],min[k+1][i+j],str[2*k+1]);
            c = eval(min[j][k],max[k+1][i+j],str[2*k+1]);
            d = eval(min[j][k],min[k+1][i+j],str[2*k+1]);
            a1 = maximum(a,b,c,d);
            b1 = minimum(a,b,c,d);
            if(a1>max[j][i+j]) max[j][i+j] = a1;
            if(b1<min[j][i+j]) min[j][i+j] = b1;
        }
    }
  return max[0][n-1];
}

Have anyone faced a similar problem? Please if possible suggest a test case for with the code will fail. It will be very helpful.
Thanks in advance.

A: I got the problem. It was integer overflow. I actually defined a1 and a2 as int inside the maximum and minimum function.
long long maximum(long long a,long long b,long long c,long long d)
{
    long long a1 = a>b?a:b;
    long long a2 = c>d?c:d;
    return a1>a2?a1:a2;
}

long long minimum(long long a,long long b,long long c,long long d)
{
    long long a1 = a<b?a:b;
    long long a2 = c<d?c:d;
    return a1<a2?a1:a2;
}

Changing it into long long solved the problem.