text:
Q: Argo workflow when a condition for substring match I want to execute a task in Argo workflow if a string starts with a particular substring.
For example, my string is tests/dev-or.yaml and I want to execute task if my string starts with tasks/
Here is my workflow but the condition is not being validated properly
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: conditional-
spec:
  entrypoint: conditional-example
  arguments:
    parameters:
    - name: should-print
      value: "tests/dev-or.yaml"

  templates:
  - name: conditional-example
    inputs:
      parameters:
      - name: should-print
    steps:
    - - name: print-hello
        template: whalesay
        when: "{{inputs.parameters.should-print }} startsWith 'tests/'"

  - name: whalesay
    container:
      image: docker/whalesay:latest
      command: [sh, -c]
      args: ["cowsay hello"]

Below is the error it is giving when I run the workflow
WorkflowFailed 7s workflow-controller  Invalid 'when' expression 'tests/dev-or.yaml startsWith 'tests/'': Unable to access unexported field 'yaml' in token 'or.yaml'

Seems it is not accepting -, .yaml and / while evaluating the when condition.
Any mistake am making in my workflow? What's the right way to use this condition?

A: tl;dr - use this: when: "'{{inputs.parameters.should-print}}' =~ '^tests/'"
Parameter substitution happens before the when expression is evaluated. So the when expression is actually tests/dev-or.yaml startsWith 'tests/'. As you can see, the first string needs quotation marks.
But even if you had when: "'{{inputs.parameters.should-print}}' startsWith 'tests/'" (single quotes added), the expression would fail with this error: Cannot transition token types from STRING [tests/dev-or.yaml] to VARIABLE [startsWith].
Argo Workflows conditionals are evaluated as govaluate expressions. govaluate does not have any built-in functions, and Argo Workflows does not augment it with any functions. So startsWith is not defined.
Instead, you should use govaluate's regex comparator. The expression will look like this: when: "'{{inputs.parameters.should-print}}' =~ '^tests/'".
This is the functional Workflow:
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: conditional-
spec:
  entrypoint: conditional-example
  arguments:
    parameters:
      - name: should-print
        value: "tests/dev-or.yaml"
  templates:
    - name: conditional-example
      inputs:
        parameters:
          - name: should-print
      steps:
        - - name: print-hello
            template: whalesay
            when: "'{{inputs.parameters.should-print}}' =~ '^tests/'"
    - name: whalesay
      container:
        image: docker/whalesay:latest
        command: [sh, -c]
        args: ["cowsay hello"]


text:
Q: Is it possible to code search engine in beautiful Soup I am using Beautiful Soup for parsing web pages.
Are there any functions in BS which i can use i making search engine or crawling the website to index it in database.

A: No, BeautifulSoup is not a search engine. It is also not a Swiss Army knife, nor can it make you a sandwich. You will need a database (preferably one that's optimized for search, like Sphinx or Lucene) to do that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to express in TypeScript the type of a Record minus some of its key in a generic manner? I have a function that filters out some keys from a Record and I want the type safety to prevent me from accessing filtered out keys.
What I got to express that is:
// Filters out the result of OnlySelected to remove never from filtered out keys
type OmitNever<T> = { [K in keyof T as T[K] extends never ? never : K]: T[K] }

// Only keeps the keys that are in the type V
type OnlySelected<T extends object, V> = {
    [K in keyof T]-?: K extends V ? T[K] : never
}

Which works great for simple use cases:
const a: A = {
    a: 1,
    b: "2",
    c: "3",
    d: "4",
    e: "5",
}
type MyType = OmitNever<OnlySelected<A, "a" | "b">>;
// type MyType = {
//    a: number;
//    b: string;
//}

But now if I try to use theses types in a generic function I have to means to convert the type of the keys that I want to keep to an union type. So I have to provide the type by hand and it's sad to have to repeat the keys to keep twice just to be type safe:
const filterRecord = <T extends Record<any, any>, TO_KEEP>(record: T, keys: Array<keyof T>) => {
    return Object.keys(record)
        .reduce((acc, it) => {
            if (keys.includes(it)) {
                acc[it as keyof OmitNever<OnlySelected<T, TO_KEEP>>] = record[it];
            }
            return acc;
        }, {} as OmitNever<OnlySelected<T, TO_KEEP>>)
}

const res = filterRecord<A, "d" | "e">(a, ["d", "e"]);
console.log(res.d)
console.log(res.e)
console.log(res.a)

Anyone knows the solution or a better design?
See the playground here.

A: You can define filterRecord's TO_KEEP as extends keyof T, then use TO_KEEP[] as the parameter type. TypeScript will infer correctly then (but keep reading):
const filterRecord = <T extends Record<any, any>, TO_KEEP extends keyof T>(
    record: T,
    keys: TO_KEEP[]
) => {
    return Object.keys(record).reduce((acc, it) => {
        if ((keys as readonly string[]).includes(it)) {
            acc[it as keyof OmitNever<OnlySelected<T, TO_KEEP>>] = record[it];
        }
        return acc;
    }, {} as OmitNever<OnlySelected<T, TO_KEEP>>);
};

Playground example
Note that I did have to add a broadening type assertion within the implementation there (keys as readonly string[]) in order to use includes, but that's harmless.

Side note: Unless you're using it for some other purpose, you can avoid needing OmitNever by changing your definition of OnlySelected slightly (but keep reading):
type OnlySelected<T extends object, V> = {
    [K in keyof T as K extends V ? K : never]-?: T[K];
    // −−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^−−−−−^^^^
};

Playground example

But, OnlySelected seems like it's doing the same thing the built-in Required and Pick do, so you could just use them(or define OnlySelected in terms of Required and Pick). (Playground example) (Thanks to caTS for pointing out the Required part, I'd missed the flag mod and just mentioned Pick before.)


text:
Q: How to print a 'null' for any of many values that may have no value I'm running some statistics stuff (example):
Chi_min=str(min(chi))
Chi_max=str(max(chi))
Teff_min=str(min(Temp))
Teff_max=str(max(Temp))
Tin_min=str(min(Tin))
Tin_max=str(max(Tin))
Tau_min=str(min(Tau))
Tau_max=str(max(Tau))
Mdots_min=str(min(Mdots))
Mdots_max=str(max(Mdots))
Chi_sdev=str(sp.stats.tstd(chi))
Teff_sdev=str(sp.stats.tstd(Temp))
Tin_sdev=str(sp.stats.tstd(Tin))
Tau_sdev=str(sp.stats.tstd(Tau))
Mdots_sdev=str(sp.stats.tstd(Mdots))

and I have the results being printed out onto a single line like so
NewResults=NewResults+str(data[RowStar][0])+'\t'+str(RowStar+1)+'\t'+str(ChiThresh)+'\t'+str(BestX)+'\t'+str(Teff)+'\t'+Teff_min+'\t'+Teff_max+'\t'+Teff_sdev+'\t'+Teff_sdev2+'\t'+Teff_med+'\t'+str(Tempin)+'\t'+Tin_min+'\t'+Tin_max+'\t'+Tin_sdev+'\t'+Tin_med

I'm missing a few columns when it writes to the file. I suspect that it's not putting anything down for any null values. What is the easiest way to have python print out a value of 'null' for any value that doesn't have any output?

A: One possible solution is to rely on the fact that an empty string evaluates as being False.
As such, you can do the following for each entry:
Chi_min = str(min(chi)) or "null"


text:
Q: Error in Stored Procedure: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints I am using DataAdapter("SDM_Tran_GenerateInvoice") inside DataSet("SDMDAL.xsd") in my project.
Below is the structure of DataAdapter along with the Stored Procedure names in it:

Below is the Table structure Im using for the same:

I am calling this DataAdapter inside Class file named as SDM.InvoiceBLL.cs:
using SDMDALTableAdapters;

public class SDM_Invoice
{
    private SDM_Tran_GenerateInvoiceTableAdapter _GenerateInvoiceTableAdapter = null;
    protected SDM_Tran_GenerateInvoiceTableAdapter Adapter
    {
        get
        {
            if (_GenerateInvoiceTableAdapter == null)
                _GenerateInvoiceTableAdapter = new SDM_Tran_GenerateInvoiceTableAdapter();

            return _GenerateInvoiceTableAdapter;
        }
    }

    #region GET
    public SDMDAL.SDM_Tran_GenerateInvoiceDataTable SelectInvoice(string _SPID)
    {
        return Adapter.SelectInvoice(_SPID);         }
    public SDMDAL.SDM_Tran_GenerateInvoiceDataTable GetInvoiceBillingBySPID(string _SPID)
    {
        return Adapter.GetInvoiceBillingBySPID(_SPID); //getting error for this Stored Procedure

    }
    public SDMDAL.SDM_Tran_GenerateInvoiceDataTable GetInvoiceID()
    {
        return Adapter.GetInvoiceID();
    }
    public SDMDAL.SDM_Tran_GenerateInvoiceDataTable GetInvoiceNumber()
    {
        return Adapter.GetInvoiceNumber();
    }
    #endregion
}

and then calling the SelectInvoice() function of class file inside Default.aspx.cs page, to display records in RadGrid:
protected void rgInvoice_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
        rgInvoice.DataSource = SDM.Invoice.GetInvoiceBillingBySPID(lblId.Text);
}

Below is the GetInvoiceBillingBySPID(_SPID) Stored Procedure
ALTER PROCEDURE [dbo].[SDM_Select_BillingBySPID_Invoice]
    @SPID as nvarchar(50)
    AS
BEGIN

    SET NOCOUNT ON;
SELECT
--B.ID,
B.BillingID,
DCIDescription, --
(SELECT BUName FROM dbo.SDM_Master_BU WITH (NOLOCK) WHERE BUID=AfoBUID) as BUName, --
(SELECT BUfoStatusID FROM dbo.SDM_Master_BU WITH (NOLOCK) WHERE BUID=AfoBUID) as BUfoStatusID --
FROM SDM_Tran_Billing B WITH (NOLOCK),
dbo.SDM_Tran_DCI WITH (NOLOCK),
dbo.SDM_Tran_Allocation WITH (NOLOCK)
WHERE B.BfoAllocationID=AllocationID and AfoDCIID=DCIID and DCIfoSPID=@SPID and B.BfoStatusID=1

END

but when I run Default.aspx page, everytime I get below error at line  return Adapter.GetInvoiceBillingBySPID(_SPID);

Below is the code of the location it is showing in the Error Snapshot - Source File:

