text:
Q: Do "factoradic" lists form a finitary monad? I'm trying to understand better what it means for a monad to be finitary.  I know that Lawvere theories correspond to finitary monads, but I don't really understand the definition in terms of filtered colimits.
Normal lists satisfy
$$L(X) = 1 + X\cdot L(X).$$
Now suppose that at position n in the list, we can use either an
element of X or one of n extra values:
$$F(X) = 1 + X\cdot F(X + 1)$$
An element of F(0) is a numeral in "factoradic" or "base factorial".
$F$ is a monad with the usual list operations.  Is it finitary?  If so, what does the corresponding Lawvere theory look like?  If not, how does it fail to preserve filtered colimits?

A: Yes, it is finitary. If you think about $X$ as a set of variable and about $T(X)$ as a set of structures of some sort, then $T : Set \to Set$ is finitary if every structure $t \in T(X)$ can use only finite number of variables (roughly speaking). Every list uses only a finite number of variables (up to its length), so does every $F$-structure.
Another example of a functor like yours is the functor of untyped lambda terms which satisfies the following equation:
$$C(X) = X + C(X) \times C(X) + C(X + 1)$$
Elements of $C(X)$ are untyped lambda terms whose free variables belong to $X$. Since any lambda term can use only a finite number of variables from $X$, this functor is also finitary.
An example of a non-finitary monad is the monad of trees with infinite number of children:
$$I(X) = X + (\mathbb{N} \to I(X))$$
Since an infinite tree can use an infinite number of variables, it is not finitary. A formal proof of this fact goes like this. Let $X$ be an infinte set. Then it is a directed colimit of its finite subsets, but every tree in the colimit $colim_{Y \subset_{fin} X}(I(Y))$ uses only a finite number of variables (namely, the variables from $Y$), so it is not (canonically) isomorphic to the set of all trees $I(X)$. Thus $I$ does not preserve directed colimits.
Algebraic theories is a more explicit way of talking about theories than Lawvere theories. You can always describe an algebraic theory that corresponds to a (finitary) monad $T$ as a theory with $T(\{x_1, \ldots x_n\})$ $n$-ary operations. Sometimes there is a more simple description. For example, the theory that corresponds to $L$ is equivalent to the theory of monoids. Another way to present this theory as the theory with one $n$-ary operation for every $n$ (and a bunch of axioms). You can think of such operation as the concatenation of $n$ elements of a monoid.
Now, you can present the theory for $F$ in a similar way. It will have the same operation as the theory for $L$, but it will also have operations that correspond to the concatenation of a list in which some elements are not elements of your structure, but the new elements that you add in the definition of $F$. Overall, it will have infinitely many $n$-ary operations for every $n > 0$. You can explicitly describe them in terms of lists in which you may have $n$ different holes in $n$-th place. In general, it is a non-trivial task to find a simple presentation for a monad in terms of operations. There is probably a more simple description of the theory for $F$ than the one that I have in mind.


text:
Q: VSCode create custom colorized language syntax highlighter extension for a custom language Where and how do we change the colors for the syntax highlighters for specific languages?
GOAL: Ideally, I'd like to:
1. Understand how to create an extension that modifies the colors of code
2. Branch and modify this extension to do what I want (but I can't find out which is the file to add colors to) Freemarker Highlighting Extension
All I've found was information on editor.tokenColorCustomizations for the editor in general, but this is apparently not allowed in settings.json for individual languages: "This setting does not support per-language configuration." **

I have found plenty of information on how to create your own language extensions, etc., but none of them deal with the code colorization details.
The search term "visual studio how to create an extension to color code a language" comes up with pretty much everything but what I'm trying to figure out.
It seems that Yo Code may be part of the solution, but again, no specifics about colorization.
Things I've researched / read:

*

*TextMate language grammars (there is one for the language I'm trying to re-color (https://github.com/bburbach/textmate-freemarker-bundle/blob/master/FreeMarker.tmbundle/Syntaxes/FreeMarker.tmLanguage) and even an extension for Freemarker, but no way to change the color scheme

*Gone through the repo for the extension I mention above but see nowhere that the colors are declared (https://github.com/dcortes92/vs-freemarker)

*Various VSCode support pages on syntax highlighting (https://code.visualstudio.com/api/extension-guides/color-theme, https://code.visualstudio.com/docs/getstarted/settings, https://code.visualstudio.com/api/language-extensions/semantic-highlight-guide, https://code.visualstudio.com/api/references/theme-color

*And lots of other random pages about syntax highlighting

Maybe it's obvious to some of you, but I am unable to find the answers I need. So if the SO community can help point me in the right direction without giving me a hard time, I'd appreciate it.

A: The TextMate language grammar gives a scope to certain parts of the file: keyword, string, number.
The Theme file has a section where it assigns colors to the TextMate scopes. From the generic to maybe the detailed scopes for a particular language. And most likely the semantic colors (unused variable, unreachable code, ...).
If your particular language already has a TextMate language you modify editor.tokenColorCustomizations in settings.json (VSC Configuration), and specific the textMateRule. Better to do it for a particular theme.
  "editor.tokenColorCustomizations": {
    "[One Dark Pro]": {
      "textMateRules": [
        { "scope":"punctuation.definition.comment",
          "settings": {"foreground": "#229977"}
        },
        { "scope":"variable.other.property.js",
          "settings": {"foreground": "#00ff00"}
        }
      ]
    }
  }

These are dummy colors

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can we explicitly solve the Hamilton–Jacobi equation for a particle in a uniform magnetic field? HJE for nonrelativistic charged particle in an electromagnetic field is
$$\frac{1}{2m}\left(\nabla S - q\mathbf{A}\right)^2 + q\phi + \frac{\partial S}{\partial t} = 0.$$
For a uniform magnetic field $\mathbf{B} = B_0 \hat{\mathbf{z}}$ and a particular choice of gauge this becomes something like:
$$\left(\frac{\partial S}{\partial x}\right)^2 + \left(\frac{\partial S}{\partial y} - qB_0 x\right)^2 + \left(\frac{\partial S}{\partial z}\right)^2 = -2m \frac{\partial S}{\partial t}.$$
Can we solve this explicitly? It seems to me we can start by separating the variables $t, z$ by letting $S = f(x, y) + p_z z - Et$, giving
$$\left(\frac{\partial f}{\partial x}\right)^2 + \left(\frac{\partial f}{\partial y} - qB_0 x\right)^2 = 2mE - p_z^2,$$
but I'm really bad at solving differential equations, so I don't know how to proceed. I also have no intuition for what the solution $S$ is supposed to look like, even though I already know how a particle moves in a uniform magnetic field, so I don't have any idea how to guess a form for $S$.

A: Hints:

*

*Since there is no explicit time dependence in the Landau problem, we can use Hamilton's characteristic function $W$ rather than Hamilton's principal function $$\tag{1} S~=~W - Et.$$
Thus
$$\tag{2} \left(\frac{\partial W}{\partial x}\right)^2 + \left(\frac{\partial W}{\partial y} - qB_0 x\right)^2 + \left(\frac{\partial W}{\partial z}\right)^2 = 2m E .$$

*The two variables $y$ and $z$ are cyclic variables, so the corresponding momenta $p_y$ and $p_z$ are conserved, and Hamilton's characteristic function becomes $$\tag{3}W(x,y,z)~=~ w(x) +p_y y +p_z z.$$ Thus the first-order PDE (2) reduces to a first-order ODE
$$\tag{4} \left(\frac{dw}{d x}\right)^2 + \left(p_y - qB_0 x\right)^2 + p_z^2 = 2m E ,$$
which has a well-known explicit solution.

A: 1) Follow the procedure of paragraph $3.3$  (A Charged Particle in a Magnetic Field) page $77$ of this paper, by specializing your case with $k=\lambda=0$, so that $y=r$
2) You finally get the formula $(46)$ at the top of the page $80$, and you may take:
$S = f(y)+ \gamma\theta - \alpha t$
So you have a differential equation for $f$, and you may get the result, from W.A. for instance : here
Remark : The example is given in $2$ dimensions, so with $3$ dimensions, you may simply take $p_z$= Cte and $\alpha \to  \alpha - \dfrac{p_z^2}{2m}$


text:
Q: Determining the Lagrangian function and deriving the Euler-Lagrange equation of the following conservative system Image of conservative system
The image is a conservative system where $l_{1}$ and $l_{2}$ are the lengths of the two linear elastic springs at rest, while $k_{1}$ and $k_{2}$ are the elastic constants. We let $\theta_{1}$ and $x_{1}(t)$ be the degrees of freedom identifying the position of the mass $m_{1}$ and  $g$ be the acceleration of gravity.
I have to find the Lagrangian function and derive the Euler-Lagrange equations.
I'm struggling to obtain the Lagrangian. I know the quantity is given by $L=T-V$, but I don't know if I'm expressing the kinetic and potential energy with respect to the generalized coordinates $\theta_{1}$ and $x_{1}(t)$ correctly.
The length $L$ is a constraint on the system, so I was thinking of expressing the position of the mass as $r_{x} = L - (l_{1}+x_{1}(t))cos(\theta_{1}(t))$ and $r_{y} = L - (l_{1}+x_{1}(t))sin(\theta_{1}(t))$. With the position of the mass, I can express the energy with respect to the generalized coordinates.
For the kinetic energy, $T=\frac{1}{2}m(\dot{r})^2 = \frac{1}{2}m((\frac{dr_{x}}{dt})^2+(\frac{dr_{y}}{dt})^2)$. I can differentiate this; I just need to know if the expression is correct.
For the potential energy, $V = \frac{1}{2}k_{eff}(\Delta x)^2 + mgh=\frac{1}{2}(k_{1}+k_{2})(x_{1}(t))^2 + mg(l_{1}+x_{1}(t))sin(\theta_{1}(t))$.
Are these expressions correct? I only need help finding the Lagrangian. I can find the equations of motion once I have the Lagrangian.
Thanks for the help!

A: I personally would define the origin of the coordinate system to be the attachment point of spring 1 with the wall, and the position of the mass to be $((l_1 + x_1) cos(\theta_1), -(l_1+x_1) sin(\theta_1))$.
The potential energy is
\begin{equation}
V = \frac{1}{2} k_1 x_1^2 + \frac{1}{2} k_2 x_2^2 + mgh
\end{equation}
so you want to represent $x_2$ and $h$ in terms of $x_1$ and $\theta_1$.  That's relatively easy (particluarly $h$):
\begin{equation}
h = -(l_1+x_1) sin(\theta_1)
\end{equation}
\begin{equation}
 l_2 + x_2 = \sqrt{(l_1+x_1)^2 sin(\theta_1)^2 + (L-(l_1+x_1)cos(\theta_1))^2} \, .
\end{equation}
Now just start substituting in.
Your mistakes were: 1) you miscalculated the potential energy of spring 2 -- it depends on $x_2$, not $x_1$, and 2) your sign for gravitational potential energy is wrong.


text:
Q: How to define all-or-nothing type? I want a generic type that satisfies the below cases:
type AB = {a: string, b: string};
type AllOrNothing<T> = ...                   // how to define this such that...

const empty: AllOrNothing<AB> = {};            // case 1: nothing, OK
const ab: AllOrNothing<AB> = {a:"a",b:"b"};    // case 2: all fields, OK
const a: AllOrNothing<AB> = {a:""};            // case 3: partial, NOT OK

