text:
Q: Understanding pexpect's async properly I'm trying to write a gdb frontend using pexpect to communicate with gdb/mi. I'm new to pexpect and trying to figure out async property of expect_exact() function. I wrote a simple test which looks like this:
def attach(str):
    global p
    p=pexpect.spawnu('sudo gdb --interpreter=mi')
    p.expect_exact("(gdb) ")
    GDB_Engine.send_command("set target-async 1")
    GDB_Engine.send_command("set pagination off")
    GDB_Engine.send_command("set non-stop on")
    GDB_Engine.send_command("attach " + str + "&")

def test():
    for x in range(0,3):
        global p
        time.sleep(0.5)
        GDB_Engine.send_command("find 0x00400000,+500,1")

def send_command(str):
    global p
    p.sendline(str)
    p.expect_exact("(gdb) ",async=False)
    print(p.before)

In main I simply call attach() and then test() functions. The result is this:
find 0x00400000,+500,1
&"find 0x00400000,+500,1\n"
~"0x400006\n"
~"0x400014\n"
~"0x40002a\n"
~"0x400061\n"
~"0x400069\n"
~"0x4000a8\n"
~"0x4000b0\n"
~"0x4000d2\n"
~"0x4000da\n"
~"0x4000e8\n"
~"0x4000f2\n"
~"0x40012a\n"
~"0x40019a\n"
~"13 patterns found.\n"
^done

find 0x00400000,+500,1
&"find 0x00400000,+500,1\n"
~"0x400006\n"
~"0x400014\n"
~"0x40002a\n"
~"0x400061\n"
~"0x400069\n"
~"0x4000a8\n"
~"0x4000b0\n"
~"0x4000d2\n"
~"0x4000da\n"
~"0x4000e8\n"
~"0x4000f2\n"
~"0x40012a\n"
~"0x40019a\n"
~"13 patterns found.\n"
^done

find 0x00400000,+500,1
&"find 0x00400000,+500,1\n"
~"0x400006\n"
~"0x400014\n"
~"0x40002a\n"
~"0x400061\n"
~"0x400069\n"
~"0x4000a8\n"
~"0x4000b0\n"
~"0x4000d2\n"
~"0x4000da\n"
~"0x4000e8\n"
~"0x4000f2\n"
~"0x40012a\n"
~"0x40019a\n"
~"13 patterns found.\n"
^done

Works as expected, but if I pass the argument async as True in the function send_command(), the result output becomes something like this:
=thread-group-added,id="i1"
~"GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1\n"
~"Copyright (C) 2014 Free Software Foundation, Inc.\n"
~"License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"\nand \"show warranty\" for details.\n"
~"This GDB was configured as \"x86_64-linux-gnu\".\nType \"show configuration\" for configuration details."
~"\nFor bug reporting instructions, please see:\n"
~"<http://www.gnu.org/software/gdb/bugs/>.\n"
~"Find the GDB manual and other documentation resources online at:\n<http://www.gnu.org/software/gdb/documentation/>.\n"
~"For help, type \"help\".\n"
~"Type \"apropos word\" to search for commands related to \"word\".\n"
=cmd-param-changed,param="disassembly-flavor",value="intel"

=thread-group-added,id="i1"
~"GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1\n"
~"Copyright (C) 2014 Free Software Foundation, Inc.\n"
~"License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"\nand \"show warranty\" for details.\n"
~"This GDB was configured as \"x86_64-linux-gnu\".\nType \"show configuration\" for configuration details."
~"\nFor bug reporting instructions, please see:\n"
~"<http://www.gnu.org/software/gdb/bugs/>.\n"
~"Find the GDB manual and other documentation resources online at:\n<http://www.gnu.org/software/gdb/documentation/>.\n"
~"For help, type \"help\".\n"
~"Type \"apropos word\" to search for commands related to \"word\".\n"
=cmd-param-changed,param="disassembly-flavor",value="intel"

=thread-group-added,id="i1"
~"GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1\n"
~"Copyright (C) 2014 Free Software Foundation, Inc.\n"
~"License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"\nand \"show warranty\" for details.\n"
~"This GDB was configured as \"x86_64-linux-gnu\".\nType \"show configuration\" for configuration details."
~"\nFor bug reporting instructions, please see:\n"
~"<http://www.gnu.org/software/gdb/bugs/>.\n"
~"Find the GDB manual and other documentation resources online at:\n<http://www.gnu.org/software/gdb/documentation/>.\n"
~"For help, type \"help\".\n"
~"Type \"apropos word\" to search for commands related to \"word\".\n"
=cmd-param-changed,param="disassembly-flavor",value="intel"

It only prints the result of the first command executed(which is p=pexpect.spawnu('sudo gdb --interpreter=mi'). Why does this happen? What's the proper usage of async property?

A: From pexpect docs:

On Python 3.4, or Python 3.3 with asyncio installed, passing
  async=True  will make this return an asyncio coroutine,
  which you can yield from to get the same result that this method would
  normally give directly. So, inside a coroutine, you can replace this code:

index = p.expect(patterns)

With this non-blocking form:

index = yield from p.expect(patterns, async=True)

See coroutines.


text:
Q: Need a search method and a sort method for a catalog I have a project coming up for a Java class that I need help with. I am honestly not good at Java or passionate about it at all. However, I need to pass this course, so I need some assistance. I'm making a program that acts as an online bookstore. It starts with a main menu:
public static void menu(){
     System.out.println("----MAIN MENU----");
    System.out.println("1. View Catalog");
    System.out.println("2. Search Catalog");
    System.out.println("3. Sort Catalog");
    System.out.println("4. Checkout");
    System.out.println("5. Exit");
    System.out.println("Option: ");
    }

So far I've made the catalog:
public static void viewCatalog(){
    System.out.println("Welcome to the ABC Catalog!");
    System.out.println("Product Description   Product Category   Product Price");
    System.out.println("-----------------------------------------------------------");
    System.out.println("Alumni Drink ware   Gifts                  25.00 ");
    System.out.println("Binders             School Supplies         3.00 ");
    System.out.println("Bookbag             School Supplies        20.00 ");
    System.out.println("Fabulous Desserts   Textbooks              25.00 ");
    System.out.println("Folders             School Supplies         1.00 ");
    System.out.println("Gift Cards          Gifts                  25.00 ");
    System.out.println("Highlighters        School Supplies         1.00 ");
    System.out.println("Jacket              Campus Gear            65.00 ");
    System.out.println("JAVA Programming    Textbooks             150.00 ");
    System.out.println("Network Solutions   Textbooks              75.00 ");
    System.out.println("Pencils             School Supplies         1.00 ");
    System.out.println("Pens                School Supplies         2.00 ");
    System.out.println("Shorts              Campus Gear            10.00 ");
    System.out.println("Sweatshirts         Campus Gear            40.00 ");
    System.out.println("T-Shirts            Campus Gear            15.00 ");
    System.out.println("Web Design Ideas    Textbooks              25.00 ");
    System.out.println("---------------------------------------------------------");
}

But I need a way to be able to enter some criteria, search the catalog, and print the matching criteria. I also need a method that sorts the catalog by either increasing price, decreasing price, alphabetical order, category type, or product description. The project has to have at least one object oriented method. I also need a way to add items from the catalog to a cart.
Any code snippets would be much appreciated. I'm not interested in any lectures about cheating, so please don't post anything like that. I hope someone will have some sympathy for a Web Dev student who just needs to pass this course in order to move on to courses that I am more passionate about.

A: Okay, I'll try to answer as many as I can:
You can do searching by simply for-looping through an array until you find an entry that matches what you're looking for.
There are a few native sorting methods that use compareTo, but if you need lots of different ways to sort it may be better to write your own.
I'd say, if you only need to sort by one criteria, see if you can use a function from the standard libraries.
Hopefully that helped.

A: You need a data structure to hold your data. A list is fine for your case. Create Item objects from the data and put them in a list. Code may have errors since I dont have an IDE to test it.
class Item
{
   public Item(String d, String c, double p)
   {
      description = d;
      category = c;
      price = p;
   }
   String description;
   String category;
   double price;
}

You can make fields private and write setter and getter fields. Now create an Item object for every line in the catalog and add them to a list.
List<Item> list = new ArrayList<>();
Item item = new Item("Binders","School Supplies","3.00");
list.add(item);

Sort your item by using a custom comparator. This one sorts the list using description field. If you want to sort it decreasing order you can just run a regular sort and reverse the resulting list.
void sortByDescription(List<Item> list)
{
     Collections.sort(list, new Comparator<Item>(){
          public int compare(final Item o1, final Item o2){
              return o1.description.compareTo(o2.description);
          }
     });
}

void sortByDescriptionBackwards(List<Item> list)
{
   sortByDescription(list);
   Collections.reverse(list);
}

Search method takes a String parameter and looks for a match in all 3 fields of the item object. If it finds a match item is added to a result list and that list is returned. Original list in not changed.
List<Item> search(final String searchFor)
{
    List<Item> searchResults = new ArrayList<>();
    for(int i = 0; i<list.size(); i++)
    {
        Item item = list.get(i);
        if(item.description.contains(searchFor) ||
             item.category.contains(searchFor) ||
                String.valueOf(item.prize).contains(searchFor) )
       {searchResults.add(item);}
    }
    return searchResults;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Validate a coordinate if is inside a Polygon I have a table called Coordinates with 4 columns(Id,Longitude,Latitude,CityId) where Id is the PK, Longitude and Latitude are the coordinate and finally CityId is a FK with a table called Cities, in my Cities table i have 3 Cities, every city has a List of Coordinates, my question is how can i verify in which city is a Point(Latitude,Longitude), it means return the CityId of the city which belongs the point, Im using .Net Core,Entity FrameworkCore, I need a function that returns to me the cityId from a Point sent.
I have searched but anything I found is to verify if a point is into a Polygon, it returns a true or false, but in my case I have 3 polygons(for 3 Cities), so I don't need a bollean because I have 3 polygons, I need the City Id which the point belongs.
Some help will be appreciate, thanks advanced
This is my Table Coordinates:

A: You probably want to use STIntersection of the geography type in SQL Server (I presume you are using, based on the screenshot of SSMS). This will be good in SQL Server 2016+.
declare @g geography = 'POLYGON((-1 -1, 1 -1, 1 1, -1 1, -1 -1))'
declare @intersects geography = 'POINT(0 0)'
declare @notIntersects geography = 'POINT(-2 -2)'

select @g.STIntersection(@intersects).ToString(),
       @g.STIntersection(@notIntersects).ToString()

(No column name)    (No column name)
POINT (0 0)         GEOMETRYCOLLECTION EMPTY

You could query for all points associated with a CityId (they're in order, yes?), and construct a geography from them, then query for intersections. Alternatively, you could modify your schema to use geography with a polygon for the city points.
To use this functionality from EF Core, you'll need geography column types and use the data types from Net Topology Suite.


text:
Q: How to sum up an array of integers in C# Is there a better shorter way than iterating over the array?
int[] arr = new int[] { 1, 2, 3 };
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
    sum += arr[i];
}

clarification:
Better primary means cleaner code but hints on performance improvement are also welcome. (Like already mentioned: splitting large arrays).

It's not like I was looking for killer performance improvement - I just wondered if this very kind of syntactic sugar wasn't already available: "There's String.Join - what the heck about int[]?".

A: Yes there is. With .NET 3.5:
int sum = arr.Sum();
Console.WriteLine(sum);

If you're not using .NET 3.5 you could do this:
int sum = 0;
Array.ForEach(arr, delegate(int i) { sum += i; });
Console.WriteLine(sum);

A: An alternative also it to use the Aggregate() extension method.
var sum = arr.Aggregate((temp, x) => temp+x);

A: It depends on how you define better. If you want the code to look cleaner, you can use .Sum() as mentioned in other answers. If you want the operation to run quickly and you have a large array, you can make it parallel by breaking it into sub sums and then sum the results.

A: For extremely large arrays it may pay off to perform the calculation using more than one processors/cores of the machine.
long sum = 0;
var options = new ParallelOptions()
    { MaxDegreeOfParallelism = Environment.ProcessorCount };
Parallel.ForEach(Partitioner.Create(0, arr.Length), options, range =>
{
    long localSum = 0;
    for (int i = range.Item1; i < range.Item2; i++)
    {
        localSum += arr[i];
    }
    Interlocked.Add(ref sum, localSum);
});

A: One problem with the for loop solutions above is that for the following input array with all positive values, the sum result is negative:
int[] arr = new int[] { Int32.MaxValue, 1 };
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
    sum += arr[i];
}
Console.WriteLine(sum);

The sum is -2147483648, as the positive result is too big for the int data type and overflows into a negative value.
For the same input array the arr.Sum() suggestions cause an overflow exception to be thrown.
A more robust solution is to use a larger data type, such as a "long" in this case, for the "sum" as follows:
int[] arr = new int[] { Int32.MaxValue, 1 };
long sum = 0;
for (int i = 0; i < arr.Length; i++)
{
    sum += arr[i];
}

The same improvement works for summation of other integer data types, such as short, and sbyte. For arrays of unsigned integer data types such as uint, ushort and byte, using an unsigned long (ulong) for the sum avoids the overflow exception.
The for loop solution is also many times faster than Linq .Sum()
To run even faster, HPCsharp nuget package implements all of these .Sum() versions as well as SIMD/SSE versions and multi-core parallel ones, for many times faster performance.

A: Provided that you can use .NET 3.5 (or newer) and LINQ, try
int sum = arr.Sum();

A: With LINQ:
arr.Sum()

A: If you don't prefer LINQ, it is better to use foreach loop to avoid out of index.
int[] arr = new int[] { 1, 2, 3 };
int sum = 0;
foreach (var item in arr)
{
   sum += item;
}

A: Using foreach would be shorter code, but probably do exactly the same steps at runtime after JIT optimization recognizes the comparison to Length in the for-loop controlling expression.

A: In one of my apps I used :
public class ClassBlock
{
    public int[] p;
    public int Sum
    {
        get { int s = 0;  Array.ForEach(p, delegate (int i) { s += i; }); return s; }
    }
}

A: An improvement on Theodor Zoulias's nice multi-core Parallel.ForEach implementation:
    public static ulong SumToUlongPar(this uint[] arrayToSum, int startIndex, int length, int degreeOfParallelism = 0)
    {
        var concurrentSums = new ConcurrentBag<ulong>();

        int maxDegreeOfPar = degreeOfParallelism <= 0 ? Environment.ProcessorCount : degreeOfParallelism;
        var options = new ParallelOptions() { MaxDegreeOfParallelism = maxDegreeOfPar };

        Parallel.ForEach(Partitioner.Create(startIndex, startIndex + length), options, range =>
        {
            ulong localSum = 0;
            for (int i = range.Item1; i < range.Item2; i++)
                localSum += arrayToSum[i];
            concurrentSums.Add(localSum);
        });

        ulong sum = 0;
        var sumsArray = concurrentSums.ToArray();
        for (int i = 0; i < sumsArray.Length; i++)
            sum += sumsArray[i];

        return sum;
    }

which works for unsigned integer data types, since C# only support Interlocked.Add() for int and long. The above implementation can also be easily modified to support other integer and floating-point data types to do summation in parallel using multiple cores of the CPU. It is used in the HPCsharp nuget package.


text:
Q: Error:android-apt plugin is incompatible with the Android Gradle plugin. Please use 'annotationProcessor' configuration instead hoy actualice Android Studio de 2.3 a 3.0, así mismo se actualizaron los plugins del Gradle pero en este uno de mis proyectos me muestra este error
(Error:android-apt plugin is incompatible with the Android Gradle plugin.  Please use 'annotationProcessor' configuration instead). a continuación mi muild.gradle (Module:app), gracias por la ayuda.
    apply plugin: 'com.android.application'
    apply plugin: 'com.neenbedankt.android-apt'

    android {
        compileSdkVersion 26
        buildToolsVersion '26.0.2'
        defaultConfig {
        applicationId "com.tecnologias.uniagustapp"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner
        "android.support.test.runner.AndroidJUnitRunner"
         }
         buildTypes {
         release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
            'proguard-rules.pro'
                }
             }
          }

       dependencies {
       compile fileTree(dir: 'libs', include: ['*.jar'])
       androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:design:26.+'
    compile 'com.android.support:design:26.+'
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:support-v4:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:recyclerview-v7:26.+'
    compile 'com.android.support:cardview-v7:26.+'
    compile 'com.jakewharton:butterknife:8.4.0'
    compile 'com.thoughtbot:expandablerecyclerview:1.3'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'de.hdodenhof:circleimageview:2.0.0'
    testCompile 'junit:junit:4.12'
    apt 'com.jakewharton:butterknife-compiler:8.4.0'
}