Please note that I am very new in DataAdapter and Asp.Net (C#).  Please let me know what mistake I am doing in my code And what does this error mean ? Please reply in simple way so that I can understand.  Thanks in advance


text:
Q: Why is air a poor conductor of heat? Today, I was reading an article How Thermoses Work
It goes on to explain all three processes of heat transfer:

*

*Conduction

*Radiation

*Convection

In Convection, It states,

If it weren't for convection your soup would stay hot a lot longer,
  because it turns out that air is a pretty poor heat conductor.

What does it have to do with air being poor conductor for the soup to stay hot a lot longer?
In other words, if air were a good conductor of heat, would your soup stay hot for longer?

A: Well, the argument is not very well put:
Because the air is a bad conductor of heat the soup stays hot longer: only the first layer of air touching the soup gets hot fast, and heat is not transmitted efficiently to the bulk of air.
For soup, in contrast to thermos, evaporation cooling should also be considered.
Convection by continuously replacing the contacting layer of air increases the heat transfer to the bulk of air by conduction and at the same time the rate of evaporation increases, increasing cooling.
So the soup cools faster than if there were no convection.
If air were a good conductor of heat, the soup would cool  fast, as in a metal plate on a metal surface.
You could go through a read of the wiki article.
Edit: Georg's comment makes me add that of course the soup would be also cooling because  it will be radiating with the corresponding to its temperature black body spectrum. Convection increases the rate of heat loss over the loss through radiation.
To address the title, which differs from the questions in the content:

Why is air a poor conductor of heat?

It is mainly the very low density of gases that make them bad conductors of heat. In liquids and solids atoms and molecules are densely packed and transfer of energy has much smaller  distances to happen. In a gas molecules have to scatter off molecules to exchange energy in larger distances, so the probability of transfer is much smaller.

A: Air is a bad conductor because, to conduct heat current molecules should absorb heat and transmit it to neighbor by vibrating. In case of air molecules near the hot surface absorbs the heat and start vibrating, but neighbor molecule is so far that this vibration should be very high and so the heat energy required is high for small conduction to start.
Convection helps air in conduction by making molecules in air mobile so that the transfer of heat is not solely depend on the vibration of molecule, but another (or that molecule itself) can travel to transfer heat.
So , "If air were a good conductor of heat" then soup will not stay hot for longer because this time convection+conduction will both help to transfer heat away from soup.

A: Because conduction is the transfer of heat through a substances as a result of neighbouring vibrating particles, The particles in air are far apart. Heat does not travel easily by conduction through air.

A: Convection requires the hot air just above your soup that has been heated up to rise as its density reduces after being heated, allowing the colder air around the rising hotter air to replace the hotter air and the same thing will happen again. As the convection currents (the rising of the hot air and the sinking of the cold air) keep taking place just above your soup, the previously hot soup will start to lose thermal energy (heat) and your soup will cool down despite the fact that air is a poor conductor of heat. In other words, cooling of your soup only takes place in convection due to the movement of air and not the heating up of air itself. As a result, if air was a good conductor of heat, it would not make a difference.
Hope this helps.

A: Thermal conductivity in the linear regime (i.e. no convection) is determined by the rate of energy transfer by diffusion of molecules from the hot regime (high average kinetic energy) to the cold regime (low average kinetic energy). This rate is proportional to the density of molecules, the mean velocity, the mean free path, and the specific heat per particle, kappa\sim n c_p v l. This might suggest that the heat conductivity of a metal is larger because the density is bigger. This is not true, because the mean free path goes inversely as density, l \sim 1/(n\sigma), where \sigma is the scattering cross section. The main reason that metals are good conductors is that the velocity of electrons in a metal is much bigger than the velocity of air molecules (because electrons are lighter, and because at low T the electron velocity at the Fermi surface is still large because of the Pauli principle).

A: Air is a bad conductor of heat due to the fact that its  absorptivity property is less and transmittivity property is also less but reflectivity property is more.meaning that when heat is conducted,convected,and radiated through air the air donnot absorb neither transmit the heat instead reflect back and allow the heat transfer to escape freely due to its density changes in changinging temperature...therefore the molecules of air carry a very less amount of heat with them.However, the temperature of air rises in summer because is due to the presence of high amount of moisture content which has higher density , more absorptivity  and more transmittivity properties than air...so the heat transfered through these molecules absorb large amount of heat and conduct,convect and radiate the heat between neighbouring molecules...


text:
Q: Struggling to get new graphics to appear with each tick of the timer Sorry if this sounds a bit of a dim question - I'm completely new to this.  I'm trying to get a new ellipse to appear on each tick of a timer.  So far, I have:
using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {
        private Bitmap DrawingArea;
        int numberofcircles = 0;
        int[] narrary = new int[30];
        int newcircle;
        Random rnd = new Random();
        public Form1()
        {
            InitializeComponent();
            Invalidate();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            numberofcircles = numberofcircles + 1;
            newcircle = (rnd.Next(15) * 6) + 76;
            narrary[numberofcircles] = newcircle;
            Invalidate();
            timer1.Start();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DrawingArea = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            Pen pen = new Pen(Color.Black);
            using (var canvas = Graphics.FromImage(DrawingArea))
            { canvas.Clear(Color.Transparent);
                canvas.DrawLine(pen, 100, 100, 700, 100);
                for (int i = 1; i <= numberofcircles; i++)
                {
                    canvas.DrawEllipse(pen, 180 + (30 * i), narrary[i], 8, 6);
                }
            }
            this.Invalidate();
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Pen pen = new Pen(Color.Red);
            for (int i = 1; i <= numberofcircles; i++)
            {
                canvas.DrawEllipse(pen, 180 + (30 * i), narrary[i], 8, 6);
            }
                e.Graphics.DrawImage(DrawingArea, 0, 0, DrawingArea.Width, DrawingArea.Height);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            numberofcircles = numberofcircles + 1;
            newcircle = (rnd.Next(15) * 6) + 76;
            narrary[numberofcircles] = newcircle;
            for (int i = 1; i <= numberofcircles; i++)
            {
                canvas.DrawEllipse(pen, 180 + (30 * i), narrary[i], 8, 6);
            }
            Invalidate();
        }
    }
}

"canvas" and "pen" references are flagging up as errors in the Form1_Paint and timer1_Tick sections ("The name 'canvas' does not exist in the current context").  I'm sure I must be referencing them wrong, but I'm afraid I don't have the basic C# knowledge to be able to sort this out!
I'd be very grateful for any help.

A: There are a number of concepts it looks like you need explaining.
First, as noted in the comments, you need to pay attention to "scoping". In C# (and most other languages), variables have a well-defined scope that prevent them from being visible except where they are relevant. The variable you're having trouble with are "local variables", and are valid only in the method in which they are declared.
If you want those variables to be visible to other methods, they need to be declared somewhere that they are visible to all methods. For example, you could declare them as instance variables.
But in this case, that would be the wrong thing to do. Another concept you seem to have trouble with is how drawing in a Winforms program works. You should only draw to the screen in the Paint event handler. There are a couple of ways to approach this:

*

*Keep track of the data that is the basis of what you're drawing, and then redraw everything any time the Paint event is raised.

*Maintain an off-screen bitmap, drawing new data to it as needed, and then draw this bitmap to the screen when the Paint event is raised.

Either way, you cause the Paint event to be raised by calling Invalidate().
Here is an example of the first approach, based on your original code:
public partial class Form1 : Form
{
    const int maxCircleCount = 30;
    List<int> circles = new List<int>();
    Random rnd = new Random();

    public Form1()
    {
        InitializeComponent();
        DoubleBuffered = true;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Arguably, you only need to start the timer and can skip these first two lines
        circles.Add(rnd.Next(15) * 6 + 76);
        Invalidate();
        timer1.Start();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawLine(Pens.Black, 100, 100, 700, 100);
        for (int i = 0; i < circles.Count; i++)
        {
            e.Graphics.DrawEllipse(Pens.Red, 180 + (30 * i), circles[i], 8, 6);
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (circles.Count < maxCircleCount)
        {
            circles.Add(rnd.Next(15) * 6 + 76);
            Invalidate();
        }
        else
        {
            timer1.Stop();
        }
    }
}

The above will draw 30 circles after you click the button, one per timer tick, and then stop the timer. Since in your code example, when the Load event handler is called you don't have any circles yet, it wasn't clear to me what your intent with that code was. So I did not bother to draw any black circles.
Other changes include:

*

*Setting DoubleBuffered to true, to avoid flickering when Invalidate() is called.

*Using the stock Pens objects instead of creating them (note that your code, which did create new Pen objects, should have disposed the Pen objects it created…that it did not was also a bug).

*Use a List<int> for the circles. This encapsulates the storage and the count in a single object.

Note that an improvement I didn't bother to make would be to consolidate the circles.Add() and Invalidate() calls into a separate method that can be called by any place it needs to be.
Hopefully the above gets you back on track. There are lots of other questions on Stack Overflow discussing the various nuances of how to draw in a Winforms program, whether from raw data or by caching to an off-screen bitmap. You should be able to use those posts to refine your techniques.
See also e.g. Force Form To Redraw? and How do I call paint event?, which include some answers that elaborate on the basic "call Invalidate()" concept.


text:
Q: Access PowerShell pipeline properties Is there a way to expose the pipeline properties of the previous command in the output of the next command. Below will loop through each SQL Server and get databases. The output only gives me the database name but I am looking for a way to get the Server Name also in the output.
Get-AzureSqlDatabaseServer | Get-AzureSqlDatabase

A: You can combine Select-Object with the -PipelineVariable common parameter (pv) of a previous command:
Get-AzureSqlDatabaseServer -pv Server |Get-AzureSqlDatabase |Select-Object *,@{Label='ServerName';Expression={$Server.ServerName}}

A: You could use the Foreach-Object cmdlet for that:
Get-AzureSqlDatabaseServer | Foreach-Object {
    $db = $_ | Get-AzureSqlDatabase
    $db | Add-Member NoteProperty -name ServerName -value $_.ServerName
    $db
}


text:
Q: Where can I set ellipsize property for ListView control? In TextView control, I can set android:singleLine="true" and android:ellipsize="end" to truncate a long string,
but I don't know how to set the property for ListView control, could you help me ? Thanks!
<ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:background="#DDDDDD"
    android:layout_weight="1" />

<TextView
    android:id="@+id/textView5"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:ellipsize="end"
    android:singleLine="true"
    android:text="This is a web This is a web This is a web This is a web I will go to school" />

A: Ellipsizing a ListView doesn't even make any sense. Rather, you'll want to set the ellipsize attribute on any TextViews in the layout you're inflating for the list item in your Adapter.

A: When you create the adapter by doing
new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice,
    cur, cols, views);