I have tried the below:
// case 1 fails compile
export type AllOrNothing<T> = { [k in keyof T]: T[k] } | { [k in keyof T]: never };

// case 3 passes compile
export type AllOrNothing<T> = { [k in keyof T]: T[k] } | {}

A: You could do this using conditional types
First create your type like so:
type AllOrNothing<T> =
T extends "all" ? { a: "a"; b: "b"; }
: T extends "nothing" ? { a: "" } : never

This essentially creates a type saying if T is equal to all then it will be type a and if T is equal to nothing then it will be of type b. Otherwise it will never be a type
Then your type would work something like:
// This will have the all type
const all: AllOrNothing<"all"> = {
    a: "Hello",
    b: "World"
}

// It is an empty object
const nothing: AllOrNothing<"nothing"> = {
    a: ""
}

Read about conditional types here:
https://www.typescriptlang.org/docs/handbook/2/conditional-types.html

A: Your first attempt is almost correct, you need to set all of the properties to never but also make them optional.
We can use Partial for that.
type AllOrNothing<T extends Record<string, any>> = T | Partial<Record<keyof T, never>>;

type AB = { a: string, b: string };

const empty: AllOrNothing<AB> = {};               // OK
const ab: AllOrNothing<AB> = { a: "a", b: "b" };  // OK
const a: AllOrNothing<AB> = { a: "" };            // NOT OK
const c: AllOrNothing<AB> = { c: "" };            // NOT OK


text:
Q: Google Maps API V3 function closure for loops for markers I have been reading other entries into stackoverflow but I really cannot get my head around how this works:
            for(a in elements){
                var address = elements[a].location;

                var contentString = '
';

                for(b in elements[a].other_fields){
                    var current = elements[a].other_fields[b];

                    switch(current.type){
                        case "text":
                            contentString += "
" + current.label + ":	" + current.values[0].value + "
";
                        break;
                        case "date":
                            if(!current.values[0].end){
                                var end_date_output_string = "";
                            }else{
                                var end_date_output_string = " -> " + current.values[0].end;
                            }
                            contentString += "
" + current.label + ":	" + current.values[0].start + end_date_output_string + "
";
                        break;
                    }
                }

                contentString += "
";
                contentString += "<input type = 'button' onclick = 'window.open(\"" + elements[a].url + "\");' value = 'Open in Podio'>";

                geocoder.geocode( { 'address': address}, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        map.setCenter(results[0].geometry.location);
                        alert(contentString);
                        addMarker(results[0].geometry.location);
                    } else {
                        alert("Geocode was not successful for the following reason: " + status);
                    }
                });
                //open_info_window(a, contentString);
            }

                                function addMarker(location) {
                                    var marker_copy = new google.maps.Marker({
                                        position: location,
                                        map: map
                                    });

                                    marker = marker_copy;

                                    markersArray.push({
                                        "marker": marker,
                                        "info_window": null
                                    });

                                    alert("marker added: " + markersArray.lenght);
                                }

                                // Opens info windows
                                function open_info_window(key, contentString) {
                                    var infowindow = new google.maps.InfoWindow({
                                        content: contentString
                                    });

                                    alert(key);

                                    markersArray[key].info_window = infowindow;

                                    google.maps.event.addListener(markersArray[key].marker, "click", function() {
                                        markersArray[key].info_window.open(map, markersArray[key].marker);
                                    });
                                }

The part where I try to alert(contentString) will not alert what I expect and It's to do with closures but I actually have never come across such code before. Any chance you could give me a bit of help.
I want to be creating an infowindow with the contentString for the marker that i am adding.

A: I assume you'll see the result of the last iteration in the alert, this is explained in detail in this blog post.
In your case, I would switch around the order of execution: You have an outer loop which calls geocoder.geocode:
for(a in elements) {
        var address = elements[a].location;
        (function (element) {
            geocoder.geocode( { 'address': address}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    map.setCenter(results[0].geometry.location);
                    doAlert(element);
                    addMarker(results[0].geometry.location);
                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
        })(elements[a]);
}

With function doAlert:
var doAlert = function(element) {
            var contentString = '
';

            for(b in element.other_fields){
                var current = element.other_fields[b];

                switch(current.type){
                    case "text":
                        contentString += "
" + current.label + ":	" + current.values[0].value + "
";
                    break;
                    case "date":
                        if(!current.values[0].end){
                            var end_date_output_string = "";
                        }else{
                            var end_date_output_string = " -> " + current.values[0].end;
                        }
                        contentString += "
" + current.label + ":	" + current.values[0].start + end_date_output_string + "
";
                    break;
                }
            }

            contentString += "
";
            contentString += "<input type = 'button' onclick = 'window.open(\"" + elements[a].url + "\");' value = 'Open in Podio'>";

            alert(contentString);
      }

A: YES, I FIGURED IT OUT
        function codeAddress(){
            for(a in elements){
                (function(a){
                    var address = elements[a].location;

                    geocoder.geocode( { 'address': address}, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            map.setCenter(results[0].geometry.location);
                            addMarker(results[0].geometry.location);
                            alert(a);
                            var the_string = generate_string(elements, a);

                            infowindow[a] = new google.maps.InfoWindow({
                                content: the_string
                            });

                            google.maps.event.addListener(markersArray[a], "click", function() {
                                infowindow[a].open(map, markersArray[a]);
                            });
                        } else {
                            alert("Geocode was not successful for the following reason: " + status);
                        }
                    });
                })(a);
            }
        }

The trick was doing this and i have no idea how it works but it works:
(function(a){
})(a);

I assume that a is the constructor for the function so that it doesnt get created by a variable reference but instead by the actual iterator itself. Oh god i dont know. yippee


text:
Q: Developing Access DB to SQL? I built a database several years ago in Access to track over 4K pieces of equipment in and out of a shop, where it was going, current status, etc. It's dying. I would like to upgrade it, but unsure if a split Access DB or a SQL Server 2008 back with Access front would be better/sufficient. I'm leaning towards the latter.
At most 35 simultaneous users, but only on rare occasions.
Would like to track (log) changes to items each time data/status changes.
Print reports, etc.
Keep it SIMPLE for users.

A: How large is your database? If you expect that your database will not grow to larger than 10 GB, and you are familiar with SQL Server, then you can use SQL Server Express Edition. If you don't need any of the enterprise features (page/row compression, HA/DR, encryption, table partitioning, etc), it's a great way to manage smaller amounts of data...and its free!
I've never personally used a set-up with Access ADP as a front-end, but I've heard it works fine for straight-forward data management. If you have the time/resources, creating a simple web-based front end for management (or buying something out of the box that sits on SQL Server) might allow you to reduce the complexity even further.


text:
Q: Is Prism Primarily for Silverlight? The majority of the articles/tutorials/blog post I read about Microsoft's Prism Framework center around Silverlight. With the composite model being an interesting model for an existing desktop app that needs a little TLC, I'm wondering is Prism a viable technology for a desktop LOB app?

A: It is for Silverlight(Web), WPF(Desktop) and Windows Phone 7(Phone).
Basically, it is for any platform that uses XAML, MVVM combo.
And for your last question, YES, it's a very good option to go with when developing a LOB application in WPF.
But remember, you will need to spend a few days just to learn Prism (and Unity or MEF). So, be ready for it.

A: most of the online resources are for Silverlight because it wasn't until fairly recently that WPF support was officially released.   Prism 4.0 at http://compositewpf.codeplex.com/ includes WPF resources including some on sharing code between WPF & SL


text:
Q: Implement the .split method I need to implement the .split method in my own way without using prebuilt functions. The method should receive a string divided into 2 sentences by a dot and divide them through a separator.
For example, there is this string:
'word wooord wooooooooord wooooooord. wooooooooord woooooord woooord wooooooooord', separator in this case: '. '
The result should be:
['word wooord wooooooooord wooooooord", "wooooooooord woooooord woooord wooooooooord']
I tried to implement it myself, the first problem I encountered is that the words from the string are added character by character to the new array. The second problem is that the output is still a string even though I declared an array earlier.
function split(str, splitter){
    let arrSent = []
    for (let i = 0; i < str.length; i++){
        if (str[i] != splitter){
            arrSent += str[i]
        }
    }
    return arrSent
}
console.log(split('word wooord wooooooooord wooooooord. wooooooooord woooooord woooord wooooooooord', '. '))

A: Since the delimiter can have more than one character, you need a system to upfront collect a sample of characters (of the same length as the delimiter) to be then compared with the delimiter:

const split = (str, delimiter) => {

  // If delimiter is empty string just return an array of characters
  if (delimiter === "") return [...str];

  const len = delimiter.length;
  const iter = str.length - len + 1; // max needed iterations
  const arr = [""]; // Prefill it with empty string
  let idx = 0; // arr insertion pointer

  for (let i = 0; i < iter; i++) {

    // Collect len chars from str as a sample
    // to compare with the delimiter:
    let sample = "";
    for (let x = i; x < i + len; x++) {
      sample += str[x];
    }

    const isSplit = sample === delimiter;
    const isEnded = i === iter - 1;

    if (isSplit) {
      i += len - 1;  // Consume splitted characters
      idx += 1;      // Increment arr pointer
      arr[idx] = ""; // Prepare the new array key as empty string
    } else {
      // If loop ended append the entire sample.
      // Otherwise, append a single character:
      arr[idx] += isEnded ? sample : str[i];
    }
  }

  return arr
}

console.log(split("word. etc", ". "));
console.log(split("word. etc. ", ". "));
console.log(split(". word yep. . etc. ", ". "));
console.log(split("word", ". "));
console.log(split("word", "word"));
console.log(split("word", ""));
console.log(split("", ""));

above, idx (starting at 0) is used as the output's arr insertion pointer. The idx is incremented if the sample matches the delimiter. Also, if there's a match, we need to skip iterations i += len, to not include the delimiter in the output array.
To test, create many examples and right before return arr; use console.log(JSON.stringify(arr) === JSON.stringify(str.split(delimiter))); - it should return true for all the submitted tests.


text:
Q: IIS 8.5 returns old version of a file from a virtual directory I have a file in a virtual directory myfile.html. After I change the file content, some times I receive an old file version, maybe some caching is there but I don't understand where, below is my rewrite:
protected void Rewrite(HttpRequest request, HttpApplication httpApp)
{
    Uri uri = request.Url;
    if (uri == null)
    {
        return;
    }
    httpApp.Context.Response.Cache.SetNoServerCaching();
    httpApp.Context.RewritePath("PathFromVirtualDirectory/myfile.html", true);
}

In my web.config I have a few settings to disabling caching.
<staticContent>
    <clientCache cacheControlMode="DisableCache"/>
</staticContent>
<!-- additional settings -->
<caching>
    <profiles>
        <add extension="*" policy="DontCache" kernelCachePolicy="CacheUntilChange"/>
    </profiles>
</caching>

The file on the server is changed, but the get request returns old version of the file.


text:
Q: Hover not working with nth-child He I am exploring the features of CSS 3 and I walked into some trouble:
For a table I have made this CSS:
table.sortable tbody tr td {
    border-bottom:1px solid;
    height: 20px;
}

table.sortable tbody tr:hover {
    background-color:#BCD2E5 !important;
}

table.sortable tbody tr:nth-child(odd) td {
    background-color: #F3FAFF;
}
table.sortable tbody tr:nth-child(even) td {
    background-color: #FFFFFF;
}

table.new{
    background-color: rgb(255, 255, 187);
}

table.reaction{
    background-color: rgb(255, 128, 64);
}

