text:
Q: With jQuery Mobile forms, where do i put the validation message? According to the jQuery Mobile docs, this is how you set up fields in a web form:

   Text Input:
   <input type="text" name="name" id="name" value=""  />

Is there a best practice or "official" way of adding a validation message to this? I basically want the validation messages to appear under each textbox in my form.

A: I haven't seen any "official" way of supporting input-validation fields. What we're currently doing though, is using the combination of:

*

*jquery.validate

*jquery.unobtrusive.js (not a pre-requisite)

*asp.net mvc3 w/ Fluent validation (not a pre-requisite)

Here's an example of what the input-validation looks like for a single field:
Name Input:
<input data-val="true" data-val-required="Name is required" id="Name" name="Password" type="text" class="ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-d">

jquery.validate then takes care of inserting and displaying the correct message in the validation span. It doesn't support html5 input field-types yet, but I have a branch on github with the necassary changes to support this.


text:
Q: Notational Shorthand: $a$ is greater than both $b$ and $c$? Suppose I have three real scalars $a$, $b$ and $c$. I know $a>b$ and $a>c$, but know nothing about the relationship between $b$ and $c$. Like this question I want to express this relationship mathematically in a sentence, but I want to do so without using functions or writing it out in words.
Question
Is there a "proper" and unambiguous mathematical expression to express this?
 (Bonus: If so, what is it?)
Guesses
My first guess was:
$$a>b,c$$
but I realized it could be interpreted as $a>b$ with a hanging $c$. Then I thought this might work:
$$a>(b,c)$$
but then I wondered if it would look like $(b,c)$ was an ordered pair or something. I thought we might be able to borrow from set theory, but this question indicates not.
The suggestions from the answer to this question are either
$$ a \text{ is greater than either } b \text{ or } c\text{,}$$
which is rather wordy, or
$$ a > \max(b,c) \text{,}$$
which resorts to using a function. I expect that there is a way to express this notationally. My question differs from this question in that while I would like to know the notation (that answer belongs to that question), I'm asking whether such a notation even exists.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connection refused to outlook.company.com mail server through php Question,
i am using symfony mailer for 6.1 (https://symfony.com/doc/current/mailer.html)  and i seem to be getting a connection refused when trying to send an email to the server. Normally, i would assume username / password but i'm 99% sure it's sending the correct credentials to the server. When i dump the contents of the mailer object i can see the -username -password objects which match to what they should be.
Using the following settings, port 587, smtp, outlook.company_name.com, Authmode login (Tried with and without in the DSN string), I Tried enabling TLS and disabling it on the same port 587. I Was wondering if anyone has some good example(S) on getting this to work properly? I have verified the username / password as it lets me in via the web gui, but i have a feeling it's something special i'm probably doing with either the DSN string or some other setting/incorrect port maybe. I'm also not sure what the correct way to debug this would be if anyone has any tips.

A: If your Outlook service is hosted by Microsoft, it's very likely that you're seeing their policy change that no longer allows SMTP authentication using ID and password.
You need to implement XOAUTH2 support, which although technically supported by PHPMailer (which you're not actually using as it's not the same thing as Symphony mailer), is proving very difficult to get working in practice.

A: @rob Take a look at my new wiki article and see if this helps you set it up
https://github.com/PHPMailer/PHPMailer/wiki/Microsoft-Azure-and-XOAUTH2-setup-guide


text:
Q: Exception occurs when button clicked inside my custom control I have made a UWP custom templated control that contains a collection of ICommandBarElement, much like the standard CommandBar control. The problem is that as soon as I click on any of the AppBarButton contained in my CommandBar implementation, an unhandled exception occurs: "No such interface supported".
There is something I must doing wrong but I just can't see it. Here is the code for the custom control:
public sealed class MyCommandBarControl : ContentControl
{
    public MyCommandBarControl()
    {
        this.DefaultStyleKey = typeof(MyCommandBarControl);

        this.PrimaryCommands = new ObservableCollection<ICommandBarElement>();
    }

    public ObservableCollection<ICommandBarElement> PrimaryCommands
    {
        get { return (ObservableCollection<ICommandBarElement>)GetValue(PrimaryCommandsProperty); }
        set { SetValue(PrimaryCommandsProperty, value); }
    }

    /// <summary>
    /// PrimaryCommands Dependency Property
    /// </summary>
    public static readonly DependencyProperty PrimaryCommandsProperty =
        DependencyProperty.Register(
            "PrimaryCommands",
            typeof(ObservableCollection<ICommandBarElement>),
            typeof(MainPage),
            new PropertyMetadata(null, null));

    protected override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        var primaryItemsControl = GetTemplateChild("PrimaryItemsControl") as ItemsControl;
        primaryItemsControl.ItemsSource = this.PrimaryCommands;

    }

}

And the associated Style:
<Style TargetType="local:MyCommandBarControl" >
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:MyCommandBarControl">
                <Grid x:Name="LayoutRoot" Background="{TemplateBinding Background}">
                    <Grid x:Name="ContentRoot"
                          VerticalAlignment="{TemplateBinding VerticalAlignment}"
                          Margin="{TemplateBinding Padding}"
                          Height="{TemplateBinding Height}"
                          Background="{TemplateBinding Background}"
                          Opacity="{TemplateBinding Opacity}">

                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <ContentControl
                              x:Name="ContentControl"
                              Content="{TemplateBinding Content}"
                              ContentTemplate="{TemplateBinding ContentTemplate}"
                              ContentTransitions="{TemplateBinding ContentTransitions}"
                              Foreground="{TemplateBinding Foreground}"
                              HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                              HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                              VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                             IsTabStop="False"
                             Margin="10, 0, 0, 0"/>

                        <ItemsControl
                              x:Name="PrimaryItemsControl"
                              IsTabStop="False"
                              Grid.Column="1"
                              Margin="10, 0, 0, 0"
                              HorizontalAlignment="Right"
                              HorizontalContentAlignment="Right">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <StackPanel Orientation="Horizontal" />
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                        </ItemsControl>
                    </Grid>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

I have made a small project you can download that reproduces the problem. Any help resolving this exception would be appreciated.

A: Why not inherit from CommandBar control, and don't need to manage the PrimaryCommands by ourselves.
So simply change your code to the following can solve the issue:
public sealed class MyCommandBarControl : CommandBar
{
    public MyCommandBarControl()
    {
        this.DefaultStyleKey = typeof(MyCommandBarControl);

        //this.PrimaryCommands = new ObservableCollection<ICommandBarElement>();
    }

    //public ObservableCollection<ICommandBarElement> PrimaryCommands
    //{
    //    get { return (ObservableCollection<ICommandBarElement>)GetValue(PrimaryCommandsProperty); }
    //    set { SetValue(PrimaryCommandsProperty, value); }
    //}

    ///// <summary>
    ///// PrimaryCommands Dependency Property
    ///// </summary>
    //public static readonly DependencyProperty PrimaryCommandsProperty =
    //    DependencyProperty.Register(
    //        "PrimaryCommands",
    //        typeof(ObservableCollection<ICommandBarElement>),
    //        typeof(MainPage),
    //        new PropertyMetadata(null, null));

    protected override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        var primaryItemsControl = GetTemplateChild("PrimaryItemsControl") as ItemsControl;
        primaryItemsControl.ItemsSource = this.PrimaryCommands;

    }

}

[Update1]
I think there is underlying type conversion we cannot see or we have to use some interfaces like ICommandBar but we cannot use due to its protection level.
If you do hope to implement CommandBar by yourself, I think it's better to create your own Command button instead of using AppBarButton. But you need to make sure you have a solid reason to do it by yourself.
For example, the following will work if I use a default Button.
public sealed class MyCommandBarControl : ContentControl
{
    public MyCommandBarControl()
    {
        this.DefaultStyleKey = typeof(MyCommandBarControl);

        this.PrimaryCommands = new ObservableCollection<Button>();
    }

    public ObservableCollection<Button> PrimaryCommands
    {
        get { return (ObservableCollection<Button>)GetValue(PrimaryCommandsProperty); }
        set { SetValue(PrimaryCommandsProperty, value); }
    }

    /// <summary>
    /// PrimaryCommands Dependency Property
    /// </summary>
    public static readonly DependencyProperty PrimaryCommandsProperty =
        DependencyProperty.Register(
            "PrimaryCommands",
            typeof(ObservableCollection<Button>),
            typeof(MainPage),
            new PropertyMetadata(null, null));

    protected override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        var primaryItemsControl = GetTemplateChild("PrimaryItemsControl") as ItemsControl;
        primaryItemsControl.ItemsSource = this.PrimaryCommands;

    }

}

In MainPage.xaml
    <local:MyCommandBarControl>
        <local:MyCommandBarControl.Content>
            <TextBlock Text="My CommandBar" />
        </local:MyCommandBarControl.Content>

        <local:MyCommandBarControl.PrimaryCommands>
            <Button Content="Pin" Click="PinBarButton_Click" />
            <Button Content="UnPin" />
            <Button Content="Sync"  />
            <Button Content="Remove" />
        </local:MyCommandBarControl.PrimaryCommands>
    </local:MyCommandBarControl>


text:
Q: Order of unitriangular matrix I have unitriangular matrix group over a field $F_q$.
It consists of the following elements:
$$E + A = \left[\begin{matrix}
    1 & a12 & ... & a1n\\
    0 & 1 & a23 & ...\\
    ... & ... & ... & ... \\
    0 & 0 & ... & 1\\
    \end{matrix}\right]$$ $E$ is identity matrix.
I have to prove that minimum $m$: $(E+A)^{m}=E$, has a form $p^l, l <= n-1$.
In other words, prove that order of matrix $(E+A)$ has a form of $p^l, l <= n-1$.
And also find matrix with maximum order $p^{n-1}$.
So far, I know that $(E+A)^{p^{n-1}}=E$ and that $A^{n-1}=0$, but have no idea where to start.

A: Do you know the order of the group? Lagrange's theorem could be useful to show that the order of $E+A$ is of the form $p^l$.


text:
Q: Tools for plotting behavior of differential equations I have several ODEs describing the behavior of dividing particles (e.g., How to model multi-step cell differentiation). I would like to plot these ODEs based on changing values of p over time.  I would appreciate any advice on what graphics program would be suitable for this task.
Thanks.

A: I'll second Matlab but make specific metion to the Matlab toolkits pplane
and Matcont.
Matcont is particularly useful for investigating bifurcations, which seems to be what you're interested in.

A: I'd use either MATLAB or Python for that. Both have strong visualization capabilities.

A: You should have a lok at SAGE, a free open-source mathematics software.

A: Python is a flexible way of doing this, à la:
#!/usr/bin/env python3

import scipy.integrate
import matplotlib.pyplot as plt
import numpy as np

def func(p, t):
  """Takes a vector p representing the current state and the time t"""
  pdot = 0.2*[0]**0.75
  return [pdot]

t    = np.linspace(0, 100, 200)              #Return state at these time points
init = [2]                                   #Initial conditions
z    = scipy.integrate.odeint(func, init, t) #Integrate the ODE
z    = z.T[0]                                #Transpose and extract state

plt.plot(t,z)
plt.show()


text:
Q: Problem with colored table I'm new using latex and I want to do a colored table for my work. I have the following code:
\documentclass[11pt, oneside]{book}
\usepackage[table]{xcolor}
\usepackage{hhline}
\newcommand{\x}{\cellcolor[gray]{0.8}}
\usepackage{multirow}
\usepackage{rotating}
\usepackage{colortbl}