you're passing in the layout file that it's going to use to display the text.
As of SDK v17, that layout file looks like this:
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeightSmall"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:checkMark="?android:attr/listChoiceIndicatorMultiple"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
/>

Note that the text is not ellipsized.
Instead of passing in that layout, create your own similar layout file, with android:ellipsize set, and then pass in that layout to the adapter.
Make sure to use @android:id/text1 as the android:id for the TextView, as that's what the adapter uses to find it.


text:
Q: Xcode 7.2 DTCoreText 'CTLineUtils.h' file not found I have installed DTCoreText within CocoaPods, but this message always appear when trying to build:
'CTLineUtils.h' file not found

any suggestions?

A: deleted pods folder and Podfile.lock and did a pod install ...
now it's working.


text:
Q: R: plotting a raster image inside screen() is not working I am trying to plot a rasterLayer object on a plot composed of two figures using screen
First - a working case scenario when we only have one image:
library(raster)
f <- system.file("external/test.grd", package="raster")
rst <- raster(f)

plot(rst)
points(180000, 332000, col="red", pch=19)

Everything looks fine and the image looks like this:

However when I split the screen into two and try to plot the same figure using only half of the plotting region I get the following:
library(raster)
f <- system.file("external/test.grd", package="raster")
rst <- raster(f)
class(rst)

figs <- rbind(c(0, 0.5, 0, 1), # Screen1
              c(0.5, 1, 0, 1)  # Screen2
              )
screenIDs <- split.screen(figs)

screen(screenIDs[1])
plot(rst)
points(180000, 332000, col="red", pch=19)

It seems like the main image of the raster shape is being drawn correctly. However for some reason it then captures the entire plotting region and adds a boundary lines on it. After that subsequent calls to the plot (like points) add points on the whole figure rather than staying in the first half of it.
Any ideas how to solve or bypass this are most appreciated.

A: You can use layout instead of split.screen.  Demonstrated here, as in your example, with a simple layout of just 1 row of two equal-sized panels.  For how to get more complex layouts, have a look at ?layout
layout(matrix(c(1,2), 1, 2, byrow = TRUE))
plot(rst)
points(180000, 332000, col="red", pch=19)

plot(1:10,1:10) # a dummy plot to put in the right hand panel


text:
Q: -k and -l options in rysnc When read the manual of rsync, I found that
    -l, --links                 copy symlinks as symlinks
    -L, --copy-links            transform symlink into referent file/dir
        --copy-unsafe-links     only "unsafe" symlinks are transformed
        --safe-links            ignore symlinks that point outside the tree
        --munge-links           munge symlinks to make them safer
    -k, --copy-dirlinks         transform symlink to dir into referent dir
    -K, --keep-dirlinks         treat symlinked dir on receiver as dir

-l match to -K and -L to '-k`
The -k and -K is but a redundancy of  -l and -L ,
Does they just compatible backwards or have any distinctions?

A: See the excerpt below

-l, --links
  When symlinks are encountered, recreate the symlink on the destination.
-k, --copy-dirlinks
      This option causes the sending side to treat a symlink to a directory as though it were a real directory.
      This is useful if you don't want symlinks to non-directories to be affected, as they would be using --copy-links.
Without this option, if the sending side has replaced a directory with a symlink to a directory, the
      receiving side will delete anything that is in the way of the new symlink, including a directory hierarchy
      (as long as --force or --delete is in effect).
See also --keep-dirlinks for an analogous option for the receiving side.
--copy-dirlinks applies to all symlinks to directories in the source. If you want to follow only a
      few specified symlinks, a trick you can use is to pass them as additional source args with a trailing slash,
      using --relative to make the paths match up right. For example:
  rsync -r --relative src/./ src/./follow-me/ dest/

This works because rsync calls lstat(2) on the source arg as given, and the trailing slash makes lstat(2)
      follow the symlink, giving rise to a directory in the file-list which overrides the symlink found
      during the scan of "src/./".
-L, --copy-links
      When symlinks are encountered, the item that they point to (the referent) is copied, rather than the symlink.
      In older versions of rsync, this option also had the side-effect of telling the receiving side to
      follow symlinks, such as symlinks to directories. In a modern rsync such as this one, you'll need to
      specify --keep-dirlinks (-K) to get this extra behavior.
      The only exception is when sending files to an rsync that is too old to understand -K -- in that case,
      the -L option will still have the side-effect of -K on that older receiving rsync.
-K, --keep-dirlinks
      This option causes the receiving side to treat a symlink to a directory as though it were a real directory,
      but only if it matches a real directory from the sender. Without this option, the receiver's symlink would
      be deleted and replaced with a real directory.
For example, suppose you transfer a directory "foo" that contains a file "file", but "foo" is a symlink
      to directory "bar" on the receiver. Without --keep-dirlinks, the receiver deletes symlink "foo", recreates
      it as a directory, and receives the file into the new directory. With --keep-dirlinks, the receiver keeps
      the symlink and "file" ends up in "bar".
One note of caution: if you use --keep-dirlinks, you must trust all the symlinks in the copy! If it is
      possible for an untrusted user to create their own symlink to any directory, the user could then
      (on a subsequent copy) replace the symlink with a real directory and affect the content of whatever
      directory the symlink references. For backup copies, you are better off using something like a bind
      mount instead of a symlink to modify your receiving hierarchy.
See also --copy-dirlinks for an analogous option for the sending side.

For case of -L and -K:

*

*-L: When symlinks are encountered, the item that they point to (the referent) is copied, rather than the symlink.

*-K: This option causes the receiving side to treat a symlink to a directory as though it were a real directory,
but only if it matches a real directory from the sender. Without this option, the receiver's symlink would
be deleted and replaced with a real directory.

For case of -l and -k:

*

*-l: When symlinks are encountered, recreate the symlink on the destination.

*-k: This option causes the sending side to treat a symlink to a directory as though it were a real directory.
This is useful if you don't want symlinks to non-directories to be affected, as they would be using --copy-links.

See: https://ss64.com/bash/rsync_options.html


text:
Q: Java dynamic function calling I have a String array that contains names of method in the yyyyyy class
In the xxxxxx class I'm making a yyyyyy instance (say obj). Now I can call obj.function_name(), except I want to read function_name from the String array in a loop. Is this possible?

A: You can, using reflection. It is done by calling Yyyy.class.getMethod("methodName").invoke(someArgs)
You'd have to handle a bunch of exceptions, and your method must be public. Note that java coding conventions prefer methodName to method_name.
Using reflection, however, should be a last resort. You should be using more object-oriented techniques.
If you constantly need similar features, perhaps you can look at some dynamic language running on the java platform, like Groovy

A: It's possible using reflection, although you should probably question your design somewhat if you need that sort of behavior. Class.getMethod takes a String for the method name and returns a Method object, which you can then call .invoke on to call the method
These Javadoc pages should be helpful:

*

*Class.getMethod

*Method.invoke
Sample code (assuming the yyyyyy methods take one int argument, just to show argument passing):
yyyyyy obj = new yyyyyy();
String[] methodNames = {"foo", "bar", "baz"};
for(String methodName : methodNames) {
    Method method = Class.forName("yyyyyy").getMethod(methodName, new Class[] {int.class});
    method.invoke(obj, 4); // 4 is the argument to pass to the method
}


text:
Q: Spring security not redirecting to login page when users is not authenticated I am trying to block access to pages in my website, but the security config below doesn't restrict access to private pages.
My Security config:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserService detailsService;

    @Override
    protected void configure(HttpSecurity http)
        throws Exception {
        http.authorizeRequests().antMatchers("/passwordrequest/**", "/initSystem").permitAll().anyRequest()
            .authenticated().and().formLogin().loginPage("/login").usernameParameter("email").permitAll().and()
            .logout().permitAll().and().csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
        throws Exception {
        auth.userDetailsService(detailsService);
    }
}

I have got a controller for /login that puts the user onto the model so that I can assess their information. I have also implemented UserDetails and UserDetailsService as required.
Please advise on what could be going wrong. (If there is some specific code you would like me to add let me know)

A: Check if you have spring security filter configured in your web.xml to intercept all your requests for securizing..
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

A: Where is your private page in your config? you need to have that config.
Example:
http.authorizeRequests()
        .antMatchers("/adminpage/**").access("hasRole('ROLE_ADMIN')")
        .antMatchers("/privatepage/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
        .and().formLogin();


text:
Q: MBProgressHUD/MBProgressHUD.h' file not found I only get this error when I build on my device (iPhone 6 and 5s). It popped up randomly today when I pod installed Firebase/Core. I've deleted it since. However, it works fine on the simulator.
Can anyone help me with a fix?

A: Okay, so I fixed the error. Apparently it was being caused by Firebase's plist file which I forgot to delete when I removed Firebase/Core from my podfile.


text:
Q: How to use Amazon EMR–managed security groups using the AWS CLI >=1.11.59? http://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-man-sec-groups.html says in section title "To specify Amazon EMR–managed security groups using the AWS CLI":

Use the create-cluster command with the
  --emr-managed-master-security-group and --emr-managed-slave-security-group parameters.

When I run the aws emr create-cluster command using these arguments, I get the following error:
Unknown options: --emr-managed-master-security-group,--emr-managed-slave-security-group

My version of aws cli is as follows:
$ aws --version
aws-cli/1.11.59 Python/2.7.10 Darwin/16.4.0 botocore/1.5.22

What's the new mystical incantation for these unsupported options now?
Update 1: RTFMing via aws emr create-cluster help includes the following text:

   o Create an Amazon EMR cluster specifying only the  Amazon  EMR-managed
     Amazon EC2 security groups:

        aws emr create-cluster --release-label emr-5.0.0 --service-role myServiceRole --ec2-attributes InstanceProfile=myRole,EmrManagedMasterSecurityGroup=sg-master1,EmrManagedSlaveSecurityGroup=sg-slave1 --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m3.xlarge InstanceGroupType=CORE,InstanceCount=2,InstanceType=m3.xlarge

So I think to myself, "Self, I guess you use the literal values 'sg-master1' & 'sg-slave1'", so I update my script & try them, then get an error in the AWS EMR console stating Terminated with errorsInvalid id: "sg-master1" (Service: AmazonEC2; Status Code: 400; Error Code: InvalidGroupId.Malformed; Request ID: cdd335ba-59f4-407a-b7d6-9cf8a96f08d9).  No good; trudging on...

A: The answer is to place the pre-existing, actual security group ids in the --ec2-attributes argument as shown in "Update 1" in my question above.  Also see https://stackoverflow.com/a/42723084/969237.


text:
Q: Automatically insert content into News section I'm developing a Wordpress theme. One of the sections on the front page is titled News. In that section the user should be able to insert information himself (I'll make a separate file called news.php which will php included into the markup), but I also want the content to be automatically updated once the user makes a post.
For example, if the user writes a new post, I want the news section to be automatically updated to something like this:
A new post was written, find it here (where 'here' is a hyperlink pointing to the url of the post).
edit Let me try to give a little more details so it's clearer.
The news section will be an unordered list.
Thus:

