text:
Q: Algebraicity of compact Riemann surfaces I am taking a course in Riemann surfaces, in which the classical result about algebraicity of compact riemann Surfaces has been proven. However, I think there are some dubious points in the proof.
Here is the outline: let X be our compact connected Riemann surface, let g be its genus. If D is a divisor whose degree d satisfies $d\geq2g+1$, then the associated map $\varphi_{|D|}:X\rightarrow \mathbb{P}^N(\mathbb{C})$, with $N=d-g$, is a holomorphic embedding, so $Y=\varphi_{|D|}(X)$ is a closed submanifold of dimension $1$ in $\mathbb{P}^N$.
Now consider the graded $\mathbb{C}$-algebra $R(D):=\bigoplus_{n\geq0} H^0(X,\mathcal{O}_X(n\cdot D))$, with multiplication given by the product of global sections. Using what has been presented as the Castelnuovo-Mumford theorem, under these conditions there exists, for every $n\geq0$, a natural surjection
$$
H^0(X,\mathcal{O}_X(D))^{\otimes n}\rightarrow H^0(X,\mathcal{O}_X(n\cdot D))$$
which sends $s_1\otimes\dots\otimes s_n$ to $s_1\dots s_n$. Indeed, since the product of sections is commutative, we obtain a surjection
$$
\mathrm{Sym}^n(H^0(X,\mathcal{O}_X(D)))\rightarrow H^0(X,\mathcal{O}_X(n\cdot D))
$$
whence a surjective map
$$
\mathbb{C}[z_0,\dots,z_N]_n\rightarrow H^0(X,\mathcal{O}_X(n\cdot D))$$
where $\mathbb{C}[z_0,\dots,z_N]_n\cong\mathrm{Sym}^n(H^0(X,\mathcal{O}_X(D)))$ is the space of homogeneous polynomials of degree $n$.
Assembling these maps together, we obtain a surjective homomorphism of algebras
$$
\alpha:\mathbb{C}[z_0,\dots, z_N]\rightarrow R(D)$$
whose kernel $I$ is a homogeneous ideal by construction of $\alpha$; therefore we can define the projective variety $Z=V(I)\subseteq\mathbb{P}^N$. Furthermore, since $R(D)$ is a domain, $I$ is prime and $Z$ is irreducible. Using the isomorphism $\mathbb{C}[z_o,\dots,z_N]/I\cong R(D)$ and applying the Riemann-Roch theorem, we can see that the Hilbert polynomial of $Z$ is $p_Z(t)=\mathrm{deg}(D)t+1-g$, so by the Hilbert-Serre theorem $Z$ has dimension $1$ (here by dimension I mean the supremum of the lengths of chains of irreducible subvarieties). Now a straightforward calculation shows $Y\subseteq Z$. Furthermore, $Y$ is irreducible in the Zariski topology and has dimension $1$ being the image of $X$ via an embedding (here I mean, a priori, the dimension as a complex manifold). This implies $Y=Z$.
Here are my doubts:

*

*Why is $Y$ irreducible? My guess: suppose there exist homogeneous polynomials $F_1,\dots,F_r, G_1,\dots, G_s$ such that $Y=(Y\cap V(F_1,\dots,F_r))\cup (Y\cap V(G_1,\dots, G_s))$. If $Y\cap V(F_1,\dots,F_r)$ is a proper non empty subset of $Y$, its complement in $Y$ is open and contained in every $Y\cap V(G_j)$. Since the restrictions of the $G_j$ on $Y$, which is a Riemann surface, are holomorphic, they must be identically zero on $Y$, hence $Y\subset V(G_1,\dots,G_s)$.

*$Y$ is certainly a $1$-dimensional complex manifold, but why is it $1$-dimensional as a topological space with the Zariski topology? My guess: let $C$ be a Zariski closed subset of $\mathbb{P}^N$: then $Y\cap C$ is either $Y$ or a finite set of points, by holomorphicity of the functions defining $C$ and compactness and "one-dimensionality" of $Y$. If $Y\cap C$ is a proper Zariski irreducible subset of $Y$, then it must be a point.

*Assuming the two previous points, why does the equality of the dimensions imply $Y=Z$? It would certainly be true if $Y$ were Zariski closed in $Z$, but then $Y$ would be Zariski closed in $\mathbb{P}^N$, which is exactly what we want. In general, a projective variety has the same dimension of any of its proper open subsets.

Thank you kindly to anyone who will have the patience to read and help!


text:
Q: Install R-Package IKTrading from Github - error message I allow myself to post this help request as my attempts to download the R package "IKTrading" from Github repeteadly failed. I used both R V. 3.1.3. and R V.3.2.1.with identical results.
My computer runs R on Windows 7, 64bit version. Here is the session status:
R version 3.1.3 (2015-03-09) -- "Smooth Sidewalk" Copyright (C) 2015
The R Foundation for Statistical Computing Platform:
x86_64-w64-mingw32/x64 (64-bit)

Standard recommended solutions I found on the internet did not work in my case, such as:
- Running R as administrator (done)
- Making sure that that Rtools is already installed (done)
- Scrupulously respecting the order of execution of different R packages,
including more particularly devtools and quantstrat (done all that).
Here is the error message output for further investigation:
> install_github(repo="IKTrading", username="IlyaKipnis")
Downloading github repo IlyaKipnis/IKTrading@master
Installing IKTrading
Skipping 1 packages ahead of CRAN: PerformanceAnalytics
"C:/PROGRA~1/R/R-31~1.3/bin/x64/R" --no-site-file --no-environ --no-save  \
  --no-restore CMD INSTALL "C:/Users/Cédric  \
  Spahr/AppData/Local/Temp/RtmpkP2GeU/devtools15d04c2a1d0a/IlyaKipnis-IKTrading-0b4e0e5"  \
  --library="C:/Users/Cédric Spahr/Documents/R/win-library/3.1"  \
  --install-tests

* installing *source* package 'IKTrading' ...
Warning in file(file, ifelse(append, "a", "w")) :
  cannot open file 'C:/Users/Cidric Spahr/Documents/R/win-library/3.1/IKTrading/DESCRIPTION': No such file or directory
Error in file(file, ifelse(append, "a", "w")) :
  cannot open the connection
ERROR: installing package DESCRIPTION failed for package 'IKTrading'
* removing 'C:/Users/Cédric Spahr/Documents/R/win-library/3.1/IKTrading'
Error: Command failed (1)
In addition: Warning message:
Username parameter is deprecated. Please use IlyaKipnis/IKTrading

A: This worked for me:
Installing package quantstrat as IKTrading package has dependency on it.
require(devtools)
install.packages("quantstrat", repos = "http://R-Forge.R-project.org")
library(quantstrat) #Load package
install_github("IlyaKipnis/IKTrading")

If this doesn't work, try running RStudio as administrator and run these commands again. Let me know if it works !

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular 2 quickstart for visual studio 2015: Angular can't find app.module I have been trying to get the Angular quickstart to work using visual studio 2015.
I have been following the step by step tutorial on the angular.io website
https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html.
When I first ran the application I received a some 404 when a request was fired for systemjs.config.js and System.import('main.js').
After changing these path by prefixing them with src/ those issues were resolved but now I still get another 404 on the /src/app/app.module.
Looking in the main.ts file located in the src folder I see the following path:
import { AppModule } from './app/app.module';
That is exactly were the app.module is located, so why is it still giving a 404?


text:
Q: how stop session (tracking) in google analytic I use code from google analytic home page with remote ga.js. All works cool beside one thing: Avg. Time on Page. I close page in browser but my session leaves active.
I want to stop session from JS handy. I try search but nothing.
How can i do it ?
UPDATE
You miss me. I know that moment when say to GA that session is closed. My app plays in UIWebView on iOs. So I want to send termination when app is exited.
It's so simple. Isn't ?
Thanks

A: JavaScript does not know the difference between a page close and a page refresh and a page navigation away. Plus there is no reliable way with JavaScript to send the information to the server when the unload event is called.

A: Use javascript to delete the _utmb cookie:
Cookies Set By Google Analytics
function del_cookie(name) {
   document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
}

del_cookie("_utmb");

A: You are looking for the true time on site/page
Have a look to the strategy proposed by Savio


text:
Q: Refreshing form results without refreshing the page This is an explanation of my structure for a better understanding of what I am trying to do.
I have an initial form where you can select an item. After you submit the initial form you get a table with multiple rows and columns and also three buttons at the end. One of the buttons opens a modal window with another form where you can edit some values of the table.
When I am saving and closing the form I added a window.parent.location.reload(); to refresh the parent page and show the new edits. Unfortunately this will ask me If I want to resubmit the form on the parent page and it can be annoying! I need a method to refresh the parent-form's results instead of the entire page without getting dialog boxes all the time. Also, chrome wipes out all the previous data from the parent form and just reload the parent page to its' initial state.
Initial Form
<form class="form-horizontal" action="surveyCategories.cfm" method="post">
        <input type="hidden" name="post" value="1">
            <select name="survey" class="span3">
                <option value="">Select a Survey to Edit</option>
                <cfloop query="surveys">
                <option value="#id#">#name#</option>
                </cfloop>
            </select>
            <input type="submit" class="btn btn-primary" value="Submit">
        </form>

Results Table with the buttons: (This is the table I need to refresh after closing the modal)
     <form name="list" method="post" action="surveyCategories.cfm" >
     <input type="hidden" name="listFormPost" value="1">

        Select	Survey Name	Category	Category Weight

        <cfloop query="categories">

                <input class="checkbox" type="checkbox" name="mark" value="#recID#">
                #name#
                #categoryname#
                #cweight#

        </cfloop>

Add Category

Update

<button class="btn btn-danger" type="button" onClick="dlte(mark); window.parent.location.reload();" >Delete</button>

</form>

Modal Window:

    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>

Update

     <form name="update" action="updateSCpair.cfm" method="post">
        <input type="hidden" name="post2" value="1">
        <input type="hidden" name="surveyid" value="#categories.surveyid#" >

        <input type="text" value="#categories.name#" class="input-xlarge" disabled>

        <select name="categories" onChange="handleCategoryChange();">
            <option value="" selected >Select a Category</option>
            <cfloop query="ratingCat">
              <option value="#ratingCat.categoryid#"  >#ratingCat.categoryName#</option>
            </cfloop>
        </select>

        <input id="score"  name="score" class="span3" type="text"  required >

    <button class="btn" data-dismiss="modal" aria-hidden="true" onClick="window.parent.location.reload();">Close</button>
    <button class="btn btn-primary" type="button" onClick="upd();" >Save changes</button>

</form>

A: You are going to want to use AJAX.
<!DOCTYPE html>

Let's submit a form!

  <button type="button" onclick="showModal()">Show Modal Form</button>

  <form>
    <input name="name" id="parent_form_name" />
  </form>

The submitForm method takes care of the cross browser compatibility.  The onreadystatechange event is fired multiple times during the life cycle of the response.
All you care about is the readyState of 4 and the status of 200.  Your submit.cfm responds with JSON in this example for easy parsing.
You send the name value using the xmlhttp.send method.  For more then one parameter join each parameter with & ie xmlhttp.send('name=bill&age=30').
Code borrowed from: http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
I hope this helps.