\begin{document}
\begin{table}[h!]
\caption{List of proposed tasks \label{table_tasks}}
\begin{center}
\begin{tabular}{|c|c|c|c|c|c|c|c|}
\cline{3-8}
\multicolumn{1}{c}{} & \multicolumn{1}{c|}{} & \multicolumn{3}{c|}{F1} & \multicolumn{3}{c|}{F2}\\
\cline{3-8}
\multicolumn{1}{c}{} & \multicolumn{1}{c|}{} & A1 & A2 & A3 & B1 & B2 & B3\\
\hline
\multicolumn{1}{|c|}{\multirow{8}{*}{\rotatebox[origin=c]{90}{Year 1}}} & M &\x & \x & \x & & &\\
\cline{2-8}
& J &\x & \x & \x & & &\\
\cline{2-8}
& J &\x & \x & \x & & &\\
\cline{2-8}
& A &   &    & \x & & &\\
\cline{2-8}
& S &   &    & \x & & &\\
\cline{2-8}
& O &   &    &    & \x & \x & \\
\cline{2-8}
& N &   &    &    & \x & \x & \\
\cline{2-8}
& D &   &    &    & \x & \x & \\
\hline
\multicolumn{1}{|c|}{\multirow{12}{*}{\rotatebox[origin=c]{90}{Year 2}}} & J &   &    &    & \x & \x & \\
\cline{2-8}
& F &   &    &    & \x & \x & \\
\cline{2-8}
& M &   &    &    &  &  & \x \\
\cline{2-8}
& A &   &    &    &  &  & \x \\
\cline{2-8}
& M &   &    &    &  &  & \x \\
\cline{2-8}
& J &   &    &    &  &  & \x \\
\cline{2-8}
& J &   &    &    &  &  & \x \\
\cline{2-8}
& A &   &    &    &  &  & \x \\
\cline{2-8}
& S &   &    &    &  &  & \x \\
\cline{2-8}
& O &   &    &    &  &  & \x \\
\cline{2-8}
& N &   &    &    &  &  & \x \\
\cline{2-8}
& D &   &    &    &  &  & \x \\
\cline{2-8}
\hline
\end{tabular}
\end{center}
\end{table}

\end{document}

The problem is when I use \cellcolor, color overwrites the table borders. What should I do to fix this problem? I would try using \hhline, but I don't understand the command when I want to color between two or more cells. Thanks in advance


text:
Q: Copy a list to a different list where both have other classes in I have the following classes
namespace A;
public ClassA
{
     public int A {get;set;}
     public string B {get;set;}
     public List<typeA> TypeA {get;set;}
     public TypeB TypeB {get;set;}
}