News item 1

News item 2

I want the user to be able to add content to the news section, aka make new News Items, but using the visual editor of Wordpress such that the user doesn't have to understand the code and doesn't have to copy/paste the LIs.
Furthermore, whenever a new post is published, I want it to show up as:
"new post published, find it here" where 'here' is a hyperlink with linking to the post.
Is this possible to accomplish?
Thanks, Amit

A: make a Categorie, or a Custom Post Type called, "News" so when the user creates a new post, but wants it to be in the "News" section all he has to do is click on the Category "News." You could also create a custom post type, just for "News" and have custom taxonomies etc as well.
Then when you want to print the News post in your theme, write use the query post function and limit the loop to "category_name=news"

A: If i correctly understood, you need write something like this:
<?php
query_posts(array('posts_per_page' => 1));
the_post();
?>
A new post was written, find it <a href="<?php echo the_permalink();?>">here

Latest news list
<?php
query_posts(array('posts_per_page' => 6));
?>

<?php $count=0; if (have_posts()) : while (have_posts()) : the_post(); ?>

<a href="<?php echo the_permalink(); ?>"><?php the_title(); ?>

<?php endwhile; endif; ?>


text:
Q: calculating time difference in iso time format in javascript? I have two date string in ISO format. I am calculating the minutes difference between them using moment js.
var currenttime  =  new Date().toISOString();
var expiretime  = '2020-06-05T12:18:33.000Z';

let minutes = moment(expiretime, 'YYYY-MM-DD[T]HH:mm:ss. SSS[Z]').diff(moment(currenttime, 'YYYY-MM-DD[T]HH:mm:ss. SSS[Z]'), 'minutes');

console.log(minutes)

Now i have two questions

*

*Is this is the best way to calculate the minutes difference ?

*When i run new Date().toISOString() the value before z is the supposed to be the timezone but on every restart it changes ?
Please let me know what is the issue ?

A: For your first question, what you can do is simply subtract the two dates (date objects and not strings) ,
Newer date - Older date ( this will give the result in milliseconds)
or use Math.abs() function to calculate milliseconds -
var msec = Math.abs( currenttime - expiretime );

and convert this to minutes using -
var min = Math.floor((msec/1000)/60);

2)
Z in the datetime string stands for Zulu, it indicates that the time is in UTC format.
You can simply subtract two date objects.
var currenttime = new Date();
var currenttime_UTC = currenttime.getUTCDate();
var expiretime = new Date('2020-06-05T12:18:33.000Z');

var msec = Math.abs( currenttime_UTC - expiretime );
var min = Math.floor((msec/1000)/60);

A: I don't think you have to include moment for this purpose only, this can be done in ordinary Javascript.
To calculate time difference just subtract the two timestamps which will give the difference in milliseconds. Then divide by 60*1000 which will give the time difference in minutes.
let currentTime = new Date();
let expireTime = new Date('2020-06-05T12:18:33.000Z');

let minutes = (expireTime - currentTime) / (1000 * 60);

console.log(minutes);


text:
Q: Please help me create an image slider in react.js? var workArrays = [{id: 1, img: "https://scontent-lax3-2.xx.fbcdn.net/v/t1.0-9/117405206_1535037326696077_4967665142447981078_o.png?_nc_cat=111&ccb=2&_nc_sid=730e14&_nc_ohc=XlNXGJF47E0AX8lB1fk&_nc_ht=scontent-lax3-2.xx&oh=d44bd3d97c906f56746b360fc7514c64&oe=5FF77A89"},
    {id: 2, img: "https://scontent-lax3-2.xx.fbcdn.net/v/t1.0-9/117405206_1535037326696077_4967665142447981078_o.png?_nc_cat=111&ccb=2&_nc_sid=730e14&_nc_ohc=XlNXGJF47E0AX8lB1fk&_nc_ht=scontent-lax3-2.xx&oh=d44bd3d97c906f56746b360fc7514c64&oe=5FF77A89"},
    {id: 3, img: "https://scontent-lax3-2.xx.fbcdn.net/v/t1.0-9/117405206_1535037326696077_4967665142447981078_o.png?_nc_cat=111&ccb=2&_nc_sid=730e14&_nc_ohc=XlNXGJF47E0AX8lB1fk&_nc_ht=scontent-lax3-2.xx&oh=d44bd3d97c906f56746b360fc7514c64&oe=5FF77A89"},
    {id: 4, img: "https://scontent-lax3-2.xx.fbcdn.net/v/t1.0-9/117405206_1535037326696077_4967665142447981078_o.png?_nc_cat=111&ccb=2&_nc_sid=730e14&_nc_ohc=XlNXGJF47E0AX8lB1fk&_nc_ht=scontent-lax3-2.xx&oh=d44bd3d97c906f56746b360fc7514c64&oe=5FF77A89"},
    {id: 5, img: "https://scontent-lax3-2.xx.fbcdn.net/v/t1.0-9/117405206_1535037326696077_4967665142447981078_o.png?_nc_cat=111&ccb=2&_nc_sid=730e14&_nc_ohc=XlNXGJF47E0AX8lB1fk&_nc_ht=scontent-lax3-2.xx&oh=d44bd3d97c906f56746b360fc7514c64&oe=5FF77A89"}]

     var slides = workArrays.length;
    class Page1 extends React.Component{
        constructor(props){
            super(props);
            this.state = {
             // SOS: this is the initial state that I have set up.
               slides : (0)
            };
            this.leftArrow = this.leftArrow.bind(this);
            this.rightArrow = this.rightArrow.bind(this);
        }
            leftArrow(){
                this.setState({
                    // SOS: they are not doing anything when clicked
                    slides: this.state.slides - 1
                })
            }
            rightArrow(){
                this.setState({
                    // SOS: this want also not doing anything
                    slides: this.state.slides + 1 T
               })

            }
        render(){
        return(

                    <Hero/>

                        // SOS: Also my left arrown and right arrow are not showing up
                        <button onClick={this.leftArrow}></button>
                        <button onClick={this.rightArrow}></button>
                        {this.props.workArrays.map(function(work){
                            return

                                <Services img={work.img}/>

            })}

        );
        }
    }

A: You do not have the right variable bindings:
Before the class constructor you define variable
 var slides = workArrays.length;

There is a bug in the functions leftSlide and rightSlide (you use state, where you have a zero)
this.setState({
 slides: this.state.slides - 1
});

That's the reason why in this.state.slides you have -1 on click left.
Try to use on left click:
// calculate previous slide
var newCurrentSlide = this.state.slides - 1;
// if slide number < 0, then get last slide from array
if (newCurrentSlide < 0){
  newCurrentSlide = slides.length - 1;
}

this.setState({
 slides: newCurrentSlide
});

for right click:
// calculate next slide
var newCurrentSlide = this.state.slides + 1;
// if slide number >= count slides, then get first slide from array
if (newCurrentSlide >= slides){
  newCurrentSlide = 0;
}

this.setState({
 slides: newCurrentSlide
});

I suggest you rename variable slides to slidesCount - it is a better naming convention.
And if you want a dynamic slider on left and right clicks then you can show a single active image like this:
render(){
  return(

      <Hero/>

        <button onClick={this.leftArrow}></button>
        <button onClick={this.rightArrow}></button>

          <Services img={this.props.workArrays[this.state.slides].img}/>

  );
}


text:
Q: How Gradle Plugin add method to a specific block? I wonder how Gradle achieve this mechanism : add a specific method to a script block that only work in that block.
For example, If I want to use implementation method, I have to apply plugin: 'java', But I can only use implementation in dependencies{}

A: dependencies block is just a DependencyHandler.
The default implementation is DefaultDependencyHandler.
Note, that it implements MethodMixIn:

A decorated domain object type may optionally implement this interface to dynamically expose methods in addition to those declared statically on the type.
  Note that when a type implements this interface, dynamic Groovy dispatch will not be used to discover opaque methods.
  That is, methods such as methodMissing() will be ignored.

So, this mixin is something like a methodMissing in Groovy.
Whenever an unknown method is called on a Groovy object, if it has methodMissing method, it is called.
MethodMixIn seem to work similarly.
It defines a single method:
MethodAccess getAdditionalMethods();

Let's look how it is implemented in DefaultDependencyHandler?
public MethodAccess getAdditionalMethods() {
    return dynamicMethods;
}

Where dynamicMethods is initialized as:
dynamicMethods = new DynamicAddDependencyMethods(configurationContainer, new DirectDependencyAdder());

Let's check the DynamicAddDependencyMethods.
First, it defines a hasMethod, that returns true when there is a configuration with the given name:
public boolean hasMethod(String name, Object... arguments) {
    return arguments.length != 0 && configurationContainer.findByName(name) != null;
}

After applying Java plugin, you configurations will have objects like api, implementation and so on.
So, hasMethod("api") will return true, while hasMethod("API") – false, unless you have another plugin that contributes a configuration with that name.
Finaly, tryInvokeMethod in invoked whenever a configuration name is used like a function in dependencies block:
public DynamicInvokeResult tryInvokeMethod(String name, Object... arguments) {
    if (arguments.length == 0) {
        return DynamicInvokeResult.notFound();
    }
    Configuration configuration = configurationContainer.findByName(name);
    if (configuration == null) {
        return DynamicInvokeResult.notFound();
    }

    List<?> normalizedArgs = CollectionUtils.flattenCollections(arguments);
    if (normalizedArgs.size() == 2 && normalizedArgs.get(1) instanceof Closure) {
        return DynamicInvokeResult.found(dependencyAdder.add(configuration, normalizedArgs.get(0), (Closure) normalizedArgs.get(1)));
    } else if (normalizedArgs.size() == 1) {
        return DynamicInvokeResult.found(dependencyAdder.add(configuration, normalizedArgs.get(0), null));
    } else {
        for (Object arg : normalizedArgs) {
            dependencyAdder.add(configuration, arg, null);
        }
        return DynamicInvokeResult.found();
    }
}

As you see, it just looks up for a named configuration and adds the dependency to it.
That's how it's made.


