text:
Q: Using generating functions to find the number of compositions Solve the following problem in three ways:
a) as a principle of inclusion-exclusion problem,
b) using generating functions,
c) using the rule of sums.
How many compositions of $2n+1$ with three parts have no part exceeding the sum of the other two? (Thus we are concerned with compositions $y_1+y_2+y_3=2n+1$ with $y_i\leq y_j+y_k$ whenever $\{i,j,k\}=\{1,2,3\}$).
So I'm a little confused as to how to start any of these problems
For part a) I have the properties
$p_1: y_1>y_2+y_3$
$p_2: y_2>y_1+y_3$
$p_3: y_3>y_1+y_2$
And we want $e(\emptyset)=a(\emptyset)-a(p_1)-a(p_2)-a(p_3)$
Could anyone help me get on the right track? Thank you!

A: A particular solution of the equation in the nonnegative integers
$$y_1 + y_2 + y_3 = 2n + 1 \tag{1}$$
corresponds to the placement of two addition signs in a row of $2n + 1$ ones.  For instance, if $n = 5$,
$$1 1 1 1 + + 1 1 1 1 1 1 1$$
corresponds to the solution $y_1 = 4$, $y_2 = 0$, $y_3 = 7$.  The number of solutions of equation 1 in the nonnegative integers is equal to the number of ways we can place two addition signs in a row of $2n + 1$ ones, which is
$$\binom{2n + 1 + 3 - 1}{3 - 1} = \binom{2n + 3}{2}$$
since we must choose which two of the $2n + 3$ positions required for $2n + 1$ ones and two addition signs will be filled with addition signs.
From these, we must subtract those solutions in which one of the numbers exceeds the sum of the other two, which occurs if some $y_i \geq n + 1$.
Suppose that $y_1 \geq n + 1$.  Then $y_1' = y_1 - (n + 1)$ is a nonnegative integer.  Substituting $y_1' + (n + 1)$ for $y_1$ in equation 1 yields
\begin{align*}
y_1' + (n + 1) + y_2 + y_3 & = 2n + 1\\
y_1' + y_2 + y_3 & = n
\end{align*}
which is an equation in the nonnegative integers with
$$\binom{n + 3 - 1}{3 - 1} = \binom{n + 2}{2}$$
solutions.
By symmetry, the number of solutions of equation 1 in which $y_1 > y_2 + y_3$ is equal to the number of solutions in which $y_2 > y_1 + y_3$ and the number of solutions in which $y_3 > y_1 + y_2$.  Hence,
$$\binom{3}{1}\binom{n + 2}{2}$$
solutions violate the restriction that no part exceeds the sum of the other two.
Hence, the number of admissible solutions is
$$\binom{2n + 3}{2} - \binom{3}{1}\binom{n + 2}{2}$$
For the generating function, since none of the parts can exceed $n$, we want to find the coefficient of $x^{2n + 1}$ in the expansion of
$$(1 + x + x^2 + \ldots + x^n)^3$$


text:
Q: how to resolve the max count 25 limitation of watson conversation intent I want to develop one robot using watson conversation, this robot can answer some frequently asked question about my application. Here is my thinking, every question has its own intent, and the answer will be returned by response. but I have over 50 questions, that means I need to define over 50 intents, but watson conversation limited 25 intents for one workspace. Does anyone have any idea about how to resolve it? Thanks.

A: There are two options for you

*

*Purchase Standard plan ($0.0025 USD/API call)Includes upto Up to 2000 Intents.Check out more on pricing here

*Link similar questions together and try to reduce the questions.For example, take two questions regarding Bank withdrawals and Bank deposits could be asked in one intent as Bank transaction and then put type of transactions as entities(dialogue box condition as entities).

A: And besides that limit, there is another one: max 1000 API queries/month. It if fine for a proof of concept or to development phase. If you intend to go to production, you should purchase a plan. https://www.ibm.com/watson/developercloud/conversation.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem with autocorrelation in linear regression I have a linear model: acc2014 = v + b*acc2013 + cbook2013. The independent variables are economic variables. The error terms are correlated. What is the best solution for this?

A: The best way is to use a dynamic regression model with ARIMA errors. Rob Hyndman's online book has an excellent introduction and some examples.

A: There is not a best solution in general, it depends on your case. For example:

*

*including lags of the dependent/indepedented variable/s can be a good solution to take into account autocorrelation in your model

*if your goal is to analyze the coefficients you can use heteroscedasticity-consistent standard errors

*otherwise as suggested you can change the underlying model of residuals


text:
Q: pass variable from one function to another javascript (i work on a google maps project)
I'm trying to pass latlon variable form function showPosition to hello function, but i cant.
When i print latlon in showPosition function everything work.
When i print latlon on hello function i get blank page.

var latlon;

window.onload = function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
   var latlon = position.coords.latitude + "," + position.coords.longitude;
   /*document.write (latlon); */
}

function hello() {
    variablelatlon = latlon;
    document.write (variablelatlon);
}

showPosition();
hello();

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}

I change my code to this. But i dont see any coordinates as result.

var x = document.getElementById("demo");
var coordlat;
var coordlng;

window.onload = function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
   var latlon = position.coords.latitude + "," + position.coords.longitude;
   coordlat = position.coords.latitude;
   coordlng = position.coords.longitude;
}

function hello() {
    document.write (coordlat);
    document.write (coordlng);
}

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}

showPosition();
hello();

A: Just remove var:
function showPosition(position) {
   latlon = position.coords.latitude + "," + position.coords.longitude;
   /*document.write (latlon); */
}

The fact is, whenever you define a variable by the keyphrase var, you make that variable local for that scope and global for all inside functions.
You already defined latlon as a global variable. When you put var before that inside another function, it would be local inside the function scope. So, it would not affect the global one.

A: You declared a global variable latlon but then make it local by redeclaring it in function showPosition. This should help:
var latlon;

window.onload = function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
// You declared global variable laton but then make it local by redeclaring it in function showPosition
function showPosition(position) {
    /*var*/
    latlon = position.coords.latitude + "," + position.coords.longitude;
    /*document.write (latlon); */
}


text:
Q: How can I see the console of a .bat file started with child-process package? I'm making a discord bot where my friends can type a command and it will start a minecraft server on my pc. I'm using child-process to run the specified .bat file in node.js. The only problem is I can't see the server console (the cmd prompt window). My code looks like this:
let exec = require('child_process').exec;
exec("cmd /c \"path to .bat file\"");

It works, and after a while the server starts and we can join, but I can't see the command prompt window that it is running out of. How can I see the console?


text:
Q: SQL query function when for loop is terminated I have loop like
for (i=0, i < var.lenght , i++ )

and I would like to execute a sql query when the loop is terminated, how to do that? I trien promise then but it didn't work

A: You can try:
for (i=0, i < var.lenght , i++ ) {
    something in the loop
}

Then put your query here;


text:
Q: How to compute conditional expectation, $\textbf{E}[X|r(X) \leq w]$? Let $X\sim \textbf{U}[0,1]$, and $r(X) = 0.5X^2 + 0.3X$, then what is $\textbf{E}[X|r(X) \leq w]$?
This honestly seems just so simple, but I am not confident. Is it simply,
\begin{align}
\int_0^w r(X)dX \approx 0.17w^3+0.15w^2?
\end{align}
Or is is because $X$ is constrained by $w$, $$0 \leq X \leq 1 \Rightarrow 0 \leq r(X) \leq w \leq 0.8,$$
I am supposed to find the inverse of $r(X)$,
\begin{align}
r^{-1}(X) = -0.3 \pm 0.1\sqrt{200X+9},
\end{align}
making the expectation, $\textbf{E}[X|X \leq r^{-1}(w)]$
which is,
\begin{align}
\textbf{E}[X|X \leq r^{-1}(w)] = \int_0^{-0.3 \pm 0.1\sqrt{200w+9}} xdx = \frac{-0.3 \pm 0.1\sqrt{200w+9}}{2}?
\end{align}
Where $0 \leq w \leq 0.8$.
Yeah, I am just stuck because I am not terribly certain how to interpret and operate on the condition of the expectation...

A: $$.5x^2+.3x-w\le0$$
First solve the equality
$$.5x^2+.3x-w=0\Rightarrow x=-.3\pm\sqrt{.09+2w}$$
Now you may recall from high school math that this can be factored into $(x-(-.3+\sqrt{.09+2w}))(x-(-.3-\sqrt{.09+2w}))\le0$ and will be positive when $x$ is less than both of those values or greater than both of those values and negative when it is between those two values. In fact $-.3-\sqrt{.9+2w}<0$ and $X$ is uniform on $[0,1]$ so we know $X$ is between $0$ and $-.3+\sqrt{.09+2w}$.
Given this we now find the conditional expectation $\mathbb E(X|X<-.3+\sqrt{.09+2w})$. This involves reweighing the density of $X$ to $$\frac {f(X)}{\Pr(X<-.3+\sqrt{.09+2w})},0<X<-.3+\sqrt{.09+2w}\\
=\frac 1 {-.3+\sqrt{.09+2w}}$$
Then the expected value is
$$\begin{split}\int_0^{-.3+\sqrt{.09+2w}}\frac x{-.3+\sqrt{.09+2w}}dx&=\frac{x^2}{2(-.3+\sqrt{.09+2w})}\bigg|_{x=0}^{-.3+\sqrt{.09+2w}}\\
&=\frac{-.3+\sqrt{.09+2w}}{2}\end{split}$$


text:
Q: Is  List extends T> f() a useful signature Is <T> List<? extends T> f() a useful signature? Is there any problem with it / using it?
This was an interview question. I know this:

*

*It compiles fine