A: En el siguiente link tienes los pasos para migrar de apt a annotationProcessor
From apt to annotationProcessor
Básicamente:

*

*Comprobar que tienes una versión de Gradle +2.2

*Eliminar el plugin apt del archivo build.gradle (2 línea 'apply plugin: 'android-apt'

*Cambiar las dependencias apt por annotationProcessor.

Espero que funcione.


text:
Q: Issues with flushend (last citation cut, etc.) I've been having issues using the flushend package to balance the last page's columns. I'm using it to balance bibliographies mainly.
Flushend tends to (1) cut the last citation, (2) result in uneven spacing, and/or (3) repeat the citation at the end of the first column.
This seems to be installation dependent as colleagues of mine do not run into these issues. I am using pdflatex in TexLive 2013 (full install) on Windows.
Here is an MWE with issues (1) and (2) appearing:
\documentclass[conference, 9pt]{IEEEtran}
\usepackage{flushend}
% \usepackage{balance}

\begin{document}
\nocite{*}
% \balance

\begin{thebibliography}{1}

\bibitem{test1}
J.~Doe and J.~Doe, ``This is a paper title, this is a paper title, this is a
  paper title, this is a paper title,'' in \emph{Some Proceedings}, Somewhere,
  Somewhere, 2014.

\bibitem{test2}
------, ``This is a paper title, this is a paper title, this is a paper title,
  this is a paper title,'' in \emph{Some Proceedings}, Somewhere, Somewhere,
  2014.

\bibitem{test3}
------, ``This is a paper title, this is a paper title, this is a paper title,
  this is a paper title,'' in \emph{Some Proceedings}, Somewhere, Somewhere,
  2014.

\bibitem{test4}
------, ``This is a paper title, this is a paper title, this is a paper title,
  this is a paper title,'' in \emph{Some Proceedings}, Somewhere, Somewhere,
  2014.

\bibitem{test5}
------, ``This is a paper title, this is a paper title, this is a paper title,
  this is a paper title,'' in \emph{Some Proceedings}, Somewhere, Somewhere,
  2014.

\bibitem{test6}
------, ``This is a paper title, this is a paper title, this is a paper title,
  this is a paper title,'' in \emph{Some Proceedings}, Somewhere, Somewhere,
  2014.

\end{thebibliography}

\end{document}

Here is how the output looks:

Here is the output using the balance package (not ideal but better):

A: The bugfix flushed.sty, v3.1 2015/04/14, package version has some extra improvements.
Here is how the output looks now:

To correct indent on the last line use package option keeplastbox:

To suppress extra glue spread on the right column additionally use package option nospread:

To make right column shorter use \atColsEnd{\vskip10pt}:

To make right column longer use \atColsEnd{\vskip-20pt}:


text:
Q: Crosswalks on ios - how to import 'XWalkView.h' When use it in Objective-C? I try to import 'XWalkView.h' all the day,but I can't,It always appears 'not found',I know little about Swift...

A: Confirm that "XWalkView.h" is added in your project by "Show in Finder". If that file is not there inside your project folder then try to add "XWalkView.h" after removing old copy.


text:
Q: You can have javascript functions that create other functions. How does this work? function greaterThan(n) {
return function(m) { return m > n; };
}
var greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
// true

I am trying to understand higher order functions. I understand that the above has one function that creates another function inside it. I also understand that greaterThan10 stores the function:   return function(m) { return m > n; };
I don't understand how this results in true ? Doesn't passing the 11 override the 10 passed previously? How are both 10 & 11 stored, I don't get this? Thank-you

A: Calling var greaterThan10 = greaterThan(10); results in greaterThan10 having the following value:
var greaterThan10 = function (m) { return m > 10; };

Therefore, calling this function with 11 as a parameter (as in your example) returns 11 > 10, which is true.

A:
Doesn't passing the 11 override the 10 passed previously?

Nope, since greaterThan function is called once with 10. So, n is populated with 10.
After that greaterThan10 function is called with value 11 which populates m (not n since greaterThan10 takes parameter m) and n is not touched at all as it takes the previous value stored in the reference of greaterThan.
Note that greaterThan function is not called again, so n is not populated again and hence its value remain same.


text:
Q: Eclipse show java error when I change drive where is storage I've changed the eclipse folder from d: to f: and when I start is showing a Java popup error "Could not create the Java Virtual Machine"

A: As long as your JDK location has not changed , this error should not come up. Can you try starting eclipse with the -vm option
eclipse -vm /bin/javaw and see if it starts up ?


text:
Q: Variável declarada no viewDidLoad não é encontrada no Botão - Swift 2 Tenho uma array que gera uma palavra ao carregar o viewController, e salva uma posição aleatória na variável declarada na viewDidLoad ou antes dentro da class. Mas dentro do botão não acha a variável para receber e utilizar o conteúdo.
aqui somente o código gerando a palavra aleatória do array que funciona perfeitamente:
let palavra: Array = ["ABC", "DEF"]
let randomIndex = Int(arc4random_uniform(UInt32(palavra.count)))
let string = Array(palavra.characters)

depois só preciso fazer uma comparação dentro do botão, quero comparar uma string digitada, comparando cada letra da string com cada letra da palavra digitada. Então pensei em gerar um array e percorrer as posições comparando.
mas dentro do botão não reconhece a variável ja criada.
obrigado
Fernando.

A: O que possivelmente está ocorrendo é um problema de escopo:
Uma variável (ou uma constante let) declarada no corpo de uma função somente será acessível dentro dela (neste caso, da func viewDidLoad()).
Ao mover a declaração para um nível acima (no nível da classe) você conseguirá utilizar esta variável ou constante dentro da viewDidLoad.
Algo como:
class ViewController : UIViewController {

    @IBOutlet var myButton : UIButton!

    let palavra: Array = ["ABC", "DEF"]
    let randomIndex = Int(arc4random_uniform(UInt32(palavra.count)))
    let minhaString = Array(palavra.characters)

    func viewDidLoad() {
        self.myButton.text = minhaString
       }
}

Espero ter ajudado! :)