A: You can try something like.
window.location = 'http://yourlocation';
If this does not work then you can submit form via AJAX. Please see here or if you are using jQuery then here


text:
Q: Trying to make an animation with matplotlib This is my attempt at the animation I am trying to make:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots(figsize=(10,10))
ax.set_xlim([0,1])
ax.set_ylim([0,1])

def animate(t):
    circle1 = plt.Circle((0.5, 0.5), 0.1*t, color='k',fill=False)
    circle2 = plt.Circle((0.5, 0.5), 0.16*t, color='deepskyblue',fill=False)
    circle3 = plt.Circle((0.5, 0.5), 0.22*t, color='deepskyblue',fill=False)
    circle4 = plt.Circle((0.5, 0.5), 0.28*t, color='deepskyblue',fill=False)
    circle5 = plt.Circle((0.5, 0.5), 0.34*t, color='deepskyblue',fill=False)
    circle6 = plt.Circle((0.5, 0.5), 0.40*t, color='deepskyblue',fill=False)
    circle7 = plt.Circle((0.5, 0.5), 0.46*t, color='k',fill=False)
    ax.add_patch(circle1)
    ax.add_patch(circle2)
    ax.add_patch(circle3)
    ax.add_patch(circle4)
    ax.add_patch(circle5)
    ax.add_patch(circle6)
    ax.add_patch(circle7)
    plt.scatter(.5,.5,color='k')
    plt.annotate('',(.5,.5-.1*t),(.5,.5),arrowprops={'width':1,'color':'k'})
    plt.annotate('',(.5+.46*t,.5),(.5,.5),arrowprops={'width':1,'color':'k'})
    plt.annotate('',(.5-.2*t,.5+.15*t),(.5,.5),arrowprops={'width':.5,'color':'red'})
    return ax

FuncAnimation(fig, animate, frames=np.arange(0.0, 1, .01), interval=10, blit=True, repeat=True)

I would like to get the following figure (which is what I get when I call animate(1)), but expanding from just a point to that size:
Click to see figure.
I know that I am not supposed to return ax, because I get the error message TypeError: 'AxesSubplot' object is not iterable. I don't know, however, what animate should be returning. Any help you could give would be amazing!

A: You are supposed to return a sequence of Artists, in this case
return circle1, circle2, circle3, circle4, circle5, circle6, circle7

But it seems you also want the annotations to get updated, so you'd have to return those as well.
text1 = plt.annotate('',(.5,.5-.1*t),(.5,.5),arrowprops={'width':1,'color':'k'})
# etc...
return circle1, ..., circle7, text1, text2, text3

A better way
Instead of having multiple names, such as circle1, circle2, etc, put all the Circle objects in a list and then access them with circles[index]. That way you can update the radius of the original objects instead of creating new ones in each animate call.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def create_circles():
    radii = np.arange(0.1, .47, 0.06)
    colors = ['k'] + ['deepskyblue'] * 5 + ['k']
    circles = [plt.Circle((0.5, 0.5), color=c, fill=False) for c in colors]
    for circle in circles:
        ax.add_patch(circle)
    return circles, radii

def create_annotations():
    widths = [1, 1, .5]
    colors = ['k', 'k', 'red']
    annotations = [plt.annotate('', (.5, .5), (.5, .5), arrowprops={'width': w, 'color': c})
                   for w, c in zip(widths, colors)]
    lengths = [(0, -.1), (+.46, 0), (-.2, .15)]
    return annotations, lengths

fig, ax = plt.subplots(figsize=(10,10))
ax.set_xlim([0,1])
ax.set_ylim([0,1])

center = [plt.scatter(.5, .5, color='k')]
circles, radii = create_circles()
annotations, lengths = create_annotations()

def animate(t):
    for circle, radius in zip(circles, radii):
        circle.set_radius(radius * t)
    for ann, (x, y) in zip(annotations, lengths):
        ann.xy = (.5+x*t, .5+y*t)
    return center + circles + annotations

FuncAnimation(fig, animate, frames=np.arange(0.0, 1, .01), interval=10, blit=True, repeat=True)


text:
Q: How to remove CRLF blanklines I have a log file that has blank spaces and I would like to remove them, however, in some cases real loglines end with CR and some end with CR LF.
How can I sed/awk/TR the blank lines that have CR LF and no text? I have added the returns to each line below to show you how it looks in Notepad++.
I Tried the following command, however, it's in some cases removing last charters from other log lines.
sed -i "s/.$//" %Logs%\%DIR1%/%FILENAME1

Turns this
08-22 08:54:53.612 I/SystemServer(  760): StartUserManagerServic
08-22 08:54:53.612 I/SystemServiceManager(  760): Starting com.android.server.pm.UserManagerService$LifeCycl
08-22 08:54:53.613 I/SystemServer(  760): InitAttributerCach

Into this
08-22 08:54:53.612 I/SystemServer(  760): StartUserManagerService
08-22 08:54:53.612 I/SystemServiceManager(  760): Starting com.android.server.pm.UserManagerService$LifeCycle
08-22 08:54:53.613 I/SystemServer(  760): InitAttributerCache

Example: log with CRLF added. Trying to remove the blank spaces without cutting off the real loglines
08-22 09:13:42.018 D/TESTAPP( 7560): <<< Server Application info >>> <CR><LF>
08-22 09:13:42.018 D/TESTAPP( 7560): Name: Subscription<CR><LF>
08-22 09:13:42.018 D/TESTAPP( 7560): Package: com.bla.bla2<CR><LF>
08-22 09:13:42.018 D/TESTAPP( 7560): Version Name: 1.0.32.47<CR><LF>
08-22 09:13:42.018 D/TESTAPP( 7560): Version Code: 32<CR>
<CR><LF>
08-22 09:13:42.019 I/TESTAPP( 7560): (95): Upgrade for Subscription is not available<CR>
<CR><LF>
08-22 09:13:42.020 W/TESTAPP( 7560): (95): Unable to get the information of ccom.bla.bla as it is not installed<CR>
<CR><LF>
08-22 09:13:42.021 W/TESTAPP( 7560): (95): Unable to get the information of com.bla.bla as it is not installed<CR>
<CR><LF>
08-22 09:13:42.023 W/TESTAPP( 7560): (95): Unable to get the information of com.bla.bla<CR>

A: sed -i "s/\r//" test.log will fix the issue where you have CR CRLF


text:
Q: Using @Resource to load environment entries I'm trying to load bean runtime configuration.
@Stateless
public class MyBean implements MyLocal{
   @Resource String runtimeSetting1="default_value";
   //....
}

I cannot find out how to create custom resource on app server side (Glassfish) - I have no idea what I should enter in "Factory Class" field.
Maybe there is a better way of loading configuration...
Thanks.

A: To my knowledge, the standard way in Java EE is to declare env-entry for configuration data. This applies to all Java EE components like EJB 3 bean class, servlet, filters, interceptors, listener classes, etc. Here, declare something like this in your ejb-jar.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd">
  <enterprise-beans>
    <session>
      <ejb-name>FooBean</ejb-name>
      <env-entry>
        <description>foobar entry</description>
        <env-entry-name>foo</env-entry-name>
        <env-entry-type>java.lang.String</env-entry-type>
        <env-entry-value>bar</env-entry-value>
      </env-entry>
      ...
    </session>
    ...
  </enterprise-beans>
  ....
</ejb-jar>

Then look up the env-entry with JNDI or inject it by its name. For example, to inject it in your bean:
@Resource(name="foo")
private String myProperty;


text:
Q: How to escape single quotes in php for tsql string (ms sql) how can i escape the single quotes in stuff function? I'm connecting Microsoft SQL with PHP.
$hcode = $_GET['hcode'];
$sql = "SELECT AB.HCode, STUFF(AB.Name1,1,6, '') FROM Article AB WHERE Mandant=1 AND Language= 'EN' AND HCode= '".$hcode."' AND AB.Name1 IS NOT NULL";
$result = sqlsrv_query($conn, $sql);

A: To escape strings with single quotes for MS SQL, we would need to escape it by adding an another single quote.
The following function does this. So, you may try using this function:
public static function mssql_escape($unsafe_str)
{
    if (get_magic_quotes_gpc())
    {
        $unsafe_str = stripslashes($unsafe_str);
    }
    return $escaped_str = str_replace("'", "''", $unsafe_str);
}
//for example $unsafe = "AB'CD'EF";
$escaped = mssql_escape($unsafe);
echo $escaped;// Would output the escaped string as  "AB''CD''EF"


text:
Q: $y'' + by' + cy = 0$, where $b,c$ are real constants, find the condition statisfies $\lim_{t\to\infty} y(t) = 0$ $y'' + by' + cy = 0$, where $b,c$ are real constants, find the condition which satisfies
$$\lim_{t\to\infty} y(t) = 0$$
Here is what I've tried
There are three cases to consider

*

*$b^2 - 4c >0$ for $b > \sqrt{b^2 - 4c} > 0, \lim_{t\to\infty} y(t) = 0$
Hence, $b >0, c>0$

*$b^2 - 4c <0$ for $b >0, \lim_{t\to\infty} y(t) = 0$

*$b^2 - 4c =0$ for $b > 0, \lim_{t\to\infty} y(t) = 0$
Hence, $b >0, c>0$ is the final answer. Am I correct?

A: If the roots of the characteristic equation are real, your differential equation will be something of the form
$y = A e^{r_1 t} + B e^{r_2 t}$
If they are complex, i.e. $a \pm ib$
$y = A e^{a t}\cos bt + B e^{a t}\sin bt$
if $\lim_\limits{t\to \infty} y(t) = 0$ then the real parts of the roots are less than 0.
Either $r_1,r_2$ are both real, and both negative, or the real part of the complex roots is less than zero.
In either case we require $b,c > 0$


text:
Q: What affirms channel current direction in nMOS and pMOS? In circuit designing, it is a common phenomenon to presume that in case of nMOS the channel current flows from drain to source (also seen in schematics), while in the case of pMOS, channel current flows from source to drain.
What characteristic in MOSFETs coerces this distinction? Is it simply something to do with fabrication?
Because, as far as I understand, the distinction between the two comes from the substrate/wells (p-type/n-type in case of nMOS and n-type/p-type in the case of pMOS) and the gate voltages (+ve for nMOS and -ve for pMOS), but once the channel is formed then the channels along with the wells and the source drain contacts should be able to basically behave like a resistor, allowing channel current flow in both directions.

A: They can conduct in both directions, but you have to take into account also the intrinsic diode.
Example of N-MOSFET. They are both correct, except that 2nd is almost useless since it won't work as ON/OFF switch.

simulate this circuit – Schematic created using CircuitLab

A:
it is a common phenomenon to presume...

To presume something wouldn't be regarded as a phenomenon (not in humans anyway).
Channels can carry current in either direction because there is nothing in particular about the channel of a MOSFET that makes it uni-directional to current. MOSFETs generally have a 4-quadrant response to the applied drain-source voltage: -

Picture from here.