*Use it like List<? extends Number> lst = obj.<Number>f(), and then I can call on lst only those List methods that do not contain T in their signatures (say, isEmpty(), size(), but not add(T), remove(T)
Does that fully answer the question?

A: This method signature is "useful", in the sense that you can implement non-trivial, non-degenerate methods with it (that is, returning null and throwing errors are not your only options). As the following example shows, such a method can be useful for implementing some algebraic structures like e.g. monoids.
First, observe that List<? extends T> is a type with the following properties:

*

*You know that all elements of this list conform to the type T, so whenever you extract an element from this list, you can use it in position where a T is expected. You can read from this list.

*The exact type is unknown, so you can never be certain that an instance of a particular subtype of T can be added to this list. That is, you effectively cannot add new elements to such a list (unless you use nulls / type casts / exploit unsoundness of Java's type system, that is).

In combination, it means that List<? extends T> is kind-of like an append-protected list, with type-level append-protection.
You can actually do meaningful computations with such "append-protected" lists. Here are a few examples:

*

*You can create append-protected lists with a single element:
public static <T> List<? extends T> pure(T t) {
  List<T> result = new LinkedList<T>();
  result.add(t);
  return result;
}

*You can create append-protected lists from ordinary lists:
public static <T> List<? extends T> toAppendProtected(List<T> original) {
  List<T> result = new LinkedList<T>();
  result.addAll(original);
  return result;
}

*You can combine append-protected lists:
public static <T> List<? extends T> combineAppendProtected(
  List<? extends T> a,
  List<? extends T> b
) {
  List<T> result = new LinkedList<T>();
  result.addAll(a);
  result.addAll(b);
  return result;
}

*And, most importantly for this question, you can implement a method that returns an empty append-protected list of given type:
public static <T> List<? extends T> emptyAppendProtected() {
  return new LinkedList<T>();
}

Together, combine and empty form an actual algebraic structure (a monoid), and methods like pure ensure that it's non-degenerate (i.e. it has more elements that just an empty list). Indeed, if you had an interface similar to the usual Monoid typeclass:
  public static interface Monoid<X> {
    X empty();
    X combine(X a, X b);
  }

then you could use the above methods to implement it as follows:
  public static <T> Monoid<List<? extends T>> appendProtectedListsMonoid() {
    return new Monoid<List<? extends T>>() {
      public List<? extends T> empty() {
        return ReadOnlyLists.<T>emptyAppendProtected();
      }

      public List<? extends T> combine(
        List<? extends T> a,
        List<? extends T> b
      ) {
        return combineAppendProtected(a, b);
      }
    };
  }

This shows that methods with the signature given in your question can be used to implement some common design patterns / algebraic structures (monoids). Admittedly, the example is somewhat contrived, you probably wouldn't want to use it in practice, because you don't want to astonish the users of your API too much.

Full compilable example:
import java.util.*;

class AppendProtectedLists {

  public static <T> List<? extends T> emptyAppendProtected() {
    return new LinkedList<T>();
  }

  public static <T> List<? extends T> combineAppendProtected(
    List<? extends T> a,
    List<? extends T> b
  ) {
    List<T> result = new LinkedList<T>();
    result.addAll(a);
    result.addAll(b);
    return result;
  }

  public static <T> List<? extends T> toAppendProtected(List<T> original) {
    List<T> result = new LinkedList<T>();
    result.addAll(original);
    return result;
  }

  public static <T> List<? extends T> pure(T t) {
    List<T> result = new LinkedList<T>();
    result.add(t);
    return result;
  }

  public static interface Monoid<X> {
    X empty();
    X combine(X a, X b);
  }

  public static <T> Monoid<List<? extends T>> appendProtectedListsMonoid() {
    return new Monoid<List<? extends T>>() {
      public List<? extends T> empty() {
        return AppendProtectedLists.<T>emptyAppendProtected();
      }

      public List<? extends T> combine(
        List<? extends T> a,
        List<? extends T> b
      ) {
        return combineAppendProtected(a, b);
      }
    };
  }

  public static void main(String[] args) {
    Monoid<List<? extends String>> monoid = appendProtectedListsMonoid();
    List<? extends String> e = monoid.empty();
    // e.add("hi"); // refuses to compile, which is good: write protection!
    List<? extends String> a = pure("a");
    List<? extends String> b = pure("b");
    List<? extends String> c = monoid.combine(e, monoid.combine(a, b));
    System.out.println(c); // output: [a, b]
  }

}

A: I interpret "is it a useful signature" to mean "can you think of a use-case for it".
T is determined at the call site, not inside the method, so there are only two things that you can return from the method: null or an empty list.
Given that you can create both of these values in roughly as much code as invoking this method, there isn't really a good reason to use it.

Actually, another value that can be safely returned is a list where all of the elements are null. But this isn't useful either, since you can only invoke methods which add or remove literal null from the return value, because of the ? extends in the type bound. So all you've got is thing which counts the number of nulls it contains. Which isn't useful either.

A: The official Generics tutorial suggests not to use wildcard return types.

These guidelines do not apply to a method's return type. Using a wildcard as a return type should be avoided because it forces programmers using the code to deal with wildcards."

The reasoning given isn't exactly convincing, though.

A: It's not particularly useful, for the reasons given in other answers. However, consider it's "usefulness" in a class like the following (although it's probably a bit of an antipattern):
public class Repository {
    private List<Object> lst = new ArrayList<>();

    public <T> void add(T item) {
        lst.add(item);
    }

    @SuppressWarnings("unchecked")
    public <T> List<? extends T> f() {
        return (List<? extends T>) lst;
    }

    public static void main(String[] args) {
        Repository rep = new Repository();
        rep.add(BigInteger.ONE);
        rep.add(Double.valueOf(2.0));
        List<? extends Number> list = rep.f();
        System.out.println(list.get(0).doubleValue() + list.get(1).doubleValue());
    }
}

Note the following features:

*

*The declared return type of f() means that the caller can set whatever T they like and the method will return the required type. If f() weren't declared like that, then the caller would need to cast every call to get(N) to the required type.

*As it uses a wildcard, the declared return type makes the returned list read-only. This can often be a useful feature. When caller a getter, you don't want it to return a list you can write to. Often, getters use Collections.unmodifiableList() which forces a list to be read-only at run-time, but using the wildcard generic parameter forces the list to be read-only at compile-time!

*The drawback is that it's not particularly type-safe. It is up to the caller to ensure that f() returns a type where T is a common superclass of all the previously added items.

*It would typically be much better to make the class Repository generic instead of the method f().


text:
Q: java.lang.ArrayStoreException: org.eclipse.e4.ui.model.application.ui.menu.impl.MenuContributionImpl I am adding a menuContribution to an eclipse plugin and I am getting the error message above. Below is the fragment.e4xmi
<?xml version="1.0" encoding="ASCII"?>
<fragment:ModelFragments xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:commands="http://www.eclipse.org/ui/2010/UIModel/application/commands" xmlns:fragment="http://www.eclipse.org/ui/2010/UIModel/fragment" xmlns:menu="http://www.eclipse.org/ui/2010/UIModel/application/ui/menu" xmi:id="_PPqj4EOQEeedq-IevvWAag">
  <fragments xsi:type="fragment:StringModelFragment" xmi:id="_p3R7sEOQEeedq-IevvWAag" featurename="commands" parentElementId="org.eclipse.e4.legacy.ide.application">
    <elements xsi:type="commands:Command" xmi:id="_4tuLgEOQEeedq-IevvWAag" elementId="com.bodastage.e4.clock.ui.command.hello" commandName="Hello" description="Says Hello World"/>
  </fragments>
  <fragments xsi:type="fragment:StringModelFragment" xmi:id="_hDBbUEOREeedq-IevvWAag" featurename="handlers" parentElementId="org.eclipse.e4.legacy.ide.application">
    <elements xsi:type="commands:Handler" xmi:id="_pG9ckEOREeedq-IevvWAag" elementId="com.bodastage.e4.clock.ui.handler.HelloHandler" contributionURI="bundleclass://com.bodastage.e4.clock.ui/com.bodastage.e4.clock.ui.handlers.HelloHandler" command="_4tuLgEOQEeedq-IevvWAag"/>
  </fragments>
  <fragments xsi:type="fragment:StringModelFragment" xmi:id="_8OBJMEZTEeehrvUiei9LJA" featurename="handlers" parentElementId="org.eclipse.e4.legacy.ide.application">
    <elements xsi:type="menu:MenuContribution" xmi:id="_JcJ-cEZUEeehrvUiei9LJA" elementId="com.bodastage.e4.clock.ui.menucontribution.0" parentId="help">
      <children xsi:type="menu:HandledMenuItem" xmi:id="_OSQxwEZUEeehrvUiei9LJA" elementId="com.bodastage.e4.clock.ui.handledmenuitem.Hello" label="Hello" iconURI="platform:/plugin/com.bodastage.e4.clock.ui/icons/sample.gif" command="_4tuLgEOQEeedq-IevvWAag"/>
    </elements>
  </fragments>
</fragment:ModelFragments>

Below is the run log:
Starting application: 1179
!SESSION 2017-06-01 02:10:52.203 -----------------------------------------------
eclipse.buildId=4.6.3.M20170301-0400
java.version=1.8.0_121
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_GB
Framework arguments:  -product org.eclipse.platform.ide
Command-line arguments:  -product org.eclipse.platform.ide -data C:\Users\Emmanuel\workspace/../runtime-EclipseApplication -dev file:C:/Users/Emmanuel/workspace/.metadata/.plugins/org.eclipse.pde.core/Eclipse Application/dev.properties -debug C:\Users\Emmanuel\workspace\.metadata\.plugins\org.eclipse.pde.core\Eclipse Application/.options -os win32 -ws win32 -arch x86_64 -consoleLog

!ENTRY org.eclipse.osgi 4 0 2017-06-01 02:10:54.335
!MESSAGE Application error
!STACK 1
java.lang.ArrayStoreException: org.eclipse.e4.ui.model.application.ui.menu.impl.MenuContributionImpl
    at org.eclipse.emf.common.util.BasicEList.assign(BasicEList.java:118)
    at org.eclipse.emf.common.util.BasicEList.addUnique(BasicEList.java:417)
    at org.eclipse.emf.common.notify.impl.NotifyingListImpl.doAddUnique(NotifyingListImpl.java:325)
    at org.eclipse.emf.common.notify.impl.NotifyingListImpl.addUnique(NotifyingListImpl.java:309)
    at org.eclipse.emf.common.util.AbstractEList.add(AbstractEList.java:303)
    at org.eclipse.e4.ui.model.internal.ModelUtils.mergeList(ModelUtils.java:197)
    at org.eclipse.e4.ui.model.internal.ModelUtils.merge(ModelUtils.java:145)
    at org.eclipse.e4.ui.model.fragment.impl.StringModelFragmentImpl.mergeIdList(StringModelFragmentImpl.java:322)
    at org.eclipse.e4.ui.model.fragment.impl.StringModelFragmentImpl.merge(StringModelFragmentImpl.java:300)
    at org.eclipse.e4.ui.internal.workbench.ModelAssembler.processModelFragment(ModelAssembler.java:272)
    at org.eclipse.e4.ui.internal.workbench.ModelAssembler.processFragmentConfigurationElement(ModelAssembler.java:162)
    at org.eclipse.e4.ui.internal.workbench.ModelAssembler.processFragments(ModelAssembler.java:118)
    at org.eclipse.e4.ui.internal.workbench.ModelAssembler.processModel(ModelAssembler.java:96)
    at org.eclipse.e4.ui.internal.workbench.ResourceHandler.loadMostRecentModel(ResourceHandler.java:197)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.loadApplicationModel(E4Application.java:377)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.createE4Workbench(E4Application.java:252)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:632)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1519)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1492)