text:
Q: jquery click function element scrolling inside a div instead of html, body I have few group of list element inside a div. This div is scroll able. I have few link element for specify the list group. If user click on this specific link then div will scroll and specific list group will be show on top of the div.
Regular scrollTop function almost working. Main issue is targeted list group is targeting html, body not parent div .language-list-alph.

Snippet is below.

$(function(){
    $('.quick-lang-shorting .shorting-list li a').on('click', function(e){
        e.preventDefault();
        var target = this.hash;
        var $target = $(target);
        $('.language-list-alph').stop().animate({'scrollTop': $target.offset().top}, 1200);
    });
});
*:after,
*:before{
  content: '';
  display: table;
}
*:after{
  clear: both;
}
*{
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
body{
  margin: 0;
  padding: 100px 30px 30px;
}
.translation-lang,
.quick-lang-shorting{
  display: block;
  float: left;
  min-height: 1px;
}
.translation-lang{
  width: -webkit-calc(100% - 50px);
  width: -moz-calc(100% - 50px);
  width: calc(100% - 50px);
}
.language-list-alph{
  display: block;
  height: 600px;
  overflow-x: hidden;
  overflow-y: auto;
  padding-right: 17px;
  width: 100%;
}
.lang-list-group{
  list-style: inside none;
  margin-bottom: 0;
  margin-top: 0;
  padding-left: 0;
}
.lang-list-group li{
  border-bottom: 1px solid #121212;
  padding: 10px 15px;
}
.quick-lang-shorting{
  width: 50px;
}
.shorting-list{
  list-style: inside none;
  margin-bottom: 0;
  margin-top: 0;
  padding-left: 0;
}
.shorting-list li{
  float: left;
  text-align: right;
  width: 100%;
}

        Argentina

        Belgium

        Brasil

        Bulgaria

        Canada

        China

        Ivory Coast

        Denmark

        Estonia

        France

        Greece

        Hungary

        India

        Ireland

        Ireland

        Argentina

        Argentina

        Argentina

        Argentina

        Argentina

        Argentina

        Argentina

        Argentina

        Argentina

        Argentina

        Argentina

        Argentina

        Argentina

        Argentina

        Argentina

        Argentina

A

B

C

D

E

F

G

H

I

J

K

L

M

N

O

P

Q

R

S

T

U

V

W

X

Y

Z

How can I target the div (.language-list-alph) instead of html, body?

If any one want to edit this question it will be appreciate.


text:
Q: unlink doesn't work I am trying to use unlink command on my server Apache/2.2.3 PHP Version 5.2.10. I have been using the same script on a bunch of other servers including my local PC. Unfortunately, the command doesn't work.
I tried this so far:

*

*chmod everything to 777

*putting new files and unlinking them

*also I notice that I can't upload or saveXML files to the server

I am guessing that it is some kind of setting inside the php.ini file, but I don't know which.

A: May be it's a safe_mode?

A: Solved
Checking if it is writable first and then unlink it seem to do the trick
if (is_writable("$bannerlink")) unlink("$bannerlink");

thanks to everybody


text:
Q: efficient "parallax effect" for vertical img-list while scrolling I have a list of images and want to move the images slowly up/down while scrolling down/up.
The images itself are set by "object-fit: cover;" and "object-position: center 50%;", so I have space to move the image down to the maximum of "object-position: center 100%;" while scrolling up. And the opposite, to move the image up to the minimum of "object-position: center 0;" while scrolling down.
For short: When user scrolls the list of images down, then each image should slowly show more from its hidden top and vice versa.
I find this nice parralax-effect on whatsapp client (ios). When user is scrolling down, the media content is scrolling a little up and vice versa. I want to achieve exactly the same.
So I made the following code - it works, however, performance is bad and I look for a better solution. Does anyone know a better solution for this problem? Maybe by using "pure css parralax" (http://keithclark.co.uk/articles/pure-css-parallax-websites/). This would be the best solution - however, I cannot adopt this technique to my problem.
You can copy/paste it to a new index.html and it will work as it is.
Here is the full working code (with bad performance):

(function() {
     document.addEventListener('DOMContentLoaded', function() {

      /** returns true, if node is in viewport.
      */
function node_is_in_viewport(element) {

         var rect = element.getBoundingClientRect();
         var html = document.documentElement;

         return (
           rect.top >= 0 &&
           rect.left >= 0 &&
           rect.bottom <= (window.innerHeight || html.clientHeight) &&
           rect.right <= (window.innerWidth || html.clientWidth)
         );
      }

      /** returns "y-value" of css-property "object-position"
      */
      function getObjectPosY(translateString){
       var n = translateString.indexOf('%');
       var n1 = translateString.lastIndexOf("%");

       var res = parseInt(translateString.slice(n+1,n1));
       return res;
      }

      var list_img = document.querySelector('.list-img');
      var pos_list = list_img.scrollTop;
      var all_imgs = document.querySelectorAll('.list-img>li img');

      console.log('actual position of the list:');
      console.log(pos_list);

      list_img.addEventListener('scroll',  function(e){

        var scroll = this.scrollTop;

        // positive number means "scroll down"
        // negative number means "scroll up"
        var offsetScrollTreshold = scroll - pos_list; // unused

        // move image 1 unit up/down
        var offsetScroll = 3;
        var speed = 1;

        console.log('position of list (pos_list):');
        console.log(pos_list);

        console.log('scroll:');
        console.log(scroll);

        console.log('offset (scroll - pos_list):');
        console.log(offsetScrollTreshold);

        if(scroll > pos_list) {
          console.log('User is scrolling DOWN');
          console.log('I want to show more from the hidden top of all the images within the actual viewport while user is scrolling down. But each image should not exceed its original image size.');

          list_img.classList.add('scroll-down');
          list_img.classList.remove('scroll-up');

             [].forEach.call(all_imgs, function(node) {

              var node_in_view = node_is_in_viewport(node);

              // if image is in viewport move it up to "make a parallax effect"
              if(node_in_view){
               console.log('-----');
               console.log('actual img to move up (new Y must be lower):');
               console.log(node.src);

               var old_y = 0;

               var theCSSprop = window.getComputedStyle(node, null).getPropertyValue('object-position');
               if( theCSSprop.indexOf('%')!=-1 ){
                console.log(theCSSprop);

                // returns the actual "y"-position of the image
                old_y = getObjectPosY(theCSSprop);
                console.log('old_y:');
                console.log(old_y);
               }

               // User is scrolling down, so I want to view more from the "top of the image" which is actually a little hidden (because of object-fit: center 50%)
               // to view more from the top of the image, I have to set the y-value (actually: 50%) lower, but not more than 0.
               if(old_y > 0 && old_y <= 100){

            console.log('scroll image "slowly" up while user is scrolling down (parallax effect)');
                var new_y = old_y - offsetScroll * speed;

                if(new_y<0){
                 new_y = 0;
            }

                console.log('new_y:');
                console.log(new_y);
                node.style.objectPosition = '50% '+ new_y + '%';
               }
              }

          });
            }
            else {

             console.log('User is scrolling UP');
         console.log('I want to show more from the hidden bottom of all the images within the actual viewport while user is scrolling up. But each image should not exceed its original image size.');

         list_img.classList.remove('scroll-down');
         list_img.classList.add('scroll-up');

         [].forEach.call(all_imgs, function(node) {

          var node_in_view = node_is_in_viewport(node);

          // if image is in viewport move it down to "make a parallax effect"
              if(node_in_view){

               console.log('actual img to move down (new Y must be higher):');
               console.log(node.src);

               var theCSSprop = window.getComputedStyle(node, null).getPropertyValue('object-position');
               if(theCSSprop.indexOf('%')!=-1){
                console.log(theCSSprop);

                // returns the actual "y"-position of the image
                old_y = getObjectPosY(theCSSprop);

                console.log('old_y:');
                console.log(old_y);
               }

               // User is scrolling up, so I want to view more from the "bottom of the image" which is actually a little hidden (because of object-fit: center 50%)
               // to view more from the bottom of the image, I have to set the y-value (actually: 50%) higher, but not more than 100%.
               if(old_y >= 0 && old_y < 100){

                console.log('scroll image "slowly" down while user is scrolling up (parallax effect)');

                var new_y = old_y + offsetScroll * speed;

                if(new_y>100){
                 new_y = 100;
            }

                console.log('new_y:');
                console.log(new_y);

                node.style.objectPosition = '50% '+ new_y + '%';
               }
              }
         });
        }

       pos_list = scroll;
       console.log('pos_list:');
       console.log(pos_list);

      });/*end eventlistener scroll */

     }); /*end .DOMContentLoaded */
    }());

    body, html, #ctn_infinity, .list-img{
     height: 100%;
     width: 100%;
     margin: 0;
     padding: 0;
    }

    .list-img{
     height: 90vh;
     overflow: auto;
    }

    .list-img{
     list-style: none;
     width: 400px;
    }

    .list-img>li{
     display: flex;
     flex-direction: column;
     border: 2px solid black;
     margin: 16px auto;
    }

    .list-img div{
     background: yellow;
    }

    .list-img img{
     object-fit: cover;
     width: 100%;
     /* original image size: 400 width x 200 height */
     /* I use object position center: when scrolling up or down, images should "slowly" show its hidden part of its images (max. 25px top or 25px down)  */
     height: 150px;
     /* Unfortunately, I cannot use "transform: translateY(-5px);", because this will move the whole img-container instead of the img itself up/down" */
     object-position: center 50%;
    }

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>HTML-TEST</title>

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

lorem epsum..

A: I can't find object-position on csstriggers.com. But I checked it myself, and as soon as I change the object position of an element with object-fit: cover, I get a Recalculate style and a Paint.
In case you aren't familiar with these, these are ways your browser updates your screen after specific events. And the events your code trigger are very heavy. Now on every scroll event your code triggers expensive paint events on the browsers window.
Basically what you want to do is refactor it so that your code doesn't have to be repaint. You will probably want to change the objectPosition to a .style.transorm = "translate3d(0, " + new_y + ", 0)";. Those shouldn't trigger the paint events as it does now.
Thing with this though, that there could be ways it will still trigger paints. I recommend you reading about scrolling performance  since it's too much to explain on stack overflow, Paul Lewis wrote a nice article about this.


text:
Q: Failed to Deploy to Heroku: npm ERR! Error: version not found: 1.1.49 : npm/1.1.49 So I'm trying to build a Node.js app (Hastebin) to Heroku but it's failing:
Counting objects: 33, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (32/32), done.
Writing objects: 100% (33/33), 61.60 KiB | 0 bytes/s, done.
Total 33 (delta 2), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Node.js app detected
remote:
remote: -----> Reading application state
remote:        package.json...
remote:        build directory...
remote:        cache directory...
remote:        environment variables...
remote:
remote:        Node engine:         0.8.10
remote:        Npm engine:          1.1.49
remote:        Start mechanism:     Procfile
remote:        node_modules source: package.json
remote:        node_modules cached: false
remote:
remote:        NPM_CONFIG_PRODUCTION=true
remote:        NODE_MODULES_CACHE=true
remote:
remote: -----> Installing binaries
remote:        Downloading and installing node 0.8.10...
remote:        Downloading and installing npm 1.1.49 (replacing version 1.1.62)...
remote:        npm ERR! Error: version not found: 1.1.49 : npm/1.1.49
remote:        npm ERR!     at RegClient.<anonymous> (/tmp/build_08856eedd22bd2c0d60af50d4929a3ee/.heroku/node/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:259:14)
remote:        npm ERR!     at Request.init.self.callback (/tmp/build_08856eedd22bd2c0d60af50d4929a3ee/.heroku/node/lib/node_modules/npm/node_modules/request/main.js:120:22)
remote:        npm ERR!     at Request.EventEmitter.emit (events.js:96:17)
remote:        npm ERR!     at Request.<anonymous> (/tmp/build_08856eedd22bd2c0d60af50d4929a3ee/.heroku/node/lib/node_modules/npm/node_modules/request/main.js:648:16)
remote:        npm ERR!     at Request.EventEmitter.emit (events.js:123:20)
remote:        npm ERR!     at IncomingMessage.Request.start.self.req.self.httpModule.request.buffer (/tmp/build_08856eedd22bd2c0d60af50d4929a3ee/.heroku/node/lib/node_modules/npm/node_modules/request/main.js:610:14)
remote:        npm ERR!     at IncomingMessage.EventEmitter.emit (events.js:123:20)
remote:        npm ERR!     at IncomingMessage._emitEnd (http.js:366:10)
remote:        npm ERR!     at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
remote:        npm ERR!     at CleartextStream.socketOnData (http.js:1366:20)
remote:        npm ERR! If you need help, you may report this log at:
remote:        npm ERR!     <http://github.com/isaacs/npm/issues>
remote:        npm ERR! or email it to:
remote:        npm ERR!     <npm-@googlegroups.com>
remote:
remote:        npm ERR! System Linux 3.13.0-40-generic
remote:        npm ERR! command "/tmp/build_08856eedd22bd2c0d60af50d4929a3ee/.heroku/node/bin/node" "/tmp/build_08856eedd22bd2c0d60af50d4929a3ee/.heroku/node/bin/npm" "install" "--unsafe-perm" "--quiet" "-g" "npm@1.1.49"
remote:        npm ERR! cwd /app
remote:        npm ERR! node -v v0.8.10
remote:        npm ERR! npm -v 1.1.62
remote:        npm ERR!
remote:        npm ERR! Additional logging details can be found in:
remote:        npm ERR!     /app/npm-debug.log
remote:        npm ERR! not ok code 0
remote:
remote: -----> Build failed
remote:
remote:        We're sorry this build is failing! If you can't find the issue in application code,
remote:        please submit a ticket so we can help: https://help.heroku.com/
remote:        You can also try reverting to our legacy Node.js buildpack:
remote:        heroku config:set BUILDPACK_URL=https://github.com/heroku/heroku-buildpack-nodejs#v63
remote:
remote:        Love,
remote:        Heroku
remote:
remote:  !     Push rejected, failed to compile Node.js app
remote:
remote: Verifying deploy...
remote:
remote: !   Push rejected to tuxbin.
remote:
To https://git.heroku.com/tuxbin.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/tuxbin.git'

By the looks of things it seems there's an issue with the version of npm. Is there a specific version of npm I should be using?

A:
remote:        Node engine:         0.8.10
  remote:        Npm engine:          1.1.49

These are very old versions of both node and npm. You may want to bump the versions in package.json to something like 0.10.38 (and just leaving npm off to use the default, bundled version)?


text:
Q: Recursively parse all category links and get all products I've been playing around with web-scraping (for this practice exercise using Python 3.6.2) and I feel like I'm loosing it a bit. Given this example link, here's what I want to do:
First, as you can see, there are multiple categories on the page. Clicking each of the categories from above will give me other categories, then other ones, an so on, until I reach the products page. So I have to go in depth x number of times. I thought recursion will help me achieve this, but somewhere I did something wrong.
Code:
Here, I'll explain the way I approached the problem. First, I created a session and a simple generic function which will return a lxml.html.HtmlElement object:
from lxml import html
from requests import Session

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/62.0.3202.94 Safari/537.36"
}
TEST_LINK = 'https://www.richelieu.com/us/en/category/custom-made-cabinet-doors-and-drawers/1000128'