public class typeA
{ // properties }

public class TypeB
{ // properties }

namespace B;
public ClassB
{
     public string BB {get;set;}
     public List<A.typeA> TypeA {get;set;}
}

I'm trying to copy from A.ClassA into B.ClassB.
The code I'm using to copy the data from is this
public class CopyClass
{
    public static void CopyObject<T>(object sourceObject, ref T destObject)
    {
        if (sourceObject == null || destObject == null)
            return;

        Type sourceType = sourceObject.GetType();
        Type targetType = destObject.GetType();

        //  Loop through the source properties
        foreach (PropertyInfo p in sourceType.GetProperties())
        {
            PropertyInfo targetObj = targetType.GetProperty(p.Name);
            //  If there is none, skip
            if (targetObj == null)
                continue;

            try
            {
                if (p.GetType() == targetObj.GetType())
                    targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);
                    * exception thrown for non-primitives
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception copying : ex.Message = {ex.Message}, inner = {ex.InnerException?.Message}");
            }
        }
    }
}

The issue comes when I try to copy the non-primitive types (an exception is thrown at * in the code above). Is it possible to do a deep copy so I can just copy the corresponding properties in ClassA and ClassB including the collections?

A: As p and targetObj are both PropertyInfo type,
if (p.GetType() == targetObj.GetType())

always returns true. So you will mismatch types.
Use
if (p.PropertyType == targetObj.PropertyType)


text:
Q: How to draw a tree structure? (A two-dimensional space allocation tree recursion algorithm?) I have an arbitrary tree structure of nodes. I want to draw this tree to provide users a visual representation. I need to recurse over the tree and for each node add a graphic item to a list, and then just draw the list of items once tree recursion has finished. The recursion and drawing of items is of course trivial - what's a bit more complicated is  how to position the graphic nodes so they do not overlap with other branches.
I'm using Android but that is not important - I'm looking for an approach, possibly an algorithm that can maintain a picture of 2D space as it passes over the tree so it just allocates the most appropriate coordinates for each node as it makes the pass.
Any ideas?
Update
This is the article with the best and most complete algorithm.

A: I suggest drawing the tree linewise. You do this by using some kind of moving "drawing cursor".
You could store an attribute width for each node which is calculated as follows:

*

*the width of a leave is 1

*the width of an inner node is the sum of all childrens' widths

Then, you draw the root "in the first line" in the middle, which means, you just take root's width's half.
Then, you generate a grid over the image such that each gridline corresponds to one line resp. one step from left to right and each intersection of grid lines can contain a node and each node has enough space.
Then, you iterate through the childs and while iterating, you accumulate the children's widths and draw the children "in the next line". To draw currentChild, you move your drawing cursor currentWidth/2 to the right, draw currentChild, and move the drawing cursor the remaining currentWidth/2 to the right.
In order to get the nodes in a good order, you might consider a breadth first search.
I hope my explanation is clear, but I think it will be better, if I draw a little picture.
This is our tree (x are nodes, everything else edges)
   +-------x--+-------+
   |          |       |
 +-x-+     +-+x+-+  +-x-+
 |   |     | | | |  | | |
 x   x     x x x x  x x x

So, you calculate the leaf's widths:
   +-------x--+-------+
   |          |       |
 +-x-+     +-+x+-+  +-x-+
 |   |     | | | |  | | |
 1   1     1 1 1 1  1 1 1

Then, bottom up, the widths as sums of childrens' widths:
   +-------9--+-------+
   |          |       |
 +-2-+     +-+4+-+  +-3-+
 |   |     | | | |  | | |
 1   1     1 1 1 1  1 1 1

So, you start at the root (width 9) and go 4.5 steps to the rigt in the first line.
Then, you move your "drawing cursor" to the second line, "column 0" (go to left).
The first child has width 2, so we go 2/2=1 grid lines to the right and draw the node and move the drawing cursor the remaining 1 grid lines to the right in order to finish the node. So, the next node has width 4, which means, that we go right 4/2=2 grid lines, draw, go the remaining 2 steps, and so on.
And so on with the next line. At the end (or in intermediate steps), connect the nodes.
This procedure ensures that there are no overlapping nodes (if grid lines are far enough from each other), but it might lead to quite large tree diagrams that could use the space more efficiently.
In order to detect unused space, one might just scan the lines after the above process and look if there are unused grid line intersections and then possibly realign some nodes in order to fill space.

A: I would try the Walker algorithm.  Here's an academic paper on the algorithm.  If you want code to look at, look at the NodeLinkTreeLayout in Prefuse.  Prefuse is open source so there shouldn't be any problems adapting the code to your situation as long as you follow the terms of the license.

A: Take a look at Dot. You can convert your tree to the dot representation and then using Graphviz visualize in any format you like. For example Doxygen uses it to represent the structure of program.

A: Graphviz and mfgraph are powerful, but they're for general graphs and are probably overkill for trees.
Try googling on tree+layout+algorithm or see Graphic Javascript Tree with Layout.
The latter is old but it uses HTML canvas and javascript, and it explains the code, so both the code and the approach should be portable.

A: Depending on the nature of your data, a TreeMap may be more appropriate than a tinkertoy representation.


text:
Q: How to use one array in two functions in PHP? I have an array with the following content:
 $array_test = array ("User1"=>"Test1",
                      "User2"=>"Test2");

First column shall be $uservalue and second $testvalue in the functions. It worked, when I use a single column array for the first function loop through the array in the function.
And I would like to use this array in the following two functions.
The first column of the array should be use as $uservalue.
function do_show(array $options) {
    global $showresult, $master;
    $cn = $uservalue;
    $config = $options["config"]->value;
    // an empty show tag
    $show = new SimpleXMLElement("<show/>");
    // add the user tag
    $user = $show->addChild("user");
    // add the "cn" attribute
    $user->addAttribute("cn", $cn);
    if ($config)
        $user->addAttribute("config", "true");

    print "cmd: " . htmlspecialchars($show->asXML()) . "\n";

    // do it
    $showresult = $masterPBX->Admin($show->asXML());
    print "result: " . htmlspecialchars($showresult) . "\n";
    }

Second function where I would like to use the second Column of the array as Value for $testvalue:
function do_modify(array $options) {
    global $showresult, $master;
    $mod = $testvalue;
    $modify = new SimpleXMLElement("$showresult");
    $user = $modify->user;
    $path = explode("/device/hw/", $mod);
    $srch = $user;
    $nsegments = count($path);
    $i = 1;
    foreach ($path as $p) {
        if ($i == $nsegments) {
            // last part, the modification
            list($attr, $value) = explode("=", $p);
            $srch[$attr] = $value;
        } else {
            $srch = $srch->$p;
        }
        $i++;
    }

    // wrap the modified user tag in to a <modify> tag
    $modify = new SimpleXMLElement("<modify>" . $user->asXML() . "</modify>");
    print "cmd: " . htmlspecialchars($cmd = $modify->asXML()) . "\n";
    $result = $master->Admin($cmd);
    print "result: " . htmlspecialchars($result);
}

How can I archieve this? I found these two functions in the wiki of the software I would like to implement this... Therefore I know that using global variables is not a good option.

A: You can split your array into two arrays using following code and pass appropriate array to relevant function.
$array_test = array ("User1"=>"Test1",
                      "User2"=>"Test2");
$array_users = array_keys($array_test);
$array_tests = array_values($array_test);

Here is the link for details on both array_values and array_keys functions.

A: Pass the array as a function parameter to both functions...or make the array global. Pass by reference if you want to change original array (your array changes made inside the function to be visible outside of the function).


text:
Q: Webhook returns internal server error connecting Paypal to WooCommerce I need to use the Paypal IPN for two services. So, following the Zapier guide, I created a Webhook that sends a POST request to this URL https://italianindie.com/?wc-api=WC_Gateway_Paypal. It's the WooCommerce IPN URL for Paypal.
I've been using the same URL for months and it works. Orders and refunds are correctly processed.
But when I test the Zap, it gets an internal server error. How can I fix this?


text:
Q: Cross database permissions through stored procedure permissions I have a stored procedure set up in DATABASE1 that among other things makes a call to a stored procedure call sp_start_job (this is a stored procedure in the msdb database that will fire off an agent job).
I have created a proxy login and mapped this login to user accounts in msdb and DATABASE1 databases.
In my original stored procedure, I am using EXEC as proxylogin. This proxy user has rights to execute this procedure and in the msdb database can execute the sp_start_job procedure and is additionally a member of the SqlAgentOperator,SqlAgentUser, and SqlAgentReader Roles. I have also given the user in DATABASE1 AND msdb authenicate permissions.
The idea is that any user that can execute the original procedure will actually run it under the proxylogin's credentials so I do not have to assign these permissions out. I am still running into permission error, does anyone have insight into this problem?

A: We got around this by turning cross database ownership chaining on


text:
Q: Android TV-box experience. I need to develop Android TV-Box (android device, which use TV, as the screen) app.
Anyone done this? I can not find a good example to understand all the intricacies of this interaction. Maybe you will be able to help me?

A: As far as I know, the only difference is that you will have different input peripherials. You don't have touch screen, don't have keyboard. Rather, you'll have Bluetooth and network connections. The UI is the same as for mobile devices.
And of course, you won't have ScreenOrientationChange :)

A: If you are talking IP TV-BOX, then Android is a good choice if your streaming media solution is not that complex.
If you are going to do DVB TV-BOX with Android, you have to consider a lot more like CA, DVB tuner, DVB player etc.


text:
Q: Shell script to create a file if it doesn't exist? I need to create a shell script that checks for the presence of a file and if it doesn't exist, creates it and moves on to the next command, or just moves on to the next command. What I have doesn't do that.
#!/bin/bash

# Check for the file that gets created when the script successfully finishes.
if [! -f /Scripts/file.txt]
then
: # Do nothing. Go to the next step?
else
mkdir /Scripts # file.txt will come at the end of the script
fi

# Next command (macOS preference setting)
defaults write ...

Return is
line 5: [!: command not found
mkdir: /Scripts: File exists

No idea what to do. Every place a Google search brings me indicates something different.

A: Possibly simpler solution, no need to do explicit tests, just use:
mkdir -p /Scripts
touch /Scripts/file.txt

If you don't want the "modification" time of an existing file.txt to be changed by touch, you can use touch -a /Scripts/file.txt to make touch only change the "access" and "change" times.

A: You have a syntactical error.  You require spaces before and after the [ and ].

A: #!/bin/bash

# Check for the file that gets created when the script successfully finishes.
CHECKFILE="/Scripts/file.txt"

CHECKDIR=$( dirname "$CHECKFILE" )

# The directory with the file must exist
mkdir -p "$CHECKDIR"
if [ ! -f "$CHECKFILE" ]; then
    # What to do if the file is not there
fi
touch "$CHECKFILE"

The above assumes that there are no "tricks" such as creating a directory called /Scripts/file.txt (which could be a way of forcing the script to always enter the if branch). If the "file" is a directory, the -f test will fail and the touch command will not change anything.

A: You are getting the error because there is no space between [ and ! however there are also some flaws in your code.  First you are checking if the file does not exist, and if not you are doing nothing.  If the file DOES exist you are making a directory (but not doing anything to create the file).
You also don't need the null operation, you should be able to simply do:
#! /bin/bash -
if [[ ! -e /Scripts/file.txt ]]; then
    mkdir -p /Scripts
    touch /Scripts/file.txt
fi

[command2]

This is checking if /Scripts/file.txt does not exist it will create the /Scripts directory and then the file.txt file.  You could also check for the existence of the directory separately if you wanted.  Additionally notice I am using -e instead of -f as you asked simply to check for the existence of a file which is what -e will do where -f checks that it is a "regular file" http://tldp.org/LDP/abs/html/fto.html

A: To start with, shell script is not bash script, so let's make your code more general:
#!/bin/sh

Every Posix system must have that file; bash is strictly optional.
No need to test if the directory exists, just
dir=/Scripts
mkdir -p $dir

To create the file if it doesn't exist,
filename=$dir/file.txt
test -f $filename || touch $filename

Or if you prefer,
filename=$dir/file.txt
if [ ! -f $filename ]
then
    touch $filename
fi

A: my approach
#!/bin/sh

# input might contains spaces and other characters
FILEPATH="/tmp/some where/the file.blah"

# extract the file + dir names
FILE="`basename "${FILEPATH}"`"
DIR="`dirname "${FILEPATH}"`"

# create the dir, then the file
mkdir -p "${DIR}" && touch "${DIR}/${FILE}"

# show result
ls -l "$FILEPATH"

output
  ./dofile.sh
  -rw-r--r-- 1 jmullee jmullee 0 Nov 15 21:23 /tmp/some where/the file.blah

.


text:
Q: Given that $x=\frac{a}{\frac{a}{x+b}+c+b}+c$, prove that $c=-b$ Question: Given that $x=\frac{a}{\frac{a}{x+b}+c+b}+c$ for all real $x\neq -b $, prove that $a\neq 0$ and that $c=-b$.
Proving that $a\neq 0$ probably involves a proof by contradiction, but I  am not sure exactly what this involves. I also think this can be shown without proving that $c=-b$, but $a\neq 0$ follows directly if we can prove that first.
To prove that $c=-b$, the first equation can be manipulated to obtain the result $a(b+c)=(x-c)(x+b)(b+c)$. We can safely divide both sides by $b+c$ as if $b+c=0$, $b=-c$ is satisfied anyway. This gets that $a=(x-c)(x+b)$. If we can prove that $a\neq 0$, then it follows  that $x-c\neq 0$, and so $x\neq c$. This, because the only original restraint on $x$ was that $x\neq -b$, suggests that $c=-b$, but I am not sure this logic is rigorous or correct.
If someone can prove that $a\neq 0$ and the logic at the end is valid, then I think the problem is solved, unless I made a mistake elsewhere.
Also, this problem is only  designed for strong year 10 students, so the solution is unlikely to involve much more than simple proof methods and basic algebraic manipulation.

A: I think you need to take into account the fact that the question asks you to prove that $a \neq 0$ before proving that $c=-b$.
I suppose that $x$ is a variable, which will not take the value $x=-b$...
Let's suppose $a=0$.
Then you have $\forall x, x=c$, which is not possible.
Hence $a \neq 0$.
Your initial equation becomes, as you said $a(b+c)=(x-c)(x+b)(b+c)$ by multiplying both sides by $\frac{a}{x+b}+c+b$ and then by $x+b$. Both expressions are not null (remember that $x \neq -b$).
Since $a \neq 0$, I have $(b+c)=\frac 1a(x-c)(x+b)(b+c)$ $\forall x$.
Or $(b+c)(\frac 1a(x-c)(x+b)-1)=0$ $\forall x$
This is only possible if $c=-b$.

A: I shall assume that you want the statement to hold true for all $x$. Suppose on the contrary that $a=0$, then we have $x=c$, but we can let $x$ takes two different values, $x_1 \ne x_2$ and we obtain a contradiction since we will be having $x_1 =c=c_2$. Hence $a \ne 0$.
$$x-c=\frac{a}{\frac{a}{x+b}+b+c}$$
$$x-c=\frac{a(x+b)}{a+(b+c)(x+b)}$$
$$(x-c)[a+(b+c)(x+b)]=a(x+b)$$
Suppose $c \ne -b$, and the only condition on $x$ is $x \ne -b$, then we can let $x=c$.
$$0=a(b+c)$$
Since $a \ne 0$, we have $b+c=0$.

A: IMO, the claim is wrong. If $a=0$, the equation reduces to $x=c$, unless $c+b=0$. But we know that $c+b=x+b\ne0$.
For example
$$1=\frac0{\dfrac0{1+1}+1+1}+1.$$

As $x+b\ne0$, we can always rewrite
$$x=\frac{a}{\dfrac{a}{x+b}+b+c}+c=\frac{ax+ab}{(b+c)x+b^2+bc+a}+c\\
=\frac{(a+bc+c^2)x+(b^2c+bc^2+ac+ab)}{(b+c)x+b^2+bc+a}.$$
For this to be an identity, the coefficient of $x$ in the denominator must be zero. When this is the case, it simplifies to
$$x=\frac{ax}{a}.$$

In conclusion, the problem statement is at best ambiguous and at worst wrong. It should say "for all $x\ne-b$".

A: Note that from
$$x=\frac{a}{\frac{a}{x+b}+c+b}+c$$
we need

*

*$x+b \neq 0 \implies x\neq -b$

and

*

*$\frac{a}{x+b}+c+b\neq 0$

then
$$x=\frac{a}{\frac{a}{x+b}+c+b}+c\iff \frac{ax}{x+b}+cx+bx=a+\frac{ac}{x+b}+c^2+bc\\\iff ax+cx^2+bx^2+bcx+b^2x=ax+ab+ac+c^2x+bcx+c^2b+b^2c\\\iff (b+c)x^2+(a+bc+b^2-a-c^2-bc)x-(ab+ac+c^2b+b^2c)=0\\\iff (b+c)x^2+(b^2-c^2)x-(ab+ac+c^2b+b^2c)=0$$
and then for the $x^2$ and $x$ term

*

*$b=-c$

and for the constant term

*

*$ab+ac+c^2b+b^2c=ab-ab+b^3-b^3=0$


text:
Q: Get property of object property  by string in C# How to access to property of property in object instance using string  ?
I would like automate changes i will made in form for example responding to object below:
class myObject{
   Vector3 position;
   public myObject(){
       this.position = new Vector3( 1d,2d,3d);
   }
};

Form have eg three numericUpDown called respectively position_X,position_Y,position_Z;
Instead having three callbacks for events as:
private void positionX_ValueChanged(object sender, EventArgs e)
  {
    // this.model return myObject
    this.model().position.X = (double)  ((NumericUpDown)sender).Value;

  }

I would have one callback which can automatically set particular attribute in model from control name/tag
Below is javascript which describe purpose i want :)
position_Changed( sender ){
   var prop = sender.Tag.split('_'); ; // sender.Tag = 'position_X';
   this.model[ prop[0] ] [ prop[1] ] = sender.Value;
}

A: You can use either reflection or expression trees to do that.
The simple reflection way (not very fast but versatile):
object model = this.model();
object position = model.GetType().GetProperty("position").GetValue(model);
position.GetType().GetProperty("X").SetValue(position, ((NumericUpDown)sender).Value);

Note: if Vector3 is a struct you may not get the expected results (but that has to do with structs and boxing, not with the code per se).

A: To complement the previous answer, which is essentially what you're looking for:
object model = this.model();
object position = model.GetType().GetProperty("position").GetGetMethod().Invoke(model, null);
var propName = (string) ((NumericUpDown)sender).Tag;
position.GetType().GetProperty(propName).GetSetMethod().Invoke(model, new [] {((NumericUpDown)sender).Value});

That is, you could just use the Tag property of Control to specify to which property of your Vector3 object the NumericUpDown instance is "bound" to.


text:
Q: $a≤b≤c$ prime numbers :
$abc\mid{ab+ac+bc-1}\implies a=2$ I would like see explain to this step :
$$a≤b≤c, \operatorname{  are prime numbers}$$
$1)$
$$abc\mid{ab+ac+bc-1}\implies a=2$$
$2)$
$$bc\mid{2b+2c-1}\implies b=3$$
My try if correct as following :
For $1)$
$$ab+bc+ac-1<3bc$$
So :
$$abc\mid{3bc}\implies a\mid 3$$ ??
Also for second I have same problem
$$2b+2c-1<4c\implies q\mid{4} ??$$
Can someone explain to me how is this ??