An error has occurred. See the log file
C:\Users\Emmanuel\runtime-EclipseApplication\.metadata\.log.

I have failed to find any useful information after googling and browsing stackoveflow for java.lang.ArrayStoreException related questions. I will appreciate any pointers to sort this out.

A: This:
<fragments xsi:type="fragment:StringModelFragment" xmi:id="_8OBJMEZTEeehrvUiei9LJA" featurename="handlers" parentElementId="org.eclipse.e4.legacy.ide.application">
    <elements xsi:type="menu:MenuContribution" xmi:id="_JcJ-cEZUEeehrvUiei9LJA" elementId="com.bodastage.e4.clock.ui.menucontribution.0" parentId="help">
      <children xsi:type="menu:HandledMenuItem" xmi:id="_OSQxwEZUEeehrvUiei9LJA" elementId="com.bodastage.e4.clock.ui.handledmenuitem.Hello" label="Hello" iconURI="platform:/plugin/com.bodastage.e4.clock.ui/icons/sample.gif" command="_4tuLgEOQEeedq-IevvWAag"/>
    </elements>
</fragments>

is trying the add menu contributions to the list of handlers featurename="handlers" which is not allowed. You need to change this to add the menu items as children of an existing menu.

A: I solved this by changing the featurename for the menuContributions to menuContributions.  Below is a snippet showing the change.
  <fragments xsi:type="fragment:StringModelFragment" xmi:id="_hiF-4EawEeehrvUiei9LJA" featurename="menuContributions" parentElementId="org.eclipse.e4.legacy.ide.application">
    <elements xsi:type="menu:MenuContribution" xmi:id="_CnpqgEaxEeehrvUiei9LJA" elementId="com.bodastage.e4.clock.ui.menucontribution.0" parentId="help">
      <children xsi:type="menu:HandledMenuItem" xmi:id="_JsBsMEaxEeehrvUiei9LJA" elementId="com.bodastage.e4.clock.ui.handledmenuitem.Hello" label="Hello" iconURI="platform:/plugin/com.bodastage.e4.clock.ui/icons/sample.gif" command="_4tuLgEOQEeedq-IevvWAag"/>
    </elements>
  </fragments>

The links below were useful:

*

*How to contribute to the Eclipse IDE from a model fragment

*http://www.vogella.com/tutorials/EclipsePlugin/article.html#plugin_ideextensionsintroducion


text:
Q: Jquery tokeninput rails message I am trying to implement a messaging system among users.
Here the model of the database i am trying to implement.
user
  id

message
  message_id
  message_author_id
  timestamp

message_recipient
  message_id
  user_id

message_status
  message_status_id
  message_id
  user_id
  is_read
  is_deleted
  read_datetime
  deleted_datetime

The relationship would be I believe has follow
user
  has_many :messages
  has_many :message_recipient
  has_many :message_status

message
  has_many: user => author_id

message_recipient
  belongs_to :message
  belongs_to user

message_status
  belongs_to :message
  belongs_to :user

First i am not sure if the database is the correct way to implement has many recipients and not sure if its the proper rails way.
Second the goal is to implement jquery.tokeninputs, and therefore to my understanding i need to make sure that has many users will be able to take the author fields with many users.

A: Regarding your implementation, i think you may have a redundant model - depends on what you're trying to do, but it would go like this :
class User < ActiveRecord::Base
  has_many :messages
  has_many :sent_messages, through: :messages
  has_many :destined_messages, class_name: 'SentMessage'
end

# this class represents the original authored message,
# i.e. it holds the body of the message
class Message < ActiveRecord::Base
  belongs_to :user # author
  has_many :sent_messages
end

# this class represents a "copy" of the message
# that has been sent to a particular user.
# It also holds the status, which makes sense because
# you want to log the status according to each user
class SentMessage < ActiveRecord::Base
  belongs_to :message
  belongs_to :user
end

You can even merge the Message and SentMessage models if you don't care having duplicates : just make a copy of the body for each recipient.


text:
Q: How can I combine a restriction with occurence indicators in an XSD file? Suppose I have the following XSD file :
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified"  elementFormDefault="qualified" version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="PACIDemoSignedDoc" type="PACIDemoSignedDocType" />
    <xs:complexType name="PACIDemoSignedDocType">
        <xs:all>
            <xs:element name="OwnerEnglishName" type="OwnerEnglishNameType" />
        </xs:all>
    </xs:complexType>
    <xs:complexType name="OwnerEnglishNameType">
        <xs:simpleContent>
            <xs:restriction base="NameType">
                <xs:enumeration value="John"/>
                <xs:enumeration value="Jack"/>
            </xs:restriction>
        </xs:simpleContent>
    </xs:complexType>
    <xs:complexType name="NameType">
        <xs:simpleContent>
            <xs:extension base="xs:string"/>
        </xs:simpleContent>
    </xs:complexType>
</xs:schema>

My question is, where should I add the attributes minOccurs and maxOccurs for the element "OwnerEnglishName" ? I want to keep xs:all as I want to avoid having to order my XML file in sequence but it prohibits me from adding the Occurs directly in the <xs:element name="OwnerEnglishName" type="OwnerEnglishNameType" />
 line...
I'm also guessing I can't add the Occur attributes inside OwnerEnglishNameType, anyone have any idea ?

A:
My question is, where should I add the attributes minOccurs and
  maxOccurs for the element OwnerEnglishName ?

On the (non-global) declaration of OwnerEnglishName:
<xs:element name="OwnerEnglishName" type="OwnerEnglishNameType"
            minOccurs="0" maxOccurs="1"/>

I want to keep xs:all as I want to avoid having to order my XML file in > sequence

In XSD 1.0, you cannot have maxOccurs="unbounded" under xs:all; in XSD 1.1, you can.
However, you don't need xs:all with a single child element; you can use xs:sequence since there's no second element for order to matter.

Update (per OP change of example in comments to include additional child elements to xs:all):
You then have three options:

*

*Impose an ordering.   This is nearly always the best answer as the
 perceived need to allow any ordering is almost always unnecessary
 in practice.

*Use XSD 1.1, which allows children of xsd:all to have maxOccurs="unbounded".

*Change the XML design to use a wrapper element around the child element of xsd:all which you wish to allow to repeat.  (See here for an example.)

A: Okay, I have solved my problem, here's the answer if others have the same problem :
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" targetNamespace="test" xmlns="test" elementFormDefault="qualified" version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="animal" type="AnimalType" />
    <xs:complexType name="AnimalType">
        <xs:all>
            <xs:element name="cats" type="Cats" />
        </xs:all>
    </xs:complexType>
    <xs:simpleType name="CatType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="John"/>
            <xs:enumeration value="Jack"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:complexType name="Cats">
        <xs:sequence>
            <xs:element maxOccurs="5" minOccurs="2" name="cat" type="Cat"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="Cat">
        <xs:simpleContent>
            <xs:extension base="CatType"/>
        </xs:simpleContent>
    </xs:complexType>
</xs:schema>

which validates the following xml :
<?xml version="1.0" encoding="UTF-8"?>
<animal xmlns="d" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="test schema.xsd">
    <cats>
        <cat>John</cat>
        <cat>Jack</cat>
    </cats>
</animal>

I have successfully bypassed the Occurs restriction of xs:all by adding child elements following xs:sequence.


text:
Q: How to calculate the probability that the value of $S_1$ is $x$ amount higher than vaule of $S_2$ I have two samples. $S_1$ has mean of $83.17$, with standard deviation of $15.50$. $S_2$ has a mean of $84.00$ and standard deviation of $23.95$. How do you calculate the probability that $S_1$ is greater than $S_2$ by some value $x$ or more?

A: We need some assumptions which have not been stated. First we need the assumption of independence. We will also assume that our random variables have normal distribution. The sample sizes are not specified. We will assume they are large. If they are quite small (and specified) the problem can be solved, but is more complicated.
Let $S_1$ and $S_2$ be independent normally distributed random variables, with means
$\mu_1$ and $\mu_2$, and variances $\sigma_1^2$ and $\sigma_2^2$ respectively. Let $W=S_1-S_2$. Then $W$ has normal distribution, with mean $\mu_1-\mu_2$, and variance $\sigma_1^2+\sigma_2^2$ (the plus sign here is correct).
Calculate the mean and variance of $W$. Then find the standard deviation of $W$. Since $W$ has normal distribution, you have arrived at a familiar kind of problem.
Remark: The standard deviations seem awfully high.


text:
Q: Add a fragment to a FragmentContainer android studio I have an Activity with a bottom navigation view made of fragments which looks like this:

When I click on "Friends" fragment I would like to make something like that on the top of it, meaning to add another 2 fragments to this one :

For "Add friends" I want the layout of the "Friends" Fragment and for the other 2 ("Pending requests" and "Your Friends") I want a different layout which I'm gonna create.
My question is how can I do that? Is it possible to add a FragmentContainer to my "Friends" fragment and to add the 2 new fragments to it? I tried something but when I open "Pending requests" from "Add friends" tab the SearchBar is still there and it shouldn't be.
Friends.xml :
<FrameLayout 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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/fragment_friends"
    tools:context=".Fragments.UsersFragment"
    android:background="@color/purple_500">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <Button
            android:id="@+id/addfriends"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Add friends" />

        <Button
            android:id="@+id/pending"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Pending requests" />

        <Button
            android:id="@+id/yourfriends"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Your Friends" />
    </LinearLayout>

    <androidx.appcompat.widget.SearchView
    android:layout_width="350dp"
    android:layout_height="wrap_content"
        android:id="@+id/searchView"
        android:layout_marginTop="60dp"
        android:layout_marginStart="25dp"
        android:iconifiedByDefault="false"
        app:defaultQueryHint="Search Here"
        android:layout_alignParentTop="true"
        android:background="@drawable/rounded_buttons"
   />

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginTop="120dp"
        >

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:listitem="@layout/item" />
    </RelativeLayout>

</FrameLayout>

In .java :
        Button Badd = (Button) v.findViewById(R.id.addfriends);
        Button Bpending = (Button) v.findViewById(R.id.pending);
        Button Bfriends = (Button) v.findViewById(R.id.yourfriends);

        Badd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment friendsfragment = new FriendsFragment();

                getActivity().getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fragment_friends, friendsfragment, "findThisFragment")
                        .addToBackStack(null)
                        .commit();
            }
        });

        Bpending.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment pendingFragment = new PendingFragment();

                getActivity().getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fragment_friends, pendingFragment, "findThisFragment")
                        .addToBackStack(null)
                        .commit();
            }
        });

        Bfriends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment yourFriendsFragment = new YourFriendsFragment();

                getActivity().getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fragment_friends, yourFriendsFragment, "findThisFragment")
                        .addToBackStack(null)
                        .commit();
            }
        });