table.send{
    background-color: rgba(154, 211, 109, 0.470588);
}

The problem is that the hover is not working but if I comment the nth-child selector out it does actually work. Also in some cases I have to give some rows different background color's. This is for the users so they can see the status of some stuf really easy. So if I assign a class like class="send" to a row it has to get the background color form the class send.
Why is this not working out?! or did I miss something!?

A: You are applying the background-color for the nth-child rows to the td. The background-color on the td is showing above the background-color of the tr.
Changing your CSS to the following worked for me (remove the td from the end nth-child selectors):
table.sortable tbody tr:hover {
    background-color:#BCD2E5 !important;
}

table.sortable tbody tr:nth-child(odd) {
    background-color: #F3FAFF;
}
table.sortable tbody tr:nth-child(even) {
    background-color: #FFFFFF;
}

OR
Add td to the end of your hover selector, like so:
table.sortable tbody tr:hover td {
    background-color:#BCD2E5 !important;
}

See this codepen: http://codepen.io/keithwyland/pen/woLmh

ALSO
If you move the hover selector after the nth-child selectors in the CSS, then you shouldn't need the !important. So, like this:
table.sortable tbody tr:nth-child(odd) {
    background-color: #F3FAFF;
}
table.sortable tbody tr:nth-child(even) {
    background-color: #FFFFFF;
}

table.sortable tbody tr:hover {
    background-color:#BCD2E5;
}


text:
Q: Is this vulnerable to mass assignment? I use this to allow users to vote on an Entry:
 <% form_tag url_for(entry_votes_path(@entry)), :id => 'voting_form', :remote => true do %>
      <%= hidden_field_tag 'vote[user_id]', current_user.id  %>
      <%= submit_tag 'Vote for this entry', :id => 'voting_button' %>
 <% end %>

This is my controller code:
def create
    @entry = Entry.find(params[:entry_id])
    @vote = @entry.votes.build(params[:vote])

    respond_to do |format|
    if @vote.save
        format.html { redirect_to @entry }
        format.js
      end
    end
  end

I have two questions

*

*How can I assign current_user.id without using a hidden field?

*Also, I'm not using attr_accessible or attr_protected on the Vote model right now. How should I secure the model to make sure someone can't create a lot of votes? Right now, all the fields in the Vote model are set by the params hash -- should I use attr_protected on say, the entry_id foreign key and then set it separately in the controller?

A:
I'm not using attr_accessible
  or attr_protected on the Vote model
  right now...

Then, by definition, mass assignment is possible from the query string.

Should I use attr_protected on say,
  the entry_id foreign key and then set
  it separately in the controller?

In general, it's better to use attr_accessible than attr_protected.  This is because attr_accessible establishes a default of deny-all to mass assignment and lets you define whitelisted exceptions.  On the other hand, attr_protected forces you to blacklist specific attributes.  When you modify the program and add a new attribute with attr_accessible set, the program will fail if you need to whitelist the attribute and forget.  In other words, it fails safely.  Alternatively, if you add a new attribute with attr_protected set, the program will work even if the new attribute should have been included in the blacklist.  On other words, it fails insecurely.
The rule here is to protect any attribute which it would be dangerous to allow to be set from the query string.  Protecting the key helps prevent injection of new rows but it may be necessary to protect other fields if you want to prevent the ability to change the contents of existing rows.
A good reference on this may be found at guides.rubyonrails.org.


text:
Q: How can a Chrome extension's content script determine the injected page's referrer? What is the best way to determine a page's referrer within the context of a content script in a Chrome extension?
It looks possible to intercept requests' headers using the chrome.webRequest module, but it would then take some book-keeping and message-passing in order to get it into the content script.
That approach feels kludgy.  Is there a better way?

A: How about document.referrer?


text:
Q: Multiplying lists of lists in netlogo I have two different lists (list1 and list2) such that:
list1  = [ [a1 a2 a2]
           [b1 b2 b3] ]

list2  = [ [c1 c2 c3]
           [d1 d2 d3] ]

I would like to multipliy the lists in the following way, to create a new list3 such that.
list3 = [ [a1\*c1  a2\*c2  a3\*c3]
          [b1\*d1  b2\*d2  b3\*d3]]

I could write a loop which iterates over each element, however, I think there might be a nicer way to use somehow the map function in netlogo.
Thanks for your answers!

A: I'm not sure that this is terribly elegant, but a double map will take care of an arbitrary number of lists of lists.
to test
  let list1 [ [2 6 12] [20 30 42] ]
  let list2 [ [1 2 3] [4 5 6] ]
  let list3 (map [[x1 x2] -> (map [[y1 y2] -> y1 / y2] x1 x2) ] list1 list2)
  show list3
end


text:
Q: Staying DRY while re-using gulp task. How is this normally handled? I have a Gulp task which spins up a local server with gulp-connect and then opens a browser window to interact with the server through open.
The code looks like this:
const gulp = require('gulp');
const connect = require('gulp-connect');
const open = require('open');
const path = require('path');

// Create a local server for hosting the project.
// Responds to livereload commands so file changes don't require refreshing.
gulp.task('connect', (done) => {
  const host = 'localhost';
  const port = 8080;

  connect.server({
    host,
    port,
    // Needs to be path.resolve and not just './'
    // https://github.com/AveVlad/gulp-connect/issues/54
    root: path.resolve('./'),
    livereload: true
  });

  // Open default browser to the compiled directory.
  // Presumably useful since a connect server was just spun up for development.
  open(`http://${host}:${port}/compiled/`);
  done();
});

Currently, this function only supports opening to the browser to the compiled directory. I would like to extend it so that I can optionally open to the dist directory.
It's worth noting that I'm not calling the connect task directly from the command line. Instead, I'm running other tasks, such as build, which would like to convey to connect its desire to open to the dist directory:
gulp.task('build', (done) => {
    // TODO: Have connect open to 'dist' and not 'compiled'
    runSequence('compile', 'build', 'connect', done);
});

I saw a few posts on passing command line arguments into Gulp tasks, but I don't think this is relevant due to the fact I'm not running the command explicitly from the command line, but I could be incorrect.
What's the proper way to dynamically configure this task?
EDIT: This works, but feels hacky:
const argv = require('yargs').argv;

const directoryName = argv._[0] === 'build' ? 'dist' : 'compiled';
open(`http://${host}:${port}/${directoryName}/`);

A: Since the connect task has nothing to do with gulp, you can refactor it into a function, which you call from your other tasks.
function connect(dir) {
  const host = 'localhost';
  const port = 8080;

  connect.server({
    host,
    port,
    root: path.resolve('./'),
    livereload: true
  });

  open(`http://${host}:${port}/${dir}/`);
}

gulp.task('build', (done) => {
    runSequence('compile', 'task2', 'task3', () => {
        connect('dist');
        done();
    });
});

The downside to this solution is that you can't run gulp connect from the command line. But it would be trivial to create a connect task that uses the function above if you wanted that.


text:
Q: RabbitMQ mirroring is possible when an anonymous(randomly named) queue is created? I've made several policies for policy making test. And it worked well.
What if I'm making a randomly named queue and want to make it mirrored?

A: "Completely" randomly named, hardly... You could prepend a word to it or something, and do "begging with" pattern in the policy for example. Search for Some examples in this page.


text:
Q: Utl_File not generating file in the server path I have executed a block of code which generates a simple text file using utl_file package
with a word 'test' and outputs the file to the location in server.
When i run the procedure it compiles successfully but the file is not
generated in the path.
set serveroutput on
declare
l_file utl_file.file_type;
l_dir varchar2(500):='WMS_IFILEOUT';
l_file_name varchar2(500):='test.txt';
begin
l_file :=utl_file.fopen(l_dir,l_file_name,'w',32767);
utl_file.put_line(l_file,'test123');
utl_file.fclose(l_file);
end;

The path and directory are available in the dba_directories
and read and write privileges are available on it.
I noticed that when i print
show parameter utl_file
then no values are displayed alongside to it.
Do I have to set this parameter in order to generate the files in the server path.
If so, can you please tell how to set it.
Thanks

A: I tried code you posted; the only modification was to rename directory).
SQL> DECLARE
  2     l_file       UTL_FILE.file_type;
  3     l_dir        VARCHAR2 (500) := 'DPDIR';
  4     l_file_name  VARCHAR2 (500) := 'test.txt';
  5  BEGIN
  6     l_file :=
  7        UTL_FILE.fopen (l_dir,
  8                        l_file_name,
  9                        'w',
 10                        32767);
 11     UTL_FILE.put_line (l_file, 'test123');
 12     UTL_FILE.fclose (l_file);
 13  END;
 14  /

PL/SQL procedure successfully completed.

SQL>

Result: file is here:

So ... no, there's nothing else you should do. Everything you wrote seems to be just fine (from my point of view).

You said something about "show parameter utl_file" - what is that, exactly? UTL_FILE is a package, and you have to have EXECUTE privilege on it. You already have it, otherwise procedure wouldn't work at all.


text:
Q: Recursion Tower of Hanoi Consider the standard recursive solution to the Towers of Hanoi problem. In the traditional problem, all moves cost the same. Now, suppose the cost of a move is the size of the disk, with $1$ being the cost of the smallest disk, $2$ the second smallest, and so on. Express, as a recurrence relation, the cost of solving the $n$-disk problem.
Hey I don't understand this question at all since the traditional problem the cost would just be $(2^n - 1) \cdot cost$. But now we have to keep track of each disk which is unknown.

A: As the question asks you to simply write a recurrence relation for the cost, I am assuming it is for the original recursive solution. If instead you mean to at the same time minimize the cost, that could potentially be a different problem. The latter I have not considered in any detail.

Suppose $C(n)$ denotes the cost of solving it with $n$ discs. Then the $C(n+1)$ case goes as follows:

*

*We have the cost $C(n)$ of a sequence that will have to be performed twice

*Just add the cost of moving the $(n+1)$-th disc, and you are done

Writing out the details of this will establish a recurrence relation for $C(n+1)$ expressed in terms of $C(n)$ and some simple expression for the cost of the $(n+1)$-th disc. Can you take it from there?


text:
Q: Angular variable in set Timeout doesn't refresh? I've got some question. Why doesn't h1 value refresh after it is changed in function? Should do the refresh because as far as I know about Angular, it always does a refresh on change of variable, or I'm on the wrong track?

angular.module('ionicApp', ['ionic'])
.controller('MainCtrl', function($scope) {
$scope.CurrentCount = 0;
$scope.CallCounter = function(){
    setTimeout(function(){
      console.log($scope.CurrentCount)
      if($scope.CurrentCount != 9){
      $scope.CurrentCount = $scope.CurrentCount+1;
      $scope.CallCounter();
    }},1000);
  }
});
body {
  cursor: url('http://ionicframework.com/img/finger.png'), auto;
}

.container h1{
  text-align:center;
  color:green;
}

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title>Count Down</title>
    <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">

{{CurrentCount}}

CountDown

A: Update in setTimeout is happening outside angular's knowledge, hence the view is not updating. Do it inside $timeout.
angular.module('ionicApp', ['ionic'])
.controller('MainCtrl', function($scope, $timeout) {
$scope.CurrentCount = 0;
$scope.CallCounter = function(){
    $timeout(function(){
      console.log($scope.CurrentCount)
      if($scope.CurrentCount != 9){
      $scope.CurrentCount = $scope.CurrentCount+1;
      $scope.CallCounter();
    }},1000);
  }
});