A: I believe this question is related to your earlier question at Prove that : $(ab-1)(ac-1)(bc-1)\equiv 0\pmod{abc}\implies (a,b,c)=(2,3,5)$ and my answer to it. However, you have $a \lt b \lt c$ there instead of $a \le b \le c$, so I assume you want the same thing here as well.
Since you are dealing with positive integers,
$$abc \mid ab+ac+bc-1 \tag{1}\label{eq1A}$$
means that, for some positive integer $k$, you have
$$ab + ac + bc - 1 = k(abc) \tag{2}\label{eq2A}$$
Now, since $k \ge 1$, this means
$$ab + ac + bc - 1 \ge abc \tag{3}\label{eq3A}$$
with the equality occurring only if $k = 1$. Now
$$c \gt a \implies cb \gt ab \tag{4}\label{eq4A}$$
where I multiplied both sides of the inequality by the positive integer $b$, and
$$b \gt a \implies bc \gt ac \tag{5}\label{eq5A}$$
where I multiplied both sides of the inequality with the positive integer $c$. Using these results, along with \eqref{eq3A}, you get
$$\begin{equation}\begin{aligned}
bc + bc + bc - 1 & \gt ab + ac + bc - 1 \\
3bc - 1 & \gt abc \\
3bc - abc & \gt 1 \\
(3-a)bc & \gt 1
\end{aligned}\end{equation}\tag{6}\label{eq6A}$$
If $a \ge 3$, then $3 - a \le 0$, so the left hand side of \eqref{eq6A} would be either $0$ or negative. However, as it must be $\gt 1$, this can't be true. As $a$ is a prime, this means $a = 2$ is the only possibility. Also, note using this in \eqref{eq6A} gives $bc \gt 1$, which is true.
As for
$$bc \mid 2b+2c-1 \tag{7}\label{eq7A}$$
you have, as explained earlier for \eqref{eq1A}, that
$$\begin{equation}\begin{aligned}
2b + 2c - 1 & \ge bc \\
2c - 1 & \ge (b - 2)c
\end{aligned}\end{equation}\tag{8}\label{eq8A}$$
If $b \gt 3$, then since $b$ is a prime you have $b \ge 5 \implies b - 2 \ge 3$, but you then get from \eqref{eq8A} that $2c - 1 \ge 3c \implies -1 \ge c$, which is not true. Thus, $b = 3$ is the only possibility available. Note it also works since \eqref{eq8A} then just states that $2c - 1 \ge c \implies c \ge 1$.
Regarding your attempts, for your $1$), I'm not sure where you got
$$ab+bc+ac-1 < 3bc \tag{9}\label{eq9A}$$
As you can see in \eqref{eq3A}, you have that $ab + bc + ac - 1$ is at least the value of $abc$. In \eqref{eq9A}, the inequality is reversed. Also, from this, I'm not sure how you got to
$$abc\mid{3bc}\implies a\mid 3 \tag{10}\label{eq10A}$$
An inequality like in \eqref{eq9A} doesn't imply anything about divisibility, but the reverse can be true, as used for \eqref{eq1A} and \eqref{eq7A}.
Regarding your other statement of
$$2b+2c-1<4c\implies q\mid{4} \tag{11}\label{eq11A}$$
Since $b \lt c$, it's true that $2b + 2c - 1 \lt 4c$. However, I'm not sure what $q$ is and why the inequality would imply that $q \mid 4$.


text:
Q: I am not able to write the x path It is showing Exception in thread "main"

org.openqa.selenium.ElementNotInteractableException: element not interactable for the log in button of the freecrm.com

System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_2\\chromedriver2.exe");

WebDriver driver = new ChromeDriver();

driver.get("https://freecrm.com");

driver.findElement(By.xpath("//a//span[text()='Log In']")).click();

image description

A: Error says, its unable to interact. When we look at UI once, When we hover on Login, button getting enabled (i.e. changing color to Green) to click. My suggestion is to do mouse move on to the element using Actions class with the same xpath what you tried and click using Actions class like:
new Actions(driver).moveToElement(By.xpath("//a//span[text()='Log In']")).click();
You can try this approach..

A: Use the xpath as "//span[text()='Log In']". It will work


text:
Q: Ctypes accessing structure member pointer to another structure I'm trying to access structure pointer member pointing to another structure. Below is the scenario in my case.
c_header.h
typedef struct {
    uint8_t* addr;
    uint32_t size;
    uint8_t id;
} input_info_t;

typedef struct {
    type_t work_type;
    format_t format;
    float runtime;
    /*input*/
    input_info_t *input_info;
    /*output*/
    output_info_t *output_info;
} all_output_t;

I have casted the above structure into ctypes datatype like below
ctypes_header.py
class input_info_t(ctypes.Structure):
    _fields_ = [
        ('addr', ctypes.POINTER(ctypes.c_uint8)),
        ('size', ctypes.c_uint32),
        ('id', ctypes.c_uint8)
    ]

class output_buffer(ctypes.Structure):
    _fields_ = [
        ('work_type', type_t),
        ('format', format_option),
        ('runtime', ctypes.c_float),
        ('input_info', ctypes.POINTER(input_info_t)),
        ('output_info', ctypes.POINTER(output_info_t))
    ]

In C we will access input_info_t member from all_output_t structure, will do like
all_output_t->input_info->addr
Like the same i want to access in ctypes casted datatypes. I tried input_info.input_info_t.addr ,but getting the below error
Input addr =  <test.common.data_types.LP_input_info object at 0x7fa0ee0140>
Exception ignored on calling ctypes callback function: <function callback_function at 0x7fa111f1f0>
Traceback (most recent call last):
  File "../wrapper.py", line 61, in callback_function
    print('Input buffer length = ', buf_obj.input_info.addr)
AttributeError: 'LP_input_info' object has no attribute 'addr'

A: Just like in C, pointers need to be dereferenced.  In ctypes, use .contents:
import ctypes

class input_info_t(ctypes.Structure):
    _fields_ = (('addr', ctypes.POINTER(ctypes.c_uint8)),
                ('size', ctypes.c_uint32),
                ('id', ctypes.c_uint8))

# dropped fields that weren't defined by OP:
class output_buffer(ctypes.Structure):
    _fields_ = (('runtime', ctypes.c_float),
                ('input_info', ctypes.POINTER(input_info_t)))

# Initialize a sample output_buffer structure...
a = ctypes.c_uint8(123)
ibuf = input_info_t(ctypes.pointer(a), 456, 7)
obuf = output_buffer(1.5, ctypes.pointer(ibuf))

# Use .contents to dereference the two pointers.
print(obuf.input_info.contents.addr.contents.value)

Output:
123


text:
Q: Show that the locus of the centroids of equilateral triangles inscribed in the parabola $y^2=4ax$ is the parabola $9y^2-4ax+32a^2=0.$ Show that the locus of the centroids of equilateral triangles inscribed in the parabola $y^2=4ax$ is the parabola $9y^2-4ax+32a^2=0.$
I tried to solve it.I took three coordinates of the equilateral triangle as $(x_1,y_1),(x_2,y_2),(x_3,y_3)$
let the coordinates of the centroid be $(h,k)$.
$h=\frac{x_1+x_2+x_3}{3},k=\frac{y_1+y_2+y_3}{3}$
$h=\frac{y^2_1+y^2_2+y^2_3}{12a}$
But eliminating $y_1,y_2,y_3$ is difficult.Is my method correct or is there any other better method.Please help me.

A: If you want to try yourself, translate into algebra the fact the triangle of vertices $(x_1,y_1)$, $(x_2,y_2)$ and $(x_3,y_3)$ is equilateral. Two equations are enough since congruence is transitive: don't use distance but orthogonality.
Then you need some algebraic manipulations to get the result.
Otherwise the complete solution is in Gelca,Andreescu Putnam and Beyond (2007), pp. 213-214.

A: Writing the solution from Gelca,Andreescu Putnam and Beyond (2007), pp. 213-214 as Tony suggested:

Let us determine first some algebraic conditions that the coordinates $(x_i, y_i)$,
$i = 1, 2, 3$, of the vertices of a triangle should satisfy in order for the triangle to be equilateral. The equation of the median from $(x_3, y_3)$ is $$\dfrac{y-y_3}{x-x_3}=\dfrac{y_1+y_2-2y_3}{x_1+x_2-2x_3}$$
or $$(x_1-x_2)(x_1+x_2-2x_3)+(y_1-y_2)(y_1+y_2-2y_3)=0$$
So this relation along with the two obtained by circular permutations of the indices are necessary and sufficient conditions for the triangle to be equilateral. Of course, the third
condition is redundant. In the case of three points on the parabola, namely $\left(\dfrac{y_i^2}{4a},y_i\right)$ , $i=1,2,3$, after dividing by $y_1-y_2$, respectively, by $y_2-y_3$ (which are both nonzero), we obtain $$(y_1+y_2)(y_1^2+y_2^2-2y_3^2)+16a^2(y_1+y_2-2y_3)=0 \\ (y_2+y_3)(y_2^2+y_3^2-2y_1^2)+16a^2(y_2+y_3-2y_1)=0$$
Subtracting the two gives $$y_1^3-y_3^3+(y_1-y_3)(y_2^2-2y_1y_3)+48a^2(y_1-y_3)=0$$
Divide this by $y_1-y_3 \ne 0$ to transform it into $$y_1^2+y_2^2+y_3^2+3(y_1y_2+y_2y_3+y_3y_1)+48a^2=0$$
This is the condition by the $y$ -coordinates of the vertices of the triangle. Keeping in mind that the coordinates of the centroid of the triangle are $$x=\dfrac{y_1^2+y_2^2+y_3^2}{12a}, y=\dfrac{y_1+y_2+y_3}{3}$$ we rewrite the relations as $$-\dfrac{1}{2}(y_1^2+y_2^2+y_3^2)+\dfrac{3}{2}(y_1+y_2+y_3)+48a^3=0$$ then substitute $12ax=y_1^2+y_2^2+y_3^2$ and $3y=y_1+y_2+y_3$ to obtain the equation of the locus $$-6ax+\dfrac{27}{2}y^2+48a^2=0$$ or $$9y^2-4ax+32a^2=0$$

A: Let the centroid be $G(h,k)$ and the vertices be $P(t_1), Q(t_2), R(t_3)$ in parametric form.
Since $G$ is also the circumcenter, we have that $P,Q,R$ lie on the circle of the form $x^2+y^2-2hx-2ky+c=0$
Setting $x=at^2, y=2at$ we get
$a^2t^4+(4a^2-2ah)t^2-4akt+c=0$
Noting that the sum of roots is zero, the roots of the above quartic are then $t_1,t_2,t_3, -(t_1+t_2+t_3)$
Considering roots taken two at a time,
$t_1t_2+t_2t_3+t_3t_1-(t_1+t_2+t_3)^2 = \dfrac{4a^2-2ah}{a^2}$
We have $3h =a(t_1^2+t_2^2+t_3^2)$ and $3k = 2a(t_1+t_2+t_3)$
The above relation can be written as $t_1^2+t_2^2+t_3^2+(t_1+t_2+t_3)^2 = \dfrac{2(2ah-4a^2)}{a^2}$ or
$\dfrac{3h}{a}+\left(\dfrac{3k}{2a}\right)^2 = \dfrac{2(2ah-4a^2)}{a^2}$
from which we get that $G$ lies on $9y^2-4ax+32a^2=0$


text:
Q: JQuery Product Slider Errors I am new to JQuery and am trying to create a product slider for my website. I was having some troubles so I made a basic version of it in this question. For some reason I am having no luck in getting it to work and have no idea why.
The three product boxes will animate as a section rather than individually, similar to this one https://smartslider3.com/product-carousel/. The animation will go from right to left when clicking the previous button and left to right when clicking the next button but I have just left it as slide up and slide down at the moment because I don't know the correct code for the animation. Touch swipe support would also be nice to have.

$( document ).ready(function() {
    $("#slider-next-button").click(function(){

        var currentSlider = $(".active");
        var nextSlide = currentSlider.next();

        currentSlider.slideDown(2000);
        currentSlider.removeClass(active);
        nextSlide.slideUp(2000);
        nextSlide.slideUp(2000);
        })
});
;
.content{
    width: 80%;
    margin: auto;
}
.slider-section{
    background-color: lightgrey;
    height: 600px;
    padding: 50px 0px 0px 0px;
}
.slider-container{
    display: grid;
    grid-template-columns: 1fr 12fr 1fr;
    grid-column-gap: 20px;
}
.slider-previous-button{
    height: 40px;
    border-radius: 20px;
    background-color: grey;
    cursor: pointer;
}
.slider-next-button{
    height: 40px;
    border-radius: 20px;
    background-color: grey;
    cursor: pointer;
}
.slider-items{
    display: none;
    grid-template-columns: 1fr 1fr 1fr;
    grid-column-gap: 20px;
}
.slider-items.active{
    display: grid;
}