session_ = Session()

def get_page(url):
    page = session_.get(url, headers=HEADERS).text
    return html.fromstring(page)

Then, I thought I'll need two other functions:

*

*one to get the category links

*and another one to get the product links

To distinguish between one and another, I figured out that only on category pages, there's a title which contains CATEGORIES every time, so I used that:
def read_categories(page):
    categs = []
    try:
        if 'CATEGORIES' in page.xpath('//div[@class="boxData"][2]/h2')[0].text.strip():
            for a in page.xpath('//*[@id="carouselSegment2b"]//li//a'):
                categs.append(a.attrib["href"])
            return categs
        else:
            return None
    except Exception:
        return None

def read_products(page):
    return [
        a_tag.attrib["href"]
        for a_tag in page.xpath("//ul[@id='prodResult']/li//div[@class='imgWrapper']/a")
    ]

Now, the only thing left, is the recursion part, where I'm sure I did something wrong:
def read_all_categories(page):
    cat = read_categories(page)
    if not cat:
        yield read_products(page)
    else:
        yield from read_all_categories(page)

def main():
    main_page = get_page(TEST_LINK)

    for links in read_all_categories(main_page):
        print(links)

Here's all the code put together:
from lxml import html
from requests import Session

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/62.0.3202.94 Safari/537.36"
}
TEST_LINK = 'https://www.richelieu.com/us/en/category/custom-made-cabinet-doors-and-drawers/1000128'

session_ = Session()

def get_page(url):
    page = session_.get(url, headers=HEADERS).text
    return html.fromstring(page)

def read_categories(page):
    categs = []
    try:
        if 'CATEGORIES' in page.xpath('//div[@class="boxData"][2]/h2')[0].text.strip():
            for a in page.xpath('//*[@id="carouselSegment2b"]//li//a'):
                categs.append(a.attrib["href"])
            return categs
        else:
            return None
    except Exception:
        return None

def read_products(page):
    return [
        a_tag.attrib["href"]
        for a_tag in page.xpath("//ul[@id='prodResult']/li//div[@class='imgWrapper']/a")
    ]

def read_all_categories(page):
    cat = read_categories(page)
    if not cat:
        yield read_products(page)
    else:
        yield from read_all_categories(page)

def main():
    main_page = get_page(TEST_LINK)

    for links in read_all_categories(main_page):
        print(links)

if __name__ == '__main__':
    main()

Could someone please point me into the right direction regarding the recursion function?

A: Here is how I would solve this:
from lxml import html as html_parser
from requests import Session

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 "
                  "(KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"
}

def dig_up_products(url, session=Session()):
    html = session.get(url, headers=HEADERS).text
    page = html_parser.fromstring(html)

    # if it appears to be a categories page, recurse
    for link in page.xpath('//h2[contains(., "CATEGORIES")]/'
                           'following-sibling::div[@id="carouselSegment1b"]//li//a'):
        yield from dig_up_products(link.attrib["href"], session)

    # if it appears to be a products page, return the links
    for link in page.xpath('//ul[@id="prodResult"]/li//div[@class="imgWrapper"]/a'):
        yield link.attrib["href"]

def main():
    start = 'https://www.richelieu.com/us/en/category/custom-made-cabinet-doors-and-drawers/1000128'

    for link in dig_up_products(start):
        print(link)

if __name__ == '__main__':
    main()

There is nothing wrong with iterating over an empty XPath expression result, so you can simply put both cases (categories page/products page) into the same function, as long as the XPath expressions are specific enough to identify each case.

A: You can do like this as well to make your script slightly concise. I used lxml library along with css selector to do the job. The script will parse all the links under category and look for the dead end, when it appears then it parse title from there and do the whole stuff over and over again until all the links are exhausted.
from lxml.html import fromstring
import requests

def products_links(link):
    res = requests.get(link, headers={"User-Agent": "Mozilla/5.0"})
    page = fromstring(res.text)

    try:
        for item in page.cssselect(".contentHeading h1"): #check for the match available in target page
            print(item.text)
    except:
        pass

    for link in page.cssselect("h2:contains('CATEGORIES')+[id^='carouselSegment'] .touchcarousel-item a"):
        products_links(link.attrib["href"])

if __name__ == '__main__':

    main_page = 'https://www.richelieu.com/us/en/category/custom-made-cabinet-doors-and-drawers/1000128'
    products_links(main_page)

Partial result:
BRILLANTÉ DOORS
BRILLANTÉ DRAWER FRONTS
BRILLANTÉ CUT TO SIZE PANELS
BRILLANTÉ EDGEBANDING
LACQUERED ZENIT DOORS
ZENIT CUT-TO-SIZE PANELS
EDGEBANDING
ZENIT CUT-TO-SIZE PANELS


text:
Q: Angular net::ERR_SSL_PROTOCOL_ERROR i have in

*

*Angular application (front).

*Api Laravel (Back).

*Domaine SSL (https).

Like this when i disable SSL on my server it work with http:
        let url = 'http://api.hamham.me/public/api/items';

         this.http.get(url, {
              headers: new HttpHeaders().set('Accept', 'application/json'),
            }).subscribe((res) => {
          this.items = res;
        });

but when i use https
it give me this error