A: you should use $timeout instead of setTimeout, because setTimeout hasn't info about angular scope. So it should be
angular.module('ionicApp', ['ionic'])
    .controller('MainCtrl', function ($scope, $timeout) {
    $scope.CurrentCount = 0;
    $scope.CallCounter = function () {
        $timeout(function () {
            console.log($scope.CurrentCount)
            if ($scope.CurrentCount != 9) {
                $scope.CurrentCount = $scope.CurrentCount + 1;
                $scope.CallCounter();
            }
        }, 1000);
    }
});

A:

angular.module('ionicApp', ['ionic'])
.controller('MainCtrl', function($scope,$timeout) {
$scope.CurrentCount = 0;
$scope.CallCounter = function(){
    $timeout(function(){
      console.log($scope.CurrentCount)
      if($scope.CurrentCount != 9){
      $scope.CurrentCount = $scope.CurrentCount+1;
      $scope.CallCounter();
    }},1000);
  }
});
body {
  cursor: url('http://ionicframework.com/img/finger.png'), auto;
}

.container h1{
  text-align:center;
  color:green;
}

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title>Count Down</title>
    <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">

{{CurrentCount}}

CountDown


text:
Q: Frequent, lengthy voice recording damaging to iPhone?
Possible Duplicate:
Apple iPhone 4 flash memory

I have an iPhone 4S and lately I've been seeking a way to record some class lectures. Today, I decided to try out using the Voice Memos app on my iPhone and I was absolutely stunned by the quality.
However, if I use my iPhone I'll be recording 1/4GB - 1GB every weekday for the foreseeable future and I'm worried the frequent data read/write will damage my iPhone. I know that flash drives will die after 1000 read/writes, and I'm pretty sure that iPhone's memory is flash-based. I'll need to keep my phone healthy for another year.
Will frequent, intensive daily R/W kill the phone?

A: Not likely. Use your phone to do whatever you want to do with it.
Per iFixit's teardown there's a Toshiba MLC NAND flash chip in there. You've got at least 10,000 write cycles for the flash, which means you could fill the phone up 10,000 times before you had any problems. If you're figuring a gigabyte of recording each day, a 16GB phone gives you 40+ years of recording time.
(If somebody can find a datasheet for the part, you could confirm the potential number of write cycles. My 10,000 is an educated guess based on typical MLC.)


text:
Q: Sample code for dropdown box in javascript Happy Saturday community, i've been building my first website and have learned tons about css,javascript,php,mvc framework and much more. Can anyone help me with a dropdown box like some of the bootsrap examples.... something like
 ---------------------------
 |      HEADER            +|

 ---------------------------

 ---------------------------
 |      HEADER            -|
 ---------------------------
 ---------------------------
 ---------------------------
----------------------------

EDIT:

Action

Another action

Something else here

Separated link

when expanded ???

A: You can do this easily using jQuery. But the main idea is to toggle the display property on an element inside your header
, such as the
 that you might use to make a navbar.
Working example: http://jsfiddle.net/Kk78h/ (Make sure to click on the '+' sign.)

Header +

Nav1

Nav2

Nav3

Nav4

#header { width: 500px;}
h1 { text-align: center; }
h1 #adjust {vertical-align: super; font-size: 20px; color: red; cursor: pointer;}
ul { height: 100px; list-style: none; display: none;}
li { float: left; width: 25%;}

$('#adjust').click(function() {
    $('ul').toggle();
    var cval = $('#adjust').html();
    $('#adjust').html(cval == '+' ? '-' : '+');
});


text:
Q: Loadrunner siebel I have red a lot about loadrunner online and quite often I come across Siebel. People say they use Siebel to record i.e. But is Siebel something that is used also on regular web applications? Not being the Oracle Siebel product under test? Is this Siebel some magic protocol that fits other platforms as well?
What is the deal with Siebel?

A: You often see questions related to Siebel because it is a very correlation intensive protocol and the vast majority of users of LoadRunner are weak in this core foundation mechanical tool skill, the collection of dynamic data and presentation back into the script.
Siebel uses a structure called the Siebel Star array, which is substantial in size and requires correlation for proper handling of the Seibel web client.   Siebel has available a correlation library which can handle a good portion of the Star Array challenges, but manual skills are still required on top of this to manage dynamic elements which are outside of the star-array structure.  It is my understanding that Siebel charges for the use of this library, so if one is technically competent with correlation then you should be able to construct your own correlation rules to handle repeated Siebel script development activities.

A: Siebel-Web is a protocol in LoadRunner, probably created to handle web-services/pages created with the Siebel CRM platform.
Siebel-Web is HTTP based, but having seen the HTML responses from Siebel CRM services I strongly recommend using the Siebel-Web protocol instead of HTML/HTTP protocol ...

A: Siebel-Web is a proprietary protocol that isn't used outside of the Oracle Siebel CRM context. So, using this for a different website would not be beneficial and only complicate your LoadRunner approach.

A: Performance testing Siebel CRM application is definitely not straightforward as it's a complicated web application which uses Internet explorer's high interactivity framework and the data exchanged required good amount of parsing.
Oracle provides a Correlation Library (ssdtcorr.dll) along with Siebel installation to deal with correlation of LR vugen scripts for Siebel protocol. Click here for more info. But that doesn't always help.
Additional best practices can be found here.


text:
Q: How to avoid ui-block div (jquery mobile) to overlap in internet explorer? I have this simple divs, developed in jquery mobile style:
  <fieldset class="ui-grid-b">

      <legend>Question 1 haveng a looong text to explain what the user need to answer</legend>

          <select name="question1" id="question1">
            <option value='0'>Choose...</option>
    <option value='1'>Option 1</option>
    </select>

 </fieldset>

CSS:
.ui-grid-b .ui-block-a {
padding-top:20px;
width: 60%;
}
.ui-grid-b .ui-block-b {
width: 30%;
}
.ui-grid-b .ui-block-c {
width: 10%; padding-top:20px;
}

The code represent a page divided in three column (div ui-block-a, ui-block-b, ui-block-c) , occuping respectively 60%, 30% and 10% of the entire page space. All works fine on every browser on earth, but not on explorer. On explorer, if the ui-block-a text is too long, instead of continuing on a new line, it continues under the select. How can i avoid the ui-block-a to be overlapped by ui-block-b?

A: change the css as
div{
   word-break: break-all;
 }
.ui-grid-b .ui-block-a {
padding-top:20px;
width: 60%;
float:left;
}
.ui-grid-b .ui-block-b {
width: 30%;
float:left;
}
.ui-grid-b .ui-block-c {
width: 10%; padding-top:20px;
float:left;
}

demo:jsfiddle

A: Maybe IE is interpretting fieldset and legend literally as they are intended (with legend being a direct descendent of fieldset - http://www.w3.org/wiki/HTML/Elements/fieldset) and is applying some browser specific styling that is messing up your intentions.
If you try this layout with div's instead of fieldset and legend, my guess is it will work.
Since a fieldset's legend is normally rendered by browsers as a floating title at the top of the parent container, interrupting the border (see example http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_fieldset) I think IE is ensuring this behaviour by forcing the wrap to none.


text:
Q: A non-trivial upper bound on the integral of Lipschitz functions over a bounded support Let $x \in \mathcal{X} = [0,1]^n$, and $f(x)$ be an $L$-Lipschitz function. Let $f(0)=0$. What is (the exact or a non-trivial upper bound on) $\int_{x\in\mathcal{X}} |f(x)|\,\mathrm{d}x$?What about $\int_{x\in\mathcal{X}} |f(x)|^2\,\mathrm{d}x$?

A: If $f:[0,1]^n\to\mathbb{R}$ is $L$-Lipschitz and $f(0)=0$, then $|f(x)|\le L\|x\|$, which obviously implies that the function $x\mapsto L\|x\|$ is the maximizer for both problems.


text:
Q: Can't execute Python script from PHP document I am running a PHP document on an Apache server on my Raspberry Pi and I want it to run a file when a button is clicked. I put some echo commands under the command to make the file run and it prints out but the file doesn't run. The index.php file and lightson.py and lightsoff.py files are all in the same directory (/var/www) and I have added #!/usr/bin/env python to the top of both files and made them executable by using chmod +x lightson.py. If I run the command from the shell it works and turns on the light just like I want with the exact same command as in the file but yet it wont run through the command. The code:

<title>Light Controller</title>

<?php
if (isset($_POST['LightON']))
{
shell_exec("sudo python /var/www/lightson.py");
echo("on");
}
if (isset($_POST['LightOFF']))
{
shell_exec("sudo python /var/www/lightsoff.py");
echo("Off");
}
?>

<form method="post">
<button name="LightON">Light ON</button>
<button name="LightOFF">Light OFF</button>

</form>

A: as you said you are running it like apache->php->shell_exec(SUDO..)
So the apache user has to be in sudoers file, better you don't give sudo to apache instead give apache (www-data) user right to run your python program
put first line in your python script: #!/usr/bin/env python so the script knows which program to open it with..
then
change group:
chgrp www-data /path/to/python-script.py

make it executabel
chmod +x /path/to/python-script.py

try it
shell_exec("/path/to/python-script.py");

I hope it works ;)
TIPP: Apache and PHP are for delivering Documents and Strings, if you want some kind of control and an API start with nodejs and https://www.npmjs.com/package/rpi-gpio package. This way you will have one place for your solid automation environment

A: This worked for me:
test.php
<?php
    echo shell_exec("python test.py");
?>

test.py
f = open("test.txt", "a+")
f.write("hiya buddy!!\n")
f.close()
print "some output"

Here's my relevant ls -l output from /var/www/html:
jason@Jason-one /var/www/html $ ls -l
-rw-r--r--  1 jason    jason    44 Sep 20 18:12 test.php
-rwxr-xr-x  1 jason    jason    82 Sep 20 17:44 test.py
-rw-rw-rw-  1 jason    jason    38 Sep 20 18:15 test.txt

Since I don't have GPIO pins on my laptop, I decided to write to a file as a test. Notice I didn't have to use sudo because of the way I set the permissions on test.py.


text:
Q: The differentials of compositions of $C^{\infty}$ maps obey a chain rule. $M,N,L$ are  $n_{1},n_{2},n_{3}$-differentiable manifolds respectively, $m\in M$, $f:M\rightarrow N$ and $g:N\rightarrow L$ are $C^{\infty}$, and let $J_{f}(m)$ denotes the Jacobian of $f$ at $m$. I could prove $(gof)_{*}|_{m}=g_{*}|_{f(m)}of_{*}|_{m}$ but I couldn't complete that $J_{gof}(m)=J_{g}(f(m))\times J_{f}(m)$.
My works is below:
$J_{gof}(m)=\big[\frac{\partial(z_{i}(gof))}{\partial x_{j}}|_{m}\big]_{n_{3}\times n_{1}}$
$J_{g}(f(m))\times J_{f}(m)=\big[\frac{\partial(z_{i}og)}{\partial y_{j}}|_{f(m)}\big]_{n_{3}\times n_{2}}\times\big[\frac{\partial(y_{i}of)}{\partial x_{j}}|_{m}\big]_{n_{2}\times n_{1}}$
$=\big[\sum_{k=1}^{n_{2}}(\frac{\partial(z_{i}og)}{\partial y_{k}}|_{f(m)}\cdot\frac{\partial(y_{k}of)}{\partial x_{j}}|_{m})\big]_{n_{3}\times n_{1}}$
$\frac{\partial(z_{i}og)}{\partial y_{i}}|_{f(m)}\cdot\frac{\partial(y_{i}of)}{\partial x_{i}}|_{m}=g_{*}|_{f(m)}(\frac{\partial z_{i}}{\partial y_{k}})\cdot f_{*}|_{m}(\frac{\partial y_{k}}{\partial x_{j}})$
I think perhaps I should show that $\sum_{k=1}^{n_{2}}\big(g_{*}|_{f(m)}(\frac{\partial z_{i}}{\partial y_{k}})\cdot f_{*}|_{m}(\frac{\partial y_{k}}{\partial x_{j}})\big)=(g_{*}|_{f(m)}of_{*}|_{m})(\frac{\partial z_{i}}{\partial x_{j}})$ that it is $(gof)_{*}|_{m}(\frac{\partial z_{i}}{\partial x_{j}})$ from the first part.