Please help !


text:
Q: update datetime field in model form only shows plain text instead datepicker Django I'm trying to update my DateTimeField field , but it only shows a plain text of numbers instead of the date picker
class MyModel(models.Model):
    date= models.DateTimeField(default=timezone.now)
    #others

forms.py
class UpdateMyModelForm(forms.ModelForm):
    date= forms.DateTimeField(required=True,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime'}))

class Meta:
    model = MyModel
    fields = ['date','others]

when i use forms.DateTimeField it doesnt show the previous date which i've selected before! and when i remove forms.DateTimeField it only show a plain text type=text i also tried to use
class DateInput(forms.DateInput):
    input_type = 'date'

but it shows only show Y-m-d : year-month-day i have to display hour and minute as well ? is there something else i have to change please

A: First of all, I recommend you to use
date = forms.DateTimeInput(attrs={'type': 'datetime-local'}) in your forms.py
Secondly, if you want to see the previous date, add a datefilter in your template.
for example:
Date:<input class="mt-4 ml-4" type="datetime-local" name="date" value="{{form.date.value | date:'c'}}"  id="id_deadline_date">
the date filter that will help is | date:'c'
after these changes, I think you will be able to see the previous date.
I have explained why you should use a date filter in this link.


text:
Q: How to use filesystemwatcher changed event file size displaying the last changed size only? private void Fsw_Changed(object sender, FileSystemEventArgs e)
        {
            if (e.ChangeType != WatcherChangeTypes.Changed)
            {
                return;
            }
            else
            {
                var info = new FileInfo(e.FullPath);
                var theSize = info.Length;

                if (!richTextBoxLogChanges.Text.Contains($"Size Changed: {theSize}"))
                {
                    AppendText(richTextBoxLogChanges, $"Size Changed: {theSize}", Color.Yellow);
                    AppendText(richTextBoxLogChanges, "\n", Color.LightGreen);
                }
            }
        }

The result is :
Size Changed: 5436
Size Changed: 10783
Size Changed: 60274

It's showing the process of the size changes and instead i want it to show only the last size 60274
Also how can i display the file name that was changed ? for example this line format :
The File : text.txt size changed from 12KB to 60,274KB (and to format the size to something reasonable).
The AppendText method :
public void AppendText(RichTextBox box, string text, Color color)
        {
            box.SelectionStart = box.TextLength;
            box.SelectionLength = 0;

            box.SelectionColor = color;
            box.AppendText(text);
            box.SelectionColor = box.ForeColor;
        }


text:
Q: Regarding DOCTYPE in Tables I need to know the importance of DOCTYPE..
Which will be good for tables?
when specifying doctype 4.01,table structure changes sometimes..
if we remove doctype,it is working perfect..
so i need help guidelines for usage of tables and doctype from stackoverflow users

A: What is Doctype:  "<!DOCTYPE html>" What does it mean?
Doens't matter which one you will use, but you should use latest one - HTML5. Different behavior is mostly just CSS in different browsers which can be fixed by CSS Reset (http://bit.ly/QCpdbC).
Hope that I'll helps to you.


text:
Q: java - performing file operations on remote locations hi
i want to perform operations on files like rename, copy and etc.
these are not local files. they are located on remote computers.
I have 2 options:
1. run some kind of a telnet client (a framework that i already have in my system) from the java code. connect to the remote computer and perform a cmd operation.
2. perform a regular java.io operation on the remote path.
the problem with 1 is that its not cross platform (only theoretical problem for me), and that i generally dont want to use this telnet framework.
the problem with 2 is that large operations on remote files is slower, compared to same operation being performed on the machine itself with telnet.
am i right?
any other options?
any additional inputs?
thanks.

A: If you can deploy your application to the remote computer, you can simply write your own little client and server for these file operations.


text:
Q: Command Prompt "tree" shows Unicode in console but outputs to file in ASCII In Windows 10's cmd.exe, if I do
tree
C:.
├───a
│   ├───b
│   └───etc...

it clearly display the Unicode bars and dashes correctly on the console.
But if I redirect this output to a file
tree > tree.txt

the contents of the file are:
C:.
³ÄÄÄa
³   ÃÄÄÄb
³   ÀÄÄÄetc...

It fails to properly write the Unicode characters.
It can't even read back what it wrote:
tree > tree.txt
type tree.txt
C:.
����a
�   ����b
�   ����etc...

(it may appear as "�" here (question marks in a tilted square) but in the console they appear as empty boxes)
I've already tried these suggestions without luck:

Try chcp 1252 or chcp 65001 from the command line. With Lucida Console or other font support.

CMD /U /c tree > tree.txt

I was using this command incorrectly, now fixed, but I still get the same result as just tree - it displays fine in the console, but file output is still those weird characters.
It's strange that the text displays on the console just fine, but writing to file messes up the encoding. What could be the issue here?

A: The encoding that is generally used for the box-drawing characters is 850, but even that doesn't help on my Windows 8.1 system. I've only found one way around cmd's poor handling of text encodings: using a program that does handle encoding well, namely, PowerShell.
It's the > redirection that wrecks the characters, so we'll just suck up the tree output and jam it in a file without simple cmd redirection:
Invoke-Expression "tree" | Out-File "tree.txt"

Or, shorter:
iex "tree" > "tree.txt"

To create an instance of PowerShell that runs that command and then exits, use this in a command prompt or batch file:
powershell -command "iex \"tree\" > \"tree.txt\""

The resulting file can be viewed successfully in Notepad or by a normal type.

A: tree /A Display the tree using standard ASCII characters. You can use this option if you want to save the directory tree in a file for further processing or print the tree on a printer which does not support the graphical symbols that TREE normally uses.
source: https://jpsoft.com/help/tree.htm


text:
Q: Scrolling UITableView in iOS 9 results in overlapped labels After upgrading to Xcode 7 and iOS 9 beta, I am getting this error in one of my UITableViews. Whenever I scroll, my second label overlaps the first label in most of the cells. What is weird is that two of the current cells don't have this issue. See pictures for details.

 override func viewDidAppear(animated: Bool) {

    namesArray.removeAll(keepCapacity: false)
    locationsArray.removeAll(keepCapacity: false)

    let query = PFQuery(className: "Schools")
    // query.whereKey(key: String, containedIn: [AnyObject])

    query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
        if error == nil {
            query.orderByAscending("schoolName")

            if let objects = query.findObjects() as? [PFObject] {

                for object in objects {

                    self.namesArray.append(object.valueForKey("schoolName") as! String)
                    self.locationsArray.append(object.valueForKey("schoolLocation") as! String)
                    self.schoolTable.reloadData()
                }
            }
        } else {
            print("Shit, it didn't work...")
        }
    }
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell:ChangeSchoolListTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! ChangeSchoolListTableViewCell

    if namesArray.count > 0 {
        cell.nameLabel.text = namesArray[indexPath.row]
        cell.locationLabel.text = locationsArray[indexPath.row]
    }
    return cell
}

class ChangeSchoolListTableViewCell: UITableViewCell {

@IBOutlet var nameLabel: UILabel!
@IBOutlet var locationLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
}

Thank you very much.

A: I think you are adding one label over another in the table. You need to add one label and reuse it instead of adding another label. The solution is to use a custom UITableViewCell subclass. Also it will be helpful if you show the code of UITableView methods.

A: I think, you call reloadData from a background thread. If it is so, then it is a main problem, to solve it, you should call reloadData from the main thread. You can see here how to call a block of code on the main thread from the background thread.

A: You need to remove subviews of uitableviewcell's contentview before adding subviews.


text:
Q: Why don't currents in Superconductors lose energy as light? We are told that in superconductors, there is no internal resistance. So if a current is induced in a superconducting material (like an Eddie Current), it should theoretically flow forever (or until the material heats up). However, in atoms, we know the electron could not be rotating around the protons because the constant acceleration inwards produces light which radiates away energy. I was wondering why superconductors don't also radiate away their energy as light as the electrons loop around the circuit.
If the electron's wavefunction is localized, then even though the charge distribution appears smooth macroscopically, the microscopic changes should still add up and radiate light. If it's similar to atoms and the electrons don't radiate light because the wavefunction is distributed around the circuit in discrete states, then does that mean currents in superconductors can only exist in loops whose lengths are an integer multiple of the electron's wavelength (so not all radii of Eddie currents are possible)?

A: A superconducting current is constant in time and produces a static magnetic field. A radiative field requires a current that varies in time.

A: That is good reasoning.  See lecture for a detailed discussion.  The magnetic flux through a superconducting loop, and thus the current in a superconducting loop (carrying a DC current), is quantized.

A:
However, in atoms, we know the electron could not be rotating around the protons because the constant acceleration inwards produces light which radiates away energy

Close.
The electron will lose energy until it gets to the lowest possible energy state. That might be the ground state, or it might be some higher-energy state if the lower states are occupied by other electrons. Once they reach that state, they stop radiating.
Superconductors work the same way. Once everyone is in a stable state, there's no lower-energy level to move to, and the radiation stops.

A: Supercurrents are a flow of the Bose-Einstein-Condensate (BEC), where each boson is an electron pair. BEC-bosons have a minimum and quantized kinetic energy and, thus, cannot emit their energy by arbitrarily small portions. So below BEC temperature the pairs don't lose any energy.


text:
Q: What happens when my proposal gets launched I would like to know what exactly happens if my proposal gets launched. How would I contribute to the site? Does it make me a moderator or do I communicate with stack exchange admins? I would like a detailed walkthrough to what happens when someone owns a launched proposal.

A: You are just a normal user like any others. Okay, you had a good idea and the community supported your proposal, but that doesn't make the community yours.
If you are a active member during all phases of the proposal, you might be picked as a moderator through the election phase. If not, you just have to earn your moderation privileges like any others.
And sorry, you won't get a t-shirt, nor special access to the SE team.


text:
Q: kwic() function returns less rows than it should I'm currently trying to perform a sentiment analysis on a kwic object, but I'm afraid that the kwic() function does not return all rows it should return. I'm not quite sure what exactly the issue is which makes it hard to post a reproducible example, so I hope that a detailed explanation of what I'm trying to do will suffice.
I subsetted the original dataset containing speeches I want to analyze to a new data frame that only includes speeches mentioning certain keywords. I used the following code to create this subset:
ostalgie_cluster <- full_data %>%
  filter(grepl('Schwester Agnes|Intershop|Interflug|Trabant|Trabi|Ostalgie',
                speechContent,
                ignore.case = TRUE))

The resulting data frame consists of 201 observations. When I perform kwic() on the same initial dataset using the following code, however, it returns a data frame with only 82 observations. Does anyone know what might cause this? Again, I'm sorry I can't provide a reproducible example, but when I try to create a reprex from scratch it just.. works...
#create quanteda corpus object
qtd_speeches_corp <- corpus(full_data,
                            docid_field = "id",
                            text_field = "speechContent")

#tokenize speeches
qtd_tokens <- tokens(qtd_speeches_corp,
                     remove_punct = TRUE,
                     remove_numbers = TRUE,
                     remove_symbols = TRUE,
                     padding = FALSE) %>%
  tokens_remove(stopwords("de"), padding = FALSE) %>%
  tokens_compound(pattern = phrase(c("Schwester Agnes")), concatenator = " ")

ostalgie_words <- c("Schwester Agnes", "Intershop", "Interflug", "Trabant", "Trabi", "Ostalgie")

test_kwic <- kwic(qtd_tokens,
                  pattern = ostalgie_words,
                  window = 5)

A: It's something of a guess without having a reproducible example (your input full_data, namely) but here's my best guess. Your kwic() call is using the default "glob" pattern matching, and what you want is a regular expression match instead.
Fix it this way:
kwic(qtd_tokens, pattern = ostalgie_words, valuetype = "regex",
     window = 5


text:
Q: Лицензия MIT и GitHub Если в моем проекте есть сторонние модули слегка (а некоторые не слегка) модифицированные у которых лицензия MIT, могу ли я вместе с ними выкладывать и лицензировать свой проект.

A: Да.
Вы можете публиковать, распространять и сублицензировать программное обеспечение, имеющее лицензию MIT.
Но следует учесть, что Вы должны сохранить уведомление об авторском праве на сторонние модули и включить его во все копии или значимые части Вашего Программного обеспечения.

Перевод текста лицензии:

Copyright (c) <год> <владельцы прав>
Данная лицензия разрешает лицам, получившим копию данного программного
  обеспечения и сопутствующей документации (в дальнейшем именуемыми
  «Программное обеспечение»), безвозмездно использовать Программное
  обеспечение без ограничений, включая неограниченное право на
  использование, копирование, изменение, слияние, публикацию,
  распространение, сублицензирование и/или продажу копий Программного
  обеспечения, а также лицам, которым предоставляется данное Программное
  обеспечение, при соблюдении следующих условий:
Указанное выше уведомление об авторском праве и данные условия должны
  быть включены во все копии или значимые части данного Программного
  обеспечения.
ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ
  КАКИХ-ЛИБО ГАРАНТИЙ, ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ
  ГАРАНТИИ ТОВАРНОЙ ПРИГОДНОСТИ, СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ
  НАЗНАЧЕНИЮ И ОТСУТСТВИЯ НАРУШЕНИЙ, НО НЕ ОГРАНИЧИВАЯСЬ ИМИ. НИ В КАКОМ
  СЛУЧАЕ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО
  КАКИМ-ЛИБО ИСКАМ, ЗА УЩЕРБ ИЛИ ПО ИНЫМ ТРЕБОВАНИЯМ, В ТОМ ЧИСЛЕ, ПРИ
  ДЕЙСТВИИ КОНТРАКТА, ДЕЛИКТЕ ИЛИ ИНОЙ СИТУАЦИИ, ВОЗНИКШИМ ИЗ-ЗА
  ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ ИЛИ ИНЫХ ДЕЙСТВИЙ С ПРОГРАММНЫМ
  ОБЕСПЕЧЕНИЕМ.


text:
Q: add subtitle to a movie
Possible Duplicates:
How do I hard code a movie with subtitles?
How to soft code an MKV with subtitles?

Do you know a good (& free if is possible) software which allow me to embed a subtitle in a movie? My movie is a flv file type.

A: Avidemux is a good tool. And it is free.
See this for info about subtitles embedding


text:
Q: We are exposing OData APIs (which are essentially REST APIs). Is that a good approach or does it have any overhead? We are exposing OData APIs (which are essentially REST APIs), Over the datasource, which
are REST APIs.  Is that a good approach to build wrapper of OData over REST APIs or should we directly interact with the database as the source.

A: There are significant overheads in terms of development, runtime performance and maintenance.
In general it is not a standard approach, but it is an option if performance is not an issue and you need some interface to aggregate multiple APIs and you really want to use the OData Protocol or a subset of its URL Query semantics.

OData over the top of simpler Web API or other REST endpoints is generally an anti-pattern. It will depend heavily on the backend API implementations and how you've mapped the OData routes and queries to them, but generally it is a lot of effort with diminishing returns, there are also significant SDLC overheads because this becomes a very non-standard implementation so you will need specialized and experienced support when/if there are issues.
I have recently worked on an OData Implementation that was mapped to a series of Repo DBs. The general performance and bandwidth arguments for adopting OData could not be realised because any wrapper over the top of another service can at best only be slightly slower than the slowest component in the chain. Overall the service was a lot slower and had considerable memory and caching issues to deal with the cross API relationship resolutions.
There are many non-performance arguments for OData that are in fact general arguments for Web API, security and caching are generally easier concepts to bolt into standard Web API that does not have the graph-like support for navigation properties.
One of the killer features of OData is the deep linking navigation support and the performance gains that can be realised by translating OData URL queries to linq expressions which can be deferred and executed by the storage engine. The general issue with non-OData APIs is that they are less likely to support IQueryable extensions and it is hard to translate the original intent in the URL in an efficient way to the target APIs.

An alternative is to design a staging or common data schema and use ETL processes to resolve the data from the disparate APIs into this centralised data store, then build an OData API to interact with this schema. This is effectively a cached OData service, rather than being a direct pass through to the external APIs but you can achieve some really impressive performance benefits from a solution like this.


text:
Q: Authorizing Google Charts to access private spreadsheets I am trying to create a Web App using Google Apps Script to query data from my Google Sheet using Google Charts.
I have been able to successfully query the spreadsheet when the Google Sheet is publicly shared, however since the spreadsheet contains confidential info I would rather do it privately using authorizations.
The reason why I want to use Google Charts visualisation functions (as opposed to the server side Spreadsheet App) is because of the speed of querying large data sets.
I have tried following the steps in the above documentation. That is, creating a client id then using the gapi.auth library to authenticate myself but I continue to receive an error.
When i add the authorization library and first part of the code from the documentation (with console.log simply to see where it get's up to):
<script src="https://apis.google.com/js/auth.js?onload=init"></script>

<script>
var clientId = '1234.apps.googleusercontent.com';
var scopes = 'https://spreadsheets.google.com/feeds';

function init() {

console.log("here");

gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true},handleAuthResult);

}

</script>

I receive the following error:

1289869776-mae_html_user_bin_i18n_mae_html_user.js:41 dropping
postMessage.. was from unexpected window

Any guidance is appreciated.

A: Since you are creating your web app using Google Apps Script, it's not necessary to "authorize Google Charts to access private charts" because you could use Google Apps Script services and methods to get the data from the spreadsheets and pass them to Google Charts.
On Converting from UiApp + Chart Service to Html Service + Google Visualization API it's shown how to convert the old dashboard example from from UiApp + Chart Service to HtmlService + Google Visualization API. This illustrates how to create a Google Apps Script web app that builds a chart from Google Spreadsheet data without "requiring authorization" as it's "implicitly" handled by Google Apps Script.
From the above link

Two functions cooperate to retrieve the dashboard's data and display it. As soon as the visualization API is loaded, the sendQuery() function is invoked. Using the google.script.run facility, it sends its request to the server-side getSpreadsheetData() function. This is an asynchronous operation, so two callbacks are provided, a successHandler and a failureHandler. One or the other will receive the result of the server call, depending on the outcome.

H/T to jfllmartin, author of an answer to Converting my google dashboard app from the UI service to the HTML service where the above link was shared.
Related

*

*How to create google dashboard including piechart and range select filter from a spreadsheet?

*Display Spreadsheet data in Sites with Html Service

A: can I suggest you change from using Google sheets to using firebase with Google sheets or just Firebase, and then with Google appscript in the back end.
I often use a Google script to problematically update Firebase with data from the Google sheet. I then enjoy the speed and security of Firebase to deliver a super fast user experience.
There are two go to pages for using Firebase in appscript. The example page and the quick start.
Furthermore, I gave up using Google's own charting library and starting using high charts or chartJS, as they are more accessible.


text:
Q: Simple integration testing using bash with CMake and CTest? I have a C++ CMake project where I use Google Test for unit testing and I'm happy with the XML reports produced using ctest -T Test. Now I would like to implement couple of integration tests that run specific application scenarios and expect a specific output e.g. running a C++ executable with default values should produce a specific output e.g. the following integration_test_01.sh bash shell would be such a test:
 #!/bin/bash
 ./my_algorithm > out && grep "mse\=1\.2345e\-6" out
 if [ $? == 0 ]; then
     echo "integration test succeeded"
 else
     echo "integration test failed" >&2
 fi
 rm out | cat

Is there a way to integrate such test with CMake or CTest and maybe even get some XML output?

A: With CMake and CTest you can add a test for my_algorithm in the following way:
add_executable(my_algorithm ...)
add_test(NAME integration_test_01 COMMAND my_algorithm)
set_tests_properties(integration_test_01
    PROPERTIES PASS_REGULAR_EXPRESSION "mse\\=1\\.2345e\\-6")

The output of the command my_algorithm will be checked against the specified regular expression and if the output does not match the test will fail.
When you run tests with ctest -T Test the generated XML report will contain the actual output of the command nested in a <Measurement> tag.


text:
Q: spark broadcast isn't being saved at the executors memory I used spark-shell on EMR - Spark version 2.2.0 / 2.1.0.
While trying to broadcast simple object (my CSV file contain only 1 column and it's less then 2 MB) I noticed it isn't being kept on each executor memory and just in the driver memory although it should be as suggested in the documentation https://jaceklaskowski.gitbooks.io/mastering-apache-spark/spark-TorrentBroadcast.html
Attached print screen before the broadcast (i.e. sc.broadcast(arr_collected) ) and after the broadcast which shows my conclusion. Additionally I checked the worker's machine memory usage and same as in Spark UI, it's not being change after the broadcasting.
1- print screen before broadcast
2- print screen after broadcast
Attached the log for the broadcasting process after adding 'log4j.logger.org.apache.spark.storage.BlockManager=TRACE' like suggested here -
https://jaceklaskowski.gitbooks.io/mastering-apache-spark/spark-blockmanager.html
3- print screen broadcast logging
Below there is the code -
val input  = "s3://bucketName/pathToFile.csv"
val df = spark.read.format("com.databricks.spark.csv").option("header", "true").option("delimiter", ",").load(input)
val df_2 = df_read_for_bc.withColumn("is_exist",lit("true").cast("Boolean"))
val arr_collected = df_2.collect()

val broadcast_map_fraud_locations4 = sc.broadcast(arr_collected)

Any ideas?

A: Can you please use the broadcast varialables to join the data or do some kind of operation. It might be lazy so not using any memory


text:
Q: Activating a list of GCP APIs for a list of Projects using Terraform I have two lists
projects = ["prj01", "prj02", "prj03", "prj04", "prj05", "prj06", ]

apis = ["api1", "api2", "api3", "api4", "api5", "api6", "api7", "api8", "api9", "api10", ]

Using Terraform, I need to loop through the projects list one at a time and apply all the apis to each of the projects.
Can someone help me with this please.

A: Terraform builtin function setproduct allows you to create a new list after applying cartesian product.
E.g. setproduct(["prj01","prj02"], ["api1", "api2"])
this will result in a new list:
[
 [ "prj01", "api1" ],
 [ "prj01", "api2" ]
],
[
 [ "prj02", "api1" ],
 [ "prj02", "api2" ]
]

You can read more about this function at: https://www.terraform.io/language/functions/setproduct


text:
Q: Как установить модули для grunt не локально? Как установить модули node js не локально или указать путь к ним в grunt?
Мне нужно, чтобы в папке проекта не лежали тяжелые модули node js, они занимают место, мешают поиску в папке и.т.д.


text:
Q: how do manually remove microphone phone permission for camera plugin in flutter Is it possible to remove asking microphone permission for camera plugin for android device using flutter
I have tried like below in my AndroidManifest.xml
but it shows error
Any one can help me to solve this issue. Thanks in advance

A: One important thing. enableAudio: false parameter can only be passed as the last parameter to the CameraController. Like below:
_controller = CameraController(firstCamera, ResolutionPreset.medium,
    enableAudio: false);

All other attempts will cause syntax error. Adding this one helps to avoid adding additional NSMicrophoneUsageDescription in info.plist. Otherwise app will crash with this error:

"This app has crashed because it attempted to access privacy-sensitive
data without a usage description. The app's Info.plist must contain an
NSMicrophoneUsageDescription key with a string value explaining to the
user how the app uses this data."

A: You can request camera permission only by passing the parameter enableAudio: false to the CameraController (0.5.2+1 ++).

A: disable audio for camera controller
controller = CameraController(
        cameras.first,
        ResolutionPreset.medium,
        enableAudio: false,
        imageFormatGroup: Helpers.isIOS ? ImageFormatGroup.bgra8888 : ImageFormatGroup.yuv420,
    );


text:
Q: Monaco-editor : Is there a way to prevent cursor/editor's focus from being lost on clicking outside the editor ( on blur ) Monaco-editor :- Is there a way to prevent cursor/editor focus from being lost on clicking outside the editor.
My scenario :- I have a list of items in a dropdown that is outside the editor , user can select a dropdown item and I am calling executeEdits to paste this selected item in the editor's previous cursor position.
When the user opens the dropdown the focus from the editor is lost, user is now not sure where his selected dropdown value will be inserted.
Is there a way in which I can prevent the editor from losing it's focus on blur. ?


text:
Q: Session Data lost after refresh browser in Laravel app In my laravel application i just want to store input data in a session and use it every where But the data is lost when i refresh the browser.
my controller:
public function usepoint(Request $request){
    $fdata = $request->input_point;
    Session::put('test', $fdata);
    return Redirect()->back();
}

view page:

use Point :

 <form method="get" action="{{url('cart/usepoint')}}">

 <input class="" type="" name="input_point" value="" style="width:40%"> <button type="submit" class="btn btn btn-primary ">use</button>

 </form>

Session data:

 <input class="del_point" type="text" name="del_point" value="{{Session::get('test')}}"  style="width: 40%" readonly>

route:
Route::get('cart/usepoint','cartController@usepoint');

A: add this in your config/session.php configuration:
 'expire_on_close' => false,

If the problem still occurs, check if you have any dd()'s in your application. Apparently, according to this, dd() makes it so your session doesn't get stored correctly and you can't read data from that session.

A: you can try to pass data to view using with() method inside controller:
$fdata = $request->input_point;
return redirect()->back()->with('success', $fdata );


text:
Q: Add object to an object from a function in JavaScript First I hit the button Add then 'Show' and lastly Show Object
The problem is that when I hit the button Show Object I get only one object for the last input element instead one object for each input element.
How can I add new objects from inside a function without loosing most of them?
Here is the code:

$(document).ready(function() {
  // body...
  var tableInput = "
<input type='text'/>	<input type='text'/>
";
  var obj = {};
  const rowNo = 2;

  $("h1").text("Helllo Sonq");
  console.log("function called!");

  $("#add").click(function() {
    $("#table").append(tableInput)
  })

  $("#show").click(function() {
    $(":text").each(function(index) {
      console.log(index + ': ' + $(this).val());
      var rowno = "row" + parseInt(index / rowNo)
      obj[rowno] = new Object()
      obj[rowno]["element" + index.toString()] = $(this).val();
      // obj[rowno]["element" + index.toString()] = $(this).val();
    })
  })

  $("#show-object").click(function() {
    console.log(obj);
  })
})
<!DOCTYPE html>

  <title>Page Title</title>

Hello Riko!

  <button id="add">Add</button>
  <button id="show">Show</button>
  <button id="show-object">Show Object</button>

      Name
      Age

Into the function :
$("#show").click(function(){
    $(":text").each(function(index) {

I want to add an object to the global obj for each iterated input type=text element.

A: Since you target the rows then you should loop through them first then inside every row loop throug the inputs just like :
$("tbody>tr").each(function(index) {
  var rowno = "row" + index;
  obj[rowno] = {};

  $(":text", this).each(function(index) {
    console.log(index + ': ' + $(this).val());

    obj[rowno]["element" + index] = $(this).val();
  });
});

NOTE : My suggestion adjust also the table using thead/tbody.

$(document).ready(function() {
  var tableInput = "
<input type='text'/>	<input type='text'/>
";
  var obj = {};
  const rowNo = 2;

  $("h1").text("Helllo Sonq");
  console.log("function called!");

  $("#add").click(function() {
    $("#table>tbody").append(tableInput)
  })

  $("#show").click(function() {
    $("tbody>tr").each(function(index) {
      var rowno = "row" + index;
      obj[rowno] = {};

      $(":text", this).each(function(index) {
        console.log(index + ': ' + $(this).val());

        obj[rowno]["element" + index] = $(this).val();
      })
    })
  })

  $("#show-object").click(function() {
    console.log(obj);
  })
})

Hello Riko!

<button id="add">Add</button>
<button id="show">Show</button>
<button id="show-object">Show Object</button>

      Name
      Age

A: The first time you do var rowno = "row" + parseInt(index/rowNo) , var rowno is filled with row0. Since 0/2 is 0.
But then, the second time, the same row, var rowno = "row" + parseInt(index/rowNo) gives you also a value of 0, since 1/2 does 0.5, wich gets truncated to 0. By doing so, you are replacing the object at position 'row0', wich is what an object in javascript does.
You should not use parseInt

A: Just create obj[rowno] = new Object() if it does not exist:
if (!obj[rowno]) {
  obj[rowno] = new Object()
}

because it is recreating the new instance so, the previous one has vanished.
$("#show").click(function() {
  $(":text").each(function(index) {
    console.log(index + ': ' + $(this).val());
    var rowno = "row" + parseInt(index / rowNo)
    if (!obj[rowno]) {
      obj[rowno] = new Object()
    }
    obj[rowno]["element" + index.toString()] = $(this).val();
  })
})

N.B.

parseInt(index / 2) returns 0 when index = 0
   parseInt(index / 2) returns 0 when index = 1


text:
Q: How can I get the Authorization Code from the OAuth 2.0 request with Authorization Code Grant? I am creating an OAuth 2.0 client which can fetch access tokens for all the requests just like the postman or SOAP UI.
When we Redirect the user to the Auth URL, the server sends the Authorization Code in return back to the client and immediately it redirects to the redirect URI.
I want to fetch the Authorization Code.
Example :
Let's consider the example of Google :
For Google suppose we have :
Auth URI: https://accounts.google.com/o/oauth2/v2/auth
Redirect URI: https://www.example.com/oauth2/callback
the first step will be to redirect to Auth URI with client id and redirect URI as parameters :
For this I have used following in MVC :
    public ActionResult LoginUsingGoogle()
    {
        return Redirect($"https://accounts.google.com/o/oauth2/v2/auth?client_id={ClientId}&response_type=code&scope=openid%20email%20profile&redirect_uri={RedirectUrl}&state=abcdef");
    }

Once it redirects successfully it send authorization code in return which can further be used to fetch access token.
I want to fetch this authorization code so that I can further hit a POST request with authorization code as a parameter to fetch access token.
How can I fetch this intermediate authorization code?
How tools like Postman and SOAP UI make it possible to read authorization code?
Also :

*

*The redirect URI is not on my server, it can be anywhere.

*I am trying to do it from MVC that is why I have used Response.Redirect


text:
Q: Xamarin Forms time picker without pop-up? Currently in both iOS and android the time picker works like this: you have a time field, and when you tap it, the time picker pops up and you make your selection.
What I'm trying to find out, in Xamarin forms, is if you can expose the time picker itself as part of the main page's UI, and not as part of a pop-up. So that you can set the time right on the existing UI without having to load another.
Is that possible?


text:
Q: Why isn't the inline element inheriting height from its children? I'm trying to make a rather complicated grid of images and information (almost like Pinterest).  Specifically, I'm trying to inline position one set of
s right after another.  I have it working but one aspect is causing issues so I'm trying to ask about this small piece to avoid the complication of the whole problem.
In order to horizontally align the images and their information we are using inline
s with other inline-block level elements inside of them.  Everything works correctly for the most part except that the
s have almost no height.
HTML and CSS is in JSFiddle here if you want to mess with it in addition to below:
HTML:

                Title One
                One Point One

                Title Two
                Two Point One

CSS:
.Container {
    list-style-type:none;
}
.Container li {
    background-color:grey;
    display:inline;
    text-align:center;
}
.Container li .Item {
    border:solid 2px #ccc;
    display:inline-block;
    min-height:50px;
    vertical-align:top;
    width:170px;
}
.Container li .Item .Info {
    display:inline-block;
}
.Container li .Item .Info a {
    display:inline-block;
    width:160px;
}

If you check out the result in the jsfiddle link you can see that the grey background only encompasses a small strip of the whole
.  I know that changing the
 to display:inline-block solves this problem but that isn't feasible for other reasons.
So first of all, I'm just looking to see if anyone understands why the inline
 element doesn't have any height.  I can't find anything in the spec that explains this.  I know I can't add height to an inline element but any explanation as to why this is happening that might enable me to fix would be great.
Secondly, if you inspect the elements using IE's Developer Mode you will see that although the background color is in the correct location, the actual location of the
's bounding box is at the bottom of the container according to hovering over the element.  I could deal with this problem if it was at the top in every browser but it apparently varies.
NOTE: I don't really care about older browsers in this case but I don't use HTML5 or JavaScript positioning.
Thanks.

A: Inline elements don't have the option to set the height. Inline elements are elements that are on a line, and thus inherit height of the line. Block elements are elements that take up full width and can have assigned width, height, and other stuff that make them easier to style.
For a detailed explanation in the specs see:
http://www.w3.org/TR/CSS2/visuren.html#inline-formatting
inline-block makes an element appear inline, but you can assign height and width to it, and it will expand with the content within. I didn't use inline-block very often because of it's buggy behaviour in IE, but those days are over now apperantly:
http://www.quirksmode.org/css/display.html
Making the
 using inline-block solves this, but you say this is not an option for you. Why not? Another solution is to make those li's block elements, and make them float to the left. If you have problems with overlapping content, use the overflow property on the whole ul to make sure the ul is pushing down other content.
ul.Container {
  list-style-type: none;
  overflow: hidden; /* so height expands with the floated content */
}

ul.Container li {
  display: block;
  float: left;
  ... more styling ...
}

Is this something that solves your puzzle?

A: The relevant bit of the CSS 2.1 spec is section 10.6.1 Inline, non-replaced elements of section 10.6 Calculating heights and margins. It says:

The 'height' property does not apply. The height of the content area
  should be based on the font, but this specification does not specify
  how. A UA may, e.g., use the em-box or the maximum ascender and
  descender of the font. (The latter would ensure that glyphs with parts
  above or below the em-box still fall within the content area, but
  leads to differently sized boxes for different fonts; the former would
  ensure authors can control background styling relative to the
  'line-height', but leads to glyphs painting outside their content
  area.)

The
 element is styled inline, and it's content is a single inline-block object which can't span lines, so the content area of the
 is only one line high. The height of the
's content area is therefore the 1 x f(height of the font). See http://jsfiddle.net/dh8nU/1/ for a demonstration where an increase in the height of the font has made the grey area larger.
The section goes on to say:

The vertical padding, border and margin of an inline, non-replaced box
  start at the top and bottom of the content area, and has nothing to do
  with the 'line-height'. But only the 'line-height' is used when
  calculating the height of the line box.
  [my emphasis]

When you place larger inline-block elements in an inline element, the height of line box increases to contain the inline-block elements, but as per the text above, this does not increase the height of the containing inline element.


text:
Q: Widget filling values in two fields I know that if I need a custom "selector" for a field in django-admin I need to create a custom widget.
But what if the widget have to produce two values, for example X and Y coordinates, how can I fill them in two different fields from the model?

A: You can look at the implementation of the date-time field, that renders as 2 fields in the admin.
Going top-down,
the admin uses
class AdminSplitDateTime(forms.SplitDateTimeWidget):
    """
    A SplitDateTime Widget that has some admin-specific styling.
    """
    def __init__(self, attrs=None):
        widgets = [AdminDateWidget, AdminTimeWidget]
        # Note that we're calling MultiWidget, not SplitDateTimeWidget, because
        # we want to define widgets.
        forms.MultiWidget.__init__(self, widgets, attrs)

    def format_output(self, rendered_widgets):
        return mark_safe(u'
%s %s
%s %s
' % \
            (_('Date:'), rendered_widgets[0], _('Time:'), rendered_widgets[1]))

which in turn uses SplitDateTimeWidget:
class SplitDateTimeWidget(MultiWidget):
    """
    A Widget that splits datetime input into two <input type="text"> boxes.
    """
    date_format = DateInput.format
    time_format = TimeInput.format

    def __init__(self, attrs=None, date_format=None, time_format=None):
        if date_format:
            self.date_format = date_format
        if time_format:
            self.time_format = time_format
        widgets = (DateInput(attrs=attrs, format=self.date_format),
                   TimeInput(attrs=attrs, format=self.time_format))
        super(SplitDateTimeWidget, self).__init__(widgets, attrs)

    def decompress(self, value):
        if value:
            return [value.date(), value.time().replace(microsecond=0)]
        return [None, None]

Which in turn extends the MultiWidget defined in django.forms.widgets which you should also extend. It has many useful methods which you can override.
class MultiWidget(Widget):
"""
A widget that is composed of multiple widgets.

Its render() method is different than other widgets', because it has to
figure out how to split a single value for display in multiple widgets.
The ``value`` argument can be one of two things:

    * A list.
    * A normal value (e.g., a string) that has been "compressed" from
      a list of values.

In the second case -- i.e., if the value is NOT a list -- render() will
first "decompress" the value into a list before rendering it. It does so by
calling the decompress() method, which MultiWidget subclasses must
implement. This method takes a single "compressed" value and returns a
list.

When render() does its HTML rendering, each value in the list is rendered
with the corresponding widget -- the first value is rendered in the first
widget, the second value is rendered in the second widget, etc.

Subclasses may implement format_output(), which takes the list of rendered
widgets and returns a string of HTML that formats them any way you'd like.

You'll probably want to use this class with MultiValueField.
"""
def __init__(self, widgets, attrs=None):
    self.widgets = [isinstance(w, type) and w() or w for w in widgets]
    super(MultiWidget, self).__init__(attrs)

def render(self, name, value, attrs=None):
    # value is a list of values, each corresponding to a widget
    # in self.widgets.
    if not isinstance(value, list):
        value = self.decompress(value)
    output = []
    final_attrs = self.build_attrs(attrs)
    id_ = final_attrs.get('id', None)
    for i, widget in enumerate(self.widgets):
        try:
            widget_value = value[i]
        except IndexError:
            widget_value = None
        if id_:
            final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
        output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
    return mark_safe(self.format_output(output))

def id_for_label(self, id_):
    # See the comment for RadioSelect.id_for_label()
    if id_:
        id_ += '_0'
    return id_
id_for_label = classmethod(id_for_label)

def value_from_datadict(self, data, files, name):
    return [widget.value_from_datadict(data, files, name + '_%s' % i) for i, widget in enumerate(self.widgets)]

def _has_changed(self, initial, data):
    if initial is None:
        initial = [u'' for x in range(0, len(data))]
    else:
        if not isinstance(initial, list):
            initial = self.decompress(initial)
    for widget, initial, data in zip(self.widgets, initial, data):
        if widget._has_changed(initial, data):
            return True
    return False

def format_output(self, rendered_widgets):
    """
    Given a list of rendered widgets (as strings), returns a Unicode string
    representing the HTML for the whole lot.

    This hook allows you to format the HTML design of the widgets, if
    needed.
    """
    return u''.join(rendered_widgets)

def decompress(self, value):
    """
    Returns a list of decompressed values for the given compressed value.
    The given value can be assumed to be valid, but not necessarily
    non-empty.
    """
    raise NotImplementedError('Subclasses must implement this method.')

def _get_media(self):
    "Media for a multiwidget is the combination of all media of the subwidgets"
    media = Media()
    for w in self.widgets:
        media = media + w.media
    return media
media = property(_get_media)

def __deepcopy__(self, memo):
    obj = super(MultiWidget, self).__deepcopy__(memo)
    obj.widgets = copy.deepcopy(self.widgets)
    return obj

A: Jannis Leidel released a widget quite a long time ago. django-coordinatesfield
As far as I remember, it took the coordinates from a map and passed it a single field and some javascript cut it into 2 coordinates for 2 fields.
Combined with a custom form it should work quite well

A: Here's an example for a ModelForm:
http://www.adamalton.co.uk/blog/displaying-django-genericforeignkey-as-single-form-field/
Add an extra form field to the form (for your single widget) and exclude the two 'real' fields, then override the init and save methods to do the extra logic that makes it work.
Also, same question:
How to get a single widget to set 2 fields in Django?

A: You can make the widget render two (hidden) html inputs, whose names relate to the model's fields that need to be filled and assign the necessary values via javascript to them!


text:
Q: Keep duplciate items in list of tuples if only the first index matches between the tuples Input [(1,3), (3,1), (1,5), (2,3), (2,4), (44,33), (33,22), (44,22), (22,33)]
Expected Output [(1,3), (1,5), (2,3), (2,4), (44,33), (44,22)]
I am trying to figure out the above and have tried lots of stuff. So far my only success has been,
for x in range(len(list1)):
if list1[0][0] == list1[x][0]:
    print(list1[x])

Output: (1, 3) \n (1, 5)
Any sort of advice or help would be appreciated.

A: Use a collections.defaultdict(list) keyed by the first value, and keep only the values that are ultimately duplicated:
from collections import defaultdict  # At top of file, for collecting values by first element
from itertools import chain          # At top of file, for flattening result

dct = defaultdict(list)
inp = [(1,3), (3,1), (1,5), (2,3), (2,4), (44,33), (33,22), (44,22), (22,33)]
# For each tuple
for tup in inp:
   first, _ = tup  # Extract first element (and verify it's actually a pair)
   dct[first].append(tup)  # Collect with other tuples sharing the same first element

# Extract all lists which have two or more elements (first element duplicated at least once)
# Would be list of lists, with each inner list sharing the same first element
onlydups = [lst for firstelem, lst in dct.items() if len(lst) > 1]

# Flattens to make single list of all results (if desired)
flattened_output = list(chain.from_iterable(onlydups))

Importantly, this doesn't required ordered input, and scales well, doing O(n) work (scaling your solution naively would produce a O(n²) solution, considerably slower for larger inputs).

A: Another approach is the following :
def sort(L:list):
    K = []
    for i in L :
        if set(i) not in K :
            K.append(set(i))
    output = [tuple(m) for m in K]
    return output

output :
[(1, 3), (1, 5), (2, 3), (2, 4), (33, 44), (33, 22), (44, 22)]


text:
Q: Please help me debug an SSL issue using WWW::Mechanize (or LWP::UserAgent for that matter) I'm using WWW::Mechanize to load the catalog from our product provider into our database. I run this script every 2 hours everyday and it completes in arround 12 minutes by using around 50 simultaneous threads.
Everything was working perfectly, until this weekend. They put their website offline for a scheduled maintenance and, once they where online again, my script no longer worked. After analyzing things, it comes down to the following code failing:
use strict;
use warnings;

use WWW::Mechanize;

my $mec = WWW::Mechanize->new;
$mec->get('https://www.imstores.com/Ingrammicromx/login/login.aspx');

print $mec->content;

The code dies (after about 60 seconds) with the following message:
Error GETing https://www.imstores.com/Ingrammicromx/login/login.aspx:
Can't connect to www.imstores.com:443 at test.pl line 7.

Now, these are the points that are making me difficult to find the problem:

*

*It's not network-related - if I visit the same URL from any of my browsers, I get the page.

*If I try the same code on a remote machine that contains an exact copy of my Perl installation, it works.

*If I use Net::SSL before WWW::Mechanize, it takes a very LONG time, but finally gets the page.

*If I try any other SSL page, like 'https://www.paypal.com', it works and very fast.

*Then again, it was working before their scheduled maintenance.
I'm not sure what else to try. If I switch to the non-SSL version, it works, but I don't want to do that since we automate purchasing operations.
Along with many things that have crossed my mind, thinking about why it works on the remote machine and why I can open the page in my browsers in the local one:
Is it possible to get blocked with my SSL public key? Is that possible? If so, what public key is LWP/Mechanize using for SSL sessions and how can I use a different one?
Some data on my current setup:

*

*OS: Windows 7 Ultimate x64

*Perl version: 5.16.3 x64

*LWP::UserAgent version: 6.05

*WWW::Mechanize version: 1.72

*IO::Socket version: 1.34

*IO::Socket::SSL version: 1.85

*Net::SSL version: 2.85

*Crypt::SSLeay version: 0.64

Thanks in advance for any helpful comment.

A: Here's the actual reason for the problem: You need to use SSLv3 or TLS1 instead of TLS1.2 to connect to that server. This is probably why it worked when you used Net::SSL first; I believe it tries different ciphers in a way that WWW:Mechanize doesn't.
This is how I found it:
I tried connecting from several different servers, and I find that the ones that worked have an older SSL version. I then checked the difference between what ciphers are used in the versions, and tried connecting with different ciphers.
When I connect using TLS1.2, I get:
$ openssl s_client -connect www.imstores.com:443 -tls1_2
CONNECTED(00000003)
write:errno=54
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 322 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
---

But when I connect with SSLv3 or TLS1, I get:
$ openssl s_client -connect www.imstores.com:443 -tls1
CONNECTED(00000003)
depth=0 /serialNumber=O3gPUAuGGROuHEhlyLaeJfj7SOn6tFTx/C=US/O=www.imstores.com/OU=GT29846307/OU=See www.geotrust.com/resources/cps (c)11/OU=Domain Control Validated - QuickSSL(R) Premium/CN=www.imstores.com
verify error:num=20:unable to get local issuer certificate
[...and so on, including server certificate...]

Exactly how to make WWW:Mechanize use TLS1 or SSLv3 is left as an exercise to the student.


text:
Q: Turtle is drawing SVG image upside down I've done a program that take an SVG image and redraws it with the turtle module.
The problem is that the image is redrawn perfectly but it's upside down.
from svgpathtools import svg2paths2, Path, Line
from tkinter import Tk, filedialog
import turtle

root = Tk()
root.withdraw()

open_file = filedialog.askopenfilenames(filetypes=[("Image Files", ".svg")])
file = open_file[0]
paths, attributes, svg_attributes = svg2paths2(file)

if len(paths) == 1:
    exit()

turtle.setworldcoordinates(0, 0, 500, 500)

def Vector(pathB):
    X1 = pathB[0].real
    Y1 = pathB[0].imag

    X2 = pathB[1].real
    Y2 = pathB[1].imag

    turtle.goto(X1,Y1)
    turtle.pendown()
    turtle.goto(X2,Y2)
    turtle.penup()

def Linear(x, y , t):
    return (x*(1-t)) + (y*t)

def Linear2(x, y,t):
    return Linear(x[0], y[0], t), Linear(x[1],y[1],t)

def Bezier(P0,P1,P2,P3, t):
    c1 = Linear2(P1,P2,t)
    c2 = Linear2(P0,c1,t)
    c3 = Linear2(c2, P3, t)
    c4 = Linear2(c2, c3, t)

    return c4

def BezierTurtle(P0,P1,P2,P3):
    t = 0
    while t < 1:
        t+= 0.001
        x,y = Bezier(P0,P1,P2,P3,t)
        if turtle.distance(x,y) >= 1:
            turtle.goto(x,y)
            turtle.pendown()

for l in range(len(paths)):
    bluepath = paths[l]
    for i in range(len(bluepath)):
        print(turtle.pos())
        turtle.penup()
        if isinstance(bluepath[i],Line):
            Vector(bluepath[i])
        else:
            P0 = (bluepath[i][0].real, bluepath[i][0].imag)
            P1 = (bluepath[i][1].real, bluepath[i][1].imag)
            P2 = (bluepath[i][2].real, bluepath[i][2].imag)
            P3 = (bluepath[i][3].real, bluepath[i][3].imag)
            BezierTurtle(P0,P1,P2,P3)
            turtle.penup()

turtle.done()


text:
Q: What type of barcode scanner do I need to access scanner output in Java app? For my project I need to scan barcodes and save them in a database.
I thought about doing this by running a Java app in the background that listens to the port used by the scanner and saves the output of the scanner to the database.
My resources are very limited and I would like to know if I need a special type of scanner for this task. This is the cheapest scanner I found in ebay. Is it valid for this task? Otherwise, what type of scanner should I look for?
Please guide me

A: Most barcode scanners meant to be used with PC's will plug in and act like keyboards. They provide the scanned information as if it had been typed at a keyboard by a user.
So, chances are there's no special "port used by the scanner" and it won't make a difference for this purpose what scanner you choose - you can write a simple app that accepts input from the user and stores it in the database.
You'll want to make sure that the barcode scanner can read the barcodes you're working with, and make sure that the distance from the barcode and scanning speed are appropriate for your application.


text:
Q: How can I add control flow into a mysql function? I want to optimise a mysql 5.7 function that reads settings from a table. the function returns a 1 or 2 if the date parsed in is in 'semester 1' or 'semester 2'.  the dates for semester 1 and 2 change each year.
we have confirmed that dateIn is a valid date.
the function is:
DELIMITER //
CREATE  function getSemester (dateIN date)
RETURNS INT DETERMINISTIC
BEGIN
    DECLARE sem int;
    select if( dateIN < a.mindate,1,2) into sem
    from (SELECT min(date(value)) mindate FROM `settings` WHERE name = CONCAT('sem2_',year(dateIN),'_start') ) a;
    return sem;
END//
DELIMITER ;

settings is defined as:
CREATE TABLE `settings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`value` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

the settings data is:
INSERT INTO `mdl_sap_settings` (`id`, `name`, `value`)
VALUES
    (4, 'sem2_2012_start', '2012/7/16'),
    (15, 'sem2_2013_start', '2013/7/1'),
    (25, 'sem2_2014_start', '2014/6/30'),
    (29, 'sem2_2015_start', '2015/6/29'),
    (37, 'sem2_2016_start', '2016/6/27'),
    (42, 'sem2_2011_start', '2011/7/16'),
    (50, 'sem2_2017_start', '2017/6/26'),
    (56, 'sem2_2018_start', '2018/6/25'),
    (63, 'sem2_2019_start', '2019/6/24');

the issue is the function is slow quite slow when called on 20,000 rows. I thought to optimise it by having some sort of flow control in the function something like:
if (year(dateIN) = 2012)
{
   return dateIN < '2012-07-16' ? 1 : 2;
}
if (year(dateIN) = 2013)
{
   return dateIN < '2013-07-01' ? 1 : 2;
}

... etc.

We need to keep the select as is query because if the code is not maintained we want it to return the correct values.
i was just wondering if this sort of control flow is possible in a mysql function, or is there an alternative way to optimise the function?

A: I don't have 20k records to test with but if I were you, I'd rewrite your function like this and see if that helps.
DELIMITER //
CREATE  function getSemester (dateIN date)
RETURNS INT DETERMINISTIC
BEGIN
    DECLARE sem int;
    DECLARE nameByDate varchar(255);
    SET nameByDate = (SELECT CONCAT('sem2_',year(dateIN),'_start') );
    select if( dateIN < a.mindate,1,2) into sem
    from (SELECT min(date(value)) mindate FROM `test`.`settings` WHERE name = nameByDate ) a;
    return sem;
END//
DELIMITER ;

I'd avoid adding a concat in the where clause as there is a performance hit on large dataset. So I moved it out of where clause and assigned it to a variable once. If that doesn't help you can also try the query with explain and see if that provides any hints.
EXPLAIN select getSemester('2019/6/24');

Good luck.

A: With 20,000 rows in the results table, the my query run without the getSemester function in 157 msec.
with the version of getSemster in the question it was taking 1.1 seconds.
with this optimisation the query was running in 0.9 seconds.
DELIMITER //
CREATE  function getSemester (dateIN date)
RETURNS tinyint DETERMINISTIC
BEGIN
    DECLARE sem tinyint;
    DECLARE sem2_start_label char(16);
    set sem2_start_label = CONCAT('sem2_',year(dateIN),'_start');
    select case year(dateIN)
        when 2012 then
            case when dateIN < date('2012-07-16') then 1 else 2 end
        when 2013 then
            case when dateIN < date('2013-07-01') then 1 else 2 end
        when 2014 then
            case when dateIN < date('2014-06-30') then 1 else 2 end
        when 2015 then
            case when dateIN < date('2015-06-29') then 1 else 2 end
        when 2016 then
            case when dateIN < date('2016-06-27') then 1 else 2 end
        when 2017 then
            case when dateIN < date('2017-06-26') then 1 else 2 end
        when 2018 then
            case when dateIN < date('2018-06-25') then 1 else 2 end
        when 2019 then
            case when dateIN < date('2019-06-24') then 1 else 2 end
        else
            case when dateIN < (SELECT min(date(value)) mindate FROM `settings` WHERE name = sem2_start_label ) then 1 else 2 end
    end into sem;
    return sem;
END//
DELIMITER ;

what i did was only select the date from the settings table when it was unknown -- seems to give a small optimisation.