text:
Q: Call jquery autocomplete after button click event I want to call a jquery autocomplete function but after a button click. In button click event gridview and textbox are visible else they are invisible.
Below are my code
Script
 $(document).ready(function () {
            SearchText();
        });
        function SearchText()
        {
            $(".autosuggest").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "CalendarDetails.aspx/GetAutoCompleteData",
                        data: "{'Col3':'" + document.getElementById('txtSearch').value + "'}",
                        dataType: "json",
                        success: function (data) {
                            response(data.d);
                        },
                        error: function (result) {
                            alert("Error");
                        }
                    });
                }
            });
        }

HTML
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
            <asp:Label ID="Label4" runat="server" Text="ID" Font-Bold="True"></asp:Label>

        <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>

            <asp:Label ID="Label1" runat="server" Text="Start Date" Font-Bold="True"></asp:Label>
            <input type="text" id="datepickerStart" runat="server" />

        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="datepickerStart" ErrorMessage="*Mandatory field" ForeColor="Red"></asp:RequiredFieldValidator>

            <asp:Label ID="Label2" runat="server" Text="End date" Font-Bold="True"></asp:Label>

             <input type="text" id="datepickerEnd" runat="server" />
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="datepickerEnd" ErrorMessage="*Mandatory field" ForeColor="Red"></asp:RequiredFieldValidator>

            <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />

EDIT
<input type="text" id="txtSearch" class="autosuggest" />
            <asp:UpdatePanel ID="UpdatePanel1"  runat="server" UpdateMode="Conditional" >

            <ContentTemplate>
                <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>

                <asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="20" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDataBound="GridView1_RowDataBound">
                    <HeaderStyle BackColor="#FFCC99" />

                </asp:GridView>

            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="GridView1" EventName="PageIndexChanging" />
                <asp:AsyncPostBackTrigger ControlID="btnSubmit" EventName="Click" />
            </Triggers>
        </asp:UpdatePanel>

Code behind
[WebMethod]
    public static List<string> GetAutoCompleteData(string Col3)
    {
        List<string> result = new List<string>();
        if ((dtClone != null) && (dtClone.Rows.Count > 0))
        {
            DataRow[] foundRows;
            string expression = "Col3 LIKE '%" + Col3 + "%'";

            // Use the Select method to find all rows matching the filter.
            foundRows = dtClone.Select(expression);
            for (int i = 0; i < foundRows.Length; i++)
                result.Add(foundRows[i][2].ToString());
        }
        return result;

    }

The problem is after button click event autocomplete(jquery) for search operation is not working.
Please help me where is the issue. Where I am wrong

A: Looking at your code it looks like your search text box is outside the update panel. So the following code should work:
$(document).ready(function () {
    $(".autosuggest").autocomplete({
        source: function (request, response) {
            var col3 = $("#txtSearch").val();
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "CalendarDetails.aspx/GetAutoCompleteData",
                data: { Col3: JSON.stringify(col3) },
                dataType: "json",
                success: function (data) {
                    response(data.d);
                },
                error: function (result) {
                    alert("Error");
                }
            });
        },
    });
});

In case the search textbox is inside the update panel then it will be loaded via ajax and you have to bind the jquery event to a DOM element above the update panel.
Update Panel wrapped inside a div:

    <asp:UpdatePanel ID="UpdatePanel1"  runat="server" UpdateMode="Conditional" >
        <input type="text" id="txtSearch" class="autosuggest" />
    </asp:UpdatePanel>

Bind the event to the div:
$(document).ready(function () {
    $("#someDivOutsideUpdatePanel .autosuggest").autocomplete({
        // Same code as above
    });
});


text:
Q: An almost reverse triangle inequality involving two complex numbers Given two complex numbers $u$ and $v$, numerically it seems that
$$1+\vert u\vert +\vert v\vert\le \vert 1+u\vert +\vert 1+v\vert+\vert u+v\vert+\vert 1+u+v\vert\tag{$*$}$$
with equality holding for example when $(u=v=-1)$ Or $(u=\exp(\frac{2i\pi}{3}),v=\exp(\frac{4i\pi}{3}))$    but these are not the only cases.
This inequality does not follow in a clear way to me from Hlawka's inequality, but it looks some how similar to a difficult inequality
$$\vert u\vert +\vert v\vert\le \vert 1+u\vert +\vert 1+v\vert+\vert1+uv\vert$$
which was proved in this paper.
I would appreciate any idea or help in proving $(*)$.

A: This follows from Hlawka. Denormalizing the inequality, you want to show
$$|x| + |y| + |z| \leq |x+y| + |y+z| + |z+x| + |x+y+z|$$
Substitute $u = y+z, v = z+x, w = x+y$, you want to show
$$|v+w-u| + |w+u-v| + |u+v-w| \leq 2(|u| + |v| + |w|) + |u+v+w|$$
But Hlawka tells you that
$$\begin{align*}
\text{Right hand side} &\ge (|u| + |v| + |w|) + (|u+v| + |v+w| + |w+u|) \\
&= (|v+w| + |u|) + (|w+u| + |v|) + (|u+v| + |w|) \\
&\ge |v+w-u| + |w+u-v| + |u+v-w| \\
&= \text{Left hand side}
\end{align*}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Under the transformation $ w=\sqrt \frac{1-iz}{z-i}$, Under the transformation $\displaystyle w=\sqrt \frac{1-iz}{z-i}$, the region $D=\{z \in \mathbb{C} : |z|\leq1\}$ is transformed to

$1).\displaystyle \{z \in \mathbb{C} :0< arg (z)< \pi\}$
$2).\displaystyle\{z \in \mathbb{C} :-\pi< arg (z)< 0\}$
$3).\displaystyle \{z \in \mathbb{C} :0< arg (z)< \frac{\pi}{2}
\;or \;  \pi< arg (z)< \frac{3\pi}{2}\
\}$
$4).\displaystyle\{z \in \mathbb{C} :\frac{\pi}{2} < arg (z)< \pi\;\;or\;{\frac{3\pi}{2} :< arg (z)< 2\pi\}
}$

As i try to solve the question by taking random value of $z$  let take $z=0$ ,thus after the calculation i get $w=\sqrt i$ ,whose principal value i calculated and got $\displaystyle\frac{\pi}{4}$
 so the answer can be $1$ or $3$ but further i don't have idea how to solve ,because if i try for another value of $z$ calculations becomes bit tricky
Please help
Thank you

A: Consider $w_1=\dfrac{1-iz}{z-i}$. Since the pole $i\in\partial G$, then the image of $\partial G$ -- is straight line. We'll find her by two points: since $w_1(1)=1$, $w_1(-1)=-1$, then $w_1(\partial G)=\mathbb{R}$. Since $w_1(0)=i$, then $w_1(G)$ is upper half plane. Here is $|w_1|>0$ and $0<\text {arg}w_1<\pi$
Now consider $w=\sqrt {w_1}$. We need to find the image of upper half plane. But we know that $\sqrt{w_1}=\sqrt{|w_1|}e^{i\frac{{arg}w_1+2\pi k}{2}}$, $k=0,1$. All that's left is view possible values of fraction $\displaystyle\frac{{arg}w_1+2\pi k}{2}$.


text:
Q: Javafx: button handler in a button handler Button a=new Button();
...
a.setOnAction(new EventHandler<ActionEvent>()
    {
        public void handle(ActionEvent e)
        {
             Button []b=new Button();
         ...
        }
    });

After clicking the button a, the other buttons b will show up. I want to make an event handler for the buttons b. What should I do?

A: It's called adding a Node(button) dynamically. You can practice with this approach.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXApplication91 extends Application
{
    int idControl = 0;

    @Override
    public void start(Stage primaryStage)
    {
        VBox root = new VBox();

        Button btn = new Button();
        btn.setText("Add New Button");
        btn.setId("Button " + idControl);
        btn.setOnAction(new EventHandler<ActionEvent>()
        {
            @Override
            public void handle(ActionEvent event)
            {
                idControl++;
                Button tempButton = new Button();
                tempButton.setText("Button " + idControl);
                tempButton.setId("Button " + idControl);
                tempButton.setOnAction(new EventHandler<ActionEvent>(){
                    @Override
                    public void handle(ActionEvent event2)
                    {
                        System.out.println("You clicked: " + ((Button)event2.getSource()).getId());
                    }
                });

                root.getChildren().add(tempButton);
            }
        });

        root.getChildren().add(btn);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }
}

This app creates a button on start up. If you click the button it creates a new button. Each new button, when clicked, shows the id of the button being clicked.

A: You dont have to have a button handler inside a button handler, if the Button b shows up only after clicking Button a, you could add another Button b handler (outside Button a handler), Button b cannot not fire a click event if its not visible