A: If you believe $(g \circ f)_*|_m = g_*|_{f(m)} \circ f_*|_m$, and want to know that $J_{g \circ f}(m) = J_g(f(m)) \times J_f(m)$, then the question is pretty much why matrix multiplication is the same as composition of linear transformations, which you can check directly!


text:
Q: Laravel 8 File Validation I'm new to laravel and I have been struggling to validate uploaded files.
Below is the code that handles validation:
// (I tried mime, mimes, mimetypes) none of them are validating any of the files correctly.
        $validator = Validator::make($request->all(), [
            'proposal_summary' => 'mimetypes:application/pdf|max:2048',
            'plagiarism_report' => 'mimetypes:pdf,doc,docx,txt|max:2048',
            'final_proposal' => 'mimes:pdf,doc,docx,txt|max:2048',
        ]);

I tested this with PDF, docx and txt files, all without success. I get an error saying the files must be a file of type: pdf, doc, docx, txt. Even though they are. I am sure I am doing something wrong, so any help would be appreciated. Please let me know if you require more code or further explanation.

A: Try using the mimes validation rule. You can also call the validate() method on the Request instead of Validator::make() method:
// dd(request()->all()); // Use this to debug the request content

$validated = request()->validate([
    'proposal_summary'   => ['mimes:pdf', 'max:2048'],
    'plagiarism_report'  => ['mimes:pdf,doc,docx,txt', 'max:2048'],
    'final_proposal'     => ['mimes:pdf,doc,docx,txt', 'max:2048'],
]);

// dd($validated); // Use this to debug validated content

https://laravel.com/docs/8.x/validation#rule-mimes


text:
Q: Limiting behavior of tail probability of gaussian vector Given a standard Gaussian vector in $\mathbb{R}^d$, that is $Z \sim N(0, I_d)$, can we specify a function $R(\cdot)$ and constant $K$ such that :
$$\mathbb{P}(||Z||_2 > t) R(t) \to K$$ as $t \to \infty$?
I'm not certain what to make of this exercise. Are $R(\cdot)$ and $K$ to be exact or unique or are there multiple valid choices?
I was thinking of using subexponential tail bounds (since $||Z||^2_2 = \sum_1^d Z_i^2 \sim \chi(d)$ and is sub-exponential $SE(4d,4)$) which would give us
$$\mathbb{P}(||Z||_2^2 > t^2 + d) \leq \exp{\frac{-t^2}{8}} $$
which would allow me to take $R(t) = \exp{\frac{+t^2}{8}}$ and $K=1$.
Is this sound as an approach? If not, what would be a better direction to proceed? If it is a sound approach, are there better ways to go about this?
Edit: for $d=1$, the standard univariate gaussian, I am familiar with the following result:
For $t > 0$:
$$\dfrac{\mathbb{P}(|Z|>t)}{\frac{1}{\sqrt{2 \pi}} \frac{1}{t} e^{-t^{2} / 2}} = \dfrac{2\mathbb{P}(Z>t)}{\frac{1}{\sqrt{2 \pi}} \frac{1}{t} e^{-t^{2} / 2}} \to 2$$
as $t \to \infty$.
So would $K=2$ and $R(t) =\left(\frac{1}{\sqrt{2 \pi}} \frac{1}{t} e^{-t^{2} / 2}\right)^{-1}$ (or something of this form) be better candidates?


text:
Q: How to get Xcode build onto Apple app connect? I just successfully ran Xcode for an app I am making and the build said it was successful with the hammer graphic on the screen, even though it stated there were some errors. I used the built-in simulator to check the app and everything is working fine. The question I have is, how do I get this app build onto app connect? I have logged my account info into Xcode and when I go to the Organizer screen I can see the name of my app, but nothing in the archives. This app is already on the app store, so I am creating the 2.0 build for it and have all of that ready on the App store.
How can I get my app build loaded into the app store so that I can release for review?

A: Set destination scheme to: generic iOS device
Archive project by going to: Product > Archive

A: Hope these will help you :)
Uploading App to Appstore Connect
Updating already existing App on Appstore


text:
Q: How to get accurate time stamps from the computer? I'm working in matlab and I need to get a very precise time measurement.
The accuracy I need is at least 1ms (and preferably much better than that).
It needs to be a timestamp and not just a duration measurement, because I need it for clock synchronization.
Answers for python can also help.
For clarification - I know how to get the current time. My problem is with the accuracy. As far as I know, the "clock" function is not accurate enough.


text:
Q: How to capture and save to file from webcam using DSPack and Delphi 5 right now I'm trying to make a program using Delphi 5 to take a photo from webcam.
I'm using delphi 5 and DSPack 2.3.1 because many people suggest it, and yes this is my first time programming multimedia with delphi.
I've been able to list and add camera that connect to my computer dynamically. I'm also able to display what the webcam "see", opening a video and capture it.
But now I can't capture a picture from the webcam.
I have a TImage which I named "Image", to check the picture is captured or not. When I use my code to open a video and capture it, it displayed in the TImage. But when I try to capture a webcam, it's just blank and not capturing anything. The file I saved also blank.
Could someone check which part of my code goes wrong?
Thanks before...
here's part of my code
var SysDev: TSysDevEnum;
    FotoBitmap: TBitmap;

implementation

{$R *.DFM}

procedure Form1.FormCreate(Sender: TObject);
var
  i: integer;
  Device: TMenuItem;
begin
  SysDev:= TSysDevEnum.Create(CLSID_VideoInputDeviceCategory);
  if SysDev.CountFilters > 0 then
    for i := 0 to SysDev.CountFilters - 1 do
    begin
      Device := TMenuItem.Create(Devices);
      Device.Caption := SysDev.Filters[i].FriendlyName;
      Device.Tag := i;
      Device.OnClick := OnSelectDevice;
      Devices.Add(Device);
    end;
end;

procedure Form1.FormCloseQuery(Sender: TObject;
  var CanClose: Boolean);
begin
  SysDev.Free;
  FilterGraph.ClearGraph;
  FilterGraph.Active := false;
end;

procedureForm1.OnSelectDevice(sender: TObject);
var
  CaptureGraph: ICaptureGraphBuilder2;
  SourceFilter, DestFilter: IBaseFilter;
begin
  FilterGraph.ClearGraph;
  FilterGraph.Active := false;

  Filter.BaseFilter.Moniker := SysDev.GetMoniker(TMenuItem(Sender).tag);
  Filter.FilterGraph := FilterGraph;

  FilterGraph.Active := true;

  FilterGraph.QueryInterface(ICaptureGraphBuilder2, CaptureGraph);

  Filter.QueryInterface(IBaseFilter, SourceFilter);

  VideoWindow.QueryInterface(IBaseFilter, DestFilter);

  if Filter.BaseFilter.DataLength > 0 then
    CaptureGraph.RenderStream(nil, nil, SourceFilter, nil, DestFilter);

  FilterGraph.Play;
  CaptureGraph := nil;
  SourceFilter := nil;
  DestFilter   := nil;
end;