net::ERR_SSL_PROTOCOL_ERROR

Error sceenshoot
please help me how can i get data from my API with https


text:
Q: Use OpenGL ES to create an iPhone painting tool? Is it feasible to use OpenGL ES to create an iPhone raster graphics editor like SketchBook Mobile(http://usa.autodesk.com/adsk/servlet/pc/item?siteID=123112&id=13872203)? Any related reference(tutorial, sample) you can recommend?
Why I try to use OpenGL ES? Because it's hardware accelerated and cross-platform.
Thanks in advance!

A: Apple's own GLpaint sample app might be a good starting point.


text:
Q: override setter with call to inherited setter I am a little bit confused: can I override a setter / getter but still use the super setter/getter? If yes - how?
Use case:
class A {
  void set value(num a) {
    // do something smart here
  }
}

class B extends A {
  void set value(num a) {
    // call parent setter and then do something even smarter
  }
}

If this is not possible how can one still preserve the API but expand the logic in the new class. The users of the code already use instance.value = ... so I do not want to change it to method call is possible.
Please help:)

A: Only need call super.value = a
class A {
  void set value(String value) {
    print(value.toUpperCase());
  }
}

class B extends A {

  void set value(String value) {
    super.value = value;
    print(value.toLowerCase());
  }
}

void main() {
  B b = new B();
  b.value = "Hello World";
}

A: You can access to parent with super. :
class B extends A {
  void set value(num a) {
    super.value = a;
  }
}


text:
Q: Alfresco share "site content" (docsummary) dashlets customization There are three filters out of the box.
1. I've Recently modified,
2. I'm editing and
3 my favorite
inside site content(docsummary) dashlets alfresco share.
I need to add one more filter called "modified by other user".
Is it possible, could someone please put lights on it.

A: To modify "site content" dashlets:
you need to add <filter type="editingOthers" /> in file docsummary.get.config.xml
And add filter.editingOthers=Modified By Others in file docsummary.get_en.properties
After this you may have to change web script to search desired parameter for your dashlet. For that make changes in doclist.get.js file located in  alfresco\tomcat\webapps\alfresco\WEB-INF\classes\alfresco\templates\webscripts\org\alfresco\slingshot\documentlibrary\doclist.get.js.
For ref: https://wiki.alfresco.com/wiki/Web_Scripts#Advanced_Implementations


text:
Q: Population vs Sample Space In probability theory, it is my understanding that the sample space $\Omega$ is the set of all possible outcomes of an experiment. In my mind, I am thinking of it as a set of data points such as height, faces of a die, etc. depending on what your experiment is measuring. I am also of the understanding that these outcomes could really take any data form like tuples (0,1), single values (1), strings like "true" or "false", etc.
I am trying to understand how this relates to the concept of a population. For example, if my experiment is measuring the heights of NBA players, then would the population be the set of all those measurements while a sample space would be a (non-strict) subset of it? I have read other questions online about this, but am still confused.

A: In statistics, it depends on whether we are interested in sampling from finite populations. Usually we are not, except when we are in the survey literature. The concept of the population for finite population sampling is straightforward. It is the population from which you sample. For example, for NBA players, it would be the actual players themselves in a particular season.
More often, we assume we are sampling from an infinite population. This can be applied to the case even when the population you sample from is apparently finite. For example, with the sampling of NBA players, we can imagine a larger population of "potential" NBA players, including future players. Since this hypothetical population does not exist, we can imagine it to have infinite possibilities. In this sense, the population is more than just the sample space. It also has a population distribution associated with it. In classical statistics, this distribution is assumed "fixed but unknown", and the purpose of our sample is to make inferences (intelligent guesses) about it. We also tend to make assumptions to ensure we have a "nice" problem to work with. For example, we would typically assume height is on a continuous scale, even though measurements are of finite precision (discrete). We may even assume it follows a Normal distribution if that helps.
This is to say, a "population" is generally a hypothetical construct to allow us to do maths. It may be regarded as an approximation to the "real" population we are interested in making inference on.

A: Sample space is a concept in probability theory, its a component of the probability space $(\Omega,F,P)$, in your case you can say the sample space is the heights of all the NBA players.
While "population" is a term used in statistics. It's used in combination with the term "samples" to emphasize "samples" is a subset of the "population". The population is also the heights of all the NBA players.
It happens that these two concepts referring to the same thing in your case, but it's not generally true for all other cases.


text:
Q: How can I get the HTML generated with javascript? I want to get the HTML content of a web page but most of the content is generated by javascript.
Is it posible to get this generated HTML (with python if posible)?

A: The only way I know of to do this from your server is to run the page in an actual browser engine that will parse the HTML, build the normal DOM environment, run the javascript in the page and then reach into that DOM engine and get the innerHTML from the body tag.
This could be done by firing up Chrome with the appropriate URL from Python and then using a Chrome plugin to fetch the dynamically generated HTML after the page was done initializing itself and communicate back to your Python.

A: Checkout Selenium. It have a python driver, which might be what you're looking for.

A: If most of the content is generated by Javascript then the Javascript may be doing ajax calls to retrieve the content. You may be able to call those server side scripts from your Python app.
Do check that it doesn't violate the website's terms though and get permission.


text:
Q: How do I add conditions in a WHERE SQL clause or return all results if filters are empty I have an SQL statement with a WHERE clause where I am adding additional filters if a variable passed into the stored procedure IN parameter is a certain value.
The IN parameter is called filterID and can be empty if I need all records, or have the value SEN,EAL or MAGT if I want to only select the records which have IDs in those columns from the LEFT JOINED tables.
This is the extract from the SQL query to show the joining of the tables and the additional filter.
LEFT JOIN tbl_sen ON tbl_pupil.pupilID = tbl_sen.pupilID
        LEFT JOIN tbl_eal ON tbl_pupil.pupilID = tbl_eal.pupilID
        LEFT JOIN tbl_magt ON tbl_pupil.pupilID = tbl_magt.pupilID
        WHERE
        tbl_test.schoolID=schoolID
        AND (
            (filterID='SEN' AND tbl_sen.senID IS NOT NULL) OR
            (filterID='EAL' AND tbl_eal.ealID IS NOT NULL) OR
            (filterID='MAGT' AND tbl_magt.magtID IS NOT NULL))
        AND tbl_test.import=1;

WHen I execute the stored procedure with the values, it shows the correct results. However, if I don't want to add the filter and pass filterID as empty/NULL, it returns 0 results when I need it to return ALL the results.
Can anyone spot what I'm doing wrong?

A: ...
AND CASE filterID WHEN 'SEN' THEN tbl_sen.senID IS NOT NULL
                  WHEN 'EAL' THEN tbl_eal.ealID IS NOT NULL
                  WHEN 'MAGT' THEN tbl_magt.magtID IS NOT NULL
                  ELSE filterID IS NULL END
AND ...

As I understand the filterID is local variable (SP parameter) so there is no problem to use it twice (rather than bound parameter of the query - in this case you may use user-defined intermediate variable).
Simplified DEMO

A: AND (
    (filterID='SEN' AND tbl_sen.senID IS NOT NULL) OR
    (filterID='EAL' AND tbl_eal.ealID IS NOT NULL) OR
    (filterID='MAGT' AND tbl_magt.magtID IS NOT NULL) OR
    (filterID IS NULL)
)


text:
Q: Power series - interval of convergence For
$f(x) = \sum_{n=2}^{\infty} \frac{(x+1)^n}{n(n-1)}$
I have showed that $f'(x) = \sum_{n=1}^{\infty} \frac{(x+1)^n}{n}$ and that $f''(x)=\frac{-1}{x}$ at all points where f converges absolutely. ( f converges absolutely whenever $\vert x + 1\vert < 1$. )
I now have to prove that $f(x)=1+x-xln(-x)$ on the convergence interval. I tried to do this by doing the following $f'(x) = \int -1/x~dx = -ln(x)$ and then I used this result to get
 $f(x) = \int -ln(x)~dx= x-xln(x)$.
But this is not correct and I cannot see what I did wrong.

A: Now that the question has been settled in comments, we give another way to evaluate the sum.
Let $t=x+1$, and use the partial fractions decomposition $\frac{1}{n(n-1)}=\frac{1}{n-1}-\frac{1}{n}$ to rewrite our sum as
$$\sum_2^\infty \frac{t^n}{n-1} -\sum_2^\infty \frac{t^n}{n}.$$
The first sum is $\sum_1^\infty t\cdot \frac{t^k}{k}$.  We know that the series for $\ln(1-t)$ is $\sum_1^\infty \frac{t^k}{k}$, so our first series is $t\ln(1-t)$.  The second series is easier, just $\ln(1-t)$ with first term missing, so $\ln t-t$.
We end up with $t\ln (1-t)-\ln(1-t)+t$. Now put $t=x+1$.


text:
Q: Getting started with javascript, got a questions I'm following w3school beginner tutorial for JS. There's something I don't understand from code below:

<!DOCTYPE html>

Can someone explain me the logic of text+=cars[i]? I understand that += means increment, but I can´t understand the logic behind adding the array element to variable text.
Thank you so much for your quick replies! I've got a follow up question: is there an alternative to display the same type of information with having to use the

var text = "";

and

text+=cars[i]

pieces of code? If so, how would the snippet of code look like and what should I insert into HTML if not

text

?
Thanks again!

A: a+=b is short for a=a+b. In your case you have text = text + cars[i] + "
".
text is a string, and you are using + to append a value from the array (that contains strings), and then append "
"

A: The value of text at the end of the loop is going to be
Saab
Volvo
BMW

where br stands for line break. So that each of them gets printed on new line.
And the last line of code
document.getElementById("demo").innerHTML = text;
changes the value of html element which has id of demo to that of text.

A: text += cars[i] + '
';

Concatenates element i of the cars array to the text, separated by a
 tag.

A: Consider it like this,
text+=cars[i] + "
";

is actually
text=text+cars[i]+"
";

so that rather than deleting the old value it will concatenate the new word with existing string.(String Concatenation).
PS:As a fellow beginner a small piece of advice rather than following W3 Schools please go to site like codecademy which helps you to learn along with practice and proper explanation.

A: Don't think of += as incrementing, that's ++.
a = a + b
a += b;

Those two statements are the same. The bottom one takes the variable on the left side (a) and appends the right side to it (b), and then assigns it all back to he left side (a). So it's just a shorthand.
So what you're doing in your code is appending the string from cars[i] to your variable text.
This would do the same thing:
text = text + cars[i] + "
";

Once the loop runs, you will have the following in text:
Saab
Volvo
BMW

A: In javascript + is used for string concatenation
The code
for(var i = 0; i < cars.length; i++) {
   text+=cars[i] + "
";
}

is picking each element from the array and concatenating "" to it.
If you console log the text before setting the innerHTML, it looks something like this -
"Saab
Volvo
BMW
"