A: I think the part of the discussion you are missing is that for a generic, four-terminal MOSFET it is possible for the source and drain to be swapped depending on the applied voltage. For an NMOS transistor, the source is by definition the terminal at the lower voltage so current always flows from drain to source. For a PMOS transistor, the source is always by definition the terminal at the higher voltage so current always flow from source to drain. If you think about how a bidirectional transmission gate works in CMOS VLSI design
you can see this behavior, as the notion of "source" and "drain" flips when the direction of current flow reverses.
Sometimes MOSFETs are packaged as discrete devices with only three terminals. The MOSFET body will be connected to one of terminals, which effectively forces that terminal to be the source.

A: For a four-terminal symmetric MOSFET, the terminology of "source" and "drain" pertains to the locations where the channel carriers travel from, and to, respectively. An nFET has electrons as the majority carriers in its channel after it inverts (from weakly p-doped), and as they flow from source to drain, the conventional (positive) current is drain to source.
On the other hand, on a pFET, holes flow from source to drain in an inverted channel formed in an n-substrate or n-well, and hence the conventional current flows in the same direction.
It's worth noting the following points:

*

*A four-terminal transistor may be fabricated with one of its implants doped lightly. This is called a "lightly-doped drain" technique, and provides performance/reliability benefits when that implant is used as the drain terminal. It will still operate as a MOSFET with current flow in the other direction, but will not realize the same level of performance (e.g. it may be more susceptible to hot carrier injection effects)

*Even if a MOSFET is symmetrical, for purposes of netlisting, schematic capture, and layout, one implant is called source and one is called drain. A correct device model will, however, have correct behavior if the current flow is opposite the expected direction based on pin names.

A: When talking about MOSFETs on an IC, these mostly have a symmetrical structure like this:

Picture from here.
Note how Drain and Source are physically identical.
When using these type of MOSFETs (so when designing a circuit that will be etched on a chip!) then the direction of the current defines which area we call source and which we call drain.
In some situations that direction is unclear (typical example is a "passgate circuit" which is a bidirectional switch), then it is up to the designer to choose which side is the source and which is the drain.
The explanation above does not apply to discrete MOSFETs (and also on-chip High voltage MOSFETs) as these have a non-symmetrical structure. Here's an example of such a Vertical MOSFET:

In such a MOSFET the Drain is constructed such that is can withstand a high voltage and/or it can dissipate a lot of power by mounting the device with the drain side directly on the metal case of the MOSFET and mounting the MOSFET on a heatsink.

A: The FET works as a (bad) diode in the other direction, so when you design a circuit, that defines what kind of FET you can place.


text:
Q: Error 'android.support.v7.appcompat.R$id' appears in /data/app/com.example.username.projectname NoSuchFieldError in Android Studio.
This problem is occurred while running other application also. I try with other applications also.
Please help me,I can't figure out how this error is coming. Here I want to make a toolbar which have some menu items.
Error:-
 java.lang.NoSuchFieldError: No static field title of type I in class
 Landroid/support/v7/appcompat/R$id; or its superclasses (declaration of
 'android.support.v7.appcompat.R$id' appears in
 /data/app/com.example.manojbudhaayer.newapplicaton-2/split_lib_slice_2_apk.apk)

MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = (Toolbar) findViewById(R.id.toolbar);

    setSupportActionBar(toolbar);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main,menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id ==R.id.profile){

        return true;
    }
    if (id == R.id.setting){

        return true;
    }
    if (id == R.id.mylink){

        return true;
    }
    if (id == R.id.refresh){

       return true;
    }

    return true;
}
}

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

<android.support.constraint.ConstraintLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="com.example.manojbudhaayer.newapplicaton.MainActivity">

<include
   android:id="@+id/toolbar"
   layout="@layout/toolbar"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

 </android.support.constraint.ConstraintLayout>

toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.Toolbar
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@color/colorPrimary"
 ></android.support.v7.widget.Toolbar>

 </LinearLayout>

menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item android:id="@+id/profile"
    android:title="Profile"
    android:orderInCategory="101"
    app:showAsAction="ifRoom"/>

<item android:id="@+id/setting"
    android:title="Setting"
    android:orderInCategory="102"
    app:showAsAction="ifRoom"/>

<item android:id="@+id/mylink"
    android:title="My fb Link"
    android:orderInCategory="103"
    app:showAsAction="ifRoom"/>

<item android:id="@+id/refresh"
    android:title="Refresh"
    android:orderInCategory="104"
    app:showAsAction="ifRoom"/>

</menu>

style.xml
<resources>

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

</style>

</resources>

A: it's because of both library and module with the same name or inflating multiple XML layouts with duplicate resource id. rename the layout in one of the modules.


text:
Q: What HTTP Verb Should I Use For Comparing Data I have an endpoint that takes a list of email address (could be a very long list) and finds users with that email. What HTTP verb is best for this?
I am thinking GET as there is no backend mutation but is GET ideal for sending this kind of data to the server?

A: As you are only searching based on free-text I would suggest using GET, it covers everything you need.
Your method is not creating/updating/deleting any data, simply collecting and passing it back.
This is exactly the purpose of the GET method.


text:
Q: total count each day sorted, result grouped by week My query looks like this right now pretty straightforward:
select
    count(*),
    date(visit_date),
    DATE_FORMAT(visit_date,"%a")
from visits
group by date(visit_date)

Here is the result:
http://d.pr/FmMg
what I want to happen is:

*

*for each week the count is sorted

Can you modify my query so it satisfies the criteria?

A: Assuming, you no longer need the count by day and are ONLY looking for count by week:
SELECT
   count(*),
   yearweek(visit_date)
FROM visits
GROUP BY yearweek(visit_date)
ORDER BY yearweek(visit_date) ASC;

A: Are you trying to do like this?
- you can use Datepart to get week number and sort by that.
select
    count(*),
    date(visit_date),
    DATE_FORMAT(visit_date,"%a")
from
    visits
group by
    date(visit_date)
order by
    datepart(yyyy,visit_date),
    datepart(wk,visit_date),
    count(*)


text:
Q: How to make comma align with the bottom of mathematical equations How do you make commas in mathematical equations align with the bottom of mathematical equations, looking something like this:

\linespread{0.6}

$\begin{bmatrix}[1.6] a\\b\\ \end{bmatrix}$\\
\-\hspace{3.5ex}$^{,}$

Instead of the normal behaviour, which puts the comma in the middle
$\begin{bmatrix} a\\b\\ \end{bmatrix},$

Similar behaviour with tall maths equations. Is there a way to correct these?
(The [1.6] is from here:How can I increase the line spacing in a matrix?)

A: Try this:
\def\lowcomma{_{\textstyle,}}

and you can use it:
${\begin{bmatrix}[1.6] a\\b\\ \end{bmatrix}}\lowcomma$

A: This approach uses \smallmatrix to get an inline matrix that doesn't leave the text baseline, and adjustbox to lower the comma by the amount of its height. It declares the \lowcomma as math punctuation to get the spacing right.
\documentclass[varwidth, preview]{standalone}

\usepackage{amsmath}
\usepackage{unicode-math}
\usepackage{adjustbox}

\newlength\commaheight

\newcommand\lowcomma{%
\settoheight{\commaheight}{\text{,}}%
\mathpunct{\adjustbox{valign=b,raise=-\commaheight}{\text{,}}}%
}

\begin{document}
\linespread{0.6}

\( \left[\begin{smallmatrix} a\\b\\ \end{smallmatrix}\right]
\lowcomma
\)
\end{document}


text:
Q: Cannot edit Triggered Send in Salesforce I am not able to update the Triggered Send definition in Salesforce. After deactivating, when I click on edit, its shows me the below error every time -
"The link you followed wasn't valid for your session. Return to the previous page, refresh it, and try again. "
Have tried clearing cache, new browser and everything.
What could be wrong?