text:
Q: Can't access friends's informations with the graph API I'd like to retrieve, for instance, a friend's birthday, using the graph API.
So I pick a friend whose birthday my profile can see, go to the Graph API Explorer, generate an access token with the friends_birthday privilege, and input [friend_name]/?fields=birthday and... it doesn't return anything. The birthday field on the side is grayed out, with a mouse-over text that says

"Field is empty or disallowed by the access token".

The worst part is that it works fine for some friends, but not for others. Is it related to the level of visibility they set for this information on their profile? I assumed that the app can see everything my profile can see (if I give it full privileges), but maybe that's not the case. Or is there something wrong with my request?

A: I had the same problem and the answer is that your friend can change the permissions it gives to apps.  So, for the Graph API Explorer app your friend would need to give the user_birthday permission to the app in order for you to see their birthday through the app (and you have to give the app the friends_birthday permission as well).
See here for the comment that helped me figure that out.


text:
Q: Change color of error highlighting (hard to read) in jupyter notebook I changed jupyter notebook's theme through jupyterthemes, but some of the error output is difficult to read, as it is white text with yellow highlights. How would I go about changing this?
I still want a dark themed background, which makes the text white, which makes it hard to read. I want to just change the highlighting color / error output, not the theme.
Sample image of error output here


text:
Q: Guess Diophantine equation from its solutions Take for example the equation
$$
n^2=x^2+y^2+1
$$
where $x,y$ are integers.
This equation admits solutions only for some values of $n$, to wit,
$$
n=1,3,9,17,19,33,35,51,73,81,99,\dots
$$
Can we reverse-engineer the Diophantine equation from the sequence above? I guess the solution is non-unique, but any solution will do.

A: Although perhaps not very satisfying, a Diophantine equation yielding the values of n in the question is given by
lst = {1, 3, 9, 17, 19, 33, 35, 51, 73, 81, 99};
eq = n == Sum[lst[[i]] x[i], {i, 11}]
(* n == x[1] + 3 x[2] + 9 x[3] + 17 x[4] + 19 x[5] + 33 x[6] + 35 x[7] +
        51 x[8] + 73 x[9] + 81 x[10] + 99 x[11] *)