.slider-item{
    background-color: blue;
    height: 400px;
}
<!DOCTYPE html>

    <title>Slider Test</title>
    <link rel="stylesheet" type="text/css" href="css/slidertest.css">

1

2

3

4

5

6

7

8

9


text:
Q: C++ Menu Ordering System won't accept multiple words when inputting to the txt file My code below, whenever I input the menu items, will automatically end the program if I add more than one word such as "Tequila Sunrise" rather than "Tequila". How do I fix this to make it so I can add items with more than one word in the name?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    // Restaurant Side Title
    cout << "Welcome to the Menu Ordering System. \n\n\n";

    // Create a txt file to store the menu
    fstream MenuWriteFile("drinksmenu.txt");
    fstream MenuPricesFile ("drinksprices.txt");

    // Write the menu to the file
    string myDrinks;
    double drinksPrices;
    int i;
    cout << "Please enter your first drink: ";
    cin >> myDrinks;
    MenuWriteFile << myDrinks << endl;
    cout << "Price: ";
    cin >> drinksPrices;
    MenuPricesFile << drinksPrices << endl;
    cout << "To add another drink type 1, if not type 0: ";
    cin >> i;
    while (i == 1) {
        cout << "Please enter your next drink: ";
        cin >> myDrinks;
        MenuWriteFile << myDrinks << endl;
        cout << "Price: ";
        cin >> drinksPrices;
        MenuPricesFile << drinksPrices << endl;
        cout << "To add another drink type 1, if not type 0: ";
        cin >> i;
    }

    MenuWriteFile.close();
    MenuPricesFile.close();

    // Create a text string, which is used to output the text file
     string myText;

     // Read from the text file
     ifstream MenuReadFile("drinksmenu.txt");

     while (getline (MenuReadFile, myText)) {
       cout << "\n\n" << myText << "\n";
     }

     // Close the file
     MenuReadFile.close();
    return 0;
    }

A: Use std::getline():
while (i == 1) {
  cout << "Please enter your next drink: ";
  std::getline(std::cin >> std::ws, myDrinks);
  ....


text:
Q: Is there a way to find the line that caused a warning to appear in Qt? While running my Qt5 project, I get warnings such as
QObject::startTimer: Timers cannot be started from another thread

and others.
While many answers cover what in a given code caused these warnings, or how to correct them, I would like to know where in the code was the warning generated, a traceback.
This is because I think it is being caused by my incorrect usage of some Qt functionality that causes warnings internally, such as, in the above case, functionality that uses timers to execute. Knowing the line number would be helpful for debugging, but unfortunately that is not shown, even in debug mode.
Is there a way to do this?
This question seems to be almost identical, but I am not observing anything similar to what is posted in the question there - I don't see any line numbers. I didn't understand how to apply the answer there, if applicable.
Thank you.

A: The best way is setting a breakpoint, as the others mentioned.
On Linux, it is also possible to include the backtrace in the message pattern:
qSetMessagePattern("%{file}:%{line} - %{message}\n%{backtrace depth=10 separator=\"\n\"}");

Have a look at its documentation, especially for the limitations.
Example output:
/home/thomas/src/Qt/5.8-desktop/qtbase/src/corelib/kernel/qobject.cpp:1639 - QObject::startTimer: Timers can only be used with threads started with QThread
QObject::startTimer
QTimer::start
?myapp?
__libc_start_main
?myapp?

Because I am not linking with -rdynamic, the main() function is not known in the backtrace and ?myapp? is printed instead.

A: nwp, in the comments, pointed out this answer by Nawaz, which works great when I put a break point on the warning message line, here:
case QtWarningMsg:
        fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); //break point here
        break;

This gives a proper traceback when running in the debugger mode, as I needed.


text:
Q: Getting Username By Id Could someone help me out as i'm new to PHP and MYSQLI
I'm trying to make a comment system for my movies page example below
Database Structure
Comments Table
id          int(11)         No  None    AUTO_INCREMENT
movie_id    int(11)         No  None
user_id     int(11)         No  None
message     varchar(1000)   No  None
timestamp   timestamp       No  CURRENT_TIMESTAMP

Users Table
id          int(50)         No  None    AUTO_INCREMENT
username    varchar(50)     No  None
email       varchar(100)    No  None
group       varchar(20)     No  None
password    varchar(20)     No  None

PHP CODE
<?php
$comments = mysqli_query($con,"SELECT * FROM `comments` ORDER BY `timestamp` DESC");
while($comment = mysqli_fetch_array($comments)) {
?>

<a href="www.mysite.com/movie.php?id=<?php echo $comment['movie_id']; ?>"><?php echo $comment['message']; ?>

<?php
}
mysqli_close($con);
?>

So what i want to do is get username from Users table by using user_id from Comments table
Could someone show me how to get them and how to echo them please.

A: SELECT * FROM
    `comments` c
JOIN `users` u
    ON c.user_id = u.id
ORDER BY `timestamp` DESC

Within your while loop the user name will be available as $comment['username'].
You can find more about mysql join here: http://dev.mysql.com/doc/refman/5.0/en/join.html

A: Simple way:
"SELECT * FROM users,comments WHERE users.id=comments.id ORDER BY timestamp DESC"

This should work.


text:
Q: Laravel arrays and foreach So I'm sending from Ionic app to API via POST request an array of condiments which are on mobile part represented as checkboxes. I want to get the checkboxes which are checked so I can create table rows accordingly.
The method that is called upon route triggering has this part:
$condiments = Input::only('condiments');

foreach ($condiments as $condiment) {
        if ($condiment['checked'] == 1) {
            OrderCondiment::create(['order_item_id' => $orderItem,
                                    'condiment_id' => $condiment->id]);
        }
}

But I get Illegal string offset 'checked' error. I tried with $condiment->checked but then I get Trying to get the property of non-object error...what am I missing...besides coffee
EDIT
dd($condiments)

array:1 [
  "condiments" => "[{"id":1,"name":"ut","price":3,"created_at":null,"updated_at":null,"checked":1},{"id":2,"name":"ipsam","price":5,"created_at":null,"updated_at":null,"checked":1},{"id":3,"name":"dolores","price":10,"created_at":null,"updated_at":null,"checked":1},{"id":4,"name":"esse","price":3,"created_at":null,"updated_at":null,"checked":0},{"id":5,"name":"aliquid","price":1,"created_at":null,"updated_at":null,"checked":0},{"id":6,"name":"sunt","price":3,"created_at":null,"updated_at":null,"checked":0},{"id":7,"name":"saepe","price":1,"created_at":null,"updated_at":null,"checked":0},{"id":8,"name":"impedit","price":10,"created_at":null,"updated_at":null,"checked":0},{"id":9,"name":"dolores","price":4,"created_at":null,"updated_at":null,"checked":0},{"id":10,"name":"veniam","price":2,"created_at":null,"updated_at":null,"checked":0}]"
]

A: convert string to array
$condiments = Input::only('condiments');
$condiments= json_decode( $condiments['condiments']) ;
foreach ($condiments as $condiment) {
    if ($condiment->checked == 1) {
        OrderCondiment::create(['order_item_id' => $orderItem,
                                'condiment_id' => $condiment->id]);
    }
}


text:
Q: Searching for multiple terms in a cell with AND-condition I'm trying to do a search for multiple strings in a cell with an AND-condition in Excel

E.g: I have a string HNSP1 and I want to find some cells has  HN and 1

I'm using:
=IF(SEARCH({"HN","1"},B3),600000,"")

But the result is OR-condition
Does anyone know the answer?