text:
Q: How to find solutions to the differential equation created by setting the Schwarzian Derivative equal to zero? I'm in a Masters level course on difference equations, and last week we discussed theorems which can be applied to show the stability characteristics of non-hyperbolic equilibria of first order difference equations. One of these theorems involved an application of the Schwarzian derivative:
$$
S(f) = \frac{f'''}{f'} - \frac{3}{2} (\frac{f''}{f'})^2
$$
The theorem states:
Given $ f: I \mapsto I$ and $ x_{n+1} = f(x_n), n = 0, 1, ...$ and $\bar{x}$ an equilibrium point of f.
We have for
1) ${f'}(\bar{x}) = -1$
2) ${f'}(\bar{x}) = 1$
that
i) $Sf(\bar{x}) < 0 \to \bar{x}$ is locally asymptotically stable.
ii) $Sf(\bar{x}) > 0 \to \bar{x}$ is unstable.
So, I asked myself, "What happens when $Sf(x)=0$?"
By setting the Schwarzian derivative equal to zero and simplifying I arrived at the following third order non-linear differential equation:
$$
\frac{3}{2} {f''}^2 = {f'''}{f'}
$$
By guessing the form of the solution to be $f(x) = a x^m$, I was able to find a family of solutions:
$$
f(x) = \frac{a}{x} + c
$$
and by intuition found a second
$$
f(x) = -x + c
$$
where a and c are arbitrary constants.
Interestingly, both these solutions satisfy the condition that ${f'}(\bar{x}) = -1$. Also, both of these functions when taken as difference equations, (ie:
$$
x_{n+1} = \frac{a}{x_n}
$$
exhibit solutions that are stable and (aside from the equilibrium points themselves) periodic with period 2, but not locally asymptotically stable.
My question is, have I found the only solutions to the ODE above?  If not, what are some other methods of solution/approaches to attempt to find other solutions to the ODE?

A: Let $g=f'$, so your equation becomes $$\frac{3}{2}g'^{2}=g''g \implies \frac{3}{2}\frac{g'}{g}=\frac{g''}{g'}$$
Integrating, $$\frac{3}{2}\ln(g)+C=\ln(g')$$ or $Ag^{3/2}=g'$, which is a first order separable O.D.E. solved as follows (separating variables with $A$ still an arbitrary constant):
$$Ag^{-3/2}dg=dx \implies Ag^{-1/2}=x+B \implies g=\frac{1}{(Ax+B)^{2}}$$
Since $g=f'$, we then have that $$f(x)=\frac{-1}{A}\frac{1}{Ax+B}+C \text{ or }f(x)=\frac{1}{ax+b}+c$$
where $a$, $b$ and $c$ are arbitrary constants.
This solution is valid when neither $g$ or $g'$ is zero, which gives the trivial solution $f(x)=mx+k$


text:
Q: How to Pivot in PostgreSQL Having the following data in a table:
ID     Category   Value
1234   Cat01      V001
1234   Cat02      V002
1234   Cat03      V003
1234   Cat03      V004
1234   Cat03      V005

I want to have the following output:
ID     Cat01  Cat02   Cat03
1234   V001   V002    V003
1234   V001   V002    V004
1234   V001   V002    V005

The output I want to achieve is a kind of pivot table where I have all the values vertically in a table and I want to have those values, horizontally, having the category as a column. But there are some categories that have multiples values, in that case, I need to repeat the values of all other categories and create a row per each repeated value
How can it be done in PostgreSQL?

A: This is a tricky one. crosstab() expects one (or no) value per category for each row_name.
We can work around this restriction like this:
SELECT id
     , COALESCE(cat01, max(cat01) OVER w)
     , COALESCE(cat02, max(cat02) OVER w)
     , COALESCE(cat03, max(cat03) OVER w)
FROM   crosstab(
   'SELECT id::text || row_number() OVER (PARTITION BY id, category ORDER BY value) * -1 AS ext_id
         , id, category, value
    FROM   tbl
    ORDER  BY ext_id, category, value'

   ,$$VALUES ('Cat01'::text), ('Cat02'), ('Cat03')$$
   ) AS ct (xid text, id int, cat01 text, cat02 text, cat03 text)
WINDOW w AS (PARTITION BY id);

Returns your desired result.
How?

*

*Add an extended id: ext_id from the existing id and a row number for each value of the category for the same id. This way we ensure as many rows per id in as there are values for the most common category. We get a derived table like this to build our crosstab() on:
ext_id   | id   | category | value
---------+------+----------+-------
'1234-1' | 1234 | 'Cat01'  | 'V001'
'1234-1' | 1234 | 'Cat02'  | 'V002'
'1234-1' | 1234 | 'Cat03'  | 'V003'
'1234-2' | 1234 | 'Cat03'  | 'V004'
'1234-3' | 1234 | 'Cat03'  | 'V005'

*Now we can feed it to crosstab() using the safe 2-parameter form for missing attributes. Read the basics first if you are not familiar with this:

*

*PostgreSQL Crosstab Query
The original id is carried over as "extra column". See:

*Pivot on Multiple Columns using Tablefunc

*Your question leaves room for interpretation. My solution pairs the lowest values per category first and keeps filling the following rows until there are no values left. (We could combine multiple values per category any other way, it has not been defined.) If a category is short of values for a given id, the rest is filled in with NULL values.

*In the final step I replace those NULL values with the maximum value of each category per id:
 COALESCE(cat01, max(cat01) OVER (PARTITION BY id, category))

which is effectively the same as:
 max(cat01) OVER (PARTITION BY id, category)

I am hoping to make it slightly faster if we only default to the window function if the value is NULL.

A: Take a look here for an example of how to use the CROSSTAB function. Also, take a good look at Erwin Brandstetter's post in the same thread and links within (especially the "Basics for crosstab():" link.
Be careful with NULLs (see the discussion in link).
If you're not using a PostgreSQL version compiled from source, then all you have to do to access the CROSSTAB function is to input
CREATE EXTENSION tablefunc;

On the command line (see EB link).
I'm not sure that I've totally grasped your supplementary information, but maybe the CTE approach I used to cross join status and slots (your equivalent of category and value) might help. If not, please expand on your comment. EB's code might also be of help.

A: What you look at is a crosstab. Assuming your table is called "Fact_Table", write:
select * from crosstab('select id, category, value from Fact_Table')
Also see http://www.postgresql.org/docs/9.5/static/tablefunc.html if you look for other variants.


text:
Q: ASP.NET Web API body value restriction I'm studying ASP.NET Web API, but somewhere in the explanation about complex types that comes from the request body the author confuses me:
PROFESSIONAL ASP.NET MVC 4: Chapter 11 - ASP.NET Web API

"[..] complex types (everything else) are taken from the body. There is
  an additional restriction as well: Only a single value can come from
  the body, and that value must represent the entirety of the body.
  [...]"
Brad Wilson

What does his mean with this "single value can come from the body"? The API formatters can parse only a single type of object from the body? Could you illustrate this by example?

A:
Only a single value can come from the body

Assume you have a request body like this.
{"Id":12345, "FirstName":"John", "LastName":"West"}
You want this JSON to be bound to a parameter of type like this.
public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

The action method can be like void Post(Employee emp). And it cannot be like this - void Post(Employee john, Employee duplicateJohn). Only a single value can come from the body.

and that value must represent the entirety of the body

Assume you have the same request body like this.
{"Id":12345, "FirstName":"John", "LastName":"West"}
And you have two DTOs like this.
public class Identifier
{
    public int Id { get; set; }
}

public class Name
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

You cannot have an action method like void Post(Identifier id, Name name) and expect the body to be bound partially to both the parameters. Body in its entirety must be bound to only one value. So, having a class like
public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

and binding the request body in its entirety to one value like void Post(Employee emp) is only allowed.

A: This basically means that you cannot have multipart body that describes more than one complex type. Say if you have a User type, the entire body must describe that User type and not User + ShoppingChart types.
Valid body for User type:
{
   "id" : "1",
   "username" : "someuser"
}

Invalid body for User type:
{
   "user" : {
      "id" : "1",
      "username" : "someuser"
   },

   "shoppingCart" : {
      "cartId" : "1",
      "items" : "5"
   }
}

Of course, you can create a new complex type like UserAndShoppingCart (which uses user and shopping cart classes as properties) and now the invalid body will be valid and deserializable for this new type.


text:
Q: Python - downloading a CSV file from a web page with a link I am trying to download the CSV files from this page, via a python script.
But when I try to access the CSV file directly by links in my browser, an agreement form is displayed. I have to agree to this form before I am allowed to download the file.
The exact URLs to the csv files can't be retrieved. It is a value being sent to backend db which fetches the file - e.g PERIOD_ID=2013-0:

https://www.paoilandgasreporting.state.pa.us/publicreports/Modules/DataExports/ExportProductionData.aspx?PERIOD_ID=2013-0

I've tried urllib2.open() and urllib2.read(), but it leads to the html content of agreement form, not the file content.
How do i write a python code which handles this re-direct and then fetches me the CSV file and let me save on disk ?

A: You need to set the ASP.NET_SessionId cookie. You can find this by using Chrome's Inspect element option in the context menu, or by using Firefox and the Firebug extension.
With Chrome:

*

*Right-click on the webpage (after you've agreed to the terms) and select Inspect element

*Click Resources -> Cookies

*Select the only element in the list

*Copy the Value of the ASP.NET_SessionId element

With Firebug:

*

*Right-click on the webpage (after you've agreed to the terms), and click *Inspect Element with Firebug

*Click Cookies

*Copy the Value of the ASP.NET_SessionId element

In my case, I got ihbjzynwfcfvq4nzkncbviou - it might work for you, if not you need to perform the above procedure.
Add the cookie to your request, and download the file using the requests module (based on an answer by eladc):
import requests

cookies = {'ASP.NET_SessionId': 'ihbjzynwfcfvq4nzkncbviou'}
r = requests.get(
    url=('https://www.paoilandgasreporting.state.pa.us/publicreports/Modules/'
         'DataExports/ExportProductionData.aspx?PERIOD_ID=2013-0'),
    cookies=cookies
)

with open('2013-0.csv', 'wb') as ofile:
    for chunk in r.iter_content(chunk_size=1024):
        ofile.write(chunk)
        ofile.flush()

A: Here's my suggestion, for automatically applying the server cookies and basically mimicking standard client session behavior.
(Shamelessly inspired by @pope's answer 554580.)
import urllib2
import urllib
from lxml import etree

_TARGET_URL = 'https://www.paoilandgasreporting.state.pa.us/publicreports/Modules/DataExports/ExportProductionData.aspx?PERIOD_ID=2013-0'
_AGREEMENT_URL = 'https://www.paoilandgasreporting.state.pa.us/publicreports/Modules/Welcome/Agreement.aspx'
_CSV_OUTPUT = 'urllib2_ProdExport2013-0.csv'

class _MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):

    def http_error_302(self, req, fp, code, msg, headers):
        print 'Follow redirect...'  # Any cookie manipulation in-between redirects should be implemented here.
        return urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)

    http_error_301 = http_error_303 = http_error_307 = http_error_302

cookie_processor = urllib2.HTTPCookieProcessor()

opener = urllib2.build_opener(_MyHTTPRedirectHandler, cookie_processor)
urllib2.install_opener(opener)

response_html = urllib2.urlopen(_TARGET_URL).read()

print 'Cookies collected:', cookie_processor.cookiejar

page_node, submit_form = etree.HTML(response_html), {}  # ElementTree node + dict for storing hidden input fields.
for input_name in ['ctl00$MainContent$AgreeButton', '__EVENTVALIDATION', '__VIEWSTATE']:  # Form `input` fields used on the ``Agreement.aspx`` page.
    submit_form[input_name] = page_node.xpath('//input[@name="%s"][1]' % input_name)[0].attrib['value']
    print 'Form input \'%s\' found (value: \'%s\')' % (input_name, submit_form[input_name])

# Submits the agreement form back to ``_AGREEMENT_URL``, which redirects to the CSV download at ``_TARGET_URL``.
csv_output = opener.open(_AGREEMENT_URL, data=urllib.urlencode(submit_form)).read()
print csv_output

with file(_CSV_OUTPUT, 'wb') as f:  # Dumps the CSV output to ``_CSV_OUTPUT``.
    f.write(csv_output)
    f.close()

Good luck!
[Edit]
On the why of things, I think @Steinar Lima is correct with respect to requiring a session cookie. Though unless you've already visited the Agreement.aspx page and submitted a response via the provider's website, the cookie you copy from the browser's web inspector will only result in another redirect to the Welcome to the PA DEP Oil & Gas Reporting Website welcome page. Which of course eliminates the whole point of having a Python script do the job for you.


text:
Q: ADFV2, VNET, and Linked Services I have an ADFv2, ADLS Gen2 and SQL Database all configured on a VNET. I'd like to connect from the data factory to the storage account and SQL database however I get a permission error on the data factory (see below).
I know I can stand up an integration runtime to solve the connectivity however, is there any way to configure the linked service to avoid the Virtual machine and IR config yet?
Thanks

A: I'm afraid that the error is not related to the IR,to the Permission instead.
You could refer to this link Service principal authentication to grant permission for your ADF to accessing ADLS. If ADLS is source, the READ permission is needed at least,i think.


text:
Q: Strange MathJax line break behavior in mobile browsers I originally posted this on Puzzling SE Meta [link] (which I should probably close now), but decided to move it here on Stack Exchange Meta because I found this bug occurring on other SE sites.
I was looking at one of my answers on my mobile browser (Safari for iPhone 4S iOS 7.1.2, but the result is the same on any mobile browser I've tried so far), and I found a broken MathJax snippet: the mathematical expression is mixed with the text of the answer making it hard to understand its meaning.
This happens probably because of the snippet being larger than the answer's container: the MathJax expression wraps, but the answer's text doesn't, and this causes an odd result.
I'm adding a screenshot from my iPhone:


text:
Q: Access class props inside scroll addeventlistener I am trying to position fix by passing the fixed prop from state but I am not able to setState inside handleScroll function. I am not sure how to access state inside the function.
class App extends Component {

  state = { fixed: false }

  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll);
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
  }

  handleScroll(e) {
    let scrollTop = e.srcElement.body.scrollTop;
    (scrollTop > 0) ? this.setState({ fixed: true }) : this.setState({ fixed: false });
  }

  render() {
    // grab steps
    const { steps } = this.props;
    const { fixed } = this.state;
    const { scrollToStep } = this;

    return ce('div', { className:'allTheSteps' },
      ce(pagination, { steps, fixed }),
      Object.values(steps).map((step, i) =>
        ce(Steps, { step, key: v4(), i }),
      )
    );
  };

};

A: You need to bind the handleScroll method:
class App extends Component {

  constructor(props) {
    super(props);
    this.handleScroll = this.handleScroll.bind(this);
  }

  ...

};

A: Your callback is being executed in the wrong scope. You have to bind it to the right scope. To do this, you can use ES6 arrow functions and your methods should be bound without having to do it manually.
In your example:
...
    componentDidMount() {
        window.addEventListener('scroll', (e) => this.handleScroll(e));
    }

    componentWillUnmount() {
        window.removeEventListener('scroll', (e) => this.handleScroll(e));
    }
...


text:
Q: Jenkins how to publish phpDox Is there a way to publish the results from having phpDox run in a Jenkins build? See http://jenkins-php.org/ for information on phpDox. Is there a better alternative for Jenkins than phpDox? If so is it easy to setup and install?

A: AFAIK, phpDox documentation is rendered as HTML, so you could use the HTML Publisher Plugin for Jenkins to publish it.


text:
Q: Download file from controller RedirectToAction() I have an old MVC 1.0 application that I am struggling with something relatively simple.

*

*I have a view that allows the user to upload a file.

*Some server side processing goes on.

*Finally, a new file is generated and downloads automatically to the client's machine.

I have steps 1 and 2 working. I can not get the final step to work. Here is my controller:
[AcceptVerbs(HttpVerbs.Post)]
public ViewResult SomeImporter(HttpPostedFileBase attachment, FormCollection formCollection, string submitButton, string fileName
{
    if (submitButton.Equals("Import"))
    {
        byte[] fileBytes = ImportData(fileName, new CompanyExcelColumnData());
        if (fileBytes != null)
        {
            RedirectToAction("DownloadFile", "ControllerName", new { fileBytes = fileBytes});
        }
        return View();
    }
    throw new ArgumentException("Value not valid", "submitButton");
}

public FileContentResult DownloadFile(byte[] fileBytes)
{
    return File(
                fileBytes,
                "application/ms-excel",
                string.Format("Filexyz {0}", DateTime.Now.ToString("yyyyMMdd HHmm")));
}

The code executes:
RedirectToAction("DownloadFile", "ControllerName", new { fileBytes = fileBytes});

but the file does not download. Suggestions welcome and thanks in advance.

A: Try to return ActionResult, because it is the most abstract class of the output of actions. ViewResult will force you to return a View or PartialView, so, return a File will get an exception about implicitly converttion type.
[HttpPost]
public ActionResult SomeImporter(HttpPostedFileBase attachment, FormCollection formCollection, string submitButton, string fileName
{
    if (submitButton.Equals("Import"))
    {
        byte[] fileBytes = ImportData(fileName, new CompanyExcelColumnData());
        if (fileBytes != null)
        {
            return File(
                fileBytes,
                "application/ms-excel",
                string.Format("Filexyz {0}", DateTime.Now.ToString("yyyyMMdd HHmm")));
        }
        return View();
    }
    throw new ArgumentException("Value not valid", "submitButton");
}

A: Why do RedirectToAction? Can you return File from SomeImporter action, just change the return type of SomeImporter to FileContentResult.


text:
Q: LEFT JOIN Duplicating Rows Table 1 has the join field (fieldY) duplicated many times within this table although every row in totality is unique.
When I try to run a left join I am getting 20x more rows than expected. I have tried to use solutions this post with no luck.
My expectation is that the join would yield exactly as many rows as table1 without the join. The join would just bring in one more column (fieldX)
Any ideas?
SELECT
    table1.*, table2.fieldZ
FROM
    table1
LEFT JOIN
    table2
ON
    table2.fieldX = table1.fieldY
WHERE
    criteria1 = '01/01/2019'
AND
    criteria2 > '0'
ORDER BY
    criteria2

In below photo:
fieldz = Routing #
fieldX = Bank Account # (From table2)
fieldY = Bank Account # (From table1)

*This can be joined by student ID or Bank Account #, but the problem is the same regardless because both Student ID & Bank Account # appear multiple times in Table 1`

A: Table2 must have Table 1's key across multiple records.  Needs to be 1:1 to achieve what you are describing.

A: With this query:
select t1.*, t2.routing
from table1 t1 left join table2 t2
on t2.studentid = t1.studentid

or this:
select t1.*, t2.routing
from table1 t1 left join table2 t2
on t2.bankaccount = t1.bankaccount

you get these results:
> studentid | bankaccount |  gpa | semester | routing
> --------: | ----------: | ---: | :------- | :------
>         1 |      123456 |      | Fall     | abc
>         1 |      123456 |      | Spring   | abc
>         1 |      123456 |      | Summer   | abc
>         2 |      456789 |      | Fall     | def
>         2 |      456789 |      | Spring   | def
>         2 |      456789 |      | Summer   | def
>         3 |      321654 |      | Fall     | ghi
>         3 |      321654 |      | Spring   | ghi
>         3 |      321654 |      | Summer   | ghi

You can check the demo.


text:
Q: Local File Path does not work in my html file I'm working on a flask app, and the problem that I'm struggling now is that any local path doesn't seem to work within the html file
The structure is like this:
Code/app.py
Code/enternew.html
Code/one.jpg
Code/styles.css
and right now in my html file, I'm trying to load the css file and images in using
<link type="text/css" href="styles.css" rel="stylesheet"/>
and

but neither works
alternatively if I copy the css code to  in the  part it works, if I use an online picture it also works, such as
but if i use a local path nothing seems to load. Does anyone have any idea what could be the issue? thank you!

A: You can't link static files from the root directory like that.
By default Flask will set up ./static as the directory from which to serve files from.
Just like it sets up ./templates directory to look for templates.
Make a folder called static on your app directory and move your files there. Then link them with href="static/<your_file>".
Have a look at the project layout that Flask proposes here -> https://flask.palletsprojects.com/en/2.0.x/tutorial/layout/


text:
Q: Delete \xa0 at the end of a unicode I have a string, such as u'jdiajsi--dasdsa\xa0'. I need to get rid of \xao and obtain u'jdiajsi--dasdsa'.
First, I tried str.replace("\xa0", ", "), but it does not work. Then, I change to re.sub(r'\W+', ' ', str), but the result is "jdiajsi dasdsa". The two dashes are gone...
str = "jdiajsi--dasdsa\xa0"
str.replace("\xa0", ", ") #fail
re.sub(r'\W+', ' ', str)  #fail

The first result is no change, the second one miss --. The expected result is "jdiajsi--dasdsa"
The input is unicode rather than a string

A: Strings are immutable; none of their methods, nor any function, can change them in place, they always return a new string. You need to assign them to something to see the changed version, e.g.:
mystr = "jdiajsi--dasdsa\xa0"
mystr = mystr.replace("\xa0", ", ")
mystr = re.sub(r'\W+', ' ', mystr)

Note that I changed the name of the variable; naming a variable str cuts off access to the str constructor, which will eventually byte you.


text:
Q: Problems with Extjs.getBody I have this line of code
 var width_client = Ext.getBody().getWidth(true);

and I get that Ext.getBody() is null.
I asume that this check is doen before Ext.getBody() becames not null, but dont' know were or what to change.
Any idea how to solve this?
I use extjs 4.0.7

A: You can access document.body when it is rendered. From your question I made a conclusion that your code was located inside <head>. When this code is executed there is no <body> rendered yet. You have to wrap your code by a function and pass this function to Ext.onReady (or Ext.onDocumentReady) method:
Ext.onReady(function() {
    alert(Ext.getBody().getWidth(true));
});

Here is demo.

A: You have to wait until the page is loaded and ready.
Try this.
Ext.onReady(function() { Ext.getBody().getWidth();})


text:
Q: Add with carry on Word8 I can't find a function addWithCarry :: Word8 -> Word8 -> (Word8, Bool) already defined in base. The only function documented as caring about carries seems to be addIntC# in GHC.Prim but it seems to never be pushed upwards through the various abstraction layers.
I could obviously roll out my own by testing whether the output value is in range and it's in fact what I am currently doing but I'd rather reuse an (potentially more efficient) already defined one.
Is there such a thing?

A: If you look at the source for Word8's Num instance, you'll see that everything is done by converting to a Word# unboxed value and performing operations on that, and then narrowing down to a 8-bit value. I suspected that doing comparison on that Word# value would be more efficient, so I implemented such a thing. It's available on lpaste (which I find easier to read than StackOverflow).
Note that it includes both a test suite and Criterion benchmark. On my system, all of the various tests take ~31ns for the boxed version (user5402's implementation) and ~24ns for the primops versions.
The important function from the lpaste above is primops, which is:
primops :: Word8 -> Word8 -> (Word8, Bool)
primops (W8# x#) (W8# y#) =
    (W8# (narrow8Word# z#), isTrue# (gtWord# z# 255##))
  where
    z# = plusWord# x# y#

A: A way to do this is:
addWithCarry :: Word8 -> Word8 -> (Word8, Bool)
addWithCarry x y = (z, carry)
  where z = x + y
        carry = z < x


text:
Q: React Map GL not rendering using create-react-app I would use React Mapbox GL using create react app helper, but I cannot render the map.
I've followed This example, using that code it works, but I don't know how to build the App, so I'd prefer to use CRA.
In the console I don't have any errors, and yeah, the token is correct.
I've read somewhere that i have to use <MapGL /> instead of <MapGL> ... </MapGL>, but as you will see, I do have other components inside the map, and even removing it, it gives me this error: TypeError: null is not an object (evaluating 'context.viewport.zoom')
How can I solve?
Here is my App component:

import MapGL, {
  Popup,
  NavigationControl,
  FullscreenControl,
  ScaleControl, GeolocateControl,

} from 'react-map-gl';

...

 const [viewport, setViewport] = useState({
    latitude: 40,
    longitude: -100,
    zoom: 3.5,
    bearing: 0,
    pitch: 0
  });
  const [popupInfo, setPopupInfo] = useState(null);

return (
  <MapGL
    {...viewport}
     width="100%"
     height="100%"
     mapStyle="mapbox://styles/mapbox/dark-v9"
     onViewportChange={setViewport}
     mapboxApiAccessToken={TOKEN}
   >
    <Suspense fallback={
Loading Events
}>
     <Pins onClick={setPopupInfo} />
    </Suspense>

    {
     popupInfo && (
     <Popup
      tipSize={5}
      anchor="top"
      longitude={popupInfo.location.longitude}
      latitude={popupInfo.location.latitude}
      closeOnClick={false}
      onClose={setPopupInfo}
     >
      <EventsInfo info={popupInfo} />
     </Popup>
     )}

      <GeolocateControl style={geolocateStyle} />
      <FullscreenControl style={fullscreenControlStyle} />
      <NavigationControl style={navStyle} />
      <ScaleControl style={scaleControlStyle} />

      <GeolocateControl
       style={geolocateStyle}
       positionOptions={positionOptions}
       trackUserLocation
       auto
      />
  </MapGL>
)


text:
Q: Paste MS Word as Text but keep some styling Jquery My customer wants a UI that he will copy some text from MS Word and paste. After he pastes, my script should delete all the styling and tags of Word, but keep paragraphs (html p tags) and bold styling (html b tag).
I've prepared a UI with html5 contenteditable, there are many editable sections with different kind of content (headers, 1 and 2 column paragraphs etc.)
I've found a script that working well, doing exact the same thing I want. But if I want to use different selector (the script uses #content selector), it does not work. I want to use a class, since many sections with .editable_div class can be added to UI.
Maybe it's because I'm not so good at JS and Jquery. The script is below, how can I make it work with many sections with a class name on the page?
Thanks so much...
Index.html:
<!DOCTYPE html>

Source here...

Place MS-Word text here...

and script:
(function($) {
    $.fn.msword_html_filter = function(options) {
        var settings = $.extend( {}, options);

        function word_filter(editor){
            var content = editor.html();

            // Word comments like conditional comments etc
            content = content.replace(//gi, '');

            // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content,
            // MS Office namespaced tags, and a few other tags
            content = content.replace(/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, '');

            // Convert <s> into  for line-though
            content = content.replace(/<(\/?)s>/gi, "<$1strike>");

            // Replace nbsp entites to char since it's easier to handle
            //content = content.replace(/ /gi, "\u00a0");
            content = content.replace(/ /gi, ' ');

            // Convert ___ to string of alternating
            // breaking/non-breaking spaces of same length
            content = content.replace(/([\s\u00a0]*)<\/span>/gi, function(str, spaces) {
                return (spaces.length > 0) ? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : '';
            });

            editor.html(content);

            // Parse out list indent level for lists
            $('p', editor).each(function(){
                var str = $(this).attr('style');
                var matches = /mso-list:\w+ \w+([0-9]+)/.exec(str);
                if (matches) {
                    $(this).data('_listLevel',  parseInt(matches[1], 10));
                }
            });

            // Parse Lists
            var last_level=0;
            var pnt = null;
            $('p', editor).each(function(){
                var cur_level = $(this).data('_listLevel');
                if(cur_level != undefined){
                    var txt = $(this).text();
                    var list_tag = '

';
                    if (/^\s*\w+\./.test(txt)) {
                        var matches = /([0-9])\./.exec(txt);
                        if (matches) {
                            var start = parseInt(matches[1], 10);
                            list_tag = start>1 ? '

' : '

';
                        }else{
                            list_tag = '

';
                        }
                    }

                    if(cur_level>last_level){
                        if(last_level==0){
                            $(this).before(list_tag);
                            pnt = $(this).prev();
                        }else{
                            pnt = $(list_tag).appendTo(pnt);
                        }
                    }
                    if(cur_level<last_level){
                        for(var i=0; i<last_level-cur_level; i++){
                            pnt = pnt.parent();
                        }
                    }
                    $('span:first', this).remove();
                    pnt.append('
' + $(this).html() + '
')
                    $(this).remove();
                    last_level = cur_level;
                }else{
                    last_level = 0;
                }
            })

            $('[style]', editor).removeAttr('style');
            $('[align]', editor).removeAttr('align');
            $('span', editor).replaceWith(function() {return $(this).contents();});
            $('span:empty', editor).remove();
            $("[class^='Mso']", editor).removeAttr('class');
            $('p:empty', editor).remove();
        }

        return this.each(function() {
            $(this).on('keyup', function(){
              $('#src').text($('#editor').html());

                var content = $(this).html();
                if (/class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i.test( content )) {
                    word_filter( $(this) );
                }
            });
        });
    };
})( jQuery )

$(function(){
  $('#editor').msword_html_filter();
  $('#src').text($('#editor').html());
})

A: I found it. Selector is not the problem. $('.editable_div').msword_html_filter(); is normally working.
But if the parent div is contenteditable = true, the script is not working for children divs. I still dont know why.  Thanks you all.


text:
Q: Rsync a portion of image sequences I have an image sequence as follows:
some_images.####.jpg   0001   1000

But I had only wanted to do a rsync from 0001 to 0120, by using rsync from a local to a remote server. Can this be done using rsync command?

A: Yes, you can do this by specifying each of the 120 filenames individually:
rsync some_images0001.jpg some_images0002.jpg (etc..) yourhost:yourdir/

Knowing that, we can use bash to generate the above command with all 120 filenames automatically:
rsync some_images{0001..0120}.jpg yourhost:yourdir/


text:
Q: Como agregar ImageView a ListView He estado leyendo y por lo visto hay que crear un Adapter, pero la verdad es que no me aclaro mucho, alguien me podría hacer un ejemplo o guiarme algo más? Si hace falta más información o algo más, decidme. Gracias!
Dejo aquí mi código
MainActivity:
public class MyActivity extends ActionBarActivity {

    Button btnAgregarPersona;
    ListView lista;
    SQLControlador dbconeccion;
    TextView tv_miemID, tv_miemNombre, tv_miemFecha;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_principal);

        dbconeccion = new SQLControlador(this);
        dbconeccion.abrirBaseDeDatos();
        btnAgregarPersona = (Button) findViewById(R.id.btnAgregarPersona);
        lista = (ListView) findViewById(R.id.listViewPersonas);

        //acción del boton agregar persona
        btnAgregarPersona.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent iagregar = new Intent(MyActivity.this, AgregarPersona.class);
                startActivity(iagregar);
            }
        });

        Cursor cursor = dbconeccion.leerDatos();

        String[] from = new String[]{
                DBhelper.PERSONA_ID,
                DBhelper.PERSONA_NOMBRE,
                DBhelper.PERSONA_FECHA
        };
        int[] to = new int[]{
                R.id.persona_id,
                R.id.persona_nombre,
                R.id.persona_fecha
        };

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(
                MyActivity.this, R.layout.formato_fila, cursor, from, to);

        adapter.notifyDataSetChanged();
        lista.setAdapter(adapter);

        // acción cuando hacemos click en item para poder modificarlo o eliminarlo
        lista.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {

                tv_miemID = (TextView) view.findViewById(R.id.persona_id);
                tv_miemNombre = (TextView) view.findViewById(R.id.persona_nombre);
                tv_miemFecha = (TextView) view.findViewById(R.id.persona_fecha);

                String aux_personaId = tv_miemID.getText().toString();
                String aux_personaNombre = tv_miemNombre.getText().toString();
                String aux_personaFecha = tv_miemFecha.getText().toString();

                Intent modify_intent = new Intent(getApplicationContext(), ModificarPersona.class);
                modify_intent.putExtra("personaId", aux_personaId);
                modify_intent.putExtra("personaNombre", aux_personaNombre);
                modify_intent.putExtra("personaFecha", aux_personaFecha);
                startActivity(modify_intent);
            }
        });
    }

    }

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <Button
        android:id="@+id/btnAgregarPersona"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Agregar Cumpleaños" />

    <ListView
        android:id="@+id/listViewPersonas"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:dividerHeight="2dp">
    </ListView>

</LinearLayout>

formato_fila.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/persona_id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#00000000" />

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

        <TextView
            android:id="@+id/persona_nombre"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:padding="15dp"
            android:textSize="17sp"
            android:textStyle="bold"
            android:text="Nombre"
            android:layout_weight="1" />

        <TextView
            android:id="@+id/persona_fecha"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:padding="15dp"
            android:textSize="17sp"
            android:textStyle="bold"
            android:text="Fecha"
            android:layout_weight="1" />

    </LinearLayout>

    <View
        android:layout_width="fill_parent"
        android:layout_height="2dp"
        android:background="#3f51b5"
        android:id="@+id/separador1"
        android:layout_marginTop="10dp" />

</LinearLayout>

A: No estamos para resolver problemas, sino solamente para guiar o tratar de solucionar errores. Pediste un ejemplo practico para guiarte. En google existen miles de tutoriales.
El tema de listview es algo muy recurrente en StackOverFlowEs. Hace poco hice un ejemplo de en listview en Android y te va a servir para tu aplicación. Podes adaptar.
Este ejemplo muestra un listview con textos e imágenes. También la forma de optimizar y que no tarde en mostrar lores resultados cuando se hace scroll.


text:
Q: How do I get Putty to request the remote SHA256 blob as the key fingerprint? When I ssh from my Mac to a new remote Ubuntu server, it asks me to confirm the key fingerprint as a SHA256 base64 blob.
But when I try to connect with Putty on Windows or Ubuntu to a new remote Ubuntu server, it asks me to confirm the key fingerprint as MD5. I'd much rather confirm using a SHA256 base64 blob.
The Putty documentation for the Key Exchange configuration panel indicates that it is aware of base64 blobs, but the reference is for a setting that assumes I know the fingerprint in advance (manual configuration).
Can I/how do I tell Putty to display the new remote base64 blob key fingerprint instead of the new remote MD5 key fingerprint when connecting to a remote server and the remote fingerprint doesn't match the locally stored previous value?

A: Be careful to distinguish between blobs and hashes. The public key blob used by OpenSSH, and also PuTTY, is the same for a given key regardless of the hash(es) used. The key blob is stored in base64 by OpenSSH in its xxx_key.pub known_hosts authorized_keys files as applicable, partly because it makes it easier to copy these files and values with techniques like cut-and-paste and (especially older) email that might not handle 'binary' aka '8-bit' data. The 'fingerprint' displayed by OpenSSH (by default, unless you ask for VisualHostKey) used to be MD5(blob) displayed in hex, and now is SHA256(blob) displayed in base64. PuTTY followed OpenSSH's original lead but (as of 0.67) not the update.
You can request an enhancement following the instructions in the manual and duplicated at http://www.chiark.greenend.org.uk/~sgtatham/putty/feedback.html#feedback-features . Or it's open source; you can do the change yourself, and submit it back to them (see B.5 just after B.4). The 'fingerprint' code is currently in one place in sshdsa.c and two in sshrsa.c, but I see on the website the next release will include ecdsa and ed25519 keys, which presumably means at least one and maybe several new place(s) to create a fingerprint. To be consistent als allow base64 of a hash (not just of a blob as now) in validate_manual_key in misc.c. That's easy if you change to SHA256-b64 unconditionally and never do MD5-hex; for a submission or feature usable by other people this probably has to be configurable and/or interactive, either of which looks a good bit harder.
For Windows, I can see one very clunky workaround. Use plink to connect to the host and accept the new key, putting it in the registry. (If there was an old key, save it first.) Get the new key from the registry (in pieces), build the blob, hash and base64 it and display for confirmation. If not confirmed, delete the key from the registry (and restore any prior one).
For Unix, a slightly less clunky way is to use ssh with StrictHostKeyChecking=no to accept the new key and put the base64 blob in known_hosts, or use ssh-keyscan to get the base64 blob directly. Then base64-decode, hash, base64-encode (the hash) and display; if bad after ssh forced accept, delete the bad entry from known_hosts; if good after ssh-keyscan, add the good entry. OpenSSL can conveniently do both bits of the calculation:
awk <.ssh/known_hosts '$1~/thehostname/{print $3}' |openssl base64 -d |openssl sha256 |openssl base64

but if you don't have OpenSSL it should be easy to combine other base64 and sha256 tools.


text:
Q: Is using shared_ptr after reset undefined behaviour? I have this test program:
#include <iostream>
#include <memory>

class A {
public:
    A()
    {
        std::cout<<"A Constructor\n";
    }

    ~A(){
        std::cout<<"A Destructor\n";
    }

    void show()
    {
        std::cout<<"A::show()"<<'\n';
    }
};

int main()
{
    auto p1 = std::make_shared<A>();
    // Relinquishes ownership of p1 on the object
    // and pointer becomes NULL
    p1.reset();
    std::cout<<p1.get()<<'\n';
    std::cout<<p1.use_count()<<'\n';
    p1->show();
    return 0;
}

Which yields this output:
A Constructor
A Destructor
0
0
A::show()

I ran this via gdb and saw:
:
:
(gdb) s
A::show (this=0x0) at so.cpp:18
18              std::cout<<"A::show()"<<'\n';
(gdb) s
A::show()
:

The line A::show (this=0x0) at so.cpp:18 indicates that the underlying resource is null. I looked at another question but there the raw pointer was being used to invoke the member function. Is this case too similar to the one in that question since p1->show() too should be equivalent to something like p1.get()->show();. Is my understanding correct?

A: Just add a data member to the class and you can see visually undefined behavior.
#include <iostream>
#include <memory>

class A {
public:
    A()
    {
        std::cout<<"A Constructor\n";
    }

    ~A(){
        std::cout<<"A Destructor\n";
    }

    void show()
    {
        std::cout<<"A::show()"<<'\n';
        ++x;
    }

    int x = 0;
};

int main()
{
    std::shared_ptr<A> p1(new A);
    // Relinquishes ownership of p1 on the object
    // and pointer becomes NULL
    p1.reset();
    std::cout<<p1.get()<<'\n';
    std::cout<<p1.use_count()<<'\n';
    p1->show();
    return 0;
}

For example at run-time an error like this
Runtime error #stdin #stdout 0s 4280KB

can be shown.
That is the null-pointer was used to access the data member.


text:
Q: Save checkmarked row into appsettings. EDITED EDIT: I got a saving and now It do not work.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:countries  forKey:@"country"];
[defaults synchronize];

Saving.
But I think I must load the arrays from the appsettings. how?
Got this now:
countries = [[NSArray alloc] initWithObjects:@"All",@"Austria",@"Belarus",@"Canada",@"Czech Republic",@"Denmark",@"Germany",@"Finland",@"France",@"Latvia",@"Norway",@"Russia",@"Slovakia",@"Slovenia",@"Switzerland",@"Sweden", @"USA", nil];

A: Use  synchronize mathod of NSUserDefault.
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        int newRow = [indexPath row];
        int oldRow = (lastIndexPath != nil) ? [lastIndexPath row] : -1;

        if (newRow != oldRow)
        {
            UITableViewCell *newCell = [tableView cellForRowAtIndexPath:
                                        indexPath];
            newCell.accessoryType = UITableViewCellAccessoryCheckmark;

            UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:
                                        lastIndexPath];
            oldCell.accessoryType = UITableViewCellAccessoryNone;
            lastIndexPath = indexPath;
        }
        NSUInteger row = [indexPath row];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        //Suppose you have used **myArrayUsedInTableView**   Array to construct TableView
        ..................................................................................
        ............./*Do changes here in myArrayUsedInTableView  as per your requirement*/
        ....................................................................................
        //Now store your array myArrayUsedInTableView in NSUserDefault
        [defaults setObject:myArrayUsedInTableView  forKey:@"StoredArray"];
        [defaults synchronize];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
  }