procedure Form1.SnapshotClick(Sender: TObject);
var dir : String;
begin
  if edt_nama_foto.Text <> '' then begin
    dir := ExtractFilePath(Application.ExeName);
    FotoBitmap := TBitmap.Create;

    try
      SampleGrabber.GetBitmap(FotoBitmap);
      SampleGrabber.GetBitmap(Image.Picture.Bitmap);
      showmessage(dir + 'Image\Foto\' + edt_nama_foto.Text + '.bmp');
      FotoBitmap.SaveToFile(dir + 'Image\Foto\' + edt_nama_foto.Text + '.bmp');
    finally
      FotoBitmap.Free;
    end;
  end;
end;

procedure Form1.btn_batalClick(Sender: TObject);
begin
  modalresult:=mrCancel;
end;

procedure Form1.btn_simpanClick(Sender: TObject);
begin
  If CheckbeforeOK then
  begin
    ModalResult :=mrOK;
  end else begin
    ModalResult := mrNone;
  end;
end;

function Form1.CheckbeforeOK:Boolean;
var flag:boolean;
    MasterDataSet:TQuery;
begin
  Flag:=True;

  if flag and not(checkedit(nil, nil, edt_nama_foto, edt_nama_foto.Text, 'Nama Foto'))
  then begin
    flag := False;
  end else begin
    Snapshot.Click;
  end;
  Result := flag;
end;

procedure Form1.SampleGrabberBuffer(sender: TObject;
  SampleTime: Double; pBuffer: Pointer; BufferLen: Integer);
begin
  Image.Picture.Bitmap.Canvas.Lock;
  try
    SampleGrabber.GetBitmap(Image.Picture.Bitmap, pBuffer, BufferLen);
  finally
    Image.Picture.Bitmap.Canvas.UnLock;
  end;
end;

end.

A: The object which "transfers" video frame into image object is SampleGrabber:

SampleGrabber.GetBitmap(Image.Picture.Bitmap, pBuffer, BufferLen);

However it needs to be inserted in to filter graph when you build it, and you are apparently not doing it in your OnSelectDevice: there is no mention of SampleGrabber there at all. You need to include it into RenderStream call or otherwise get it inserted there so that video is streamed through it and your callback is called copying data into TImage.


text:
Q: Does UDP socket need to go through the Accept Process like TCP sockets? I'm working with UDP and i was wondering about the Accept Method when multiple machine need to connect to a server. So far i was working with UDPCliente class, IPEndPoint class and BeginRecieve / EndRecieve Method to create a server where multiple machine can connect at the same time.
My question is simple do i need to use Accept Method to handler incoming connection and create a new socket for each new connection ?
What is the best way to handler multiple connection with UDP ?
The code samples i've seen so far create a new UDPClient class and a IPEndPoint where the server is listening for connections after that, the code call the BeginRecieve passing a function where the data is recieved and then starts the process of BeginRecieve again.
These are the code samples i've been using so far:
public static void receiveCallback(IAsyncResult ar)
{
    UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
    IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;

    byte[] receiveBytes = u.EndReceive(ar, ref e);
    UdpState s = new UdpState();
    s.e = e;
    s.u = u;
    u.BeginReceive(new AsyncCallback(receiveCallback), s);
}

public static void receiveMessages()
{
    IPEndPoint e = new IPEndPoint(IPAddress.Any, 5050);
    UdpClient u = new UdpClient(e);
    UdpState s = new UdpState();

    s.e = e;
    s.u = u;
    u.BeginReceive(new AsyncCallback(receiveCallback), s);
}

A: UDP is connectionless, so there's nothing to accept. If you need connections over UDP, then you have to implement them. Ideally, you would assign each "connection" some kind of identifier and include it in each datagram sent to the server. In some cases, it may be sufficient just to rely on the IP address and port to identify "connections".
But you can do it however you want. UDP treats each datagram as independent.

A: Short answer - no, you don't use accept() with UDP.
In UDP there are no connections, only datagrams. One side sends them and the other might receive them. Each datagram has information about the sender (IP address and port) that your server app can extract to differentiate the clients.


text:
Q: SMB without port 445 I have a samba share, and the network my devices are on blocks communication over port 445 (the standard SMB TCP port). Linux devices and Macs can connect to this device because they can communicate with the server using port 139 (NBT over IP), which is not blocked Windows devices, however, seem to insist they communicate over port 445.
Is there any way for me to tell Windows 10 to use port 139 without relying on port 445?

A: I got this working by disabling SMBv2/v3 on Windows 10:
sc.exe config lanmanworkstation depend= bowser/mrxsmb10/nsi
sc.exe config mrxsmb20 start= disabled

then Restart the computer. To reverse this change and re-enable SMBv3 run the following commands at at the elevated command prompt
sc.exe config lanmanworkstation depend= bowser/mrxsmb10/mrxsmb20/nsi
sc.exe config mrxsmb20 start= auto

UPDATE:
I've renabled SMBv2 on Windows 10 and tried all the protocols limits on the server. NT1 works.
So you can just add the following line to the server main smb.conf file instead of the above. I prefer this method because it will affect all my Windows 10 machines centrally:
server max protocol = NT1

A: I had the same problem with a fresh install of Windows 10 (v1709) not attempting to use port 139 when connecting to SMB servers.
Turns out that the LanmanWorkstation service registry settings under
HKLM\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Linkage

were missing a few entries, first I had to find out the GUID of my NIC using
wmic nicconfig get description,index,TcpipNetbiosOptions,SettingID

and then I had to make sure all the necessary entries are present.
Bind:
\Device\Tcpip_{GUID}
\Device\NetBT_Tcpip_{GUID}

Export:
\Device\LanmanWorkstation_Tcpip_{GUID}
\Device\LanmanWorkstation_NetBT_Tcpip_{GUID}

Route:
"Tcpip" "{GUID}"
"NetBT" "Tcpip" "{GUID}"

Restart is needed and 'Enable NetBIOS over TCP/IP' must be enabled, obviously.
Note: Windows 10 is not happy about connecting to an SMB v2 server over port 139, I only needed to connect to SMB v1 servers or SMB v2 servers with port 445 open, so I did not need to disable SMB v2 on the client side.
I suggest accessing a share and using an IP address (e.g. \\192.168.1.11\share) to test if SMB1 is working.
p.s. credit goes to gwjwin and Momominta

A: Sounds like you are using naked SMB (CIFS) over public networks -- not good. At least use VPN tunneling to add security. That also solves the blocked port 445 as every port is encrypted and hidden inside the VPN tunnel. Run a VPN server program on the machine with the share. Run VPN client software to connect to the share-VPN Server machine.
If you want to avoid the technical and its only a few easily anticipated files -- store them in DropBox or similar online storage using HTTPS web interface.
HTTPS file transfers and many other better protocols exist to cross the internet. WebDAV has more or less turnkey HTTPS file server solutions.
Yes SMBv3 uses only port 445 (UDP/TCP) on Windows (and I think the latest SAMBA). Port 445 is blocked because despite many security improvements to version 3 of the SMB protocol. SMBv3 is still quite vulnerable to malware infections or data theft when exposed to anonymous users on Internet or LANs not secured from the public.
Worse the use of Ports 137, 138, and 139 are mostly linked to older versions of SMB.
Even on supposedly secure LANs, SMBv1 should be disabled if its possible to use SMBv2 or higher. SMBv3 is strongly preferred over SMBv2. Older SMB versions can be a fast way to spread problems from any infected computer across all LAN connected machines. Effectively a BIG Hole in the onboard firewalls.
P.S.
Yup it will use CPU power to encrypt data in a VPN so you need a little extra CPU room while files are being exchanged. Not really an issue if editing small files by hand. But mass data exchange for large file transfers or database access could be an issue on machines already near acceptable performance limits. If practical separate work into downloading a local copy first then operating on local copy before transferring the altered files back to the share.
As a rule of thumb a dedicated Pentium D with 2GB of RAM can push 10-15Mbps/sec continuously through a VPN. that is old 2005-2006 tech.
Any i3 gen4+ CPU or any i5 or i7 except Generation 1 CPU have special AES encryption hardware that will let them do VPN encryption literally 100 times faster. So plenty of power to do other tasks while doing VPN. File transfer speed will not be slowed by CPU considerations.


text:
Q: Google Charts X Axis Showing Up Down Values I have plotted a Google Line chart which is showing X axis values in alternating up down  format when having more values as shown below.

But I want to show it in a single line in a much better representation than the current one, a slope representation would also be fine like below.

My code for plotting the chart is as below:
var options = {
        width: '100%',
        height: '100%',
        legend: ({ position: 'top', maxLines: 1, alignment: 'end'}),
        chartArea: { left: "8%", right: "8%", top: "10%", width: "100%", height: "75%" },
        backgroundColor: 'transparent',
        tooltip: { textStyle: { color: 'black' }, isHtml: true },
        curveType: 'none',
    };

var chart = new google.visualization.LineChart($('Div')[0]);
chart.draw(view, options);

Is there any specific option that I have to apply to make the axis display in the required format?

A: see the configuration options for hAxis
for a slope representation, use --> slantedText: true

hAxis.slantedText - If true, draw the horizontal axis text at an angle, to help fit more text along the axis.

to enforce one level of labels, use --> maxAlternation: 1

hAxis.maxAlternation - Maximum number of levels of horizontal axis text. If axis text labels become too crowded, the server might shift neighboring labels up or down in order to fit labels closer together.

to keep the labels from wrapping on two lines, use --> maxTextLines: 1

maxTextLines - Maximum number of lines allowed for the text labels. Labels can span multiple lines if they are too long, and the number of lines is, by default, limited by the height of the available space.

note: you may need to adjust chartArea.bottom to allow more room along the x-axis...
see following working snippet...

google.charts.load('current', {
  packages:['corechart']
}).then(function () {
  var dateFormat = 'dd MMM';
  var formatDate = new google.visualization.DateFormat({
    pattern: dateFormat
  });

  var dataTable = new google.visualization.DataTable();
  dataTable.addColumn('string', 'X');
  dataTable.addColumn('number', 'Value');

  var oneDay = (1000 * 60 * 60 * 24);
  var startDate = new Date(2018, 9, 1);
  var endDate = new Date(2018, 9, 31);
  var ticksAxisH = [];
  for (var i = startDate.getTime(); i <= endDate.getTime(); i = i + oneDay) {
    var rowDate = new Date(i);
    var xValue = formatDate.formatValue(rowDate);
    var yValue = (2 * ((i - startDate.getTime()) / oneDay) + 8);
    dataTable.addRow([
      xValue,
      yValue
    ]);
  }

  var container = document.getElementById('chart_div');
  var chart = new google.visualization.LineChart(container);

  var options = {
    width: '100%',
    height: '100%',
    legend: {
      position: 'top',
      maxLines: 1,
      alignment: 'end'
    },
    chartArea: {
      bottom: 40,
      left: '8%',
      right: '8%',
      top: '10%',
      width: '100%',
      height: '75%'
    },
    backgroundColor: 'transparent',
    tooltip: {
      textStyle: {
        color: 'black'
      },
      isHtml: true
    },
    curveType: 'none',
    hAxis: {
      slantedText: true
    }
  };

  function drawChart() {
    chart.draw(dataTable, options);
  }

  drawChart();
  window.addEventListener('resize', drawChart, false);
});


text:
Q: Por qué 'data.Search' es 'undefined' en este código de React? Bueno, para practicar ReactJS estoy intentando hacer mi propia Pokedex. Veo que hay muchos ejemplos en internet, pero con la intención de retarme a mi mismo he decidido intentar hacerla mayormente por mi cuenta. La cosa es que veo que es muy difícil a mi nivel y lo más seguro es que tenga que usar una guía.
Por ejemplo, aquí me atasco y no se qué ocurre:
const search = (event) => {
    if (event.key === 'Enter') {
      axios.get(API_URL + state.handle).then(({ data }) => {
        let results = data.Search;

        setState((prevState) => {
          return { ...prevState, results: results };
        });
      });
    }
  };

He revisado mi código y todo parece funcionar perfecto, pero este punto me falla. Si hago console.log en el API_URL + state.handle, veo que la búsqueda es correcta, pues me sale el enlace correcto de la API de Pokemon. Sin embargo, en el siguiente punto, a la hora de pasar el data.Search a una variable falla, porque me da undefined.
Entiendo que es algo complejo y que hace falta mucho más código para entenderlo, pero, ¿podríais a primera vista deducir qué puede estar pasando? ¿Por qué es undefined? Hay que añadir que este mismo código lo uso en otro proyecto, con una API de películas en ese caso, para hacer un buscador de películas, y funciona corréctamente. Deduzco pues que el problema reside en la forma de invocar, llamar o utilizar la API, ¿no?
Alguna ayuda? Gracias!

A: Todo se ve bien, lo mas probable es que la API de pokemón te regrese los datos con una estructura diferente a tu proyecto de películas, por que no imprimes exactamente lo que recibes en data, si es así lo único que habría que hacer es re configurar como obtienes los datos e.g. Quiza los datos están en data.searchResult.content.


text:
Q: Extjs 4.2.1 - data store load all fields from the server Is there a way to make the data store to create a model containing all the fields retrieved from the server?
Lets say we have on the server side the object:
User : {
    name: "...",
    phone: "...",
    Address: {
        street: "...",
        country: "...",
    },
    ...
    ...
}

And we use the following store to load this user:
var myStore = Ext.create('Ext.data.Store', {
 proxy: {
     type: 'ajax',
     url: '...',
     reader: {
         type: 'json',
         root: 'users'
     }
 },
 fields :[name, phone],
 autoLoad: true
});

Is there a way to config the fields inside the data store to retrieve all the fields from the user without a specific mapping like the example (name, phone)? I mean, can I put something like ** in the fields attribute that will say to the data store, map all the fields retrieved as they are, and the result will be a store with the user's name, phone and address?
Thanks.

A: yes it is possible there is proper code snipet which will help you
    var fields = [];

     Ext.each(me.dataFromServer, function (record) {
         fields.push({
             name: record.fieldName
         });

      });

    var myModel =  Ext.define('myModelName',{
         extend: 'Ext.data.Model',
        idProperty: 'id', //some field
         fields: fields
     });

and our store looks like this
me.store = Ext.create('yourStore',{
         model: myModel
     });

and thic code is located in initComponent:
Your store:
extend: 'Ext.data.Store',
//model: null,

without model.


text:
Q: Python spaCy: how to set n_threads with create_pipe and add_pipe I am following the popular NER example of Spacy:
https://github.com/explosion/spaCy/blob/master/examples/training/train_ner.py
They use create_pipe and add_pipe to build the pipeline:
def main(model=None, output_dir=None, n_iter=100):
    """Load the model, set up the pipeline and train the entity recognizer."""
    if model is not None:
        nlp = spacy.load(model)  # load existing spaCy model
        print("Loaded model '%s'" % model)
    else:
        nlp = spacy.blank('en')  # create blank Language class
        print("Created blank 'en' model")

    # create the built-in pipeline components and add them to the pipeline
    # nlp.create_pipe works for built-ins that are registered with spaCy
    if 'ner' not in nlp.pipe_names:
        ner = nlp.create_pipe('ner')
        nlp.add_pipe(ner, last=True)
    # otherwise, get it so we can add labels
    else:
        ner = nlp.get_pipe('ner')

    # add labels
    for _, annotations in TRAIN_DATA:
        for ent in annotations.get('entities'):
            ner.add_label(ent[2])

    # get names of other pipes to disable them during training
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']
    with nlp.disable_pipes(*other_pipes):  # only train NER
        optimizer = nlp.begin_training()
        for itn in range(n_iter):
            random.shuffle(TRAIN_DATA)
            losses = {}
            for text, annotations in TRAIN_DATA:
                nlp.update(
                    [text],  # batch of texts
                    [annotations],  # batch of annotations
                    drop=0.5,  # dropout - make it harder to memorise data
                    sgd=optimizer,  # callable to update weights
                    losses=losses)
            print(losses)

I would like to set n_threads, as it is documented for nlp.pipe here. However, following their example there does not seem to be the possibility to specify the number of threads if nlp.pipe is not explicitly called. Am I missing something or do I need to rebuild using nlp.pipe?


text:
Q: How to add text next to the Hamburger Menu for small screens in MAGENTO 2 Some Customers do not know that the hamburger icon is the menu for small screen on magento 2. I want to add some text next to the icon. What is the best way to do that? What files contain the code of the menu?

A: You can find the code related to this in
vendor/magento/module-theme/view/frontend/templates/html/header/logo.phtml

Once you add the required text you have to do necessary changes to css files.
<?php /* @escapeNotVerified */ echo __('Menu') ?>

To hide msg from desktop
.media-width(@extremum, @break) when (@extremum = 'min') and (@break = @screen__m) {
    .nav-toggle-msg {
        display: none;
    }


text:
Q: Convergence of $\sum_{n=1}^{\infty}\frac{1}{3^n\ \sin(n)}$ Does this series converge? Root test and ratio test are inconclusive.

A: Using the same arguments as in the two answers of Does $\sum_{n=1}^\infty \frac{1}{n! \sin(n)}$ diverge or converge? we can compare the series $\sum^\infty_{n=1}\left|\frac{1}{3^n\sin n}\right|$ to $\sum^\infty_{n=1}\frac{n^7}{3^n}$, which certainly converges by the ratio test, so that the original series converges (absolutely).


text:
Q: Execute multiple line PowerShell Script from C# I am new to PowerShell. I am trying to execute PowerShell script from C#. PS Script that I have written transfer xml file from host computer (running PS script) to a remote computer. Script is as follows
$Username = "User"
$Password = "Pass"
$SecurePass = ConvertTo-SecureString -AsPlainText $Password -Force"
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList     $Username,$SecurePass"
 $contents = [IO.File]::ReadAllBytes("D:\MyFile.xml")
 Invoke-Command -ComputerName ComputerName -Credential $Cred {[IO.File]::WriteAllBytes("D:\MyFile.xml",$using:contents)}

I store username and password of remote computer, to which I want to transfer my file, in variables. Convert password to secure string and create a credential object containing username and password. Use credential to copy the contents of file from my computer to remote computer.
This code works fine if I execute these commands one by one from my powershell or by running these lines from a .ps1 powershell script from my computer.
I used following code in C# to execute above script and transfer the file.
        Runspace runSpace = RunspaceFactory.CreateRunspace();

        Pipeline pipeline = runSpace.CreatePipeline();

        runSpace.Open();

        string script = "";
        script = "$Username = \"User\"\n";
        script = script + "$Password = \"Pass\"\n";
        script = script + "$SecurePass  = ConvertTo-SecureString -AsPlainText $Password -Force\n";
        script = script + "$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$SecurePass\n";
        script = script + "$contents = [IO.File]::ReadAllBytes(\"D:\\MyFile.xml\")\n";
        script = script + "Invoke-Command -ComputerName ComputerName -Credential $Cred {[IO.File]::WriteAllBytes(\"D:\\MyFile.xml\",$using:contents)}\n";

        //   pipeline.Runspace.SessionStateProxy.SetVariable

        pipeline.AddScript(script);

        Collection<PSObject> results = pipeline.Invoke();

However, it did not transfer the file. So, I thought I need to Add each line in script one by one to the pipeline and then execute it. So I changed it to following.
        string[] commands = script.Split('\n');

        foreach (string command in commands)
        {
            pipeline.AddScript(command);
        }

        Collection<PSObject> results = pipeline.Invoke();

It did not work either. I executed single Invoke-Command from C# code on my computer and it worked fine. Also, if I try to execute other single PS commands they work. So I assessed that setting variable values like this $User = "user" is not working through C#.
I used SessionStateSetProcy.SetVariable to Store variable values in powershell session as follows.
        pipeline.Runspace.SessionStateProxy.SetVariable("User", "User");
        pipeline.Runspace.SessionStateProxy.SetVariable("Password", "Pass");
        var value = pipeline.Runspace.SessionStateProxy.GetVariable("Password");
        Console.WriteLine(value);

So, I was able to set value and retrieve as well. But, since I was using Other cmdlets like ConvertTo-SecureString, I realized I need to execute these cmdlets separately in my code.
I finally I came up with following piece of code.
        pipeline.Runspace.SessionStateProxy.SetVariable("User", "User");
        pipeline.Runspace.SessionStateProxy.SetVariable("Password", "Pass");

        Command command = new Command("ConvertTo-SecureString");
        string pass_value = pipeline.Runspace.SessionStateProxy.PSVariable.GetValue("Password").ToString();
        command.Parameters.Add("AsPlainText",pass_value);
        command.Parameters.Add("Force");

        pipeline.Runspace.SessionStateProxy.SetVariable("SecurePass",command);

        /*Build a command2*/
        Command command1 = new Command("New-Object");
        string user_name = pipeline.Runspace.SessionStateProxy.PSVariable.GetValue("User").ToString();
        command1.Parameters.Add("TypeName", "System.Management.Automation.PSCredential");
        string args = user_name + " , "+pass_value;
        command1.Parameters.Add("-ArgumentList", args);

        pipeline.Runspace.SessionStateProxy.SetVariable("Cred", command1);

        byte[] wifiXML = System.IO.File.ReadAllBytes(@"D:\MyFile.xml");
        pipeline.Runspace.SessionStateProxy.SetVariable("contents", wifiXML);

        Object a = pipeline.Runspace.SessionStateProxy.PSVariable.GetValue("contents");
        string script = "Invoke-Command -ComputerName ComputerName -Credential $Cred {[IO.File]::WriteAllBytes(\"D:\MyFile.xml\",$using:contents)}";

        pipeline.Commands.AddScript(script);
        Collection<PSObject> results = pipeline.Invoke();

It gave some weird error in System.Management.Automation. I know in SetVariable I am doing it wrong by passing command variable.
I have tried PowerShell ps = PowerShell.Create() instead of pipeline as well and tried ps.AddCommand and ps.AddParameters followed by ps.AddArgument as well. But I am not sure that once I run cmdlet ConvertTo-SecureString through ps.AddCommad, ps.AddArgument etc., how should I set it's output value to $Cred variable?
I am aware that solution to this won't be this complicated and someone must have executed multiple line powershell script through C#. All I want to accomplish is execute the .ps1 script lines mentioned in very start from C# code.I have tried bunch of methods including mentioned above to no use, so any help related to it would be much appreciated?

A: Try in this way
 string script = @"
$Username = 'User'
$Password = 'Password'
$SecurePass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList     $Username,$SecurePass
$contents = [IO.File]::ReadAllBytes('D:\MyFile.xml')
Invoke-Command -ComputerName ComputerName -Credential $Cred {[IO.File]::WriteAllBytes('D:\\MyFile.xml',$using:contents)}
";

 pipeline.Commands.AddScript(script);
 Collection<PSObject> results = pipeline.Invoke();


text:
Q: get all the values of an item in the database and turn it into id I have a request form that selects the item in the database through select and creates a pdf through DOMPDF, I need select to pull the type and value values along with the description to be able to inform them in the PDF, follow my file, I believe it is something like this

<select name="productName[]" id="productName_1" class="form-control">';

 <?php
$result_cat_post = "SELECT * FROM itens ORDER BY descricao asc";
$resultado_cat_post = mysqli_query($conn, $result_cat_post);
while ($row_cat_post = mysqli_fetch_assoc($resultado_cat_post)) {

echo '<option value="' . $row_cat_post['descricao'] . ':' . $row_cat_post['valor'] . ':' . $row_cat_post['tipo'] . '">' . $row_cat_post['descricao'] . '</option>';
}
?>

<?php
$result = $_POST['productName[]'];
$result_explode = explode(':', $result);
echo '';
echo '';
?>
/select>

currently my code is pulling everything into a union value, so when I print the "productName" in DOMPDF it shows everything together instead of separately conform the image enter image


text:
Q: Kubuntu : impossible to display R shiny in external window I hope I'm in the right place for this question.
I wrote a Shiny App with R Shiny but when I want to run the app in a external window, there's an error message from KIOExec saying (in French) : "Un dossier nommé /home/myname/.cache/kioexec/krun/28025_0/ existe déjà" which in English is basically : "A folder named /home/myname/.cache/kioexec/krun/28025_0/ already exists".
My laptop runs with Kubuntu 18.04.02 LTS, maybe it is important in order to fix this.
For now, I tried to go in /home/myname/.cache/kioexec/krun/ and it appears that there are about 40 folders and many are empty but other are not so I prefer not to delete all of them without knowing what they are.
Does somebody have a solution ?

A: Fixed it thanks to : https://www.progclub.org/blog/2018/12/14/a-folder-named-cache-kioexec-krun-13821_0-already-exists/
Here's the part that I did :
"I solved the issue (for me) by changing:
System Settings -> Personalization -> Applications -> Default Application s-> Web Browser
from:
Open http and https URLs in an application based on the contents of the URL
to:
Open http and https URLs in the following browser: firefox"
thanks anyway


text: Q: using float package, I want to have multiple images in one figure, but the position of the figure in the output is wrong Im using This answer for subfigures on StackExchange but when I use it in my paper documentation the figure appears in the refrence section!


text:
Q: MySQL SELECT, store in a variable For a stored procedure, I want to do a SELECT, and store a column's value into a variable.
How do I do this?
I want to do something like this:
    DECLARE countTemp INT;
    SET countTemp=(SELECT COUNT(Name) FROM mytable WHERE Name= var_name LIMIT 0,1);

OR, like this :
    DECLARE countTemp INT;
    SELECT countTemp=ColumnXYZ FROM mytable WHERE Name= var_name LIMIT 0,1;

But, I tried these and MySQL says my syntax is incorrect; how do I do something like this?

A: Like this :
DECLARE myvar nvarchar(50);

SELECT ATextColumn INTO myvar FROM myTable LIMIT 1,1;

SELECT CONCAT('myvar is ',myvar ,' .');

http://www.java2s.com/Code/SQL/Procedure-Function/UseselectintotoassignvaluetoanIntegervariable.htm

A: You can easily set the variable in the select query
SELECT @countTemp := ColumnXYZ FROM mytable WHERE Name= var_name LIMIT 0,1;

@countTemp is your variable!


text:
Q: Как улучшить код на Python(олимпиадная задачка)? Есть код к олимпиадной задаче, который подходит под 5 из 9 условий. Код и условия ниже.
n = int(input())
a = [int(i) for i in input().split()]
k = 0
x = []
for i in range(1, n+1):
    if i!=n:
        if sum(a[:i])%i==0 and sum(a[i:])%(n-i)==0:
            l = [str(sum(a[:i])/i)]*i + [str(sum(a[i:])/(n-i))]*(n-i)
            if l not in x:
                k+=1
                x.append(l)
if sum(a)%n==0:
    if [str(sum(a)/n)]*n not in x:
        k+=1
print(k)

A: Основные моменты:

*

*set для хранения найденных решений
даёт уникальность из коробки, теперь не нужно проверять not in x

*divmod вместо двух делений, суммы теперь тоже считаются однажды

*крайний случай(всего один участок) объединил с остальным решением if i else (0, 0)
def solve(a, n):
    variants = set();
    for i in range(n):
        left, right = a[:i], a[i:]

        l_avg, l_rem = divmod(sum(left), i) if i else (0, 0)
        r_avg, r_rem = divmod(sum(right), n - i)

        if l_rem == r_rem == 0:
            variants.add(','.join([str(l_avg)] * i + [str(r_avg)] * (n-i)))

    return len(variants)

Можно добавить микрооптимизаций, вроде бегущих сумм, но непонятно по каким критериям нужно «улучшать» этот код:
def solve(a, n):
    variants = set();
    l_sum, r_sum = 0, sum(a)
    for i in range(n):
        l_avg, l_rem = divmod(l_sum, i) if i else (0, 0)
        r_avg, r_rem = divmod(r_sum, n - i)

        if l_rem == r_rem == 0:
            # variants.add(','.join([str(l_avg)] * i + [str(r_avg)] * (n-i)))
            variants.add(f'{i}, {l_avg}, {r_avg}' if i and l_avg != r_avg else r_avg)

        l_sum += a[i]
        r_sum -= a[i]

    return len(variants)

a = [10, 4, 2, 7, 5, 8, 6, 6, 15]
assert solve(a, len(a)) == 3
a = [3, 5, 2, 7, 6, 4, 5, 8, 1, 7]
assert solve(a, len(a)) == 3


text:
Q: Why does the hard-looking double integral $\int_{0}^{1}\int_{0}^{1}\frac{x(1-x)y(1+y)}{(1-xy)\ln(xy)}dxdy=-\frac{1}{2}$? (1) originate from here problem 11322
(1)
$$\int_{0}^{1}\int_{0}^{1}\frac{x(1-x)y(1+y)}{(1-xy)\ln(xy)}dxdy=-\frac{1}{2}$$
On my recent post see here Marco Cantarini and hints from other proved the hard-looking integral.
We manage to find another hard-looking double integral type that yield simple answer via wolfram integrator.
Can anyone help us to prove (1)?

A: If we perform a change of variables $x=e^{-u},y=e^{-v}$ we may easily check that
$$J(a,b) = \iint_{(0,1)^2}\frac{x^a y^b}{\log(xy)}\,dx\,dy = -\frac{1}{a-b}\,\log\left(\frac{1+a}{1+b}\right) \tag{1}$$
from which it follows that
$$\begin{eqnarray*}K(a,b) &=& \iint_{(0,1)^2}\frac{x^a y^b(1-x)(1+y)}{\log(xy)}\,dx\,dy\\ &=& \frac{\log\left(\frac{2+a}{1+b}\right)}{1+a-b}+\frac{\log\left(\frac{1+a}{2+b}\right)}{1+b-a}+\frac{\log\left(\frac{2+a}{2+b}\right)-\log\left(\frac{1+a}{1+b}\right)}{a-b} \tag{2}\end{eqnarray*}$$
and by letting $b\to a$
$$ H(a) = \iint_{(0,1)^2}\frac{x^a y^a(1-x)(1+y)}{\log(xy)}\,dx\,dy = \frac{1}{2+a}-\frac{1}{1+a}\tag{3}$$
so, just like in the other problem, the original integral is related with a telescopic series:

$$\begin{eqnarray*}I=\iint_{(0,1)^2}\frac{xy}{1-xy}\cdot\frac{(1-x)(1+y)}{\log(xy)}\,dx\,dy &=& \sum_{n\geq 1} H(n) \\ &=& -\sum_{n\geq 1}\left(\frac{1}{n+1}-\frac{1}{n+2}\right)=\color{red}{-\frac{1}{2}}\tag{4}\end{eqnarray*} $$

as wanted. The only non-trivial step is $(1)$, that follows from Frullani's theorem.
There is also a symmetry trick. By exchanging $x$ and $y$ in the original integral and considering the arithmetic mean of the two integrals we get:
$$I=\iint_{(0,1)^2}\frac{xy}{\log(xy)}\,dx\,dy = J(1,1) = -\left.\frac{d}{dz}\log(z+1)\right|_{z=1} = \color{red}{-\frac{1}{2}}.\tag{5}$$


text:
Q: Python: SOAP response. Delete the Response header, keep the rest? I think this is simple.....
I have a script that takes a bunch of data, changes some characters, splits the data into columns and rows with headers and outputs as a CSV. This worked perfectly fine in testing with the data coming in from a text file. The real use is calling to an authenticated webservice. Which also works fine.
The issue is all the code that formats the data and makes the final CSV file doesn't work when it's called from the webservice.
The reason is the very first line of the results
<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'><env:Header></env:Header><env:Body><ns1:GetACustomReportResponse xmlns:ns1="http://www.customurlfortesting.com/gem/services/gds">< report >Header1,Header2,Header3

When I was testing initially, I just retrieved Header1,Header2,Header3 etc all seperated by a character thats replaceable. The same is still true now, but the rest of the formatting is failing at the beginning because of the stuff before the Header1. Is there a way to simply not get that info in the results?
r = requests.post(url,data=body,headers=headers)
data = str(r.text.encode('utf-8').replace("\"....etc  < im guessing I can strip that first line of the reults in here since this is where my results are but I don't exactly how to remove that line dynamically without affecting anything else. I want to remove everything from <env:Envelope to <report> including <env:Envelope and <report>

Thanks

A: got it sorted
added to the initial string definition
.rpartition('<report>')[-1]


text:
Q: Where Can I find more or less detailed description of mobjects? Can you, please, refer me to a resource(s) where I can find list of attributes and methods for manim objects? (videos or sites, if there exist such). I tried to learn it myself by looking into mobject folder, but got to say, my brain got lost. I also tried looking in the Internet, didn't find much.
Thank you

A: Currently there is no complete documentation of Manim, the closest is this that I created (but its development is paused).
So, at the moment, there is no other way to learn without having to see the source code. Manim was not designed to be Open Source, Manim is simply the Grant Sanderson tool that he uses to make his videos, and he decided to share it, but he has no responsibility to document it, whoever wants to learn will have to understand the source code (at least for now).
I have tried to contribute with my tutorials, but since Manim is constantly modified (for example, in the shaders branch, he no longer uses Pycario, but ModernGL) it is difficult to have useful documentation, since some things can work differently in a matter of months .
So for now, until someone is encouraged to do all the documentation work (which is quite a lot) we have no choice but to learn this way.


text:
Q: Temporary redirection from two directories deep to the root I have this directory structure:
|-language-A\
|-language-A\program-A
|-language-A\program-B
|-language-A\program-C
|
|-program-A\

Currently program-A is not translated to the language-A but somehow Google was able to crawl this directory and now it's showing in the search results. I need to redirect language-A\program-A to program-A in the root ... not all the folders inside language-A just that directory. This is a temporary redirection as I will remove that rule once that translation is ready.
So basically it will be something like:
http://example.com/language-A/program-A/what-ever
To:
http://example.com/program-A/what-ever

A: The question really doesn't say much so I will assume all strings are fixed and there are no parameters to pass:
You may try this:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI}   ^/language-A/program-A/?   [NC]
RewriteRule .*    program-A  [R,L]

Redirects temporarily
http://example.com/language-A/program-A
To:
http://example.com/program-A
All according to your question: I need to redirect language-A\program-A to program-A in the root...
UPDATED
According to question update:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI}   ^/language-A/program-A(.*)?   [NC]
RewriteRule .*    program-A%1  [R,L]

Redirects temporarily
http://example.com/language-A/program-A/what-ever
To:
http://example.com/program-A/what-ever
/what-ever is optional and will be passed if exists.


text:
Q: Engineering Economics Suppose that a college graduate earns about 78% more money per hour than a high- school graduate. If the lifetime earnings of a high-school graduate average $1,200,000, what is the expected value of earning a college degree?
I did (1,200,000)(1.78) = 2,136,000
I thought this was the answer but would the answer actually be 2,136,000-1,200,000 and be 936,000?


text:
Q: Using NSCache: Not clearing or removing memory how I expect I am using NSCache for my iOS app.  I know that it will handle its own memory, but I want to purge it manually.  When I tell it to removeAllObjects I don't see my memory usage go down in Instruments Allocations.
Is there another way that this would happen or does it not empty its memory how I am thinking?

A: NSCache will retain objects you add to it.
Is it possible your alloc'ing objects, adding to the cache and not releasing leading to a retain count of 2?  Narrowing it down to a small snippet that reproes the behavior with posted code may help narrow it.
Per docs:

While a key-value pair is in the cache, the cache maintains a strong
  reference to it if garbage collection is in effect; in memory-managed
  code, the cache retains the item.

Also, here's a video showing working with NSCache and allocations - in that example, they can removeAllObjects under a memory warning.  they simulate a memory warning and it does reduce the memory footprint so it should work ...
http://speirs.org/blog/2010/6/30/using-instruments-to-learn-about-nscache.html


text:
Q: REST and RDF, what's the representation strategy? Your triplestore contains a lot of nodes, and you have to make accessible this database via a REST interface.
Now, my solution would be that every named (not-anonymous) node is exported as a resource, whose representation is:

*

*all the triples having the node as a subject

*all the triples having the node as an object

*all the connected anonymous nodes.

I am a little reluctant on point number 2: this would basically give both incoming and outgoing triples.
What is your take on a REST sytle representation of a purely RDF-oriented data store ?
Do you share my point of view or not, and if not, what is your take on it ?

A: Depends on what the the data is and what the interface users want to do with it. This question is similar to what the SPARQL DESCRIBE query form should return. (It's determined by the implementation.)
For the use cases I've had with RDF data, I'd go with 1 and 3, producing a blank node closure of the resource. Additionally, you could have a separate interface for case 2, returning the incoming arcs of the resource.

A: One easy way to make an RDF dataset REST traversible is to use URLs for all traversible elements.
When the URL is accessed, for example via HTTP GET, then result shows the connected nodes (connected as properties and/or inverse properties).
More formally the returned representation could be a Concise Bounded Description of the resource.

A: (disclaimer: this may not correspond exactly to the content of your question, but it corresponds to the title)
I think that about the topic of Rest representation of RDF data is a general problem of inverting the order of concepts. For me the normal would be to have a collection of Rest documents with RDF data and use a RDF database for indexing and making global querys.
In this situation you can organize your resources in the way you prefer.
Also (if you pretend to use the URI of the node as the exported resource) your approach will have subtle problems about what is the meaning of your resources: the Rest resources you propose here are "information resources" and then they cannot be abstract resources. There will be a conflict between information and meta-information.
I published an article here explaining this view in more detail.