A: here they do it actually just to show theres no point of doing it this way they just wanna show to reach each individual inside an array and concatanate it into a string the very same thing you can do with Array.prototype.join() method dont think here that u must use as they show always concatanate into a string if you want you can simply use every single individual inside as u wish as well

A: += is not increment. It's adding (in this case concatenation) and saving result in the same variable.
var a +=b;

Is the same to:
var = a + b;

In your case script concatenates all array elements into one string and adding
 tags between them.


text:
Q: addView(View) is not supported in AdapterView with Fragments i have 2 fragments in my application , i was working to make 2 pane mode for tablet UI , and its running correctly , but the one pane mode (for usual handsets) crashes every single time run the application.
this is the MainActivity..
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (findViewById(R.id.detail_container) != null) {
        // The detail container view will be present only in the large-screen layouts
        // (res/layout-sw600dp). If this view is present, then the activity should be
        // in two-pane mode.
        mTwoPane = true;
        // In two-pane mode, show the detail view in this activity by
        // adding or replacing the detail fragment using a
        // fragment transaction.
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.detail_container, new DetailFragment(), DETAILFRAGMENT_TAG)
                    .commit();
        }
    }
       else{
        mTwoPane = false;
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.main_container, new PlaceholderFragment())
                   .commit();
    }

and i have 2 activity_main.xml , on of them in the folder layout-sw600dp
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_container"
    android:name="com.example.moviefinal.MainFragment"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="2"
    tools:layout="@android:layout/list_content"/>

this is for the 2 pane mode(Tablet UI)..
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:divider="?android:attr/dividerHorizontal"
    android:orientation="horizontal"
    tools:context="com.example.moviefinal.MainActivity">

    <!--
    This layout is a two-pane layout for the Items master/detail flow.
    -->

    <fragment
        android:id="@+id/main_container"
        android:name="com.example.moviefinal.MainFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        tools:layout="@android:layout/list_content"
    />
    <FrameLayout
        android:id="@+id/detail_container"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="4" />

</LinearLayout>

and this is the in MainFragment.java
 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             final Bundle savedInstanceState) {
         rootView = inflater.inflate(R.layout.fragment_main, container, false);
             db = new DBAdapter(this.getActivity());

            gridView = (GridView) rootView.findViewById(R.id.gridview);
            ImageAdapter imgAdapter = new ImageAdapter(getActivity());
            gridView.setAdapter(imgAdapter);

Fragment_main.xml
    <?xml version="1.0" encoding="utf-8"?>

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/gridview"
    android:name="com.example.moviefinal.MainFragment"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:columnWidth="85dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="0dp"
    android:horizontalSpacing="0dp"
    android:gravity="center"

    android:stretchMode="columnWidth"
    tools:context=".MainActivity$PlaceholderFragment"
    />

i got those errors :
10-09 14:09:15.841  16029-16029/com.example.moviefinal E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.moviefinal, PID: 16029
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.moviefinal/com.example.moviefinal.MainActivity}: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
            at android.widget.AdapterView.addView(AdapterView.java:456)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:968)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499)
            at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:548)
            at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1220)
            at android.app.Activity.performStart(Activity.java:5949)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

i think the GridView Layout caused this error!
any help! Thanks in Advance.

A: Your first problem is this:
<fragment
    android:id="@+id/main_container"
    android:name="com.example.moviefinal.MainFragment"

If you declare a fragment in XML, you can't replace it programmatically with another fragment.
Just put a FrameLayout here and add your fragment at view creation.
Also, take this out of your GridView element XML:
android:name="com.example.moviefinal.MainFragment"

I think that's what's causing the "addView() not supported" heartburn.


text:
Q: Complement but not direct summand; Lam, Lectures on Modules and Rings, Example 6.17(5) Let $S$ be a submodule of an $R$-module $M$. A submodule $C⊆M$ is said to be a complement to $S$ (in $M$) if $C$ is maximal with respect to the property that $C∩S=0$. (This does exist by Zorn Lemma.) I search for a complement in $M$ (a submodule which is a complement to a submodule of $M$) that is not a direct summand in $M$. Over $R=\mathbb Z$, I considered the module $M=C⊕S$ where $C=\langle c\rangle$ has order $8$ and $S=\langle s\rangle$ has order $2$. My question is:

Could $C_1=\langle c_1\rangle$ of order 4 generated by $c_1=2c+s$ be a candidate for a complement of $M$ which is not a direct summand there of?

I would appreciate for any help!

A: $C'$ is not a direct summand in $M$: if there is $C''$ such that $C'+C''=M$ and $C'\cap C''=0$, then $|C''|=4$, so $C''$ is either cyclic or Klein.
Since the elements of order four are $(2,0)$, $(2,1)$, $(6,0)$, respectively $(6,1)$ it's clear that $C''=\langle(2,0)\rangle=\langle(6,0)\rangle$. But $|C'+C''|=8$, so $C'+C''\ne M$.
When $C''$ is of Klein type, then it contains three elements of order two, that is, $(0,1)$, $(4,0)$ and $(4,1)$. But $(4,0)\in C'$, a contradiction.
$C'$ is a complement in $M$: if $C'\subsetneq C''$ such that $C''\cap S=0$, then $C''\oplus S=M$ (note that $|C''|=8$). So $C''\simeq\mathbb Z/8\mathbb Z$ and thus $(2,1)\in 2C''$ (note that the order of $(2,1)$ is four). It follows that $(2,1)\in2M=2C$, a contradiction.


text:
Q: I am need select a option at the tk_menuOption and after invoke um event What I want is for it to fire the event bind to each choice made.
So I will not use a button to call any event.
This is my The doubt:
set choice [list \
{News} \
{Nature} \
{City} \
{Food} \
{People} \
{Anime} \
{Tecnology} \
{Objects} \
{Others}]

tk_optionMenu . chose {*}$choice

bind . <1> {
    clipboard clear
    clipboard append [%W cget -text]
    bell
    # Procedure to be invoke, this bellow:
    load
}

proc load { } {
   # Code here!
   tk_messageBox -message "You picked the option: $chose"
}

How to can I have some a event bind for tk_optionMenu, since that I can change first each option so to after do call procedure.
As in bind . <1>, there is no time to choose. Then, it is triggered by clicking on tk_menuOption.
I even tried to switch to other properties of the bind itself, but I didn't get the expected result.
I think something is missing to make it work as proposed in the question. I think it must be a stopwatch, which waits a few milliseconds before calling the event. This is what I imagine.

A: First off, tk_optionMenu is just a procedure.
Here's the source for it, but it's really quite short:
proc ::tk_optionMenu {w varName firstValue args} {
    upvar #0 $varName var

    if {![info exists var]} {
        set var $firstValue
    }
    menubutton $w -textvariable $varName -indicatoron 1 -menu $w.menu \
            -relief raised -highlightthickness 1 -anchor c \
            -direction flush
    menu $w.menu -tearoff 0
    $w.menu add radiobutton -label $firstValue -variable $varName
    foreach i $args {
        $w.menu add radiobutton -label $i -variable $varName
    }
    return $w.menu
}

If it doesn't do what you want, just take the code and modify it.
Secondly, events on menus are really tricky! In particular, if you are on Windows or macOS then many standard events are not delivered at all due to the way that their native menuing system works. Instead, you get two possible, useful callbacks:

*

*The -command callback on the menu items; this is supported by most of the menu items, especially including all the ones which end an interaction session with the menu (such as command items and radiobutton items).

*The -postcommand callback on the overall menu which is called when the menu is posted to the screen, giving you an opportunity to alter the contents of the menu dynamically (if you need it).

If what you want can't be done with those, it probably shouldn't be done with a menu in the first place as the interaction pattern with menus is pretty strongly fixed. A listbox might be more suitable? Or something custom (you often can do those with a text or canvas; no C required).

A: While the tk_menuOption does not provide a binding for when an option is selected, it has an associated variable. So you can put a trace on that variable and do whatever you want in the handler:
trace add variable chose write {apply {{name arg op} {
    upvar 1 $name var
    clipboard clear
    clipboard append $var
    bell
    # Procedure to be invoked
    load
}}}

Note: It is not a good idea to overwrite built-in commands, like load. It is likely to break a lot of things.

A: Even though we already have the answers as good solutions that this problem addresses.
Before I even received the answer, everyone found this link - https://wiki.tcl-lang.org/page/tk_optionMenu
The description of the "snippet" in the link is as follows:
tk_optionMenu $w varName a b c d
for {set i 0} {$i < [[$w cget -menu] index end]} {incr i} {
    [$w cget -menu] entryconfig $i -command $cmd
}

That was the discovery of the answer to solve my problem. So, I want to share with friends:
My Example:
#!/bin/sh
# \
exec wish "$0" "$@"

package require Tk

. configure -width 300 -height 200

set choice [list \
{News} \
{Nature} \
{City} \
{Food} \
{People} \
{Anime} \
{Tecnology} \
{Objects} \
{Others} ]

tk_optionMenu .foo chose {*}$choice

for {set i 0} {$i < [[.foo cget -menu] index end]} {incr i} {
    [.foo cget -menu] entryconfig $i -command {load;bell}
}

proc load { } {
global chose
    # Code here!
    tk_messageBox -message "You picked the option: $chose"
}

pack .foo -side left -fill both -expand 1
.foo config -indicatoron 0 -relief flat -justify center -bg white

Print:

But, the answers given by them .. Schelte Bron and Donal Fellows, were big help. Now I learn more things that I didn't know before. Since the words load are embedded in Tcl, it is not a good idea to use them.


text:
Q: what is the right way to implement the filter in this case I'm trying to make the second <select> (Preencha o campo) to show the results after filtering on the first <select> (Propriedade). I tried to do using the filter but without success.
function Conversor() {
  const [C1, setC1] = useState('');
  const [C2, setC2] = useState('');
const Medida = [
    {id: 1, Unidade: 'ml',  valor: 1, propriedade: 'Sala'},
    {id: 2, Unidade: 'L', valor: 0.30, propriedade: 'Sala'},
    {id: 3, Unidade: 'L', valor: 9.8, propriedade: 'Quarto'},
    {id: 4, Unidade: 'Kg', valor: 0.01, propriedade: 'Cozinha'},
];

  let novamedida = Medida.filter( (ele, ind) => ind === Medida.findIndex( elem => elem.propriedade === ele.propriedade && elem.propriedade === ele.propriedade))

  return (

Exemplo

      Propriedade
      <select className="propriedade">
        {novamedida.map(item => (
        <option
          Key={item.propriedade}
          propriedade={item.propriedade}
          >
              {item.propriedade}
          </option>
        ))}
      </select>

                Preencha o campo
                <input className="campo 1" type="number" id='campo1' required="required"value={C1} onChange={(e)=> setC1(e.target.value)}/>

        <select>{Medida.map(item2 => (
        <option
          Key={item2.Unidade}
          Unidade={item2.Unidade}
          >
              {item2.Unidade}
          </option>
        ))}
        </select>

  );
}