text:
Q: Calling a specific instance's method in another class in Java Originally, this started as a nonstatic method being called from a static context error. I've since realized that I cannot reference the class itself, but a specific instance of that class. However, after giving my initialized object a specific name, I find that java will not acknowledge this specific instance, but instead refer to is as an unknown variable. When attempting to compile the code, I receive the error " cannot find symbol - variable player". I believe the code isn't recognizing the particular instance of the class as an already declared variable.
Here is the class being initialized
Link player = new Link();
addObject(player, 300, 176);

and here is the method trying to reference this specific instance's method:
int linkX = player.getX();

The second bit of code is in a method belonging to a class by the name of ChuChu. ChuChu and Link are subclasses of the same superclass. Any help would be greatly appreciated!
World class:
  public Link player;

/**
 * Constructor for objects of class ThroneRoom.
 *
 */
public ThroneRoom()
{
    // Create a new world with 600x562 cells with a cell size of 1x1 pixels.
    super(600, 562, 1);
    this.player = new Link();
    prepare();
}

/**
 * Prepare the world for the start of the program. That is: create the initial
 * objects and add them to the world.
 */
public void prepare() //R1
{
    addObject(player, 300, 176);
    addObject(new ChuChu(), 45, 267);
    addObject (new ChuChu(), 558, 267);
    addObject ( new ChuChu(), 45, 373);

}

Method for ChuChu in full
/**
 * Crawl Toward - Makes ChuChus crawl toward Link
*/
public void crawlToward ()
{
    int random = (int) Math.random() * 5;
    int linkX = player.getX();
    int linkY = player.getY();
    if(getX() >linkX)
    {
        setLocation(getX() - random, getY());
    }
    else
    {
        setLocation(getX()+random, getY());
    }

    if(getX() > linkY )
    {
        setLocation(getX(), getY()-random);
    }
    else
    {
        setLocation(getX(), getY()+random);
    }

}

I am using an IDE called Greenfoot. My problem seems to be that I am given two classes, World and Actor, and they cannot inherit from each other. From the World class, I instance objects into the visual world, and in Actor I create the objects and their methods.

A: Based on your clarifying comment this might help, Java is block scoped so something like this wouldn't work:
if(true) {
  Link player = new Link();
}
//player is outside of the block it was declared in
int linkX = player.getX();

In your case y need to declare player outside of private void prepare() (at the class level would make the most sense in this case).  you are free to instantiate it inside a block (or method in your case).  Here is a quick attempt at doing this with your class:
public class World
{
  Link player;

  public ThroneRoom()
  {
    // Create a new world with 600x562 cells with a cell size of 1x1 pixels.
    super(600, 562, 1);

    prepare();
  }

  /**
   * Prepare the world for the start of the program. That is: create the initial
   * objects and add them to the world.
   */
  private void prepare()
  {
    this.player = new Link();
    addObject(player, 300, 176);
    addObject(new ChuChu(), 45, 267);
    addObject (new ChuChu(), 558, 267);
    addObject ( new ChuChu(), 45, 373);

  }
  public void crawlToward ()
  {
    int random = (int) Math.random() * 5;
    int linkX = this.player.getX();
    int linkY = this.player.getY();
    if(getX() >linkX)
    {
      setLocation(getX() - random, getY());
    }
    else
    {
      setLocation(getX()+random, getY());
    }

    if(getX() > linkY )
    {
      setLocation(getX(), getY()-random);
    }
    else
    {
      setLocation(getX(), getY()+random);
    }
  }
}


text:
Q: Найти расстояние между первым и последним максимальным элементом массива не могу добить до конца, дошла до вывода номеров всех максимальных чисел, но найти расстояние между первым и последним не выходит. Заранее спасибо за помощь
Random r = new Random();
        int[] nums = new int[10];
        for (int i = 0; i < 10; i++)
            nums[i] = r.Next(0, 11);
        Console.WriteLine("Random array");
        foreach (int x in nums)
        {
            Console.Write($"{x} ");
        }
        Console.WriteLine();

        int maxi = nums[0];
        int mini = nums[0];
        int max = -1;
        int index1 = -1;
        int index2 = -1;
        // Цикл по всем элементам массива
        // От 0 до размера массива
        for (int i = 0; i < nums.Length; i++)
        {
            if (max <= nums[i])
            {
                // Запоминаем новое максимальное значение
                max = nums[i];
                // Запоминаем порядковый номер
                index1 = i;
            }
        }
        for (int i = 0; i < nums.Length; i++)
        {
            if (nums[i] == max)
            {
                index2 = i;
                Console.WriteLine("Номер максимального числа: " + index2);
            }
        }

A: Небольшая модификация, а второй цикл не нужен
 int index1 = 0;
 int index2 = 0;
 for (int i = 1; i < nums.Length; i++)
        {
            if (nums[index1] < nums[i])
            {   // Запоминаем порядковый номер
                index1 = i;
                index2 = i;
            }
            else if (nums[index1] == nums[i])
                index2 = i;
        }
 вывести index2-index1


text:
Q: c# regex spain mobile phone what would be a valid regex for these rules:
34 6xx xxx xxx
34 7yx xxx xxx
(note y cannot be 0 (zero))

would this one work?
34(([6][0-9]{8}$)|([7][1-9]{1}[0-9]{7}$))

A: Your regular expression should work, assuming that you are not expecting it to handle spaces.
You can further optimize your regex by extracting the common suffix of [0-9]{7} from it:
^34(?:6[0-9]|7[1-9])[0-9]{7}$

If you would like to account for optional spaces, insert \s? into your regex in places where you wish to allow space characters to be inserted:
^34\s?(?:6[0-9]|7[1-9])[0-9]\s?[0-9]{3}\s?[0-9]{3}$

A: If you need to handle this specific format with spaces, you can use
^34 ?(?:6[0-9]{2}|7[1-9][0-9])(?: ?[0-9]{3}){2}$

See RegexStorm demo
REGEX EXPLANATION:

*

*^ - Start of string

*34 ? - 34 followed by an optional space

*(?:6[0-9]{2}|7[1-9][0-9]) - A group of 2 alternatives: 6 can be followed by any 2 digits, and 7 can be followed only by non-0 and one more digit

*(?: ?[0-9]{3}){2} - 2 groups of 3 digits, optionally separated with a space

*$ - End of string.


text:
Q: Escape HTML on WP input I am slightly stuck on creating a widget, it has an input (bit like the default text widget) but got an issue adding html into it.
My code is:
$instance['content'] = ( ! empty( $new_instance['content'] ) ) ? esc_html( $new_instance['content'] ) : '';

This works partially as it let me saves the HTML (an iframe) but displays it as code in the frontend, I need it to convert the iframe code to a working video.
I have also tried:
$instance['content'] = ( ! empty( $new_instance['content'] ) ) ? strip_tags( $new_instance['content'] ) : '';

but it won't let me save the iframe content (it clears the box).
Which function do I need to use so my widget behaves the same as the default text widget.

A: The default text widget - WP_Widget_Text - can be found in wp-includes/default-widgets.php. The input is handled like this:

*

*stripslashes( wp_filter_post_kses( addslashes( $text ) ) ); for the text;

I assume this should work likewise for your custom widget. Additionally there is:

*

*wpautop( $text ) on the output, if the filter is set to do that;

But optimally you're taking a look at the source yourself.
Additionally the codex articles:

*

*Validating Sanitizing and Escaping User Data; and

*Data Validation
give you an good overview about sanitizing, escaping and validating possibilities with WP.


text:
Q: What is the reward for the Bonus at the end of Act2? At the End of Act 2, right before the boss fight.

 There is an event where you must save the people from the city being attacked and lead them to the sewer.  They can die by being attacked or poison bombed

What is the bonus you receive if you complete this event perfectly?
I did it twice now and failed miserably

A: If you manage to rescue 20 people, you will receive the Hero of Caldeum achievement.

A: In addition to the gold each person drops outside the sewer, if you go inside the sewer there are treasure chests that are supposedly based on how well you did.
I've only completed the event once since someone told me of the chests inside, so only know the chests exist, and haven't verified if you get more/better ones if you do better at the event


text:
Q: jQuery zoom in effect I am trying to create an effect on an advent calendar (a bit out of season, I know).
In short, when I open a door I want to create a zooming in/warp effect to give the illusion you are being entered into the door.
I have looked into the similar:
http://codepen.io/noahblon/pen/GKflw
http://designshack.net/tutorialexamples/jQueryZoom/jQueryZoom.html
My biggest issue is that I need to ensure this works in IE8! Yes, annoying. And yes I understand my limitations. CSS3 out of the equation, however I need to get as close to this effect.
Does anyone have any suggestions?
Thanks!