The first eleven non-trivial solutions are
tab = {n, Table[x[i], {i, 11}]} // Flatten;
Table[tab /. {n -> lst[[i]], x[i] -> 1, x[_] -> 0}, {i, 11}]
(* {{1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {3, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
    {9, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}, {17, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0},
    {19, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, {33, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
    {35, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0}, {51, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0},
    {73, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}, {81, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0},
    {99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}} *)

In fact, there is an infinite number of Diophantine equations satisfying the requirements of the question.  Obtaining a particular equation would require several constraints.


text:
Q: Code optimization with if condition check along with replaceAll I have a string in which I have to check for some if conditions and do some replace operations as follows,
for(int i =0; i<10;i++){
    if(name[i].contains("sometext")){
       name[i] = name[i].replaceAll("someregexpattern","replacementtexthere");
    }
}

Instead of checking for the presence of 'sometext' every time using the 'if' condition, can I simply put it as follows,
for(int i =0; i<10;i++){
       name[i] = name[i].replaceAll("someregexpattern","replacementtexthere");
}

Anyway, if the string 'name' does not contain the 'regexpattern' means, it wont replace anything. So, does the if condition has any significance in terms of performance.
Thanks in advance.

A: This will be valid only if sometext is the same as someregexpattern. Else, the if condition does matter.
Say your someregexpattern is indeed present in the string, but your if condition evalutes to false, in that case, you're not supposed to do the replacement. But if you remove the if statement, then the replacement will happen, which is not quite the same.
E.g:- To help you understand better.
String testCondition = "dontReplace";
        String myString = "Hi, I'm SO";
        String regex = "SO";
        String replacement = "Not SO";

        if(myString.contains(testCondition)){
            myString = myString.replaceAll(regex, replacement); // stays "Hi, I'm SO"
        }

        myString = myString.replaceAll(regex, replacement); // Becomes "Hi, I'm Not SO"

As you see, the requirement was that the String replacement should not happen because the condition was dontReplace, but since the if was removed, the replacement happened, even though it wasn't supposed to.

A: "If" itself won't affect performance.
Though function calls are pretty cheap nowadays, String.contains() will do 4-5 more function calls.
However, the former variant is better readable and less bug-prone.

A: "any significance in terms of performance" also depends on how often that entire thing is executed in your software.
A profiler run (via visualvm or so) will show you whether a significant part of your execution time is spent in String#replaceAll(). If it isn't, you won't get significant improvements by optimizing it. That sounds obvious, but it's all too often forgotten.
And if optimization won't bring significant gains, you'll almost always be better off with choosing the more readable variant of the code.


text:
Q: What is the structure in the sentence: "The reason scientists believe that..." I have this sentence from one of my IELTS books:

One of the reasons scientists think that there is a link between stress and cancer is the idea that there may be a cancer-prone personality

At first, I think that the main subject of this sentence is "one of the reasons", the verb is "is", and the object is "the idea". But after a while, I think this sentence can be rewritten like this:

Scientists think one of the reasons that there is a link between stress and cancer is the idea that there may be a cancer-prone personality

which makes me think the real main subject is "scientists", and the main verb is "think"
So I have 2 questions here:

*

*What is the main subject and main verb in this sentence?

*If the original sentence is "scientists think one of the reasons...", then what mechanism allow us to move object "one of the reasons" before the subject "scientists"?

A: I'm no expert at grammar but the following is my best effort at explaining a quite complicated (and, in my view, clumsily worded) sentence.
First, it's easier to see what's going on if you cut out the subordinate clauses, reducing the sentence to:

One of the reasons is the idea.

You should now be able to see that the subject is "One", which is modified by the prepositional phrase "of the reasons". The verb is "is" and the object is "the idea".
Of course this stripped-back sentence only makes sense if you know what "reasons" and "idea" are each referring to. Let's look at the omitted parts of the sentence to see the role they play in making the sentence meaningful.

*

*"reasons" is further explained by the clause-within-a-clause "[that] scientists think that there is a link between stress and cancer". Note that in English we like taking shortcuts such as omitting conjunctions - especially when it's "that" and there are other occurrences of "that" in the sentence.

*"the idea" is further explained by the relative clause "that there may be a cancer-prone personality."


text:
Q: IBM mobilefist 8.0 mfpconsole not loading properly after installation I'm new to IBM mobilefirst installation.
I installed MFP using command-line on DEV environment.
We have shared partition on VM where we are installaling.
Linux : Red Hat Enterprise Linux Server release 6.8 (Santiago)
Java - java version "1.7.0_121"
OpenJDK Runtime Environment (rhel-2.6.8.1.el6_8-x86_64 u121-b00)
OpenJDK 64-Bit Server VM (build 24.121-b00, mixed mode)
I installed Installation manager, WAS liberty core 8.5, MFP 8.0, with command line on linux.
Finally did :
./ant -f /opt/IBM/MobileFirst_Platform_Server/MobileFirstServer/configuration-samples/configure-liberty-oracle.xml
./ant -f /opt/IBM/MobileFirst_Platform_Server/MobileFirstServer/configuration-samples/configure-liberty-oracle.xml databases
./ant -f /opt/IBM/MobileFirst_Platform_Server/MobileFirstServer/configuration-samples/configure-liberty-oracle.xml install
For install getting below error:
Buildfile: /opt/IBM/MobileFirst_Platform_Server/MobileFirstServer/configuration-samples/configure-liberty-oracle.xml

adminstall:
[installmobilefirstadmin] [24/01/2018 10:58:03:001 MYT] Logging output of task <installmobilefirstadmin> to file /root/.mobilefirst_platform_server/configuration-logs/installmobilefirstadmin_2018_01_24_10_58_02.log
Enter the password of MobileFirst Configuration user
[installmobilefirstadmin] [24/01/2018 10:58:22:937 MYT] JEE features detected: JEE6='true', JEE7='false';
[installmobilefirstadmin] [24/01/2018 10:58:22:938 MYT] JEE features already configured: JEE6='true', JEE7='false';
[installmobilefirstadmin] [24/01/2018 10:58:22:939 MYT] JEE features being configured: JEE6='true', JEE7='false'.

BUILD FAILED
/opt/IBM/MobileFirst_Platform_Server/MobileFirstServer/configuration-samples/configure-liberty-oracle.xml:144: User admin is declared several times with different passwords.

I am able to login to mfpconsole but its just loading dashboard. Unable to register application.
getting error : Connection error. Contact the server administrator (HTTP code: 405)
what this m i missing.


text:
Q: C# .Net 5: Where are bindingNavigator and DataSet controls in Design Mode? My application is .Net 5 WinForm and it needs working with SQL DataBase.
But I don't see base WinForm components for working with DB in Visual Studio 2019 Toolbox window. I can't find here neither BindingNavigator nor DataSet, why? Data section in Visual Studio Toolbox for .Net app is very primitive, it contains only DataGridView and BindingSource. Moreover, BindingSource doesn't work, i can't assigne it with SQL Database.
What's going on?
P.S.: Everything works fine for outdated .Net Framework applications.

A: i stucked in same situation, so i will write this for who will search in future.
apparently, binding source in .net framework 5 and 6 is not supported for winform or WFP. you had to work with old framework, if you wish to use it.
although,i did add a data-set to the project and it pull all the tables from server explorer window and create all data adabtor.
i will try it and update the post.


text:
Q: How to use ngModel in ion-checkbox? I'm trying to use  with ngModel, but ngModel doesn't work there.
My code:
<ion-checkbox *ngFor="#item of items" [(ngModel)]="item.checked">
  {{item.name}}
</ion-checkbox>

But I get an error:

EXCEPTION: Expression 'checked in AddInterestItem@5:2' has changed after it was checked. Previous value: 'false'. Current value: 'false' in [checked in AddInterestItem@5:2]

example data:
this.items = [
  {name: 'Dancing', checked: false},
  {name: 'Jazz', checked: false},
  {name: 'Metal', checked: true},
  {name: 'Pop', checked: false},
  {name: 'Rock\'n\'Roll', checked: false},
  {name: 'Folk Metal', checked: true}
];

A: I am not familiar with <ion-checkbox>.
But when i tried to repeat your story with normal
<input type="checkbox" />,
I couldn't get success by applying ngFor to input type="checkbox" directly.
So what I did, I took

 and put my input type="checkbox" within it and it started working as expected.
I feel like MyAnswer could help you further.
doesn't work in mycase
<input  type="checkbox" *ngFor="#item of items" [(ngModel)]="item.checked" />{{item.name}}
/* I don't know some error occurs. you can check my plunkr by modifying it/*.

Worked properly

{{item.name}}
            <input type="checkbox" [(ngModel)]="item.checked" />

A: Just a quick update for Ionic 4:
HTML:
<ion-checkbox [(ngModel)]="iLikeIt.isChecked"></ion-checkbox>

Ts:
iLikeIt={isChecked:false}


text:
Q: functional iteration This is a past prelim question,
Let $F(x)=2x+qx^2$ with $\frac{1}{2}\leq q \leq 1$ and $x_{n+1}=F(x_{n})$.
For which interval does this iteration converge ?
I tried these but did not work;
Fixed points are $0, -\frac{1}{q}$, Since $F'(0)>1$ if there is such an interval with initials from that interval converging to a fixed point this fixed point will be $-\frac{1}{q}$.
I tried to use the idea; find closed interval C with $|F'|\leq\lambda <1$ on $C$ and $F(C)\subset C$.
Suppose we just want to find an interval not the maximal one.
Then
$F' = 2+2px$, $|2+2qx|\leq \frac{1}{2}$ this will give smaller interval, then
$-\frac{1}{2}\leq 2+2qx \leq \frac{1}{2}$, $-\frac{5}{4q} \leq x \leq -\frac{3}{4q} =: C$. But $F(C)$ is not a subset of $C$. I tried for smaller number $a$ for $|F'| < a$, but it did not work.
Question 1: Is there any way to find such $C$ ?
Question 2: How can we find maximal interval ?
any clues/ideas would be appreciated.


text:
Q: Proving a simple equation with complex numbers Fix $A \in ℂ$ and $B \in ℝ$
Let $z \in ℂ$.
Show that the equation $|z^2| + Re(Az) + B = 0$ has solutions iff $|A^2|  ≥ 4B$
I have no trouble proving the forward implication, but its the "only if" part that I can't prove. I am writing the complex numbers in polar form and then working from there with the discriminant. As far as I can tell, the $|A^2| ≥ 4B$ is not a sufficient condition to imply that the equation will have solutions. Can someone help me to see what I am doing wrong?

A: Let $z=x+iy, A=a+ib$ where $x,y,a,b$ are real
So, we have $$x^2+y^2+(xa-yb)+B=0\iff (2x+a)^2+(2y-b)^2=a^2+b^2-4B$$
As $x,y,a,b$ are real, the left hand side must be $\not<0$

A: Suppose that $|A|^2\ge4B$.  The equation can be written as
$$4z\overline z+2Az+2\overline A\overline z=-4B$$
and hence as
$$|2z+\overline A|^2=|A|^2-4B\ .$$
The RHS is a non-negative real number, say $r^2$, and so the equation has solutions.  In fact, the complete solution is
$$z=\frac{re^{i\theta}-\overline A}{2}$$
with $\theta$ real.
Comment.  In fact, this is really just the same as @lab bhattacharjee's solution.  But IMO it is a nice illustration of the simplification one can obtain by writing moduli and real parts (and imaginary parts if applicable) in terms of conjugates.


text:
Q: VBA: Clear multiple discontiguous cells I have the following code right now:
Sub ClearTimeline()
    Dim wsTimeline As Worksheet
    Set wsTimeline = ThisWorkbook.Sheets(1)

    wsTimeline.Range("B8, F25, F26, F28, F30, M17, M31, L17, L24:L25, L26, L28, L29:L30, J24:J25, J26, J28, J29:J30, K25, K26, K28, K30").ClearContents

End Sub

I want to replace the fixed cell reference by something more dynamic. The rows won't change, so I want to change how I reference the columns. I have a "reference cell", i.e. a cell I can always find/know the column of.
Sub ClearTimeline()
    Dim wsTimeline As Worksheet
    Dim referenceDay As Long

    Set wsTimeline = ThisWorkbook.Sheets(1)
    referenceDay = 10

'what works:
    wsTimeline.Range(wsTimeline.Cells(referenceDay - 9, 1)).ClearContents 'clears single cell

    wsTimeline.Range(wsTimeline.Cells(referenceDay - 9, 1), wsTimeline.Cells(referenceDay - 1, 1)).ClearContents 'clears range

End Sub

My goal is to refer to every column as 'referenceDay +/- X' because the distance to this day will stay the same even if the sheet is altered in some other way. But how do I tell Excel to do the same action for non-contiguous cells? I'm not sure how to reference them and what to put into the parentheses after wsTimeline.Range

A: If I understand correctly, the whole range of hardcoded cells should be moved to the right or to the left, depending on the column. Offset() is pretty good for this.

The "red" cells are the cells of the initial range, and the selected cells are the cells with the Offset(columnoffset:=2). I have used .Select to illustrate the difference, because there is overlapping and colors would not have been ok:
Sub ClearTimeline()

    Dim wsTimeline As Worksheet
    Set wsTimeline = ThisWorkbook.Worksheets(1)

    Dim timelineRange As Range
    Set timelineRange = wsTimeline.Range("B8, F25, F26, F28, F30, M17, M31, L17, L24:L25, L26, L28, L29:L30, J24:J25, J26, J28, J29:J30, K25, K26, K28, K30")
    timelineRange.ClearContents
    timelineRange.Interior.Color = vbRed

    timelineRange.Offset(columnoffset:=2).Select 'But in general, do not use .Select

End Sub


text:
Q: Maps not loading after google play services update I'm having a problem with a new project and trying to add a map fragment. Here's the errors;
07-10 10:22:04.184: I/Google Maps Android API(23978): Google Play services client version: 5077000
07-10 10:22:04.195: I/dalvikvm(23978): Could not find method guj.a, referenced from method gqi.a
07-10 10:22:04.195: W/dalvikvm(23978): VFY: unable to resolve static method 24936: Lguj;.a (Landroid/content/Context;)Lgri;
07-10 10:22:04.195: D/dalvikvm(23978): VFY: replacing opcode 0x71 at 0x0003
07-10 10:22:04.205: E/dalvikvm(23978): Could not find class 'gpr', referenced from method gps.a
07-10 10:22:04.205: W/dalvikvm(23978): VFY: unable to resolve new-instance 4090 (Lgpr;) in Lgps;
07-10 10:22:04.205: D/dalvikvm(23978): VFY: replacing opcode 0x22 at 0x0000
07-10 10:22:04.205: E/dalvikvm(23978): Could not find class 'gpr', referenced from method gps.a
07-10 10:22:04.205: W/dalvikvm(23978): VFY: unable to resolve new-instance 4090 (Lgpr;) in Lgps;
07-10 10:22:04.205: D/dalvikvm(23978): VFY: replacing opcode 0x22 at 0x0000
07-10 10:22:04.205: E/dalvikvm(23978): Could not find class 'gpr', referenced from method gps.a
07-10 10:22:04.205: W/dalvikvm(23978): VFY: unable to resolve new-instance 4090 (Lgpr;) in Lgps;
07-10 10:22:04.205: D/dalvikvm(23978): VFY: replacing opcode 0x22 at 0x0000
07-10 10:22:04.205: D/dalvikvm(23978): DexOpt: unable to opt direct call 0x5ea3 at 0x0a in Lgps;.a
07-10 10:22:04.205: D/dalvikvm(23978): DexOpt: unable to opt direct call 0x5ea3 at 0x0c in Lgps;.a
07-10 10:22:04.205: D/dalvikvm(23978): DexOpt: unable to opt direct call 0x5ea3 at 0x0a in Lgps;.a
07-10 10:22:04.205: W/dalvikvm(23978): VFY: unable to resolve static field 20873 (t) in Lyp;
07-10 10:22:04.205: D/dalvikvm(23978): VFY: replacing opcode 0x62 at 0x000e
07-10 10:22:04.205: W/dalvikvm(23978): VFY: unable to resolve static field 20873 (t) in Lyp;
07-10 10:22:04.205: D/dalvikvm(23978): VFY: replacing opcode 0x62 at 0x000d
07-10 10:22:04.215: I/Google Maps Android API(23978): Google Play services package version: 5084038
07-10 10:22:04.455: W/ActivityThread(23978): ClassLoader.loadClass: The class loader returned by Thread.getContextClassLoader() may fail for processes that host multiple applications. You should explicitly specify a context class loader. For example: Thread.setContextClassLoader(getClass().getClassLoader());
07-10 10:22:04.475: I/dalvikvm(23978): Failed resolving Lcom/google/android/gms/location/internal/ParcelableGeofence; interface 4023 'Lgln;'
07-10 10:22:04.475: W/dalvikvm(23978): Link of class 'Lcom/google/android/gms/location/internal/ParcelableGeofence;' failed
07-10 10:22:04.475: E/dalvikvm(23978): Could not find class 'com.google.android.gms.location.internal.ParcelableGeofence', referenced from method glt.a
07-10 10:22:04.475: W/dalvikvm(23978): VFY: unable to resolve check-cast 2086 (Lcom/google/android/gms/location/internal/ParcelableGeofence;) in Lglt;

I have another app that uses maps and this is also affected by this issue. I have updated ADT and my SDK. I have also tried removing and re-adding the Google play Lib in eclipse. I've checked and regenerated my API key info.


text:
Q: The truth table shows the following statement is a tautology, but it doesn't make sense. the truth table of the sentence $$(p \rightarrow q) \vee (q \rightarrow p)$$
is
\begin{array}{ c  c  l }
  p & q & (p \rightarrow q) \vee (q \rightarrow p) \\ \hline
  T & T & \, \, T \; T \> T \> \>  \mathbf{T} \> \> T \; T \> T\\
  T & F & \, \, T \; F \> F \> \> \mathbf{T} \> \> F \; T \> T\\
  F & T & \, \, F \; T \> T \> \> \mathbf{T} \> \> T \; F \> F\\
  F & F & \, \, F \; T \> F \> \> \mathbf{T} \> \> F \; T \> F\\
\end{array}
where the italic truth values are of subclauses and the boldface truth values are of the whole statement. From the truth table it is seen that the given statement is a tautology. So far so good. For me the problem arises when I verbally think of the statement. It can be translated into metalanguage as,
the statement "either $p$ implies $q$, or $q$ implies $p$", is a tautology.
This tautology means that, given two arbitrary statements $p$ and $q$, if $p$ does not imply $q$, then $q$ must imply $p$, and the other way  around. Or in other words, it is not the case that none of them implies the other.  This doesn't make too much sense to me.  Why it is always the case that, given two arbitrary statements, one should be implying the other for sure? Why two random statements should bound in such way?

A: In classical logic, there is nothing wrong in the above "un-natural" tautology.
You can see this recent post (with many links) about the "correct" reading of the truth functional aspects of $\rightarrow$.
You can check with truth table that :

$p \rightarrow q$ and $\lnot p \lor q$

are equivalent.
Thus, we can rewrite :

$(p→q)∨(q→p)$ (called also : Dumemtt's law)

as :

$(\lnot p \lor q) \lor (\lnot q \lor p)$.

Now we can rearrange the disjuncts to get :

$(\lnot p \lor p) \lor (\lnot q \lor q)$.

Now, the tautology "sounds" much more ... tautological.

As per comment above, you can avoid this counter-intuitive aspects leaving classical logic and adopting, for example, the intuitionsitic one; but you have to remember that the truth functional properties of the connectives (i.e. the truth table) are nor more valid in it.

A: Use the equivalences $$[A\implies B] \equiv \neg[A\land \neg B]\equiv [\neg A\lor B]$$ to show that $$[[p\implies q]\lor [q\implies p]]\equiv[[p\land \neg q]\implies[\neg q \lor p]] $$


text:
Q: Clicking cookie button with Selenium 4 error: object[] has no size and location I've been attempting to click a button in a pop-up with selenium, but I'm getting the following error:
object [HTMLDivElement] has no size and location

I have tried the normal way, with just click, since it is in the viewport and I am waiting for the page to fully load:
let pressCookieButton = await driver.findElement(By.xpath('//a[@class="btn-actiune btn-actiune--principal"]/..'))
await pressCookieButton.click();

But this does not work. It says
Element not interactible

Then, i tried to click using actions:
let pressCookieButton = await driver.findElement(By.xpath('//a[@class="btn-actiune btn-actiune--principal"]/..'))
const actions = driver.actions({ async: true });
await actions.click(pressCookieButton).perform();

But i get:
object [HTMLDivElement] has no size and location

The HTML that I am attempting to click is the following:

    Accept toate cookie-urile

Below is the full code:
const {Builder} = require('selenium-webdriver');
const {By} = require('selenium-webdriver');

(async function helloSelenium() {

    let driver = await new Builder().forBrowser('chrome').build();

    try{

        await driver.get('https://www.imobiliare.ro/vanzare-apartamente/timisoara/matei-basarab/apartament-de-vanzare-3-camere-XCB61020C');

        await driver.sleep(7000);
        console.log("clicking")

        let pressCookieButton = await driver.findElement(By.xpath('//a[@class="btn-actiune btn-actiune--principal"]/..'))

        const actions = driver.actions({ async: true });
        await actions.click(pressCookieButton).perform();

        //findElement(By.className('btn-actiune btn-actiune--principal'));
        await driver.sleep(10000);

        await pressCookieButton.click();

    }catch(error){
        console.log(error)

        await driver.sleep(5000);

        // await driver.quit()
    }

})();

A: As you can see from the GIF below, the xpath matches two elements and by using driver.findElement you are selecting the first one, while the correct one is the second.
So you should either use driver.findElements instead of driver.findElement and then select the second element, or use a selector targetting only the correct element, such as
driver.findElement(By.cssSelector('div[class*="vizibil-informare"] a[class*="principal"]'))


text:
Q: What is a good AWS client? The web based AWS console seems so limited in what it can do. For example, to create a private stream distribution, you have to create CloudFront Origin Access Identity, create private content distribution, and modify ALC on the private objects, all through XML calls (WTF?). I really expect something so common to be integrated into their Console.
Is there a client smart enough that allows me to do simple tasks in simple ways?

A: Some options are:

*

*ylastic - A web based tool that does automate many multi-step operations.

*Cloudberry Explorer - A Windows only client application

*Bucket Explorer - A cross platform client application

I'm not sure if these perform the tasks you need by they are worth a look.

A: You can configure CloudFront Private Content with cloudberry freeware. http://blog.cloudberrylab.com/2010/03/how-to-configure-private-content-for.html

A: More generally, you should probably look for cloud management softwares. They are an additional layer on top of Amazon Web Services and leverage AWS API to offer automations tools like automated backups, auto-scaling, failover by default...
Ylastic was mentionned by Geoff, but you can try Scalr (disclaimer: I work there), RightScale or enStratus.

A: I have felt this way too...but it seems the aws command line tools is the only options that I know..

A: Basic answer: No! It is even hard to find a GUI to manage more than one aws product
And no one will put in effort to develop this as aws keep changing the API interface.
For me:
For stable aws service like S3, I use Cyberduck
And the rest of them, I write my own program to do it, it is more customized for my own need and not easy to make mistake (and help me to familiar with the api)


text:
Q: Auto Block Abusive customer in Einstein ChatBot Salesforce can anyone help in auto-blocking customers when they enter abusive language in the chatbot e.g when chatbot asks for the first name, last name, or email Id? Also, we cant use blocking from IP addresses as these IP addresses are not known for some customers.

A: There is no out-of-the-box functionality for this. You can keep a list of keywords in a record somewhere that the Bot can check against, and then end the chat if a customer uses one of them.
Like, incase of bot you can build a simple rule, if value = (swear word) then go to the End chat dialog. It'd be exactly the same in an Omni routing flow if you don't have a Bot.
Related: Block Sensitive Data in Messages


text:
Q: Lasso after GLM After doing a bit of logistic regression Im trying to do Lasso regression but on typing various commands I keep getting object not found errors Here is my code so far
data <- read.csv("ahw.csv",
+                  colClasses = c("factor",
+                                 rep("numeric", 15)))

Which gives me
 $ PlacedN: Factor w/ 2 levels "0","1": 1 1 1 1 1 2 1 1 1 1 ...
 $ TrA    : num  9 13 11 9 -1 13 10 10 10 6 ...
  $ JoA    : num  0 2 0 10 6 15 8 9 9 6 ...
  $ aPr    : num  0 0 0 0 0 0 0 0 0 0 ...
  $ bPr    : num  0 1 0 0 1 0 0 0 0 0 ...
 $ mPr    : num  0 0 0 0 1 0 0 0 0 0 ...
 $ Vdw    : num  0 0 0 0 0 0 0 0 0 0 ...
 $ ALL    : num  32 46 15 16 48 50 32 9 28 4 ...
 $ COD    : num  -1 80 0 25 -1 50 47 -1 -1 -1 ...
 $ DIS.   : num  32 46 23 15 48 50 32 9 28 0 ...
 $ cIM    : num  -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 ...
 $ cFE    : num  -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 ...
  $ LAT    : num  38 38 9 20 61 58 37 12 25 5 ...
  $ CLA    : num  40 50 9 25 -1 75 61 -1 -1 -1 ...
  $ CLC    : num  -1 -1 0 25 -1 75 61 -1 -1 -1 ...
  $ LAC    : num  38 50 9 25 -1 60 61 -1 -1 -1 ...

Obviously I can call the Logistic formula up using
est <- glm(PlacedN ~ ., data=data, family="binomial")
summary(est)

So basically what is my next step to do LASSO (with logit) and also get the coefficients and any nice graphs after it
There are a few packages out there which is confusing a beginner like me
Thanks in Advance
Michael

A: The glmnet package should be useful. There is a great tutorial by the authors. But, here is a quick start using your code.
require(glmnet)
est <- glmnet(as.matrix(data[,2:16]), data$PlacedN , family="binomial")
summary(est)
plot(est)
last <- dim(coef(est))[2]
coef(est)[last]

Hope this helps!


text:
Q: lftp: login, put file in remote dir and exit in a single command: proper quoting help I want to use lftp -c to do an entire session in one go (as I'll be launching this from a script later on) and I managed with -e but that ofc leaves me with the interactive session which I don't want.
Manual states
-c commands
          Execute the given commands and exit. Commands can be separated with a semicolon,  `&&'
          or  `||'.  Remember to quote the commands argument properly in the shell.  This option
          must be used alone without other arguments.

But I don't understand how I should quote and string my commands/interactions together correctly.
lftp -e "put -O remote/dir/ /local/file.txt" -u user,pass ftpsite.com
works excellent. But I want to exit after executing the command;
lftp -c "open -u user,pass ftpsite.com" || put -O "remote/dir/ /local/file.txt"
just shouts at me, or in fact any combination of quotes I tried (|| or && regardless)

A: $ lftp -c "open -u user,pass ftpsite.com; put -O remote/dir/ /local/file.txt"

should do it.
If this doesn't work try adding to your /etc/lftp.conf the following lines:
set ftp:ssl-protect-data true
set ftp:ssl-force true
set ftp:ssl-auth TLS
set ssl:verify-certificate no

A: lftp -e "put -O remote/dir/ /local/file.txt; bye" -u user,pass ftpsite.com

A: lftp -e "put -O remote/dir/ /local/file.txt; bye" ftp.yourhost.com
and put your credentials under ~/.netrc like
machine ftp.yourhost.com login your_username password your_password
Putting passwords in the cli is absolutely no-go since those are even readable when using ps -aux during the upload.. beside the bash history also.


text:
Q: What is the proper syntax to chain multiple queries together? I'm using the HotTowel SPA template which makes use of Durandal. In my Durandal ViewModels I am using Breeze to get some data from the database.
I have a datacontext class that I put all my breeze queries in and the queries all follow the pattern like the following:
getAthletes: function (queryCompleted) {
            var query = breeze.EntityQuery.from("Athletes");
            return manager
                .executeQuery(query)
                .then(queryCompleted)
                .fail(queryFailed)
        }

Since I'm doing an asynchronous call in the activate method of the view model, I have to return the promise that comes back from these calls in the activate method.
Using a single query works great like this:
function activate() {
  datacontext.getAthlete(loadAthlete);
}

However, if I need to perform two queries I run into problems, but only in the release version of my application. I have tried doing this with the following syntax:
function activate() {
  datacontext.getAthlete(loadAthlete).then(datacontext.getOtherData(loadOtherData));
}

This will work fine in debug mode, but when I deploy it out to the server and my scripts get bundled, I get an exception which isn't very clear.

t is not a function

I've also tried chaining them together in my datacontext class like below, but I still get the same error.
getAthleteAndEfforts: function (athleteId, athleteQueryCompleted, effortsQueryCompleted) {
    var athleteQuery = breeze.EntityQuery.from("Athletes").where("id", "==", athleteId);
    var effortsQuery = breeze.EntityQuery.from("BestEfforts").where("athleteId", "==", athleteId);

    return manager.executeQuery(athleteQuery).then(athleteQueryCompleted)
        .then(manager.executeQuery(effortsQuery).then(effortsQueryCompleted))
        .fail(queryFailed);
}

So I'm assuming I just don't understand the Q.defer() enough to use it properly or there is something else going on.
What is the correct syntax to accomplish this?

A: Ok, thanks to RainerAtSpirit for pointing me in the right direction to find this. I looked at John Papa's jumpstarter examples and he has a datacontext that does this under the primeData function.
So using the syntax he used there I was able to get it to work correctly like this:
getAthleteAndEfforts: function (athleteId, athleteQueryCompleted, effortsQueryCompleted) {
    return Q.all([
                datacontext.getAthlete(athleteId, athleteQueryCompleted),
                datacontext.getAthleteEfforts(athleteId, effortsQueryCompleted)]);
}

I had seen the Q.all in the Q documentation but wasn't sure how to use it, but this example helped. I tested this and it works both in debug and release modes.

A: Not sure why the first version is working at all, but you'd return a promise when datacontext is making async calls.
function activate() {
  return datacontext.getAthlete(loadAthlete);
}

or
function activate() {
  return datacontext.getAthlete(loadAthlete).then( return datacontext.getOtherData(loadOtherData));
}

Check @John Papa's jumpstarter for more examples: https://github.com/johnpapa/PluralsightSpaJumpStartFinal/search?q=activate


text:
Q: android - Rounded Linear Layout corner overlapped by fill_parent TextView
This is what I need to the top of my layout

This is what I actually have
There would be a simple option that I'm not calculating at the moment.
Drawable for rounded corners
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#E9E9E9"/>
    <stroke android:width="4dip" android:color="#B1BCBE" />
    <corners android:radius="10dip"/>
    <padding android:left="0dip" android:top="0dip" android:right="0dip" android:bottom="0dip" />
</shape>

Layout
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/home_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/rounded_layout" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/filter_title"
            android:background="@android:color/black"
            android:textColor="@android:color/white"
            android:padding="10dp"
            android:textSize="20sp" />

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="15dp" >

            <Spinner
                android:id="@+id/sp_intorno_a_me_proximity"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:spinnerMode="dialog" />
            .
            .
            .
            <EditText
                android:id="@+id/et_intorno_a_me_username"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:textSize="20sp"
                android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
                android:hint="@string/agentNumber" />

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="20dp"
                android:layout_marginBottom="10dp"
                android:weightSum="1" >

                <Button
                    android:id="@+id/btn_intorno_a_me_close_search"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="0.5"
                    android:text="@string/annulla"
                    style="@style/HelianButtonRed"
                    android:textColor="@android:color/white" />

                <Button
                    android:id="@+id/btn_intorno_a_me_search"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="0.5"
                    android:text="@string/find"
                    style="@style/HelianButtonGreen" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

</ScrollView>

I have already tried to move the drawable to the first LinearLayout child.
How can I prevent the text view to hides the rounded corners?

A: With the help of Manishika (I voted up your answer [do the same for me! :)]) I'm posting the solution of my problem!
With this parent rounded corner style:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#E9E9E9"/>
    <stroke android:width="4dip" android:color="#B1BCBE" />
    <corners android:radius="10dip"/>
    <padding android:left="0dip" android:top="0dip" android:right="0dip" android:bottom="0dip" />
</shape>

We need to attach a specific drawable to the textview (or any view you need).
Here is the drawable for the trick:
I subtracted 2 d

    <corners
        android:topLeftRadius="8dip"
        android:topRightRadius="8dip"
        android:bottomLeftRadius="0dip"
        android:bottomRightRadius="0dip" />
</shape>

KEEP IN MIND!!
The Graphical Layout (the Preview) will NOT shows the correct rounding! You need to test it on the device (or emulator if you have no devices).

A: Try something like this in your TextView as background.
Create a new drawable .xml for TextView with following data
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#000000"/>
    <stroke android:width="4dip" android:color="#B1BCBE" />
    <corners
        android:topLeftRadius="10dip"
        android:topRightRadius="10dip"
        android:bottomLeftRadius="0dip"
        android:bottomRightRadius="0dip"

        />
    <padding android:left="0dip" android:top="0dip" android:right="0dip"
      android:bottom="0dip" />

</shape>


text:
Q: GetProductUrl does show Url but it's not a link I have made adbanners for my website and the title of the product does have a fine working link by using the following code: <a href="<?php echo $_product->getProductUrl() ?>" title="wefewf">
But using the same code for the image and buy here doesn't work. In element inspect you can actually see the link in the html but it's just plain text. Any Ideas?
EDIT: I found the problem, well not really but I've found a problem. It works if I put it somewhere outside my ad banner. So It might be css but I can't seem to find the issue here. This is the css for the image applied:
.products-grid .product-image {
    display: block;
    float: left;
    height: auto;
    max-width: 270px;
    overflow: hidden;
    position: relative;
    text-align: left;
    margin-left: 10px;
}

But then again, the css for both the working and not working is the same.

A: Can you check to see if any css property is pushing back the image in the visibility stack level.
May be due to z-index of other element the click is blocked by the overiding layer.
If possible can you show inspect screenshot with applied css properties.


text:
Q: qqplot against theoretical quantiles I want to be able to do qqplots against theoretical quantiles. I already know qqnorm() does that for the normal distribution, but that's a pretty a limited tool to me. Also, I noticed that some people simulate random processes from a given distribution and use it to compare to sample data, which is not entirely rigorous because it depends on the method of simulation. So my example would be to compare sample data to geometric distribution:
#sample data
var=rgeom(prob=0.3, n=100)

#QQplot against a theoretical geometric distribution with prob=0.5

A: You can produce such a plot easily with the ggplot2 package:
library(ggplot2)
qplot(sample = var, geom = "point", stat = "qq",
      distribution = qgeom, dparams = list(prob = 0.5))

The theoretical quantiles (x axis) are derived from a geometric distribution with a probability of 0.5.

Update (based on question in comment):
A line can be added in the following way though it is not very well suited for geometric distribution. The approach is based on this answer.
qv <- quantile(var, c(.25, .75))
qt <- qgeom(prob = 0.5, c(.25, .75))
slope <- diff(qv)/diff(qt)
int <- qv[1] - slope * qt[1]

qplot(sample = var, geom = "point", stat = "qq",
      distribution = qgeom, dparams = list(prob = 0.5)) +
  geom_abline(slope = slope, intercept = int)

A: A Q-Q plot is a plot of quantiles of a ramdom sample against quantiles of the test distribution. So,
plot(qgeom(seq(0,1,length=100),.3),quantile(var,seq(0,1,length=100)))


text:
Q: Open image created with JS on new tab Let's say I have an image that I have previously created using JS (e.g. a base64 of a canvas) and I want to open it to a new page.. I've tried the following:
const src = "base 64 of the image";
window.open(src,'Image','width=largeImage.stylewidth,height=largeImage.style.height,resizable=1');

this is now working (at least on the latest stable Chrome version).. am I missing something?

A: Try this:
    var image = new Image();
    image.src = "data:image/jpg;base64, " + "base 64 of the image";

    var w = window.open("");
    w.document.write(image.outerHTML);
    w.document.close();

Also, make sure to specify the correct content type, in my answer I'm using jpg


text:
Q: Grant access to function only for classes that have the same base class I have a baseclass, lets call it base_t. base_t has a function called void render(). I want that all classes that derive from base_t to have access to that function, but noone else. The render functions will be defined in base_t as virtual void render() = 0; making it pure virtual.
How can I achieve this in C++? Via friend? Or are there other methods of doing this?
To make it more clear, I want the class A (derived from base_t) to be able to access the function render() in class B (also derived from base_t) which is implemented by A and B but is pure virtual defined in base_t.
Here is an example:
class base_t
{
private:
    virtual void render() = 0;
};

class A : public base_t
{
private:
    virtual void render()
    {
        // Do Stuff
    }
};

class B : public base_t
{
public:
    void dostuff(A *classA)
    {
        // here I want to call render!
        classA->render();
    }

private:
    virtual void render()
    {
        // Do Stuff
    }
};

A: What about a simple:
class base_t
{
private:
    virtual void render() = 0;

protected:
   void renderOther(base_t& other){
      other.render();
   }
};

B can render A through the interface method keeping a correct encapsulation.


text:
Q: Foreign Keys constraint is not working in SQlite I am dropping pk from table 1 to table 2 as foreign key in my database using sqlite. But my table 2 is not working accordingly to foreign key constraint it is inserting record if that key is not available in table1. I am using db browser and my pragma foreign key is enabled there but its still  not working

A: I have found the solution. You have to enable pragma foreign keys in your C# code everytime you make a connection.
Let me share my code:
 conn.Open();
            string query = " insert into Installment_Details (Account_No,Month_yr,Date,Receipt_No,Amount_Received,Amount_Left,Amount_receiver) values ('" + this.Textbox_AN.Text + "','" + this.Textbox_MY.Text + "','" + this.Textbox_D.Text + "','" + this.Textbox_RN.Text + "','" + this.Textbox_AR.Text + "','" + this.Textbox_AL.Text + "','" + this.Textbox_ARR.Text + "');";
            SQLiteCommand createcommand = new SQLiteCommand("PRAGMA foreign_keys = ON", conn);
            createcommand.ExecuteNonQuery();
            createcommand = new SQLiteCommand(query, conn);
            createcommand.ExecuteNonQuery();
            MessageBox.Show("Saved Successfully");

A: It is not necessary to turn the pragma on in here:
SQLiteCommand createcommand = new SQLiteCommand("PRAGMA foreign_keys = ON", conn);

but better to turn it on when the connection is created:
ConnectionString = $"Data Source={databaseFile}; foreign keys=true";
connection = new SQLiteConnection(ConnectionString);

and then create the command and call the ExecuteNonQuery().


text:
Q: Wordpress register sidebar and call it on single post I have registered a new Sidebar called "MagazinSidebar", which I can see in the widget area.
    if ( function_exists('register_sidebar') )
register_sidebar(array('name'=>'MagazinSidebar',
'before_widget' => '
',
'after_widget' => '
',
'before_title' => '
',
'after_title' => '
',
));

and tried to call it if the category is 'Magazin', but it does not appear in the Magazin Category...
    //get template sidebar
if ( in_category( 'Magazin' )) {
if ( function_exists('dynamic_sidebar') && dynamic_sidebar('MagazinSidebar') ) ;
    }
else {
 get_sidebar();
}

Any ideas? :) Thanks

A: use get_sidebar() function with your registered sidebarname.
Here in your case use get_sidebar('MagazinSidebar').
if ( in_category( 'Magazin' )) {
get_sidebar('MagazinSidebar');
    }
else {
 get_sidebar();
}