A: I think you could just use an AND function along with IsNumber and Find to get what you need.
Try this in a cell reference B3 and you should get a true result and then return the appropriate value
=IF(AND(ISNUMBER(FIND("HN",B3),ISNUMBER(FIND("1",B3))),600000,"")


text:
Q: jquery, cannot add img in td The setup of my html is I have alphabet imgs inside td. User should click the imgs alphabetically, every correct click the img is removed. If wrong, an xmark will appear.
(not yet in the code: after three wrongs, it's game over, and then i will ask user if he wants to play again or go back to home)
This is my jquery code:
  var error = 0;
        var check = 0;
        $("table img").bind('click',function(){
            var letterArray = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
            var clickedValue = $(this).attr('name');

            if(clickedValue ==letterArray[check]){
                $(this).parent().empty();
                check+=1;
            } else {
                error+=1;
                $("error").add('	');
                if(error==3){
                    alert("Game Over. Homer will now eat you!");
                    $("table img").unbind("click");
                    $("table img").css("opacity", "0.4");
                }
            }
        });

my table in html: just posted the first 6 letters for brevity.

A: Use .appendTo() instead of .add()
Try this:
var error = 0;
        var check = 0;
        $("table img").bind('click',function(){
            var letterArray = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
            var clickedValue = $(this).attr('name');
            if(clickedValue ==letterArray[check]){
                $(this).parent().empty();
                check+=1;
            } else {
                error+=1;
                $('	').appendTo("tr#error");
                if(error==3){
                    alert("Game Over. Homer will now eat you!");
                    $("table img").unbind("click");
                    $("table img").css("opacity", "0.4");
                }
            }
        });

DEMO


text:
Q: Does it make a difference if you don't use a prop in your PureComponent render method? Say I have a PureComponent with a bunch of props. If I don't use every single prop in my render method, will it affect anything at all?
For instance, if I depend on componentWillReceiveProps being called for every single prop, even the ones that are not rendered...it will still be called, correct?
I can't imagine the React authors doing anything else... I can probably hunt down the code and take a peek myself and I will if I can't get a definitive answer here. Thanks.
NOTE: The reason I'm asking is because I'm wondering I see some code that is pulling unused variables from props here.

A:
For instance, if I depend on componentWillReceiveProps being called for every single prop, even the ones that are not rendered...it will still be called, correct?

Yes componentWillReceiveProps will still be called regardless of what effect a particular prop may or may not have on rendering.

even the ones that are not rendered

Note many props are not rendered themselves, but they may have some effect on rendering (or they may not). React would not know if a particular prop affected rendering at least until the new virtual DOM was constructed.

A: PureComponent is just like a regular component, only it implements the lifecycle method shouldComponentUpdate(). This function will ultimately determine if render() will run, so it cannot possibly rely on render() itself.

For instance, if I depend on componentWillReceiveProps being called for every single prop, even the ones that are not rendered...it will still be called, correct?

Yes, that is correct.

The code you referenced contains a common pattern, where props should be passed down, but not as a whole. The omitted props are commonly known as ownProps, which indicates that they belong solely to the component itself.
If we look at the code:
const {
    element,
    onChange: _onChange,
    value: _value,
    minLength: _minLength,
    //...
    ...props
 } = this.props;

In this case, value, minLength and debounceTimeout are only assigned to variables so they will be excluded from the props variable, which is used afterwards.
return React.createElement(element, {
    ...props,
    //...
}


text:
Q: Junk mail filter for iPhone via imap I have:

*

*Mac Book Pro running OS X 10.10.2

*iPhone 6 Plus running iOS 8.1.3

On my computer I run Mail, which checks the email every 1 min.  On my iPhone it runs every 15 mins.  So most of the time, my computer receives the email first and filters the message so my phone never gets the junk mail.  However when my computer is sleeping my iphone normally gets the email first and does not perform the filter for the junk mail.
Options:

*

*Force the computer not to sleep

*Write a script to run while sleeping asking mail query the server (I'm not sure how hard this would be)

*Ask here and see if someone has a better idea.

A: The best idea is to pay for (or set up) server side junk mail filtering. That allows all the clients to only spend time downloading non-junk.
Have a look at Mail Route (10 percent off link from the podcast where I heard about it sponsoring most recently) - http://mailroute.net/thetalkshow.html
You probably will spend more on the service than the cost to run your Mac all the time, but the filters will likely be much better on the hosted site than OS X mail client.

A: Yeah, the only thing I can really think of is setting up stricter filtering rules with your host, be that iCloud or Gmail or whathaveyou. You can weirdly only do this for iCloud using their webmail interface. You might also try using SpamSieve on your OS X inbox to train mail to sort items as Good or Junk; I believe those designations once determined are maintained for the iOS clients, but it takes a while to get it trained. I'd love a better mobile spam solution & hope someone else provides a better answer.


text:
Q: Executables not running on double clicking I am able to compile and create executables with Vala programming language and Gtk. The GUI executables run okay from command line with command:
./myGuiAppl

However, when I double click on them in file managers, they do not run. It seems they are seen as libraries and not as executables. Where is the problem and how can it be solved?

A: This is probably a design choice by file managers. On Windows it is normal to run .exe files from Windows Explorer, but on Linux applications are usually run via .desktop files from the desktop environment or from the terminal.
There is nothing you can do from a programming standpoint. Ask the vendor of your file manager if you think this should be possible.


text: Q: Incorporate python code inside a C extension I'm writing a Python module in C, but I would like the module to also contain functions written in Python. How can Python functions be added to a module written in C?


text:
Q: Communicate with an External Accessory over Wi-Fi in an iOS App I am building an app which will communicate with an external accessory capable of establishing a wi-fi bridge.
I am not able to defer the situation that how do I establish connection with this external accessory and then the device should be shown connected in my app.
After connection, there are certain actions I need to perform on the device. So a two way communication is also a requirement. How do I initiate a connection and then communicate over it.
Is any Apple framework available for it. As I am not able to find anything.
If possible, please provide a sample code on how to achieve this feat.
Thanks in advance.


text:
Q: Android using Intellij Version 14 - Update XML References only in current XML resource file I am using  Intellij Idea Version 14 for Android development. I have recently upgraded to version 14. While editing resource XML, when I change ID of any component (e.g TextView or Button) it asks a question "Update usages as well?" "This will update all XML references and Java R field references." Clicking yes changes all files where same ID is used. Version 13 was doing only in that file. Now the name is changed in entire project wherever it is used. I do not want to change code in other files. Here is a example.
File 1: First.Java and First.XML has textview with ID textViewPersonName
File 2: Second.java and Second.XML has textView with ID textViewPersonName
Now I want to change Second.XML, textViewPersonName to textViewPersonFullName. On changing this file Intellij 14 changes all files (i.e.First.Java and First.XML ) and updates  textViewPersonName in the first files to  textViewPersonFullName.
How do I change only in currently used file (i.e. Second.XML) only. Is there any setting?

A: if you refactor a id with the shortcut [SHIFT]+[F6] you can click on preview and a second window opens:

Here you can right click on the selected line and exclude that refactoring:

Hope this helps


text:
Q: How to lazy evaluate and execute javascript? I have following situation:
I have 86 charts (ChartsJS) divided into three categories. I am using JQueryUI Tabs to display each category one at the time in separate tab. The thing is, that due to to large amount of javascript embedded into the page, page load time is over 7 seconds in which JS parsing and execution takes over 5.2 of that time (measured using google chrome).
I am wondering is there a way to lazy evaluate those JavaScript parts that renders elements that are not  yet presented to the user (not on currently open tab). Please notice, that I would like not only to execute given script on tab change (this is obvious and easy to do) but to evaluate required script on demand at some given point of time after page load.
EDIT:
I need to clarify that my JS is dynamically generated thus asyncload from file is not an option. This could be a design flaw on my side.
Here is a timeline from chrome:

A: Anything in a function definition is not executed until the function is called. hence you can wrap your tab specific code in functions and call them whenever you open that tab.
in order to run a chart in chartjs you need to write the following:
var myChart = new Chart(SELECTOR, {...})

hence only call new Chart on your active selectors
//Global Configs
Chart.defaults.global.hover.mode = 'single';

function onTabOne() {
    var myChart = new Chart(SELECTOR, {...})
}
function onTabTwo() {
    var pieChart = new Chart(SELECTOR, {...})
}

NOTE
evaluation of javascript is super fast and is not heavy on machine, its basically hoisting and memory allocation for variables, you should not worry about lazy evaluation, and there is no direct way. but execution is where the heavy work takes place, and you can delay execution by wrapping things in function definitions.
there are hacky ways to get lazy evaluation, such as putting javascript in strings and using eval whenever you want to evaluate and execute the code, but i dont recommend using eval at all.
 and there is no real need to do it.


text:
Q: nested boost::shared_ptr use_count not updating I have a nested boost::shared_ptr which was occasionally getting destroyed when getting assigned to another one and going out of scope. I figured out that the use_count was not updating unless I copy the pointer to a temp. The code is self-explanatory. In the first for-loop, the use_count doesn't update, whereas it updates on the other.
#include <vector>
#include <boost/shared_ptr.hpp>
#include <iostream>
using namespace std;

int main(int argc, char const *argv[])
{
  typedef int T;
  typedef std::vector<T> content_1d_t;
  typedef boost::shared_ptr<content_1d_t> storage_1d_t;
  typedef std::vector<storage_1d_t> content_2d_t;
  typedef boost::shared_ptr<content_2d_t> storage_2d_t;

  int dim1 = 10;
  int dim2 = 1;
  content_2d_t* content_1 = new content_2d_t();
  content_1->reserve(dim2);
  storage_2d_t storage_1(content_1);

  for (int i = 0; i < dim2; ++i)
  {
    storage_1->push_back(storage_1d_t(new content_1d_t(dim1)));
  }

  //content_2d_t* content_2 = new content_2d_t(dim2);
  storage_2d_t storage_2 = storage_1;

  for (int i = 0; i < dim2; ++i)
  {
    cout<< "use count before : "<< storage_1->operator[](i).use_count()<<endl;
    storage_2->operator[](i) = storage_1->operator[](i);
    cout<< "use count after: "<< storage_1->operator[](i).use_count()<<endl;
  }

  for (int i = 0; i < dim2; ++i)
  {
    cout<< "use count before : "<< storage_1->operator[](i).use_count()<<endl;
    storage_1d_t ref = storage_1->operator[](i);
    storage_2->operator[](i) = ref;
    cout<< "use count after: "<< storage_1->operator[](i).use_count()<<endl;
  }

  /* code */
  return 0;
}

output
use count before : 1
use count after: 1
use count before : 1
use count after: 2

A: Since you do storage_2d_t storage_2 = storage_1; obviously, assigning the elements directly back onto themselves should not increase use counts.
I the second loop you print the use count during the time where you hold the temporary copy (ref). Making it explicit, you can see that indeed - as expected - the "after" count is not actually higher:
for (int i = 0; i < dim2; ++i) {
    cout << "use count before : " << (*storage_1)[i].use_count() << endl;
    {
        storage_1d_t ref = (*storage_1)[i];
        (*storage_2)[i] = ref;
        cout << "use count during: " << (*storage_1)[i].use_count() << endl;
    }
    cout << "use count after: " << (*storage_1)[i].use_count() << endl;
}

Now prints
use count before : 1
use count during: 2
use count after: 1

See it Live On Coliru

Brainwave Did you mean to deep-clone storage_1 into storage_2? It appears you have been confused by the fact that your outer storage_2d_t is also a shared pointer and hence you refer to the same vector by reference.
storage_2d_t storage_2 = boost::make_shared<content_2d_t>(*storage_1);
// or
storage_2d_t storage_2 = boost::make_shared<content_2d_t>(storage_1->begin(), storage_1->end());


text:
Q: python sshtunnel port forward not worked   my-pc                 ssh-server         another-app-server
-----------------------------------------------------------------------
 127.0.0.1:12345 ----> x.x.x.x:22  ---->  y.y.y.y:8080 [only accessed by ssh-server]

Actually i want do this as above and my-pc run windows10
from sshtunnel import SSHTunnelForwarder
from time import sleep
with SSHTunnelForwarder(
    (x.x.x.x),
    ssh_username=MY_SSH_SERVER_USER,
    ssh_private_key=MY_KEY_PATH,
    remote_bind_address=(y.y.y.y, 8080),
    local_bind_address=('127.0.0.1', 12345)
) as server :
server.start()
sleep(60)

when i run it's always tell me ERROR   | Problem setting SSH Forwarder up: Couldn't open tunnel 127.0.0.1:12345 <> y.y.y.y:8080 might be in use or destination not reachable  ...., and i use this following code it's worked.
from sshtunnel import SSHTunnelForwarder
from time import sleep
with SSHTunnelForwarder(
    (x.x.x.x),
    ssh_username=MY_SSH_SERVER_USER,
    ssh_private_key=MY_KEY_PATH,
    remote_bind_address=(y.y.y.y, 8080),
) as server :
server.start()
print(server.local_bind_port) # RANDOM PORT !! I HATE RANDOM!!
sleep(60)

but i just want bind 12345 as the port (it's now be used, i am sure), how can i do ????

A: to check if port 12345 is already used do :
netstat -aof | findstr :12345

if the command returned any process that means that it's in use.
you can either way change to other ports like 5000,1080,3000 etc


text:
Q: looping & echoing divs results outside of its parent div except the 1st child as the title says I loop several divs which is supposed to be inside their parent but only the first child is inside
there are 2 php file, one is the template the other is for generating content
here are php code :
The Template

  <?php include "isi.php" ?>

The Content (isi.php)
$sql=mysqli_query($con,"SELECT * FROM produk WHERE id_kategori2='4' ORDER BY id_produk DESC LIMIT 4");
echo "
";

while ($r=mysqli_fetch_array($sql)){

  include "diskon_stok.php";

  echo "

$r[nama_produk]

        $divharga

";
    }
  echo"
";

now the parent is div class=badan while the childs are div class=produk-box and the level 2 child is div class=produk
my intention is to make all of produk echoed inside produk-box while produk-box is echoed inside badan
but what's really happening is the first produk is echoed INSIDE produk-box, the second produk is echoed OUTSIDE of its parent div, and the rest of produk is echoed OUTSIDE of badan
here is the screenshot of google chrome inspect element :

A: echo "
'";

should be
echo '
';


text:
Q: How to filter out certain links using Jsoup I am creating a simple program that takes a search input from the user and the number of links that they want to receive. However, my code has 2 problems.

*

*When I print out the links, it also includes links for images, news, etc... I was wondering how I could only keep links related to the search.
 String searchURL = GOOGLE_SEARCH_URL + "?q="+searchTerm+"&num="+num;
 Document doc = Jsoup.connect(searchURL).userAgent("Mozilla/5.0").get();
 Elements results = doc.select("a[href]");

However, filtering the document using a[href] includes all links on the page. I also tried using h3.r > a which returned no results at all and also a > h3, which fixed my current problem, but it would only display the title and not the actual link. Here is part of the output that I want to get rid of:
Title: Google
Link: https://www.google.com/?sa=X&ved=0ahUKEwifoOa-p7bvAhUDqlkKHS8fCsIQOwgC

Title: Google
Link: https://www.google.com/?num=5&output=search&sa=X&ved=0ahUKEwifoOa-p7bvAhUDqlkKHS8fCsIQPAgE

Title: News
Link: https://www.google.com/search?q=java&num=5&source=lnms&tbm=nws&sa=X&ved=0ahUKEwifoOa-p7bvAhUDqlkKHS8fCsIQ_AUICCgB

Title: Images
Link: https://www.google.com/search?q=java&num=5&source=lnms&tbm=isch&sa=X&ved=0ahUKEwifoOa-p7bvAhUDqlkKHS8fCsIQ_AUICSgC

Title: Books
Link: https://www.google.com/search?q=java&num=5&source=lnms&tbm=bks&sa=X&ved=0ahUKEwifoOa-p7bvAhUDqlkKHS8fCsIQ_AUICigD

Title: Maps
Link: https://maps.google.com/maps?q=java&num=5&um=1&ie=UTF-8&sa=X&ved=0ahUKEwifoOa-p7bvAhUDqlkKHS8fCsIQ_AUICygE

Title: Videos
Link: https://www.google.com/search?q=java&num=5&source=lnms&tbm=vid&sa=X&ved=0ahUKEwifoOa-p7bvAhUDqlkKHS8fCsIQ_AUIDCgF
...

*Because of this, I end up with many more links than the requested amount and I think it's also including the sub links to pages(ex: When you search for Java, the first link is java.com, with its sublinks, which are the download pages).

In short, I want to be able to filter out google links such as images, news, maps, shopping, etc... and only include the main links to pages.

A: You cannot achieve your goal with jsoup, because the HTML content returned by Google doesn't contain the search results. Everything is build from JavaScript. You can check it by running:
curl https://www.google.com/\?q\=stackoverflow\&num\=3 | grep stackoverflow

You will not find any stackoverflow URL. You can try to run the JavaScript yourself, but it will be much easier to use the Google Programmable Search Engine.

A: My own solution:
        Elements title = doc.select("a > h3");
        Elements links = doc.select("a[href]");

        Map<String, String> combo = new HashMap<>();

        for (Element result : links) {
            combo.put(result.text(),result.attr("abs:href"));
        }
        for (Element result : title) {
            System.out.println("Title:"+result.text());
            String temp = getSimilar(combo, result.text());
            if(temp!=null)
                System.out.println("Link:"+temp.substring(temp.indexOf("http", temp.indexOf("http") + 1),temp.indexOf("&")));
            else
                System.out.println("No link found");
            System.out.println();
        }

    }

    public static String getSimilar(Map<String, String> combo, String sim){
        for (Map.Entry<String,String> key : combo.entrySet()){
            if(key.getKey().contains(sim))
                return key.getValue();
        }
        return null;
    }


text:
Q: Visual Studio 2010 Web development server cookie I want to develop ASP.NET Pages on local server.
I use visual studio 2010 Web development server, but cookie isn't created.
So I cannot make a login page.
What can I do for this problem?  My code:
Response.Cookies["PI"]["0"] = Server.UrlEncode(piData);

I just added cookie using the above code. But nothing is created.


text:
Q: How to read or parse .mobi file on iOS I'm developing an iOS reader App and I want to support the .mobi file by Amazon.I search but find few things about parse .mobi file on iOS.Any help will be appreciated.

A: The Mobipocket e-book format is based on the Open eBook standard using XHTML and can include JavaScript  and frames. It also supports native SQL queries to be used with embedded databases.
I am not aware of easily adaptable source code (especially for iOS), but here is the format spec, you could try to parse it, though I don't think it will be easy:  http://wiki.mobileread.com/wiki/MOBI
It might not be elegant but maybe you can use a converter (there are a few links on the page) and try a more public/better supported format instead.


text:
Q: How to update appsettings from an aspx page? I have customer specific settings in a custom.config which links back to web.config.
What I want to accomplish is to load the settings from appsettings section in custom.config into setup.aspx page. The settings will be loaded into textbox, dropdown list etc. After the user makes changes then save it back to custom.config. Is this possible? It seems to me that the appSettings section is readonly. What would be best approach to accomplish this?

A: That sounds like you need a database... config files are not really meant to store user data. Editing web.config generally causes app pool restart, not sure if custom config works the same way but I would not be surprised.

A: See the links .... But if you want to change or update the values frequently then you should use Database rather then configuration file..
AppSettings In web.config
update web.config file appsettings value


text:
Q: Script running, boot cronjob of said script not running, despite cronjob working when following an example tutorial The script in question displays the IP address of a raspberry pi, and a voltage that the raspberry pi is reading from an i2c bus, on an i2c OLED screen. Same as with the other tutorial, https://www.linuxshelltips.com/run-python-script-ubuntu-startup/
it was placed in /bin, I put the same permissions, same owner, and both were placed in the non-sudo crontab. Logically, there must be something about the script that makes a run on boot not work, despite it working when when I write "python3 display_battery*_*IP.py" in terminal. Any help would be greatly appreciated.
This is my first time posting on stakcoverflow, so my apologies if this is messy, the code has a bunch of comments because I first need to get it running properly without the additional functions:
import readline

from telnetlib import IP

import time

import Adafruit_GPIO.SPI as SPI

import Adafruit_SSD1306

from std_msgs.msg import String

from std_msgs.msg import Float32

from PIL import Image

from PIL import ImageDraw

from PIL import ImageFont

import rospy

import re

import subprocess

import smbus

# Raspberry Pi pin configuration:

RST = None     # on the PiOLED this pin isnt used

# Note the following are only used with SPI:

DC = 23

SPI_PORT = 0

SPI_DEVICE = 0

# Beaglebone Black pin configuration:

# RST = 'P9_12'

# Note the following are only used with SPI:

# DC = 'P9_15'

# SPI_PORT = 1

# SPI_DEVICE = 0

# 128x32 display with hardware I2C:

disp = Adafruit_SSD1306.SSD1306_128_32(rst=None, i2c_bus=1, gpio=1)

bus = smbus.SMBus(1)

# Initialize library.

disp.begin()

disp.clear()

disp.display()
# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.

width = disp.width
height = disp.height
image = Image.new('1', (width, height))

# Get drawing object to draw on image.

draw = ImageDraw.Draw(image)

# Draw a black filled box to clear the image.

draw.rectangle((0,0,width,height), outline=0, fill=0)

# Draw some shapes.
# First define some constants to allow easy resizing of shapes.

padding = -2
top = padding
bottom = height-padding

# Move left to right keeping track of the current x position for drawing shapes.
x = 0

# Load default font.
font = ImageFont.load_default()

IP_prev = 'No IP'
IP_filt = ''

# ro red voltage and current from Arduino Nano through I2C
        # for code on the arduino:
nano_addr = 12             # I2C adress of nano (setted in software!)
voltage_reg_nano = 0       # value to send to arduino to get voltage read back

   # Calibration values for converting from raw digital binary form to decimal form
    # Calibration values were manualy calibrated to +- 0.1V acuracy!
calVoltageA = 11
calVoltageB = 0.0
calCurrent = 37.8788
calCurrentOffset = 0.33

        # init of I2C bus with arduino nano conected

bus = smbus.SMBus(1)

xavier_IP = ""
system_voltage = 0
system_current = 0

func = 1
def func_check(func):
    if func == 1:
        draw.text((x, top+16),     "Wellness: 1 ", font=font, fill=255)
        return 0
    else:
        draw.text((x, top+16),     "Xavier: 0", font=font, fill=255)
        return 1

def read_voltage():
        # Sometimes an I/O timeout or error happens, it will run again when the error disappears
        try:
            # arduino is configure to send voltage data on "register" 0, current on 1
            # data is sent in 2 bytes, because to big for one I2C message
            voltage_msg = bus.read_i2c_block_data(nano_addr, 0, 2)

            # conversion to get real voltage
            # measurement up to 1023, so to big for 7bit I2C messages. Sends MSB first, then LSB, then remap to 0-5V
            x = (((voltage_msg[0]&0x7) << 7) + voltage_msg[1]) * 5/1023.0
            system_voltage = x * calVoltageA + calVoltageB

            #####################################################################################################################
            #voltage_msg = bus.read_i2c_block_data(nano_addr, 0, 2)
            # conversion to get real voltage
            # measurement up to 1023, so to big for 7bit I2C messages. Sends MSB first, then LSB
            #system_voltage = float((((voltage_msg[0]&0x7) << 7) + voltage_msg[1])) * calVoltageA + calVoltageB
            #####################################################################################################################
            #print("Gone through loop")
            #print(system_voltage)
            return system_voltage
       except IOError:
            print("Bus IOerror")
            return 0

def read_current():
    try:
        current_msg = bus.read_i2c_block_data(nano_addr, 1, 2)

        # conversion to get real voltage
        x = float((((current_msg[0]&0x7) << 7) + current_msg[1])) * 5 / 1023.0
        system_current = (x - calCurrentOffset) * calCurrent
            #rospy.loginfo(f"Current : {self.system_current}A")
    except IOError:
        print("BUS error")

while True:

    cmd = "ip -4 -o address show dev eth0 | awk '{print $4}'"

    # Draw a black filled box to clear the image.

    IP_bytes = subprocess.check_output(cmd, shell = True )
    IP_str = IP_bytes.decode('utf-8')
    IP_str.split('/')
    #print(IP_str)
    draw.rectangle((0,0,width,height), outline=0, fill=0)

    #with open("xavier_IP.txt", "r") as f:
    #    xavier_IP = f.readlines()

    voltage_str = str(round(read_voltage(), 1))
    #print(voltage_str)
    #read_current()

    func = func_check(func)
   # Shell scripts for system monitoring from here : https://unix.stackexchange.com/questions/119126/command-to-display-memory-usage-disk-usage-and-cpu-load
    # Write two lines of text.

    draw.text((x, top),       "IP: " + IP_str,  font=font, fill=255)
    draw.text((x, top+8),     "Voltage: "+ voltage_str, font=font, fill=255)
    #draw.text((x, top+16),     "Xavier: "+ xavier_IP, font=font, fill=255)

    # Display image.
    disp.image(image)
    disp.display()
    time.sleep(1)

Another script with the exact same OLED display setup worked on boot just fine, the difference here is the reading of voltage through the i2c bus and the display of it on the OLED, so I highly doubt the issue is related to the OLED part of the question itself. I have tried changing the permissions and ownership of the script, I have both done sudo crontab -e, and non-sudo. Before I put the script in /bin, I made a directory called ./bootscripts and attempted to make a cronjob using that placement (I am a big newbie, so I thought it might make a difference for all I know).


text:
Q: Hydrological model building for flooding analysis I am recently studying the topic in investigating the features of river and to perform flooding analysis.
I got the elevation data, and I used the elevation data to generate streams in ArcGIS and I have studied the features of river such as the stream density, stream order, stream length in ArcHydro.
The first part of my study is finished, but I have no idea how to start with the flooding analysis.
Can I build a model in ArcGIS to perform the flooding analysis? I have read some papers related to my study and I found that the Curve number method may work in my study to get the discharge of the river. However, how can I compare the calculated discharge with the capacity of river(based on cross-section) to check whether flooding will occur?
Also, how can I work on Curve number method if only rainfall data and elevation data are given, as curve number method involves many calculation parameters, such as initial abstraction and infiltration rate.

A: Maybe this will help you:
Flood Hazard Analysis:
https://www.youtube.com/watch?v=775YPgO5LLE
How to model Coastal flooding in ArcGIS:
https://www.youtube.com/watch?v=KYpsSL4R6x0
Floodplain Analysis with ArcGIS Model Builder (ppt):
https://www.google.nl/url?sa=t&rct=j&q=&esrc=s&source=web&cd=7&ved=0ahUKEwjJv6So5cnKAhWBXQ8KHYxSAS8QFgg9MAY&url=http%3A%2F%2Fwww.ce.utexas.edu%2Fprof%2Fmaidment%2Fgiswr2004%2Fnov23%2Frim.ppt&usg=AFQjCNFrMh30P2u0tdH7L3M-lzZZbBtUJw&sig2=9hKQ08fDZ6jjLzOKPRm64w&bvm=bv.112766941,d.ZWU&cad=rja


text:
Q: Lesscss Mixins with guards. Syntax Error I write my CSS with Lesscss using it on client side (with compiler less.js).
There are good examples for guards usage in documentation, but it don't work for me. I can't understand, why...
Code example goes here:
@import "common-functions.less";

// variables
@minHeaderWidth: auto;
@maxHeaderWidth: 1200px;

@minButtonsWidth: 50px;
@maxButtonsWidth: 75px;

// Mixins with guards
.applyHeaderStyles(@headerWidth, @buttonsWidth) when (ispixel(@headerWidth)) {
    .my-headerElement {
        width: @headerWidth;
    }
}
.applyHeaderStyles(@headerWidth, @buttonsWidth) when not (ispixel(@headerWidth)) {
    .my-headerElement {
        width: @headerWidth;
        margin: 0 @buttonsWidth;
    }
}

// than I use .applyHeaderWidth in @media queries
@media screen and (min-width: 1050px) {
    .applyHeaderStyles(@maxHeaderWidth, @maxButtonsWidth);
    .my-buttonElement {width: @maxButtonsWidth;}
}
@media screen and (max-width: 1049px) {
    .applyHeaderStyles(@minHeaderWidth, @minButtonsWidth);
    .my-buttonElement {width: @minButtonsWidth;}
}

Code was writen by documentation. But it doesn't work.
When I execute this code, I have Syntax Error:

Syntax Error on line 10
[link to my file] on line 10, column 58:
10    // Mixins with guards
11    .applyHeaderStyles(@headerWidth, @buttonsWidth) when (ispixel(@headerWidth)) {
12        .my-headerElement {

A: As mentioned here, updating to less.js 1.2.2 solves the problem.
From the changelog:
1.2.0
Mixin guards


text:
Q: How do I deploy a single-page app. written in ClojureScript / Figwheel to a static server? I'm playing with Figwheel and writing a simple single-page app that doesn't require any server-side intelligence.
In principle, this app. could be placed on any static web-server.
But how do I actually deploy it? It looks like the main.js which is in my Figwheel development environment is setting up the figwheel connection.
What js and html files do I actually need to put on my static server? Has Figwheel created them, or do I need to create a new main.js and index.html? And where can I find examples?
The documentation is great for how to get started using Figwheel but surprisingly reticent on what to do after you've finished development.

A: Step 1: Make the production build:
lein do clean, cljsbuild once min
Step 2: Put everything in resources/public in a publicly accessible place.
Here is the script I use to do this in an example project:
https://github.com/timothypratley/whip/blob/master/deploy.sh
The HTML resources don't change between local development and deployment. The only thing that is different are the compiled artifacts. You can deploy in fact development compiled artifacts just fine too. The only reason it is recommended to do a "production build" is that when developing locally the intermediate JS files are not stitched together, because it is faster to load only the changed code into the browser. For deployment, having a single compiled artifact is better. That single compiled JS can have advanced optimizations, or just simple optimizations depending on how you configure the builds in your project.clj. You don't really need to worry about any of this, I'm just explaining because you asked specifically what changes.
It might sound strange that the HTML page doesn't change at all, so lets explain that a little more. The HTML page includes a compiled JS, when you are running figwheel, if you open up that JS you will see it in turn just loads other JS files. But if you exit figwheel and do a clean "production" build, you will see all the code goes into the one JS file. Pretty tricky huh?
That whip project should provide the example you are seeking, please let me know if any of this is unclear.
It uses github pages and the deployment target, but again you just need everything in the resources/public directory hosted somewhere. So you can use a very similar script with any deployment target.

A: Hat tip to Timothy Pratley for his answer.
I built on it with more details.  See https://github.com/deg/clojure-then-you-think/wiki/Static-website-deploy-to-GitHub
But, since the Stack Overflow moderators are rightly worried about off-site answers going stale, here's a full copy, correct as of now:

(Hat tip to Timothy Pratley! The ideas here are based on his, from his whip project and Stack Overflow answer).
Many ClojureScript projects need no explicit server support. Either they do everything in the browser, or they use a cloud-based existing solution for their back-end. An example is my Trilystro toy project which is a re-frame browser app on the front-end and uses a Firebase app for persistent storage.
For this kind of project, a very easy deployment technique is to create a GitHub Pages project page. The cost is zero, and site availability seems to be good (in my very light testing).
Setup
GitHub configuration
GitHub's detailed instructions are on that page, but the steps are really amazingly simple:
- On GitHub, go into your projects Settings|Options.
- Turn on GitHub Pages (near the bottom of the options pages).
- Deploy your compiled project to the gh-pages branch of your project. (see below!)
- Your project will now be available at http://YOUR-GITHUB-ID.github.io/YOUR-GITHUB-REPOSITORY
- Optionally setup a custom domain
  - Add your new URL as the custom domain in the options
  - At your DNS provider, add a CNAME record pointing YOUR-GITHUB-ID.github.io. Important: do not include the repository name here. (A CNAME must point to a host, not a URL).
  - Add a file named CNAME at the root of your deployed project, containing just the URL
Clojure deployment
We brushed over one critical step above. You must compile your ClojureScript project and get it into the gh-pages branch of your GitHub repository.
In broad strokes, this is very easy: just do a lein cljsbuild and push the results up to GitHub. As always, the devil is in the details. Based on Timothy Pratley's ideas, I've created two scripts that I use in Trilystro. The latest versions are here:

*

*First project deployment: first-deploy.sh

*Ongoing deployments: deploy.sh
Let's look at them in detail:  (Note, of course, that I'll probably continue to change these files in the future. The source will be more accurate than the copies below)
Trilystro is still hard-coded into these scripts in a few place. You'll need to search and replace for your own project.
first-deploy.sh

*

*Create a directory structure outside the local repo. This is where we will keep our working copy of the deployed site.

*Initialize a git repo locally

*Add the CNAME file

*Associate this repo with the gh-pages branch on GitHub

```
#!/bin/bash

DEPLOYDIR=../trilystro-website
mkdir $DEPLOYDIR
pushd $DEPLOYDIR

git init

cat > CNAME <<EOF
trilystro.vuagain.com
EOF

git add .
git commit -m "Initial deploy to GitHub Pages"
git push --force --quiet "git@github.com:deg/trilystro.git" master:gh-pages

git branch gh-pages
git checkout gh-pages

popd

```
deploy.sh

*

*Check that the project is fully committed. We will be marking the deployment with a a git commit SHA, so we want to avoid capturing any stray changes.

*Clean and build the project. Abort if any errors occur.

*Clean the deployment directory, then reconstruct the CNAME file and copy in the compilation results.

*Also copy info about the build into the deployment, in a file called git-describe.txt

*Commit the new version to GitHub, with a comment describing the version

```
#!/bin/bash
# Adapted from https://github.com/timothypratley/whip/blob/master/deploy.sh
# See also https://stackoverflow.com/questions/37667931/how-do-i-deploy-a-single-page-app-written-in-clojurescript-figwheel-to-a-stat
set -e

DEPLOYDIR=../trilystro-website

RED='\033[0;31m'
NOCOLOR='\033[0m'

function die(){
  echo -e ${RED}"$1"${NOCOLOR}
  exit 1
}

if [ -n "$(git status --untracked-files=no --porcelain)" ]; then
  die "Aborting deploy. There are uncommited changes.";
fi

lein clean
lein cljsbuild once min || die "Lein cljsbuild failed!"

GIT_COMMIT=$(git show -s --oneline HEAD)

pushd $DEPLOYDIR
rm -rf *
cp -r ../trilystro/resources/public/* .
cat > CNAME <<EOF
trilystro.vuagain.com
EOF
popd

git describe --always               > $DEPLOYDIR/git-describe.txt
git log -1 --format=%cd --date=iso >> $DEPLOYDIR/git-describe.txt

pushd $DEPLOYDIR
git add .
git commit -m "Deploy $GIT_COMMIT"
git push "git@github.com:deg/trilystro.git" gh-pages:gh-pages

popd

```


text:
Q: Entity framework 6 generate file per entity I am a beginner of Entity framework and i am trying to migrate ( as per the migration guidelines ) one of the project from entity framework 4 to entity framework 6. At present, all entities in that project are present in separate cs file and the same way i wanna keep it after migrate to EF6. I have seen some example how to keep entities in seperate files in EF4 ( model.tt template file ) but i could not find any example how to do it EF6 ( model.tt template file )
The model.tt file is similar to this link
https://github.com/vc3/ExoModel/blob/master/ExoModel.EntityFramework/DataModel.tt
Please help to how keep entities in separate file in EF6


text:
Q: IE jQuery Opacity Anti-Aliasing Issue I am using jQuery to fade in and out a .png images of links on the home page of http://www.logandwight.com
In IE7 and IE8 the text have no anti-aliasing and are all boxy. I've tried messing with the opacity settings and then I tried animating the filter property specifically for IE but nothing seems to work.
Does anyone know whats wrong?

A: This is an inherent problem with IE, transparency, and opacity.  Unfortunately there's no good work around while animating...in this situation I just disable animations for IE users.
Maybe IE9 will finally do something about this?

A: sIFR might be a possible cross-browser solution here (with a little modification of the sIFR source, you could get those rollover effects).
sIFR is a flash-based font embedding solution that allows you to display real text in a web page using a font of your choosing.
http://www.mikeindustries.com/blog/sifr


text:
Q: Expor a PRIMARY KEY de uma entidade é considerado um problema grave de segurança? Considerando um exemplo bem básico: suponha que exista um sistema web em que o usuário pode visualizar seu perfil (e de demais usuários) por meio de um identificador único passado para uma rota, por exemplo:
https://sistema.io/profiles/<identificador>

Então foi escolhido utilizar o campo ID da entidade que contém os dados daquele usuário persistido no meu BD. Assim, supondo que meu sistema tenha um usuário João que teve seu identificador gerado no registro como 100, seu perfil poderia ser acessado por meio do seguinte link:
https://sistema.io/profiles/100

Minha questão é: expor esse tipo de dado (o ID, a chave primária da tabela) é um problema grave de segurança? Aqui eu utilizei o exemplo da URL, mas poderia ser qualquer exemplo no qual a primary key ficasse exposta para quem está utilizando a aplicação.
Eu já ouvi muito que isso é grave por conta dos relacionamentos que a entidade pode possuir mas não entendi como isso ocasionaria uma brecha de segurança na minha aplicação sem ter um exemplo claro.

A: Não, se não é validado as ações no lado do servidor, a falha está aí, expor uma chave primária pode facilitar, porém não é uma falha
Em relação a essa facilidade... Como você está falando de chave primária, vou consideraro uma aplicação usando SQL, onde os ID são gerados de forma sequencial, ou seja, em uma ou duas tentativas encontra facilmente uma linha do banco. Ter essa coluna exposta facilita encontrar uma linha específica. Mas se não há validação provavelmente consegue a lista de todas as linhas de todas as tabelas do banco (ou pelo menos a maioria)


text:
Q: Displaying current position using QGIS? How can I display my current position in the QGIS canvas, similar to the "blue point" in google mapsa?
I need this to navigate to defined points and I do not want to change the program all the time.

A: You can try to get the location of your IP address with this python code:

import requests
import json
send_url = 'http://freegeoip.net/json'
r = requests.get(send_url)
j = json.loads(r.text)
lat = j['latitude']
lon = j['longitude']
map_pos = QgsPoint(lon, lat)
rect = QgsRectangle(map_pos, map_pos)
canvas = qgis.utils.iface.mapCanvas()
canvas.setExtent(rect)
canvas.refresh()

This will find your estimated location, based on your IP address, and center the map on that location.