text:
Q: jqGrid: restoring filter (toolbar) values on page reload (I'm sure this is a UFU but I can't seem to find the cause)
Using jqGrid to display data. Double-click on a row opens a new page with drill-down info. I want to restore the filter terms when the 'back' button is clicked.
Filter terms are stored in the localStorage from grid.getGridParam( "postData" ).filters. Am attempting to restore this at load time but not getting values back.
The confounding factor is probably that I'm creating the values for the filtertoolbar at load time by finding unique values for each column (see here). This says (to me) that I can't set filter values until after the drop-lists are filled. To this end I'm trying to use the 'loadComplete' function (where the list filling function is called). Once the controls are populated I'm calling grid.jqGrid( 'setGridParam', { 'postData' : localStorage[ "filter" ]});. Unfortunately this doesn't seem to have any effect.
From everything I've read this is doable. What did I miss?
NOTE: I also tried this but figured it wasn't working owing to the values being set in 'loadComplete' above.

EDIT: filter values are being saved here:
ondblClickRow: function( rowid, iRow, iCol, e )
{
    localStorage[ 'filter' ] = grid.getGridParam("postData").filters;
    window.location = "info.php?idx=" +  grid[0].p.data[ rowid - 1 ].IssueId;
}

There are values saved from this. I test when the page is reloaded (and also eyeball it using console.log())
loadonce is definitely true.
Here are the params I use:
url: "loadIssues.php",
datatype: "json",
colNames: [  (list of values) ],
colModel: [ (array of values)  ],
pager: "#pager2",
viewrecords: true,
sortorder: "desc",
gridview: true,
autoencode: true,
ignoreCase : true,
loadonce : true,
width: 800,
height: "auto",
shrinkToFit: true,
search: true,
jsonReader: {
  repeatitems: false,
  root: "rows"
 },