export default Conversor

i try this
const mesmapropriedade = function(it) {
    if(it.propriedade == Medida.propriedade) {
      return true;
    } else {
        return false;
    }
  }

  const novaUnidade = Medida.filter(mesmapropriedade);

A: First, you should store the result of the first select inside a variable.
Then, you can filter the Medida array based on that variable, directly inside the second select:
import React, { useState } from "react";

function Conversor() {
  const Medida = [
    { id: 1, Unidade: "ml", valor: 1, propriedade: "Sala" },
    { id: 2, Unidade: "L", valor: 0.3, propriedade: "Sala" },
    { id: 3, Unidade: "L", valor: 9.8, propriedade: "Quarto" },
    { id: 4, Unidade: "Kg", valor: 0.01, propriedade: "Cozinha" }
  ];

  // let novamedida = Medida.filter( (ele, ind) => ind === Medida.findIndex( elem => elem.propriedade === ele.propriedade && elem.propriedade === ele.propriedade))
  // We put the proriedade in a list of string and remove duplicates.
  let novamedida = [...new Set(Medida.map((medida) => medida.propriedade))];

  // Store the chosen propriedade
  const [chosenPropriedade, setChosenPropriedade] = useState("");
  const [C1, setC1] = useState("");
  const [C2, setC2] = useState("");

  return (

Exemplo

          Propriedade
          <select
            className="propriedade"
            onChange={(e) => {
              setChosenPropriedade(e.target.value)
            }}
            value={chosenPropriedade}
          >
            {novamedida.map((item, index) => (
              <option key={index} value={item}>
                {item}
              </option>
            ))}
          </select>

            Preencha o campo
            <input
              className="campo 1"
              type="number"
              id="campo1"
              required="required"
              value={C1}
              onChange={(e) => setC1(e.target.value)}
            />

          <select>
            {Medida.filter(
              (medida) =>
                chosenPropriedade === "" ||
                medida.propriedade === chosenPropriedade
            ).map((item2) => (
              <option key={item2.id} Unidade={item2.Unidade}>
                {item2.Unidade}
              </option>
            ))}
          </select>

  );
}

export default Conversor;

Here Medida.filter((medida) => chosenPropriedade === ''  ||  medida.propriedade === chosenPropriedade), we just return all of the Medida if no propriedade was chosen, or we return just the ones which have the same propriedade has the chosenPropriedade.