text:
Q: Using OAuth2 on Android, there is no problem with the debug version, but GooglePlay fails I'm using Google Drive's API on Android.
OAuth has been authenticated and the publishing status is also running
But after I put the app on the shelf, this function keeps failing at login.
The resultCode received by onActivityResult is always 0.
But the same code, direct compilation (debug) is normal.
Hope someone can help me.
Credentials section I built three (because I couldn't figure out which link went wrong)

*

*The version of debug (keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android)

*The release version (jks used by Generate Signed Bundle or APK)

*Application signing key certificate in Google Play Console
Is it related to the com.google.android.gms:play-services-auth version?
I am using 18.0.0
Below is the code for my login
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestScopes(new Scope(DriveScopes.DRIVE_FILE),
new Scope(DriveScopes.DRIVE_APPDATA))
.build();


text:
Q: Is the function $\frac{1}{2}\int_{-1}^{1}\varphi(f(x,\omega)) \cdot \ \chi_{[-1,1]}(f(x,\omega)) $ continuous? Let $f:[-1,1]\times[-1,1] \to \mathbb R$ be the function $f(x,\omega) = x^3 + \omega$, then whe can define the following family $\left\{\mathbb P_x\right\}_{x\in[-1,1]}$ of Borel measures on $[-1,1]$
\begin{align*}\mathbb P_x: \mathcal B([0,1])&\to \mathbb R_+ \\
A&\mapsto \frac{1}{2}\int_{-1}^{1} \chi_A \circ f(x,\omega) d\omega,
\end{align*}
where $\chi_A$ the characteristic function of the set $A$, i.e., $\chi_A(x) =1$ if $x\in A$, $\chi_A(x) = 0$, if $x \not\in A$.
Let $\varphi:[-1,1]\to \mathbb R_+$, a bounded measurable function, then we define
$$\mathbb E_x (\varphi) = \int_{[-1,1]}\varphi(y) \ \text{d}\mathbb P_x(y) = \frac{1}{2}\int_{-1}^{1}\varphi(f(x,\omega)) \cdot \ \chi_{[-1,1]}(f(x,\omega))\ \text{d} \omega.$$

My question: Is the function $G:[-1,1]\to \mathbb R_+$, $G(x) := \mathbb E_x(\varphi)$ continuous?

My attempt
Note that $$-1\leq x^3 + \omega \leq 1 \Rightarrow -1-x^3 \leq \omega \leq 1-x^3,$$
then
\begin{align*}\frac{1}{2}\int_{-1}^{1}\varphi(f(x,\omega)) \cdot \ \chi_{[-1,1]}(f(x,\omega))\ \text{d} \omega&=\frac{1}{2}\int_{-1\lor-1-x^3}^{1\land 1+x^3}\varphi(x^3+\omega) \ \text{d} \omega\\
&=\frac{1}{2}\int_{-1+x^3\lor -1}^{1+x^3\land 1}\varphi(y) \ \text{d} y,
\end{align*}
where $a\lor b = \max\{a,b\}$ and $a\land b = \min\{a,b\}$.
Once $-1+x^3\lor -1$ and $1+x^3\land 1$ are continuous $\Rightarrow$ $\frac{1}{2}\int_{-1+x^3\lor -1}^{1+x^3\land 1}\varphi(y) \ \text{d} y$ is continuous, is this right?


text:
Q: VB Listbox change value How can i change a value in a VB Listbox?
Like this it doesn't work:
listbox.selectedItem = "Newvalue"

THX for help

A: listbox.List(listbox.ListIndex) = "NewValue"

A: Adding items to listbox:
ListBox1.Items.Add("AA")
ListBox1.Items.Add("BB")
ListBox1.Items.Add("CC")
ListBox1.Items.Add("DD")

now select anyone 1 option in the listbox:

Add this code in your button click
ListBox1.SelectedItem.Text = "newvalue"

the selected option/value "CC" is changed to "newvalue"


text:
Q: mysql how to keep key for aes_encrypt I have a question on where to store the key for aes_encrypt. See below, you can see I store the key into one separate table. My question is: can I keep the key on OS level ? Let say in one txt file and each time from MySQL somehow read the key from that file using "SQL statement" ?
drop table if exists lr_words;

create table lr_words
(
    word varchar(300)
);

insert into lr_words(word) values ('my_key');

drop function if exists lr_encrypt;
delimiter $$
create function lr_encrypt(p_text varchar(1000) character set UTF8)
   returns varbinary(200)
begin

    declare l_word varchar(300) default '';
    declare l_key_length int default 512;

    select word
      into l_word
      from lr_words;

    return aes_encrypt(p_text, SHA2(l_word,l_key_length));

end
$$

drop function if exists lr_decrypt;
delimiter $$
create function lr_decrypt(p_text varbinary(200))
   returns text character set UTF8
begin

    declare l_word varchar(300) default '';
    declare l_key_length int default 512;

    select word
      into l_word
      from lr_words;

    return cast(aes_decrypt(p_text, SHA2(l_word,l_key_length)) AS char(1000));

end
$$

select lr_encrypt(email) as email_en,
lr_decrypt(lr_encrypt(email)) as email_dec
from my_table

All this work fine, but I want to keep the key outside the database !


text:
Q: Split a list into n equal parts Given a sorted list, and a variable n, I want to break up the list into n parts. With n = 3, I expect three lists, with the last one taking on the overflow.
I expect: 0,1,2,3,4,5, 6,7,8,9,10,11, 12,13,14,15,16,17
If the number of items in the list is not divisible by n, then just put the overflow (mod n) in the last list.
This doesn't work:
static class Program
{
    static void Main(string[] args)
    {
        var input = new List<double>();
        for (int k = 0; k < 18; ++k)
        {
            input.Add(k);
        }
        var result = input.Split(3);

        foreach (var resul in result)
        {
            foreach (var res in resul)
            {
                Console.WriteLine(res);
            }
        }
    }
}

static class LinqExtensions
{
    public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
    {
        int i = 0;
        var splits = from item in list
                     group item by i++ % parts into part
                     select part.AsEnumerable();
        return splits;
    }
}

A: I think you would benefit from Linq's .Chunk() method.
If you first calculate how many parts will contain the equal item count, you can chunk list and yield return each chunk, before yield returning the remaining part of list (if list is not divisible by n).
As pointed out by Enigmativity, list should be materialized as an ICollection<T> to avoid possible multiple enumeration. The materialization can be obtained by trying to cast list to an ICollection<T>, and falling back to calling list.ToList() if that is unsuccessful.
A possible implementation of your extension method is hence:
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
{
    var collection = list is ICollection<T> c
        ? c
        : list.ToList();

    var itemCount = collection.Count;

    // return all items if source list is too short to split up
    if (itemCount < parts)
    {
        yield return collection;
        yield break;
    }

    var itemsInEachChunk = itemCount / parts;

    var chunks = itemCount % parts == 0
        ? parts
        : parts - 1;

    var itemsToChunk = chunks * itemsInEachChunk;

    foreach (var chunk in collection.Take(itemsToChunk).Chunk(itemsInEachChunk))
    {
        yield return chunk;
    }

    if (itemsToChunk < itemCount)
    {
        yield return collection.Skip(itemsToChunk);
    }
}

Example fiddle here.

A: I see two issues with your code. First, the way you're outputting the results, it's impossible to tell the groupings of the values since you're just outputing each one on its own line.
This could be resolved buy using Console.Write for each value in a group, and then adding a Console.WriteLine() when the group is done. This way the values from each group are displayed on a separate line. We also might want to pad the values so they line up nicely by getting the length of the largest value and passing that to the PadRight method:
static void Main(string[] args)
{
    var numItems = 18;
    var splitBy = 3;

    var input = Enumerable.Range(0, numItems).ToList();
    var results = input.Split(splitBy);

    // Get the length of the largest value to use for padding smaller values,
    // so all the columns will line up when we display the results
    var padValue = input.Max().ToString().Length + 1;

    foreach (var group in results)
    {
        foreach (var item in group)
        {
            Console.Write($"{item}".PadRight(padValue));
        }

        Console.WriteLine();
    }

    Console.Write("\n\nDone. Press any key to exit...");
    Console.ReadKey();
}

Now your results look pretty good, except we can see that the numbers are not grouped as we expect:
0  3  6  9  12 15
1  4  7  10 13 16
2  5  8  11 14 17

The reason for this is that we're grouping by the remainder of each item divided by the number of parts. So, the first group contains all numbers whose remainder after being divided by 3 is 0, the second is all items whose remainder is 1, etc.
To resolve this, we should instead divide the index of the item by the number of items in a row (the number of columns).
In other words, 18 items divided by 3 rows will result in 6 items per row. With integer division, all the indexes from 0 to 5 will have a remainder of 0 when divided by 6, all the indexes from 6 to 11 will have a remainder of 1 when divided by 6, and all the indexes from 12 to 17 will have a remainder of 2 when divided by 6.
However, we also have to be able to handle the overflow numbers. One way to do this is to check if the index is greater than or equal to rows * columns (i.e. it would end up on a new row instead of on the last row). If this is true, then we set it to the last row.
I'm not great at linq so there may be a better way to write this, but we can modify our extension method like so:
public static IEnumerable<IEnumerable<T>> Split<T>(
    this IEnumerable<T> list, int parts)
{
    int numItems = list.Count();
    int columns = numItems / parts;
    int overflow = numItems % parts;

    int index = 0;

    return from item in list
           group item by
               index++ >= (parts * columns) ? parts - 1 : (index - 1) / columns
           into part
           select part.AsEnumerable();
}

And now our results look better:
// For 18 items split into 3
0  1  2  3  4  5
6  7  8  9  10 11
12 13 14 15 16 17

// For 25 items split into 7
0  1  2
3  4  5
6  7  8
9  10 11
12 13 14
15 16 17
18 19 20 21 22 23 24

A: This should work.
So each list should  (ideally) have x/n elements,
where x=> No. of elements in the list &
n=> No. of lists it has to be split into
If x isn't divisible by n, then each list should have x/n (rounded down to the nearest integer). Let that no. be 'y'. While the last list should have x - y*(n - 1). Let that no. be 'z'.
What the first for-loop does is it repeats the process of creating a list with the appropriate no. of elements n times.
The if-else block is there to see if the list getting created is the last one or not. If it's the last one, it has z items. If not, it has y items.
The nested for-loops add the list items into "sub-lists" (List) which will then be added to the main list (List<List>) that is to be returned.
This solution is (noticeably) different from your signature and the other solutions offered. I used this approach because the code is (arguably) easier to understand albeit longer. When I used to look for solutions, I used to apply solutions where I could understand exactly what was going on. I wasn't able to fully understand the other solutions to this question (yet to get a proper hang of programming) so I presented the one I wrote below in case you were to end up in the same predicament.
Let me know if I should make any changes.
static class Program
    {
    static void Main(string[] args)
        {
        var input = new List<String>();
        for (int k = 0; k < 18; ++k)
            {
            input.Add(k.ToString());
            }
        var result = SplitList(input, 5);//I've used 5 but it can be any number

        foreach (var resul in result)
            {
            foreach (var res in result)
                {
                Console.WriteLine(res);
                }
            }
        }

    public static List<List<string>> SplitList (List<string> origList, int n)
        {//"n" is the number of parts you want to split your list into
        int splitLength = origList.Count / n;    //splitLength is no. of items in each list bar the last one. (In case of overflow)
        List<List<string>> listCollection = new List<List<string>>();

        for ( int i = 0; i < n; i++ )
            {
            List<string> tempStrList = new List<string>();

            if ( i < n - 1 )
                {
                for ( int j = i * splitLength; j < (i + 1) * splitLength; j++ )
                    {
                    tempStrList.Add(origList[j]);
                    }
                }
            else
                {
                for ( int j = i * splitLength; j < origList.Count; j++ )
                    {
                    tempStrList.Add(origList[j]);
                    }
                }

            listCollection.Add(tempStrList);
            }

        return listCollection;
        }
    }


text:
Q: Multifactor ANOVA- What is the connection between sample size and orthogonality? It is commonly stated that "balanced" designs in multifactor ANOVA (equal sample sizes in each group) have "orthogonal" factors. In other regression contexts, I totally get the connection between the geometry (things at right angles to each other) and the statistics. Like how a residual vector is orthogonal to a least-squares solution because the latter is the projection of the response variable vector onto the column space of the design matrix. That makes perfect sense to me.
But for ANOVA, I'm at a loss. I can't figure out how factors in ANOVA correspond to some kind of geometric objects that are orthogonal. Even more perplexing is how this can only depend on the sample size in each group.
What am I missing? Can someone explain what geometric objects are supposed to correspond to "orthogonal" factors and why their orthogonality is a function only of the sample size in each group?

A: Let's take a simple 2x2 ANOVA, with two factors, x1 and x2, each of which can take one of two values, 0 and 1. There are therefore four cells in the design: [x1=0,x2=0], [0,1], [1,0], and [1,1].
In a balanced design, there are equal numbers of cases in each cell.

As a result, the two factors, x1 and x2 are uncorrelated (orthogonal), $r = 0$.
In an unbalanced design, there are more cases in some cells than others.

As a result, the factors are not uncorrelated, and so not orthogonal:
in this example, cases where x1=1 are more likely to have x2=1, $r \approx .25$.
Demo code
library(tidyverse)
plot_design = function(df){
  long = df %>%
    mutate(.index=1:n()) %>%
    pivot_longer(-.index)
  ggplot(long, aes(name, -.index, fill = factor(value))) +
    geom_tile(color = 'white') +
    scale_fill_manual(values = c('grey', 'black')) +
    labs(x = 'Column', y = 'Row', fill = 'Value') +
    scale_y_continuous(labels = function(x) -x) +
    theme_minimal() + coord_fixed(ratio = .1)
}

balanced_ns = c(20, 20, 20, 20)
df_balanced = data.frame(
  x1 = rep(c(0, 0, 1,1), times = balanced_ns),
  x2 = rep(c(0, 1, 0, 1), times = balanced_ns)
)
plot_design(df_balanced) + labs(title = 'Balanced design') # First figure, above
cor(df_balanced)
##    x1 x2
## x1  1  0
## x2  0  1

unbalanced_ns = c(20, 20, 10, 30)
df_unbalanced = data.frame(
  x1 = rep(c(0, 0, 1, 1), times = unbalanced_ns),
  x2 = rep(c(0, 1, 0, 1), times = unbalanced_ns)
)
plot_design(df_unbalanced) + labs(title = 'Unbalanced design') # Second figure
cor(df_unbalanced)
##           x1        x2
## x1 1.0000000 0.2581989
## x2 0.2581989 1.0000000
```

A: I'll take a stab at this one, but first from a non-geometric perspective. In probability, we estimate the joint probability of two random events using the following equation:
$p(A\cap B) = p(A)\times p(B)$
We can use this equation to also calculate the deviations from independence:
$\text{observed} - \text{expected under independence} = P(A\cap B) - P(A)\times P(B)$
where $P$ represents the observed probability. (Sorry if my notation is terrible...it's not my forte).
This is exactly what the traditional chi-square test of independence uses, but it replaces probabilities with counts:
expected = row sum $\times$ col sums / table sum
So, with an ANOVA, if your sample sizes are equal in each cell, they will be independent (orthogonal) because row sums $\times$ colsums / table sums will always exactly equal the expected probability as with a chi-square test.
Or, a different way to think about it is this: assuming a random process, it would be highly unusual to have a sample where the number of males/females over 6 feet tall are equal. Why would that be unusual? Because height is NOT independent of gender.
Likewise, for an ANOVA, if we have uncorrelated variables, they should have equal sample sizes. If they're correlated, they should not.
Make sense?
Geometric Explanation
This may be better to "see" than to explain. Let's say we have two factors (a and b) where the sample sizes are the same. The R code below generates the data and plots it. If we plot a against b (or vice versa), the best fitted regression line is exactly flat:
a = c(rep(c(1,2), times=6))
b = c(rep(1, times=6), rep(2, times=6))
d = data.frame(a=a,b=b)
table(a,b) #verify orthogonality
require(ggplot2)
ggplot(data=d, aes(x=a, y=b)) +
  geom_jitter(width=.1, height = .1) +
  geom_smooth(method="lm") # flat line

If we now allow different sample sizes in each group, there's now a positive slope:
a = c(rep(c(1,2), times=6))
b = c(rep(1, times=3), rep(2, times=9))
d = data.frame(a=a,b=b)
table(a,b) #verify nonorthogonality
ggplot(data=d, aes(x=a, y=b)) +
  geom_jitter(width=.1, height = .1) +
  geom_smooth(method="lm") # nonflat line


text:
Q: Django 1.11.9 and PosgreSQL10 on Docker makes duplicated tables Today I got a weird behaviour. I am not sure this problem comes from AWS EC2 or Django itself. Today AWS shows me significant lack and poor performance.
I use PostgreSQL10 on Docker
And what should I do with replicated tables?
I can not Drop it. I had tried.

A: Thanks to @renqHIT. During the way to rename it I backed/restore on my local computer and they are gone!

A: Rename and delete the renamed table usually can solve this problem.
How do you make these tables, by Django's syncdb command?
I suppose it's a Django usage problem.
Two table with same name may come from different namespace, one is permanent table and the other is temperate table.
See this post


text:
Q: Correlation or Causality between two time series considering a sliding window I would perform a correlation and causality analysis between two time series considering only a little window of samples. In this way I would try to find if there is a correlation or a causality between the two time series without considering the whole data samples.
My problem is to detect as quickly as possible if the increase/decrease in one time series is causing an increase/decrease in the other time series.
For example, considering the figure below I would like to identify rapidly if the increase of the blu time series is correlated (or causing) to the decrease of the green time series.
I have already considered the running correlation with sliding windows and it is a good approach when I have considered windows containing at least 10 samples collected every minutes. However, because I would like to detect this situation more quickly, I have reduced the sample time to two seconds and obviously the running correlation does not work well due to high oscillation of the values of the samples  in the window.
Can anyone suggest me a valid statistic solution? there is other useful method to detect as quickly as possible this situation?
Thanks in advance


text:
Q: Concatenation of arrays How do I parse each index of 3 arrays of string and concatenate each value by same index, to have only one array?
Example input :
index 0 of array 1 value : "Car"
index 0 of array 2 value : "red"
index 0 of array 3 value : "Nikolai"

Expected output, array (all in one) :
index 0 value : "Car , red , Nikolai"

A: For the generic case where you want this concatenation also to happen for index 1, index 2, ...etc, you can use this ES6 function:

function joinTransposed(delim, ...args) {
    return args[0].map( (_, i) => args.map(w => w[i]).join(delim) );
}

// Example
var a = ["c", "y", "s", "h"],
    b = ["a", "o", "e", "i"],
    c = ["n", "u", "e", "m"];

var res = joinTransposed(' , ', a, b, c);
console.log(res);

A: Add the arrays in an array, iterate on the arrays and get the first value of it that you will concatenate in a String variable.
As last add this String variable it in a new array.
var arr1 = ['Car', 'red', 'Nikolai'];
var arr2 = ['Car', 'red', 'Nikolai'];
var arr3 = ['Car', 'red', 'Nikolai'];
var arrs = [arr1, arr2, arr3];

var concatenatedString = "";
arrs.forEach(function(arr) {
   if (concatenatedString.length > 0){
     concatenatedString += ", ";
   }
   concatenatedString += arr[0];
});

var result = [concatenatedString];

A: Wouldn't it be possible with a for loop?
for (var i = 0; i < array.length; i++) {
    newArray[i] = Array1[i] + "," + Array2[i] + "," + Array3[i]
}

A: You can use a simple for loop. Just mind that the arrays may not be of the same size.
var a = ["a", "aa", "aaa"];
var b = ["b", "bb", "bbb"];
var c = ["c", "cc"];

var all = [];

for (var i = 0; i < Math.min(a.length, b.length, c.length); i++) {
    all[i] = [a[i], b[i], c[i]].join(" , ");
}

A: With ES6 you can spread array values into a new array. So you could do something like this:
const vehicles = ["Car"];
const colors = ["Red"];
const names = ["Nikolai"];

const combined = [...vehicles, ...colors, ...names];

Sorry, now I re-read your question you only would like to combine the same index of each array:
function returnCombined(index) {
  return [vehicles[index], colors[index], names[index]];
}

A: This is a good case for .map() and .join().
var result = array.map(a => a[0]).join(", ");

Or .reduce(), though you need to .slice() the trailing comma off the result.
var result = array.reduce((s,a) => s + a[0] + ", ", "").slice(0, -2);


text:
Q: Do I need the project test to be accepted into the app store? I saw that there was a project test in the application right at the bottom of the page, Do i need to have that file to be able to be accepted in iTunes and what is that by the way?
How do I remove it if needed?
And lastly both the files are highlighted red, is that normal?

A: No, you do not need the Test project to submit your app to Apple. It is merely added for your convenience since most projects need some amount of unit testing. But it's purely optional. You can remove it either from Xcode or Finder.
And yes, it's OK for items under the "Products" section to be red. That just means that the product(s) haven't been built yet. You can ignore that. They will turn from red to black after you deploy to device or Archive the project later.


text:
Q: Fade HTML element with raw javascript It's my second question of the day related to the same problem, so I apologize for that.
I was able to put together a function to "fade out" an element, and it works just fine, my problem is that when I try to reverse it, so the element "fades in" it does not work.
I've tried to change the obvious, but I can't understand what I'm doing wrong.
My code so far is as follows:
Given I have a "div" like so:

The JavaScript function that I'm using to fade it out is:
var getElement = document.getElementById('test');
function fadeOut(elem, speed){
if(!elem.style.opacity){
    elem.style.opacity = 1;
}
var desvanecer = setInterval(function(){
    elem.style.opacity -= .02;
    if(elem.style.opacity < 0){
        clearInterval(desvanecer);
    }
}, speed / 50);
}
fadeOut(getElement, 500);

Could somebody take a look at this and let me know what I'm doing wrong, all I want to do is "FADE IN" an element to an opacity equal to "1".
By the way, I can't use jQuery, however I'm eager to learn this way.
Thanks
My attemp to reverse the function is as follows:
var getElement = document.getElementById('test');
function fadeIn(elem, speed){
if(elem.style.opacity){
    elem.style.opacity = 0;
}
var desvanecer = setInterval(function(){
    elem.style.opacity += .02;
    if(elem.style.opacity > 1){
        clearInterval(desvanecer);
    }
}, speed / 50);
}
fadeIn(getElement, 500);

A: setInterval runs in a global scope, so you need to define the timer relative to the window.
You can't concatinate the string value returned from the style property and
expect a number- you'll get '0.02.02.02.02'
Coerce a number out of the string, then add the .02.
It will work in some browsers, but IE before 9 needs a different expression
to set and read opacity.
function fadeIn(elem, speed){
    if(elem.style){
        elem.style.opacity= '0';
    }
    window.fadetimer= setInterval(function(){
        elem.style.opacity= +(elem.style.opacity)+.02;
        if(elem.style.opacity> 1){
            clearInterval(fadetimer);
        }
    },
    speed);
}


text:
Q: Creating packages from serialised items Does anyone have a code snippet or information for creating a Sitecore package from serialised .item files? Other requirements are that this needs to be accomplished without a Sitecore context or access to any of the Sitecore databases.

A: Check out Sitecore Courier Shared Source module. It simply compares two folders with serialized items and creates a diff package.


text:
Q: Progressbar circular y Webview Tengo un webview pero toma unos segundos en cargar, deseo incluir un progressbar mientras la pagina web se carga y por alguna excepción mostrar un mensaje al no poder cargar el webview con el contenido.
XML
<?xml version="1.0" encoding="utf-8"?>

<WebView

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/websantotomas"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginLeft="516dp"
    android:layout_marginStart="516dp" />

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:max="500"
    android:progress="0"
    android:progressDrawable="@drawable/circular"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="142dp" />

Clase Java
web = (WebView) findViewById(R.id.websantotomas);
    assert web != null;
web.loadUrl("http://pagina.com");
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
        ObjectAnimator animation = ObjectAnimator.ofInt (progressBar, "progress", 0, 500);
        animation.setDuration (3000);
        animation.setInterpolator (new DecelerateInterpolator());
        animation.start ();
        assert progressBar != null;
        progressBar.clearAnimation();

A: Te dejo mi ejemplo.
Tienes que definir el pogressbar en mi caso un progressWheel en el toolar, asi:
    <LinearLayout
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="end">
        <com.pnikosis.materialishprogress.ProgressWheel
            android:id="@+id/progress1"
            android:layout_width="35dp"
            android:layout_height="35dp"
            app:matProg_progressIndeterminate="true"
            app:matProg_barColor="@android:color/white"
            android:visibility="gone"/><!-- gone -->

    </LinearLayout>

Y la activity volverá visible o invisible(gone) si el sitio esta cargando
package cl.ejemplo.sitioweb.fragmentos;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.pnikosis.materialishprogress.ProgressWheel;

import cl.ejemplo.sitioweb.R;
import cl.ejemplo.sitioweb.actividades.Root;     //activity que contiene al fragment
import cl.ejemplo.sitioweb.utilidades.Datos;

public class ejemploWeb extends Fragment {

    private final static String TAG = ">>> ejemploWeb";
    public Root fragmentActivity;
    private ProgressWheel progressPw;
    private WebView intranetWv;
    private MenuItem actualizar;
    //private Menu menu;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        fragmentActivity = (Root) super.getActivity();
        final LinearLayout myLinearLayout = (LinearLayout) inflater.inflate(R.layout.fragment_intranet, container, false);
        Log.d(">>>", TAG);

        Toolbar toolbar = (Toolbar) fragmentActivity.findViewById(R.id.toolbar);
        progressPw = (ProgressWheel) toolbar.findViewById(R.id.progress1);

        intranetWv = (WebView) myLinearLayout.findViewById(R.id.intranet_wv);
        intranetWv.getSettings().setJavaScriptEnabled(true); //Funciona con JS el sitio
        intranetWv.getSettings().setDomStorageEnabled(true);
        intranetWv.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                try{
                    //Log.d(TAG, "onPageStarted >>> " + url);
                    super.onPageStarted(view, url, favicon);
                    if (url != null && url.substring(url.length()-5).toLowerCase().contains(".pdf") && !url.toLowerCase().contains("docs.google.com")) {
                        intranetWv.loadUrl("https://docs.google.com/gview?embedded=true&url=" + url);
                        //https://docs.google.com/viewer?url=
                    }
                    else if (url != null && url.substring(url.length()-5).toLowerCase().contains(".xls") && !url.toLowerCase().contains("drive.google.com")) {
                        intranetWv.loadUrl("https://drive.google.com/viewerng/viewer?embedded=true&url=" + url);
                    }
                    progressPw.setVisibility(View.VISIBLE);
                    actualizar.setVisible(false);
                }
                catch(Exception e){
                    //e.printStackTrace();
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                //Log.d(TAG, "onPageFinished >>> " + url);
                try {
                    progressPw.setVisibility(View.GONE);    //GONE
                    actualizar.setVisible(true);
                }catch (Exception e){
                    //e.printStackTrace();
                }
            }

            public boolean shouldOverrideUrlLoading(WebView view,String url) {
                if (url.startsWith("mailto:")) {
                    try{
                        Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
                        startActivity(i);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                } else if (!url.contains("ejemplo.cl")) {    //Si no esta en la intranet, abre el navegador
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } else {
                    view.loadUrl(url);
                }
                return true;
            }

        });
        if (Build.VERSION.SDK_INT >= 21) {
            intranetWv.getSettings().setMixedContentMode( WebSettings.MIXED_CONTENT_ALWAYS_ALLOW );
        }
        //Permite Zoom en la WebView y ocultamos botones
        intranetWv.setInitialScale(150);
        intranetWv.getSettings().setBuiltInZoomControls(true);
        intranetWv.getSettings().setSupportZoom(true);
        intranetWv.getSettings().setDisplayZoomControls(false);
        intranetWv.loadUrl(getString(R.string.url_intranet));
        intranetWv.clearCache(true);

        //Poder usar el botón volver del celular en el fragment
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message message) {
                switch (message.what) {
                    case 1:{
                        intranetWv.goBack();
                    }break;
                }
            }
        };
        intranetWv.setOnKeyListener(new View.OnKeyListener(){

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == MotionEvent.ACTION_UP && intranetWv.canGoBack()) {
                    handler.sendEmptyMessage(1);
                    return true;
                }

                return false;
            }

        });

        return myLinearLayout;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); // super para el menú
        setHasOptionsMenu(true);            // que tenga opciones el menú
    }

    @Override
    public void onStop() {
        super.onStop(); // super para el menú
        progressPw.setVisibility(View.GONE);    //GONE
    }

    //Definimos que iconos del menu accionan como se hace normalmente en onOptionsItemSelected y onCreateOptionsMenu //definimos el menuItem
    public void onPrepareOptionsMenu(Menu menu){
        menu.clear();
        Toolbar toolbar= (Toolbar) getActivity().findViewById(R.id.toolbar);
        toolbar.inflateMenu(R.menu.menu_intranet);
        actualizar = toolbar.getMenu().findItem(R.id.actualizar_intranet_item);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {

                switch (menuItem.getItemId()){
                    case R.id.actualizar_intranet_item:
                        Log.d(TAG, "Reload");
                        intranetWv.reload();
                        return true;
                    default:
                        return false;
                }
            }
        });
    }
}


text:
Q: Hierarchical graph with parallel edges I need to create a graph from a set of data. I have sifted through countless SO questions but not been able to find a solution that fits all the must-have requirements.
What's needed:
http://i.imgur.com/hzQHD07.png
Must-have requirements:

*

*Hierarchical placement of nodes

*Ordered placement of nodes, i.e. 'A' should be to the left of 'B'

*Parallel edges between nodes

*Minimum length of edge (to avoid label encroaching upon node, as in D--E)

*Programmatic solution, requires little to no editing of dot file for desired result

*Scale to a few thousand nodes

Very-important requirements:

*Straight lines (or ortho)

*Head and tail labels

*Option to display arrowheads

The graph could be undirected or directed but should meet the above requirements.
import networkx as nx
g = nx.Graph()

g.add_edge(node1,node3,headlabel='label 2', taillabel='label 1',fontsize='10')
g.add_edge(node1,node4,headlabel='label 4', taillabel='label 3',fontsize='10')
g.add_edge(node2,node5,headlabel='label 6', taillabel='label 5',fontsize='10')
g.add_edge(node2,node6,headlabel='label 8', taillabel='label 7',fontsize='10')
g.add_edge(node4,node5,headlabel='really long label', taillabel='really long label',fontsize='10')
g.add_edge(node4,node5)
g.add_edge(node3,node7)
g.add_edge(node7,node8)
g.add_edge(node7,node8)
g.add_edge(node4,node8)
g.add_edge(node5,node8)
g.add_edge(node5,node9,headlabel='label 12', taillabel='label 11',fontsize='10')
g.add_edge(node6,node9,headlabel='label 10', taillabel='label 9',fontsize='10')

A = nx.to_agraph(g)
A.add_subgraph([node1,node2],rank='same')
A.add_subgraph([node3,node4,node5,node6],rank='same')
A.add_subgraph([node7,node8,node9],rank='same')
A.draw('example2.png', prog='dot')

The above produces: http://i.imgur.com/1e9YTnQ.png
Of course parallel edges are not shown with the above method. I tried using a MultiDiGraph that supports parallel edges but can't get it work due to the following error, despite defining unique keys for the parallel edges (not shown in code).
Traceback (most recent call last):
  File "example3.py", line 31, in <module>
    A = nx.to_agraph(g)
  File "C:\python27\lib\site-packages\networkx-1.11rc1-py2.7.egg\networkx\drawing\nx_agraph.py", line 152, in to_agraph
    A.add_edge(u,v,key=str(key),**str_edgedata)
  File "C:\python27\lib\site-packages\pygraphviz\agraph.py", line 481, in add_edge
    eh = gv.agedge(self.handle, uh, vh, key, _Action.find)
KeyError: 'agedge: no key'

Using graphviz without networkx, as shown below, gives me the parallel edges but hierarchy and node ordering is gone. I know hierarchy can be fixed by adding rank=same to the dot file but I'd prefer to do it programmatically.
import graphviz as gv
g = gv.Graph(format='png')

g.edge(node1,node3,headlabel='label 2', taillabel='label 1',fontsize='10')
g.edge(node1,node4,headlabel='label 4', taillabel='label 3',fontsize='10')
g.edge(node2,node5,headlabel='label 6', taillabel='label 5',fontsize='10')
g.edge(node2,node6,headlabel='label 8', taillabel='label 7',fontsize='10')
g.edge(node4,node5,headlabel='really long label', taillabel='really long label',fontsize='10')
g.edge(node4,node5)
g.edge(node3,node7)
g.edge(node7,node8)
g.edge(node7,node8)
g.edge(node4,node8)
g.edge(node5,node8)
g.edge(node5,node9,headlabel='label 12', taillabel='label 11',fontsize='10')
g.edge(node6,node9,headlabel='label 10', taillabel='label 9',fontsize='10')

g.render('example')

Can't post the image link for the last rendering because of insufficient reputation.


text:
Q: Initializing the added columns to a resizable 2D vector I want to increase the number of columns of a 2D vector. Here is my sample code:
#include <vector>
using namespace std;
int main ()
{
    vector < vector <double> > U (5, vector <double> (1, 0));
    for (int ii = 0; ii < 5; ii++)
    {
        U [ii] [0] = ii + 1;
    }
    U . resize (5, vector <double> (2));
    return 0;
}

This adds an uninitialized column to the vector U, but I need the new column be initialized to zero. How can I do this?
(I use Dev-C++ 5.6.3)

A: You will need to first resize any existing rows, changing the number of columns:
for(vector<double> & v : m)
  v.resize(v.cend(), <new column count>-<old column count>, 0);

After that you add any new rows:
m.insert(m.cend(), <new row count>-<old row count>, vector<double>(<new column count>, 0));


text:
Q: graph of elliptic curve inside projective space Lets assume an elliptic curve intersect a curve inside a projective space. How does the graph of an elliptic curve (complex curve) locally look like at the point of intersection. For example how does it look like inside a line bundle of $\mathbb{P}_2$ at the point of intersection?

A: Let $E$, $C$ be your curves and suppose they intersect at a point $P$.  I think asking for a description of $E$ "locally" at $P$ must mean that you want to understand the closed subscheme of $\mathcal{O}_{C, P}$ which is defined by an equation for $E$ in an affine neighborhood of $P$, say $f(\underline{x}) = 0$.  Of course, if your curve is regular, then $\mathcal{O}_{C, P}$ is a discrete valuation ring and the ideal of $\mathcal{O}_{C, P}$ that $f$ generates will just be a power of the maximal ideal, say $(f) = \mathfrak{m}^k$.  Then I would say that $E$ locally looks like $z\mapsto z^k$.  Further, this business of thinking inside of the local ring is necessary because you can't make algebraic sense of a curve locally looking like $\mathbb{A}_1$ until you go all the way to the local ring.

A: I'm not quite sure about the formulation of the question: but there is something worth saying anyway, since it isn't often emphasised in basic texts. The points of order 3 can be identified with the inflection points of a plane cubic E (or, more accurately, taking one inflection point as origin on E for the group law, the nine 3-torsion points are the nine inflection point of a smooth plane cubic). There is a generalisation for the embedding of E in projective space of dimension n - 1 (essentially unique if E spans the space): the n-torsion is picked out by inflection of order n (higher tangency of a hyperplane).


text:
Q: Maintaining Rails environment through multiple deployment phases I've been using Capistrano to deploy several rails apps to a single EC2 instance.  The apps are all served with Apache + Passenger.  The deployment phases form most of them is as follows:
-- fetch code, stage in a "releases/[timestamp]" subdirectory of the main app directory.
-- run bundler for staged release
-- run migrations for staged release
-- run asset compilation ("assets:precompile") rake task for staged release
-- restart the delayed_job task queue processing daemon and any other background processes
-- symlink the staged release to "current" (the passenger web root)
-- restart passenger (by touching "tmp/restart" in app directory)
This is a very standard Rails deployment procedure.  I've noticed that a huge bottleneck in it is loading of the rails environment for each task that requires it.  For one of my larger apps, environment loading takes ~40 seconds or more and that's repeated n times for the n tasks that require the rails environment (running bundler, migrations, asset compilation, delayed_job daemon).  Forgive if this is a naive question, but I was wondering if there is an easy way to load the environment only once for all of these tasks (preferably easier than consolidating the implementations of all of these tasks/jobs into a single rake task that loads the environment).

A: I suggest looking into vagrant for this.  It's a quick and easy way to deploy.  It utilizes chef for customizing the vagrant box.  I think you'll want to create your own recipies (a chef thing..) to hit most of the items you've listed.  Once that's done ur good to go.

A: Update: I ultimately concocted my own solution for this which works fine. Instead of running each of the commands that depend on the rails environment individually from the shell (using the Capistrano "run" method), I've bundled them together into a single rake task that depends on the rails environment. Where I previously ran "rake db:migrate", then "rake assets:precompile", etc., I now run a single rake task whose body includes "Rake::Task['db:migrate'].invoke" and "Rake::Task['assets:precompile'].invoke". The environment now only gets loaded once.


text:
Q: net.snowflake.client.jdbc.SnowflakeSQLException: SQL access control error: Insufficient privileges to operate on schema 'PUBLIC' I am getting error when trying to use the dataframe.
This is piece of the code that Im running in databricks notebook in pyspark to get the data from snowflake
query = "SELECT * FROM TEST_TABLE LIMIT 10"
  SNOWFLAKE_SOURCE_NAME = "net.snowflake.spark.snowflake"
  df = spark.read.format(SNOWFLAKE_SOURCE_NAME).options(**sfOptions).option("query", query).load()
  print(type(df))
  print(df.count())
  print((df.count(), len(df.columns)))

Size of the dataframe and column count is correct.
when I do
df.show()

I am getting below error
  Py4JJavaError: An error occurred while calling o1263.showString.
    : net.snowflake.client.jdbc.SnowflakeSQLException: SQL access control error:
    Insufficient privileges to operate on schema 'PUBLIC'
        at net.snowflake.client.jdbc.SnowflakeUtil.checkErrorAndThrowExceptionSub(SnowflakeUtil.java:152)
        at net.snowflake.client.jdbc.SnowflakeUtil.checkErrorAndThrowException(SnowflakeUtil.java:77)
        at net.snowflake.client.core.StmtUtil.pollForOutput(StmtUtil.java:495)
        at net.snowflake.client.core.StmtUtil.execute(StmtUtil.java:372)
        at net.snowflake.client.core.SFStatement.executeHelper(SFStatement.java:575)
        at net.snowflake.client.core.SFStatement.executeQueryInternal(SFStatement.java:265)
        at net.snowflake.client.core.SFStatement.executeQuery(SFStatement.java:203)
        at net.snowflake.client.core.SFStatement.execute(SFStatement.java:874)
        at net.snowflake.client.jdbc.SnowflakeStatementV1.executeQueryInternal(SnowflakeStatementV1.java:259)
        at net.snowflake.client.jdbc.SnowflakePreparedStatementV1.executeQuery(SnowflakePreparedStatementV1.java:181)
        at net.snowflake.spark.snowflake.JDBCWrapper$$anonfun$executePreparedQueryInterruptibly$1.apply(SnowflakeJDBCWrapper.scala:317)
        at net.snowflake.spark.snowflake.JDBCWrapper$$anonfun$executePreparedQueryInterruptibly$1.apply(SnowflakeJDBCWrapper.scala:315)
        at net.snowflake.spark.snowflake.JDBCWrapper$$anonfun$1.apply(SnowflakeJDBCWrapper.scala:355)
        at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
        at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

Thanks in advance. Please help me.
EDIT: Issue was because I was not authorised to create the temporary stage when running the query in the snowflake through spark.
Issue was resolved when I changed the snowflake client options like below:
sfOptions = {
        "sfURL": "xxx.snowflakecomputing.com",
        "sfUser": "xxxx",
        "sfDatabase": "TEMP", <- changed this to TEMP from PUBLIC
        "sfSchema": "PUBLIC",
        "sfWarehouse": "xxx",
        "sfRole": "xxxx",
        "pem_private_key": private_key
    }

They authorised devs to create temporary stage in the TEMP DB only.

A: Maybe executing the follow statements to grant access privileges is helping you. Reason could be that you granted select privileges to the table object but missed to grant usage privileges on database and/or schema level.
GRANT USAGE ON DATABASE [database] TO ROLE [role];
GRANT USAGE ON SCHEMA [database].PUBLIC TO ROLE [role];
GRANT SELECT ON TABLE [database].PUBLIC.[table] TO ROLE [role];

Docs: https://docs.snowflake.com/en/sql-reference/sql/grant-privilege.html


text:
Q: Add Custom Attribute to show on Checkout page I would like to add the custom attribute i created (delivery) to show on the shipping method section of the checkout page.
I have the following code working but when more than one item is being purchased it just lists all the delivery times next to each other. like 3 days 5 days 1 week
<?php $cartItems = Mage::getSingleton('checkout/session')
          ->getQuote()
          ->getAllItems();
    foreach ($cartItems as $item) {
        $ean = Mage::getModel('catalog/product')->load($item->getProduct()->getId())->getAttributeText('delivery');
        echo $ean;
    }?>

I would then want to pull the product name so What im looking for is
Product Name:Delivery Time
or if multiple items
Product Name:Delivery Time
Product Name:Delivery Time

A: Couldn't you just do:
<?php $cartItems = Mage::getSingleton('checkout/session')
      ->getQuote()
      ->getAllItems();
foreach ($cartItems as $item) {
    $product = Mage::getModel('catalog/product')->load($item->getProduct()->getId());
    $ean = $product->getAttributeText('delivery');
    $name =  $product->getName();
    echo $name . ':' . $ean;
}?>


text:
Q: Prove this is a topology in $\mathbb{Z}^+$ Let $U\subset \mathbb{Z}^+$. Define $U$ to be open if it satisfies the condition: $n\in U\implies$ every divisor of $n$ belongs to $U$ Prove this is a topology in $\mathbb{Z}^+$
My attempt
Let $\tau=\{U_n\subset \mathbb{Z}^+ | n=x.q\,\,\,  \forall x,q\in \mathbb{Z}^+\}$. We need prove $\tau$ is a topology, for this i need prove that:

*

*$\bigcup_nU_n\in\tau$,

*$ \bigcap_{i=1}^nU_i\in\tau$,

*$ \mathbb{Z}^+,\emptyset\in\tau.$

*

*Let $x\in\bigcup_nU_n$ then $x\in U_n$ and this implies for hypothesys for $n\in U_n$ exists $q$ such that $n=x.q$. As $x$ is arbitrary, then $ \bigcup_nU_n$ is a open set, and this implies $\bigcup_nU_n\in \tau$.

*Let $x\in \bigcap_{i=1}^nU_i$ then $x\in U_i\forall i\in\mathbb{N}$ this implies for $n\in U_i $ exists $q$ such that $n=x.q$. Then,   $\bigcap_{i=1}^nU_i\in \tau$.
I'm stuck trying to prove $\emptyset\in \tau$ and the other set.
Can someone help me with this exercise?

A: The sets $U_n=\{d:d|n\} $ form only a basis for the given topology, they are not closed under arbitrary union.
Alternatively, the empty set and $\Bbb Z^+$ clearly satisfy the original condition.

A: Firstly, a typical set $U$ as described in the question would be an element of:
$ \tau = \{ U \subset \mathbb{Z}^+ \mid$ if $x \in U$ and $y \in \mathbb{Z}^+$ such that $y \mid x$ then $y \in U$}
In this form, $\emptyset$ satisfies the condition trivially. Also the set $\mathbb{Z}^+$ contains every possible divisor of any element, so $\mathbb{Z}^+ \in \tau$ as well.

As for the other conditions:

*

*Let $\{ U_{\alpha} \} \subseteq \tau$. We would like to show that $\bigcup U_\alpha \in \tau$. Let $x \in \bigcup U_\alpha$. Then there exists $U_i \in \{ U_\alpha \}$ such that $x \in U_i$.
As $x \in U_i$ and $U_i \in \tau$, if $y \in \mathbb{Z}^+$ and $y \mid x$ then $y \in U_i \subseteq \bigcup U_\alpha$. So $\bigcup U_\alpha \in \tau$

*Let $\{ U_i \} \subseteq \tau$ be a finite subset of $\tau$ of order $n$. We would like to show that $\bigcap_n U_i \in \tau$. Let $x \in \bigcap_n U_i$. If $0 \leq i \leq n$, then $x \in U_i$ and $U_i \in \tau$ and hence all of the divisors of $x$ are in $U_i$. So all of the divisors of $x$ are in $\bigcap_n U_i$. So $\bigcap_n U_i \in \tau$

A: This answer provides a more general setting.

Let $X$ be a set and let $f:X\to\wp(X)$ be a function.
Now sets $U\subseteq X$ can have the following property:$$\forall x[x\in U\implies f(x)\subseteq U]$$
and $\tau\subseteq\wp(X)$ can be defined as the collection of all subsets of $X$ that have this property.
It is obvious that $\varnothing$ and $X$ have this property so that $\varnothing,X\in\tau$.
Also it is obvious that $\tau$ is closed under intersections and unions.
So $\tau$ is a topology, special in the sense that it is closed even under arbitrary intersections.
This can be applied on $X=\mathbb Z^+$ and the function $f:\mathbb Z^+\to\wp(\mathbb Z^+)$ prescribed by $n\mapsto\{k\in\mathbb Z^+\mid k\text{ divides }n\}$


text:
Q: Laurent Series expansion of $f(z)=\frac{z+8}{z^2\cdot(z-2-2i)}$
Determine the principal part of the Laurent series expansion for $$f(z)=\frac{z+8}{z^2\cdot(z-2-2i)}$$ on $\{z\in\mathbb{C}:1<\vert z\vert < 2\}$.

I think that this is not a difficult on, but I can't find the right beginning. First of all I want get this function in partial fractions, but the didn't help me a lot. I know that I have to rearrange this term into $$\frac{1}{1-...}$$ to use the geometric series.
Any hints for me to do so? Thank you a lot!

A: Hint:
Rewrite as
$$-\frac1{2(1+i)z^2}\cdot\frac{8+z}{1-\cfrac z{2(1+i)}}=-\frac{1-i}{4z^2}\cdot\frac{8+z}{1-\cfrac{(1-i)z}{4}}.$$


text:
Q: How to direct Unicorn stdout and stderr to log4r logs? I have set up log4r as per outlined here: "How to configure Log4r with Rails 3.0.x?"
However now I'm faced with unicorn not sending its output to the log4r logs. How do you do this?

A: does this comment help?

in your config, Rails isn't overriding the "file" config value of the
  outputter - the argument is "filename" :) It defaults to the name of
  the file/command that started the process. Note that any custom file
  name you specify must have a file extension, or it will fail to stick
  the date in the file name! – Nevir Aug 24 '11 at 22:05


text:
Q: When settting the CultureInfo error is returned I am developing a SharePoint Online add-in in ASP.NET MVC 5. I have three resource files with three languages that I want CultureInfo to read when the corresponding language code is returned from Shareoint. This is my code:
In the ActionResult Index:
    var returnedLangCode= WorkPlanRepo.LangSettings();
        if (returnedLangCode!= "")
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(returnedLangCode);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(returnedLangCode);

        }
        else
        {

            Thread.CurrentThread.CurrentCulture = new CultureInfo("en");
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");
        }

The method returning sharePoint Lang settings in my class workPlanRepo:
   public string LangSettings()
    {
        CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
        var twoLetterLangName = currentCulture.TwoLetterISOLanguageName;

        return twoLetterLangName;
    }

I hev three Resource files, Default is English, then I have Swedish and Danish. All Resources are set to Public. In the view I reach for the resource file like this:
  @Html.Label(CMP.ArbetsplanWeb.App_LocalResources.GlobalRes.ResetCalender ,new { @class = "btn btn-default", id = "clearCal" })

This is the errormessage:
When settting the CultureInfo error is returned. Wanted to insert img, but the upload tool dosen´t seem to work properly.

Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure "CMP.ArbetsplanWeb.App_LocalResources.GlobalRes.resources" was correctly embedded or linked into assembly "CMP.ArbetsplanWeb" at compile time, or that all the satellite assemblies required are loadable and fully signed.

Line 75:         public static string ResetCalender {
Line 76:             get {
Line 77:                 return ResourceManager.GetString("ResetCalender", resourceCulture);
Line 78:             }
Line 79:         }

MissingManifestResourceException: Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure "CMP.ArbetsplanWeb.App_LocalResources.GlobalRes.resources" was correctly embedded or linked into assembly "CMP.ArbetsplanWeb" at compile time, or that all the satellite assemblies required are loadable and fully signed.]
     System.Resources.ManifestBasedResourceGroveler.HandleResourceStreamMissing(String fileName)

I havent registerd anything in web.config or Global.asax. I now I must be doing something wrong. But cant figure out what. I found diffrent guides and docs on this but cant figure out how to useit properly.
Thanks for all the help!!

A: Solved it. I was using a ASP.NET folder for my resources. When I changed to a regular folder everything worked.


text:
Q: Angular CLI does not reload when editing component html? I'm running the app with ng serve -o.  If I edit styles.scss and hit save then the app live reloads, but editing components (TS or HTML) does not trigger a reload.
No errors show up in in the developer console or in the CLI.
Thoughts?

A: It happens because of limit of inotify watches and extra files will not be observed, you should increas amount of it.
For Debian, RedHat, or another similar Linux distribution, run:
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

For ArchLinux, run:
echo fs.inotify.max_user_watches=524288 | sudo tee /etc/sysctl.d/40-max-user-watches.conf && sudo sysctl --system


text:
Q: PHP scandir of an url How can I use scandir with an URL. Now it looks like PHP doesn't see the URL as an URL. Is there a way to use an URL in scandir?
<form action="new_exercise.php?id=<?php echo $new_id; ?>" method="post">
        <input class="" type="text" name="name_exe" required placeholder="Project naam">
        <select name="audio" required>
          <option></option>
          <?php
          $path = 'URL comes here';
          $results = scandir($path);
          foreach ($results as $result) {
              if ($result === '.' or $result === '..') continue;

              if (is_dir($path . '/' . $result)) {
                  echo "<option>" . $result . "</option>";
              }
          }
          ?>
        <select>
        <input class="btn-success" type="submit" name="submit" value="Maak nieuwe opdracht">
    </form>

A: This is not possible. scandir() and many other file operations only work local.
If you want to get a list of files on a remote server then you need a script/API on the server that will return that file list.
Just imagine what would happen if you could read all files and directories on a remote machine? Security would be realy compromised.

A: Scandir works perfectly for local directory.

scandir — List files and directories inside the specified path

But you can't get list of files onto server, because in many cases urls are not directly mapping on files (e.g., location command of nginx webserver). Also webservers usually block possibility of getting list files for directories (see this settings for apache)