EDIT:
This is the fix: using the $( this ) was my mistake. Replacing it with a reference to the grid control fixes the problem.
Here is the code I'm using in loadComplete:
loadComplete: function( data )
{
    setSearchSelect( <column name> );

    if( localStorage.hasOwnProperty( 'filter' ))
    {
       postData = $( "#list2" ).jqGrid( "getGridParam", "postData" );
       paramNames = $( "#list2" ).jqGrid("getGridParam", "prmNames");

       postData.filters = JSON.parse( localStorage[ 'filter' ]);
       postData[paramNames.search] = true;

       localStorage.removeItem( 'filter' );

       setTimeout( function()
       {
           $( "#list2" ).trigger( "reloadGrid" );
       }, 100 );
   }
}

A: I answered in the answer and in this one how one could save the preferences in localStorage and restore it during loading the grid.
First of all I would mention that the usage of localStorage["filter"] in your code can make some conflicts. Each domain and subdomain has its own separate local storage area, but you can use different grids on different pages of your web server. Some pages could have more as one grid. So it would be better to use another rules as "filter" for the name of the property of localStorage. I used in the answer the property names which will be build from window.location.pathname and the grid id.
Now I go back to your main question. I see two main problems which you have to solve:

*

*setting the filter before the first request will be send to the server