text:
Q: Последовательное выполнение $.each Добрый день!
Каким образом можно заставить следующий код работать последовательно?
$.each(this.db, function(index, element)
{
    $.get("calc/" + element.id, function(data)
        {
            $('#result').append('
' + data.result
');
        }, "json" );
});
$('#result').append('
done
');

На данный момент, получается, что отправляется одновременно n-ое количество запросов на сервер и не дожидаясь ответа выводится "done", после чего в "случайном" порядке ответы от сервера.

A: var db = this.db; //в верхнем scope, чтобы был доступ из функции
function fetchResult() { //для рекурсии
    if (db.length>0) { //если есть что-то еще в массиве
        var element = db.shift(); //забираем первое значение
        $.get("calc/" + element.id, function(data) {
            $('#result').append('
' + data.result + '
');
            fetchResult(); //ответ пришел - следующая "итерация"
        }, "json" );
    } else {
            $('#result').append('
done
');
    }
}

A: Используйте Deferred (переходите на темную сторону силы :))
var chain = $.Deferred().resolve();
$.each(this.db, function(index, element) {
    chain = chain.then(function() {
        // Самая соль этих строк в return - он возвращает Deferred объект,
        // к которому применяется следующий .then()
        return $.getJSON("calc/" + element.id).then(function(data) {
            $('#result').append('
' + data.result + '
');
        });
    });
});
chain.then(function() {
    $('#result').append('
done
');
});

PS. Ну и раз вы собираетесь использовать тип JSON, я поменял $.get({dataType: "json"}) на $.getJSON()
Ссылки по теме:

*

*Документация jQuery.Deferred (по-английски)

*Статья на Хабре (по-русски)

*Гугл с запросами JavaScript Promise и jQuery Deferred


text:
Q: Prototype 1 Challenge in Unity
I'm slightly confused with the transform.Rotate on this challenge.
I have the plane moving on the z axis horizontally using left/right keys. However, in the tut it says use "up" to operate the vertical using: "transform.Rotate(Vector3.up, rotationSpeed * verticalInput * Time.deltaTime);"
But up just rotates the plane round the y axis so I used "right" instead:
transform.Rotate(Vector3.right, rotationSpeed * verticalInput * Time.deltaTime);
Can someone please explain why "up" will not work?

A: In your case, it seems to be Vector3.Right (1,0,0) because your moving along the z-axis for your horizontal movement (actually, the x-axis would be preferable here, if your movement is kept 2D overall as "horizontal" in 2D is along x-axis usually). Z-axis is usually depth.
Transform.Rotate(Vector3 axis, float angle, Space relativeTo = Space.Self)
always rotates around the axis given as if the axis were the pole around which to rotate and in default uses the local coordinate system of the object. So in your case, Vector3.Right actually points towards you (out of the screen) from the local transform of the plane and rotating around this axis tilts the planes nose so to say.
It's a bit fiddly to explain transform rotations but I hope this helps.


text:
Q: How to fix missing JFrame library/class? As seen in screenshot 1, NetBeans (v8.2) does not recognise JFrame when extended (this is how NetBeans generated the file, which worked fine on another computer). As seen in screenshot 2, JFrame does not appear in the package list.
I have tried:

*

*Creating a new project

*Changing the line to extends JFrame

*Restarting IDE

*Reinstalling IDE

*Googling a lot (no one else seems to have this issue)

*Listed the bug at https://issues.apache.org/jira/browse/NETBEANS-905
Any ideas?
Screenshot 1:

Screenshot 2:

A: Followed a suggestion from Laszlo Kishalmi at issues.apache.org:

*

*Went to Help -> About in NetBeans.

*Copied filepath for cache folder in "About" window, closed NetBeans.

*Browsed the folder, deleted it.

*Re-opened NetBeans and the issue was solved.

Sorted!


text:
Q: AppendArrows in slick slider not moving sliders I have a page that uses slick slider and I would like to append the arrows to a certain div, my problem is that when I do append the arrows the slider no longer moves and if I don't then it works fine. The way I have my page set up I can't get the arrows to position themselves correctly when I resize the screen. That is why I need to append the arrows to the news_slider div. If I've left something out or if you need more information please let me know.
Here is my html

1

Well Good Ambassador 1

                            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eget erat a dolor mattis semper. Morbi at elementum dolor, id eleifend mi. Cras massa nisi, sagittis vel feugiat at, vulputate eu est. Nulla eu malesuada neque. Aliquam in ultrices purus. Proin nec fringilla nisi. Etiam eu risus ullamc...

                            Read full story...

2

Well Good Ambassador 1

                            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eget erat a dolor mattis semper. Morbi at elementum dolor, id eleifend mi. Cras massa nisi, sagittis vel feugiat at, vulputate eu est. Nulla eu malesuada neque. Aliquam in ultrices purus. Proin nec fringilla nisi. Etiam eu risus ullamc...

                            Read full story...

3

Well Good Ambassador 1

                            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eget erat a dolor mattis semper. Morbi at elementum dolor, id eleifend mi. Cras massa nisi, sagittis vel feugiat at, vulputate eu est. Nulla eu malesuada neque. Aliquam in ultrices purus. Proin nec fringilla nisi. Etiam eu risus ullamc...

                            Read full story...

Here is my js
    $('.slider-nav').slick({
    dots: true,
    infinite: true,
    speed: 300,
    arrows: false,
    asNavFor: '.single-item',
    slidesToShow: 4,
    focusOnSelect: true,
    centerMode: false,
    slidesToScroll: 1,
    prevArrow: '',
    nextArrow: '',
});

$('.single-item').slick({
    dots: false,
    infinite: true,
    speed: 300,
    arrows: true,
    asNavFor: '.slider-nav',
    lazyLoad: 'ondemand',
    slidesToShow: 1,
    slidesToScroll: 1,
    appendArrows: $(".news_slider"),
    prevArrow: '',
    nextArrow: '',
});

A: I had the same problem, maybe the reason is because the use of asNavFor in slick. Here is the workaround
Outside your slider div, create another div that contains two buttons or any inline attributes like i, span etc.

    <button class="leftArrow"> Prev </button>
    <button class="rightArrow"> Next </button>

Then in your javascript,
$('.leftArrow').on('click', function(){
    $('.single-item').slick("slickPrev");
});

A: Would you be able to post your actual html and not the html generated on the page when the javascript is run to create the carousel / slider?
I setup an example where you can move the slider via arrows that are attached to a div outside the slider container.  This might help.  I tried to use as much of your example html as possible.
https://jsfiddle.net/ftm8hu7n/1/

1

Well Good Ambassador 1

                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eget erat a dolor mattis semper. Morbi at elementum dolor, id eleifend mi. Cras massa nisi, sagittis vel feugiat at, vulputate eu est. Nulla eu malesuada neque. Aliquam in ultrices purus. Proin nec fringilla nisi. Etiam eu risus ullamc...

                        Read full story...

2

Well Good Ambassador 1

                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eget erat a dolor mattis semper. Morbi at elementum dolor, id eleifend mi. Cras massa nisi, sagittis vel feugiat at, vulputate eu est. Nulla eu malesuada neque. Aliquam in ultrices purus. Proin nec fringilla nisi. Etiam eu risus ullamc...

                        Read full story...

3

Well Good Ambassador 1

                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eget erat a dolor mattis semper. Morbi at elementum dolor, id eleifend mi. Cras massa nisi, sagittis vel feugiat at, vulputate eu est. Nulla eu malesuada neque. Aliquam in ultrices purus. Proin nec fringilla nisi. Etiam eu risus ullamc...

                        Read full story...

test


text:
Q: Как вывести выборку строк в pandas Подскажите, пожалуйста, как вывести выборку строк, где в столбце (например "Адрес покупателя") были бы значения "1521..."?
Предполагаю это будет через :
value_list = ['1521...']

df[df.Адрес покупателя.isin(value_list)].

Когда так ввожу - не получается.
И сопутствующий вопрос: как обозвать эту получившуюся выборку, чтобы дальше с ней работать.
Ссылка на файлы .pynb и .xlsx:
http://dropmefiles.com/BoGd5
сам код:
value_list = ['1521..']
df[df.Адрес покупателя.isin(value_list)]

ошибка:

SyntaxError: invalid syntax

df:
+-----------------+-------------------------------+------------------+
| Сумма заказа, $ |       Адрес покупателя        | Категория товара |
+-----------------+-------------------------------+------------------+
|               2 | Проспект 40 , 152193, RU      | Для детей        |
|            5,01 | Советская, 301282, RU         | Платья           |
|               4 | Ярославская Обл. , 152104, RU | Часы             |
|            6,32 | Ул. Партизанская , 301225, RU | Платья           |
+-----------------+-------------------------------+------------------+

A: Ошибка в том, что Series.isin(list-like-object) - ищет полные совпадения - поэтому в вашем случае ничего найдено не было. Для поиска подстрок можно динамически собрать регулярное выражение (пример ниже) и воспользоваться Series.str.contains(regex_pattern).
Пример для Python 3.x (для Python 2.x возможно придется указывать u'' перед именами столбцов):
In [4]: df
Out[4]:
                              Дата покупки  Сумма заказа, $               Адрес покупателя Категория товара
0  Thu Jun 02 2016 20:02:12 GMT+0000 (UTC)             2.00       Проспект 40 , 152193, RU        Для детей
1  Fri Jun 03 2016 10:17:30 GMT+0000 (UTC)             5.01          Советская, 301282, RU           Платья
2  Fri Jun 03 2016 17:15:15 GMT+0000 (UTC)             4.00  Ярославская Обл. , 152104, RU             Часы
3  Fri Jun 03 2016 20:52:54 GMT+0000 (UTC)             6.32  Ул. Партизанская , 301225, RU           Платья

Список почтовых индексов:
In [5]: zips = ['152193','301225']

RegEx (регулярное выражение) для поиска указанных в списке индексов в строке:
In [6]: pat = r'\b(?:{})\b'.format('|'.join(zips))

In [7]: pat
Out[7]: '\\b(?:152193|301225)\\b'

Ищем в столбце Адрес покупателя подстроку по созданному выше RegEx и показываем только те строки, кот. удовлетворяют данному условию:
In [8]: df[df['Адрес покупателя'].str.contains(pat)]
Out[8]:
                              Дата покупки  Сумма заказа, $               Адрес покупателя Категория товара
0  Thu Jun 02 2016 20:02:12 GMT+0000 (UTC)             2.00       Проспект 40 , 152193, RU        Для детей
3  Fri Jun 03 2016 20:52:54 GMT+0000 (UTC)             6.32  Ул. Партизанская , 301225, RU           Платья

Пример поиска по начальным цыфрам индекса:
In [27]: zips = ['3012\d+','152193']

In [28]: pat = r'\b(?:{})\b'.format('|'.join(zips))

In [29]: pat
Out[29]: '\\b(?:3012\\d+|152193)\\b'

In [30]: df[df['Адрес покупателя'].str.contains(pat)]
Out[30]:
                              Дата покупки  Сумма заказа, $               Адрес покупателя Категория товара
0  Thu Jun 02 2016 20:02:12 GMT+0000 (UTC)             2.00       Проспект 40 , 152193, RU        Для детей
1  Fri Jun 03 2016 10:17:30 GMT+0000 (UTC)             5.01          Советская, 301282, RU           Платья
3  Fri Jun 03 2016 20:52:54 GMT+0000 (UTC)             6.32  Ул. Партизанская , 301225, RU           Платья

PS Лучше использовать явную адресацию:
df[df['Адрес покупателя'].isin(value_list)]

или для Python 2.x в том случае если названия столбцов в UTF-8:
df[df[u'Адрес покупателя'].isin(value_list)]

Адресация столбцов в Pandas через точку не работает в следующих случаях:

*

*имя столбца содержит NON-ASCII символ(ы)

*имя столбца содержит пробелы/табуляции

*имя столбца совпадает с названием метода Pandas или Numpy


text:
Q: How to position UserControl in the parent canvas I want to place this UserControl at Canvas.Left="168", Canvas.Top="213".
However, the control appears at a corner.  What should I do?
If I put the values at the point of usage for this class, the values are returned as NaN
In that case how can I get the correct Left and Top Values?
Usage:
<Canvas x:Name="DesignerCanvas"
        ClipToBounds="True"
        SnapsToDevicePixels="True">
<Gr:BareNode />
</Canvas>

UserControl:
<UserControl x:Class="DiagramDesigner.BareNode"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Grid>
    <ContentControl Width="50"
                  Height="50"
                  Padding="2"
                  Canvas.Left="168" Canvas.Top="213">
        <Ellipse IsHitTestVisible="False" >
            <Shape.Fill>
                <RadialGradientBrush Center="0.2, 0.2" GradientOrigin="0.2, 0.2" RadiusX="0.8" RadiusY="0.8">
                    <GradientStop Color="LightBlue" Offset="0"/>
                    <GradientStop Color="Blue" Offset="0.9"/>
                </RadialGradientBrush>
            </Shape.Fill>
        </Ellipse>
    </ContentControl>
   </Grid>
</UserControl>

A: I'm not sure if you tried this or not, but just from looking at the XAML it appears that you are trying to set the position of the user control inside the user control. That won't work. You need to put it where you use the user control
<Canvas x:Name="DesignerCanvas"
    ClipToBounds="True"
    SnapsToDevicePixels="True">
   <Gr:BareNode Canvas.Left="168" Canvas.Top="213"/>
</Canvas>

Take the Canvas.Left="168" Canvas.Top="213"  part out of the ContentControl declaration of inside the user control.


text:
Q: Return 200 OK response I've got a webhook which sends a XML and mail after a order is paid succesfully. The payment provider (Mollie) needs to get a 200 OK response otherwise it keeps calling my webhook, which sends the XML and mail continuesly. Anyone knows what I'm doing wrong here..?
    if($payment->status == 'paid') {
            // Create XML file
            include_once("create-xml.php");
            file_put_contents("order-" . $orders[0]['id'] . ".xml",$xml);

            // Send XML file
            include_once("send-xml.php");

            // Delete XML file
            unlink("order-" . $orders[0]['id'] . ".xml");

            // Send e-mail to customer
            include_once("send-mail.php");

            header(':', true, 200);
            header('X-PHP-Response-Code: 200', true, 200);
            return;

        }


text:
Q: Get widgetVar with JavaScript or check/uncheck all other PrimeFaces checkboxes I have several PrimeFaces checkboxes on a page. If you click the master checkbox, all other checkboxes should be checked/unchecked. With plain HTML checkboxes this would be an easy issue. But because PrimeFaces does not show the checkbox itself, but an image, the following JavaScript code does not work:
<script type="text/javascript">
$(document).ready(function() {
    var masterCheckbox = $(".ui-chkbox.master :checkbox");
    var slaveCheckboxes = $(".ui-chkbox:not(.master) :checkbox");

    updateMaster();
    masterCheckbox.change(updateSlaves);
    slaveCheckboxes.change(updateMaster);

    function updateMaster() {
        var allSlavesChecked = true;
        slaveCheckboxes.each(function() {
            if (!$(this).is(':checked')) {
                allSlavesChecked = false;
            }
        });
        masterCheckbox.attr("checked", allSlavesChecked);
    }

    function updateSlaves() {
        var masterChecked = masterCheckbox.is(":checked");
        slaveCheckboxes.each(function() {
            $(this).attr("checked", masterChecked);
        });
    }
});
</script>

I know that I could use the PrimeFaces widgetVar to toggle the checkboxes, but I do not know how to get the PrimeFaces widget objects with JavaScript. I think RichFaces adds the component property to the DOM element, but PrimeFaces does not. Does somebody know a solution for this problem?

A: You were correct -- if you create your component like this:
<p:selectBooleanCheckbox value="val" widgetVar="myCheckbox"/>

You can access the checkbox simply by refering to its widgetVar, in this case calling the PrimeFaces client-side API to mark it as checked:
<script>
   myCheckbox.check();
</script>

You could then tie the onchange event of your master checkbox to a javascript method that checked or unchecked the state of all the "slave" checkboxes depending on the state of the master checkbox (would suggest you store the state in a hidden field).
Note, it may make your life easier to instead handle the "change" ajax event and implement the check/uncheck logic on the server side. Just make sure that you provide all the ids of all the slave checkboxes in the update attribute of the p:ajax component:
<p:selectBooleanCheckbox id="masterChkBox" ...>
  <p:ajax event="change" listener="#{yourBean.handleMasterChange}" update="...all slavecheckbox ids..."/>
</p:selectBooleanCheckbox>


text:
Q: Blog site that will show blog posts from different blog sites In SharePoint 2013 i want to show blog posts from different blog sites (under same site collection) on my blog site. please suggest how can i achieve it using OOTB features.

A: A possible solution could be to use a Content By Search Webpart (CSWP) to find all your blogs. The CSWP is able to search over all your sitecollections, so it will also find all blogs within a sitecollection even if there posted on different blog sites.
You can add the CSWP to the default.aspx of your blog site. There a plenty of blogpost on internet which describe how to use the Content By Search Webpart. For eamxple:

*

*https://support.office.com/en-US/article/Configure-a-Content-Search-Web-Part-in-SharePoint-0dc16de1-dbe4-462b-babb-bf8338c36c9a
The most complicated in there is setting the correct query. The query you could use is ContentTypeId:0x0110* Path:{SiteCollection.URL}. The ContentTypeId:0x0110* is set to the ID of the Blog Content Type so only items of that specific Content Type will show. Path:{SiteCollection.URL} means we only want results from the current sitecollection.
Afther the query is set your results might look like this:

These are three blogpost which come from diffrent subsites of the same sitecollection on my development machine. The results might not look like you want them too. You can edit the way the results of the CSWP look by using display templates. The following link from microsoft explains how to create a custom display template for your search results.


text:
Q: Is it problematic if most of the weights or biases in a hidden layer are the same sign? I'm trying to diagnose overfitting in my multi-layer perceptron by looking at the weights, biases and gradients in each layer. I'm noticing that in the neural network that is overfitting, the weights in one of the hidden layers all have the same sign, and the majority of the biases in all the hidden layers have the same sign. In the network that isn't overfitting, the biases are centred on zero, with rougly equal numbers of positive and negative values. I'm using xavier initialization for both.

A: I think that the same signs of the biases or weights aren't the cause of overfitting in your network. Overfitting in a network occurs when the neurons become dependent to one another when learning. You need to make sure that your neurons are learning independently. Thus, you should try using dropouts. Dropouts remove or disable a certain percentage of neurons randomly.

A: weights and biases are a symptom of overfitting not a cause.  You're better off looking at things like the NN architecture, the train/test/validate split (consider k-fold cross validation), and regularization techniques


text:
Q: Finite Rank Operators actually I want to prove
Let $X$ be a Banach space. $T \in B(X)$ be a finite rank bounded linear operator. Then $$Tx= \sum_{i=1}^{n} f_i(x) x_i$$ where $x_1,x_2 \ldots ,x_n$ from $X$  and $f_1,f_2 \ldots f_n$ from $X^\star$ are linearly independent.