*filling the fields of the filter toolbar based on the filter

A possible solution of the second part I described in the answer (see the code of refreshSerchingToolbar function called inside of loadComplete). I used the same approach in the answer where I used localStorage for persisting users preferences of jqGrid.
Setting of filter in jqGrid can be implemented in different ways. It's important to specify which behavior you want to have in case of usage datatype: "json", loadonce: true. If you implemented server side filtering then you can set the filter inside of beforeRequest callback:
var storageName = "filters"; // or some better value

...

datatype: "json",
loadonce: true,
beforeRequest: function () {
    var $self = $(this),
        postData = $self.jqGrid("getGridParam", "postData"),
        filters = postData.filters,
        paramNames = $self.jqGrid("getGridParam", "prmNames"),
        dataType = $self.jqGrid("getGridParam", "datatype"),
        lastFilter = localStorage[storageName];

    // one can add in the below condition testing of dataType === "json" if one need to set
    // the filter on loading the data from the server only
    if ((filters === null || filters === "" || filters === undefined) && lastFilter !== undefined) {
        // current filter is not set, but it exists in localStorage
        // we need to applay it
        postData.filters = lastFilter;

        // set _search parameter to true
        postData[paramNames.search] = true;
    }

    return true;
},
loadComplete: function () {
    var filters = $(this).jqGrid("getGridParam", "postData").filters;
    if (filters !== null && filters !== "" && filters !== undefined) {
        localStorage[storageName] = filters;
    }
}

Alternatively you can just set the filter before the grid will be created like I do it in already referenced answers (this one and this one).
If you don't implemented filtering on the server side then the filter will be not applied automatically. In the case you can follow the answer and reloads the grid once after loading the data from the server. One will sees flickers, but the sorting and filter will be do applied.


text:
Q: htaccess rewriting specific folder/path to subdomain I'm trying to setup a redirect for a site.
I want rewrite file requests from a folder to a subdomain url.
At the moment, I have this in my htaccess:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_METHOD} =GET
RewriteCond %{HTTP_HOST} !^example.com
RewriteCond %{HTTP_HOST} ^g.example.com
RewriteRule ^(uploads/(.*)+ uploads/%1%{REQUEST_URI} [L]

The idea is that when a visitor requests:
http://g.example.com/uploads/somefile.png

they are served:
http://example.com/uploads/somefile.png

So it's working as expected. However the problem is that:
http://b.example.com/uploads/somefile.png

also works.
I only want http://g.example.com/ to be rewritten. http://b.example.com/ should 404.

A: This should work:
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} !^g.example.com$ [NC]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(.*)\.(JPG|GIF|PNG) [NC]
RewriteRule ^ - [R=404,L]

RewriteCond %{HTTP_HOST} ^g.example.com$ [NC]
RewriteCond %{THE_REQUEST} !^GET [NC]
RewriteRule ^ - [R=404,L]

The first rule will make sure that any URL ending with JPG, GIF, PNG that does not come from g.example.com send a 404 not found request to the user.
The second rule makes sure that g.example.com are only accessed using GET requests.


text:
Q: What is the best way to move Microsoft Office 2011 to a new Mac? I've purchased Microsoft Office for Mac Home & Office 2011 (single computer), and have installed and activated on my current Mac.
Given that I've already activated the software for my current Mac, what steps should I do to move the app to the new Mac, without having any problems re-activating the software? Would Apple's Migration Assistant automate the process completely?

A: There are no special steps. Install it using the installer just like you did on your old Mac. When prompted for the activation key, select "activate by phone" and input nothing, keep trying and it should provide a number to call.
Microsoft (unlike Adobe) does not have an automated system for licence deactivation. This has been a point of great angst among Mac users as it requires them to call Microsoft each and every time they move the Office application from one machine to another.
I believe the number in the US is: +1 (800) 936-5700. Your product support number may vary.
Here is a rundown on activation and product key information.

A: This worked for me: After an incomplete timemachine backup (I excluded the folder /System/Library) I had to do the following to get it working again on the same machine (I guess it should also work on your second Mac).
Beside the App that was installed to /Applications/Microsoft\ Office\ 2011 Restore these files from your previous installation:
/Library/LaunchDaemons/com.microsoft.office.licensing.helper.plist
/Library/PrivilegedHelperTools/com.microsoft.office.licensing.helper
/Library/Preferences/com.microsoft.office.licensing.plist

Source: this guide

A: The previous answer is missing one path/folder. For simplicity here is the complete list:
/Library/Application\ Support/Microsoft/
/Applications/Microsoft\ Office\ 2011/
/Library/LaunchDaemons/com.microsoft.office.licensing.helper.plist
/Library/PrivilegedHelperTools/com.microsoft.office.licensing.helper
/Library/Preferences/com.microsoft.office.licensing.plist

The above includes the apps, licensing and the Microsoft Office AutoUpdater


text:
Q: PHP image resampling issue When i resample a jpg in order to draw border around the image, the quality of image is horribly decreases and extremely low quality jpeg is gotten.

Here is my code:

function addBorderpng($add,$bdr=0,$color='#000000'){
                $arr = explode('.', $add);
                $extension = strtolower(end($arr));
                $border=$bdr;

$im=imagecreatefromjpeg($add);

                $width=imagesx($im);
                $height=imagesy($im);
                $img_adj_width=$width+(2*$border);
                $img_adj_height=$height+(2*$border);
                $newimage=imagecreatetruecolor($img_adj_width,$img_adj_height);

                imageantialias($newimage, true);
                $color_gb_temp =HexToRGB($color);
                $border_color = imagecolorallocate($newimage, $color_gb_temp['r'], $color_gb_temp['g'], $color_gb_temp['b']);
                imagefilledrectangle($newimage,0,0,$img_adj_width,$img_adj_height,$border_color);
                imagealphablending($newimage, true);
                imageantialias($newimage, true);
                     imagecopyresized($newimage,$im,$border,$border,0,0,$width,$height,$width,$height);
                    imagejpeg($newimage,$add,9);
            }

A: The last argument to imagejpeg is quality.

quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).

You are setting it at 9, hence low quality.

A: Also, you can try "imagecopyresampled" in place of "imagecopyresized" which handles interpolationPHP imagecopyresampled


text:
Q: Angular-CLI for visual studio Following the steps to create HeroEditor as given on angular.io , How to open it in Visual Studio?
I created an empty project and added Angular-CLI created files . Got multiple build errors on promise and set.

A: I recommend you to use Visual Studio Code. Because you can use it as Angular Studio with extensions.

*

*Create project with angular-cli

*Open VS Code and show project folder

And here are the list of extensions may help you while developing angular apps

*

*Angular Language Services

*vscode-icons

A: I have gone through the same problem few days back and come up with the few solutions :-

*

*If you want to use Visual studio 2017, there is a Project template available online i.e. Angular CLI Application ( New Project --> Online --> Search Angular CLI Application).

*If you have only front end to develop go with the Visual Studio Code (recommended).
Creating an empty project in Visual Studio Code and adding the code generated by Angular CLI is not the correct way that i got to know so please avoid that. :)
I have implemented it in both the ways i.e. Visual Studio 2017 Project Template and Visual Studio Code. Please let me know if you need any clarification on the same.


text:
Q: Simple random sampling variance estimate Consider Simple Sampling with replacement.
$\displaystyle s^2= \frac{1}{n-1} \cdot \sum_{i=1}^n (X_i-\bar X)^2$ an unbiased estimate for $\sigma^2$?
could you give me a hint?

A: I think you mean $s^2=\frac{1}{n-1}\sum_{i=1}^n (X_i-\overline X )^2$
The expected value of  $s^2$ is
$E(s^2)=E\left[\frac{1}{n-1}\sum_{i=1}^n (X_i-\overline X )^2\right]$
$=\frac{1}{n-1}E\left[\sum_{i=1}^n (X_i-\overline X)^2 \right] \quad | \pm \mu$
$=\frac{1}{n-1}E\left[\sum_{i=1}^n \left[(X_i-\mu)-(\overline X-\mu) \right]^2 \right] \quad$
Removing the square from the inner bracket
$=\frac{1}{n-1}E\left[\sum_{i=1}^n \left[(X_i-\mu)^2-2(\overline X-\mu)(X_i-\mu)+(\overline X-\mu)^2 \right]\right] \quad$
$=\frac{1}{n-1}E\left[\sum_{i=1}^n (X_i-\mu)^2-2(\overline X-\mu)\sum_{i=1}^n(X_i-\mu)+\sum_{i=1}^n(\overline X-\mu)^2 \right] \quad$
$=\frac{1}{n-1}E\left[\sum_{i=1}^n (X_i-\mu)^2-2(\overline X-\mu)\color{red}{\sum_{i=1}^n(X_i-\mu)}+n(\overline X-\mu)^2 \right] \quad$

transforming the red expression
$\sum_{i=1}^n(X_i-\mu)=n\cdot \overline X-n\cdot \mu$
Thus $2(\overline X-\mu)\color{red}{\sum_{i=1}^n(X_i-\mu)}=2(\overline X-\mu)\cdot (n\cdot \overline X-n\cdot \mu)=2n( \overline X- \mu)^2$

$=\frac{1}{n-1}E\left[\sum_{i=1}^n (X_i-\mu)^2-2n( \overline X- \mu)^2+n(\overline X-\mu)^2 \right] \quad$
$=\frac{1}{n-1}E\left[\sum_{i=1}^n (X_i-\mu)^2-n( \overline X- \mu)^2\right] \quad$
$=\frac{1}{n-1}\left[\sum_{i=1}^n E\left[(X_i-\mu)^2\right]-nE\left[( \overline X- \mu)^2\right]\right] \quad$
It is $E\left[(X_i-\mu)^2\right]=\sigma^2$ and $E\left[( \overline X- \mu)^2\right]=\sigma_{\overline x}^2=\frac{\sigma^2}{n}$
It is all comprehensible ? And can you finish it ?


text:
Q: How can I slove this Axios Interceptor problem? I am new with Axios interceptor and I could not figure out what is wrong with this code.Is this the right way to pass the data(body) using Axios Interceptor to make a post request?
import axios from 'axios';

export const userService = {
    login
};

const axiosInstance = axios.create({
  baseURL: 'https://**********/api/v1'
})

const loginRequestHandler = (request) => {
 request.data['email','password']={email,password}
  return request
}

axios.interceptors.request.use(
  request => loginRequestHandler(request),
  error =>  Promise.reject(error)
);

 function login(handlerEnabled){
    axiosInstance.post('/auth/local',{handlerEnabled})
}


text:
Q: Use selenium webdriver as a baseclass python I searched for a while for this one and was surprised i couldn't find anything, maybe because it's simple. I've been programming in python for about 3 months doing automated testing with selenium webdriver.  I was thinking it would be convenient to have a class inherit from my webdriver class to add more functionality to it.
    from selenium import webdriver

    class myPage(webdriver):

          def __init__(self):
                super(myPage, self).__init__()

          def set_up(self):
                #doStuff...

but when i do this i get the error>>>
    File "c:\Users\me\...\myProgram.py", line 6, in <module>
        class myPage(webdriver):
    TypeError: module.__init__() takes at most 2 arguments (3 given)

When I create the myPage object the code is...
    from myProgram import myPage
    class Test():
          def do(self):
                self.browser = myPage.Firefox()

So it goes through and does the self.browser = myPage.Firefox() line and when it runs the .__init__() somehow it gives it three arguments and I'm not sure where they come from. I'm clearly missing something because inheritance isn't hard to do. Thanks for any help

A: You'd have to change:
class myPage(webdriver)

To:
class myPage(webdriver.Firefox)

However that would remove the ability to choose the browser you would like to run it on. This is because webdriver isn't actually a class, but a package (I believe). When you call something like: webdriver.Firefox() it is actually an instance of the Firefox class, not the webdriver class. To get what you desire you're probably better off doing something like this:
from selenium import webdriver

class myPage(webdriver.Firefox, webdriver.Chrome, webdriver.Ie):
    def __init__(self, browser):
        if browser.lower() == "ie":
            webdriver.Ie.__init__(self)
        elif browser.lower() == "chrome":
            webdriver.Chrome.__init__(self)
        else:
            webdriver.Firefox.__init__(self)

A: The best way to do it is to inherit from webdriver.Remote.
what is selenium remote?
selenium remote is basically a way to run selenium on another server, but it can be used locally (and works like a charm).
The advantage here is that you will have one interface that works for all browsers, and supports both local and remote execution.
In the future, you might want to run tests in multiple servers via some CI tool, so this can come in handy.
implementation
class izWebDriver(webdriver.Remote):
"""
iz implementation for selenium remote web-driver
"""
def __init__(self, url, capabilities):
    super().__init__(url, capabilities)

## add more custome functions here !

How to use this implementation
new_driver = izWebDriver(driver_url, DesiredCapabilities.CHROME)

I did some more abstractions, to basically be able to do get_driver(browser='chrome').
A reference - my working framework
Take a look at my own selenium wrapper for reference, It has some knit capabilities like

*

*sharing a driver between tests\projects (for testing integration between to GUIs for example).

*Retries before failing, for example - element.click() tries to click using JS event before failing.

and many more
All the code is available in this github repo
the actual selenium wrapper is in Core folder.
Also, here is an example of a project implemented using my framework

A: @bob's answer is almost right, but with Python 3.9 and Selenium 3.1 I did
class ExtendedWebDriver(webdriver.Firefox):
    def __init__(self):
        super(ExtendedWebDriver, self).__init__()

    def find_elements_by_testid(self, testid):
        return self.find_elements_by_xpath(f"//*[@data-testid='{testid}']")

    ...

class HomepageTest(unittest.TestCase):
    def setUp(self):
        self.browser = ExtendedWebDriver()

    def tearDown(self):
        self.browser.quit()

    def test_can_access_homepage(self):
        self.browser.get(HOME)

    ...

This of course only for FF, you'll have to adapt for multiple browsers by playing with the __init__ part


text:
Q: Help understanding the compactness of $[0, 1]$. After doing some homework for my Topology course, I am confused about why this reasoning doesn't show that $[0,1]$ is not compact in $\mathbb{R}$. Clearly this isn't true, so where is the flaw?
Answer: The problem is that $[0,1]-K \neq \bigcup_{i \in \mathbb{N}} \left(\dfrac{1}{n+1},\dfrac{1}{n}\right)$ because $0 \in [0, 1] - K$.
Note that $K = \{\frac{1}{n} | n \in \mathbb{N}\}$ isn't compact because it doesn't have a least element. Additionally, note that $K$ is closed in $[0,1]$ as
$$[0,1] - K = \bigcup_{i \in \mathbb{N}} \left(\dfrac{1}{n+1},\dfrac{1}{n}\right).$$
Since $K$, a subspace of $[0,1]$, is closed and not compact, $[0, 1]$ cannot be compact in $\mathbb{R}$.
Note: However, does this reasoning work in $\mathbb{R}_k$? What about in $\mathbb{R}_l$?

A: $[0,1]\setminus K$ is the the union you wrote. Note that $0 \in [0,1]\setminus K$ but $0$ is not in the union.


text:
Q: elixir function taking a parameter with do I'm trying to wrap my head around Elixir and am confused about the following
def fun_myfunc(clause, do: expression) do

Specifically I'm a bit confused about the do: expression part.  Is this a parameter being passed into the function, and also why is there a :.  Is do a keyword in this context ?
This also gives rise to the following, question on Phoenix.  If I look at the pipeline function https://hexdocs.pm/phoenix/Phoenix.Router.html#pipeline/2 I see the following signature pipeline(plug, list).  What is list in this context and how do I infer it by looking at the documentation.  I know that they have given examples where list looks like a bunch of expressions, but how do I gather that just by looking at the documentaion.

A: do: expression is a keyword list. This is syntax sugar in two forms:

*

*As the last parameter to a function, you can omit the surrounding []

*As a keyword list, you can write key: value instead of the equivalent {:key, :value}
Both of these are documented in the above link.
The function is equivalent to:
def fun_myfunc(clause, [{:do, expression}]) do

The :do is simply an atom. It's up to the fun_myfunc to decide how to handle it.
I suspect you are actually looking at a macro defined with defmacro and misquoted it in your question. This is also how the if macro works, for example.
if foo do bar else baz is equivalent to if(foo, do: bar, else: baz), which is equivalent to if(foo, [{:do, bar}, {:else, baz}]).
As for the Phoenix part, that should be a separate question.