text:
Q: Applying a Pieter van Oostrum Page Number Positioning Algorithm to the First Page of the Endnotes In the following MWE, I have invoked a Pieter van Oostrum algorithm for selectively placing the page number at the bottom of the page (and ignoring the header) that was introduced in the post:  How to Selectively Remove the Header and Have the Page Number Only Appear at the Bottom of the Page
The algorithm works very nicely by invoking the command \thispagestyle{nohead}; however, I do not know how to apply it (or if it is possible to apply it) to the first page of the endnotes.
Consider the code:
\documentclass[openany]{book}
\usepackage{lipsum}

\usepackage{endnotes}
\usepackage{chngcntr}
\counterwithin*{endnote}{chapter}  % Reset endnote numbering everyv%new chapter
\usepackage{fancyhdr}

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% ENDNOTE MACRO ---

\let\latexchapter\chapter
\makeatletter
\renewcommand\enoteheading{
  \setcounter{secnumdepth}{-2}
  \latexchapter*{\notesname\markboth{NOTES}{}}
  \mbox{}\par\vskip-\baselineskip
  \let\@afterindentfalse\@afterindenttrue
}
\makeatother

\usepackage{xparse}

\RenewDocumentCommand {\chapter}{som}{%
\IfBooleanTF{#1}
  {\latexchapter*{#3}%
   \setcounter{endnote}{0}%
   \addtoendnotes{%
     \noexpand\enotedivision{\noexpand\subsection}
       {\unexpanded{#3}}}%
  }
  {\IfNoValueTF{#2}
     {\latexchapter{#3}}
     {\latexchapter[#2]{#3}}%
   \addtoendnotes{%
     \noexpand\enotedivision{\noexpand\subsection}
       {\chaptername\ \thechapter. \unexpanded{#3}}}%
  }%
}
\makeatletter
\def\enotedivision#1#2{\@ifnextchar\enotedivision{}{#1{#2}}}
\makeatletter

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %

% PIETER VAN OOSTRUM algorithm to selectively place the page number at the bottom of the page by using \thispagestyle{nohead} within the document.

\fancyhf{}
\pagestyle{fancy}
\renewcommand{\headrulewidth}{0pt}
% definitions for \pagestyle{fancy}
\fancyhf{}
\fancyhead[LE,RO]{\emph{\Large \thepage}}
% Same for \pagestyle{plain} - used for first chapter pages.
\fancypagestyle{plain}{
  \fancyhf{}
  \fancyhead[LE,RO]{\emph{\Large \thepage}}
}
\fancypagestyle{nohead}{
  \fancyhf{}
  \fancyfoot[C]{\emph{\Large \thepage}}
}

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %

\begin{document}
\LARGE

\chapter*{CHAPTER 1}
\thispagestyle{nohead}
\lipsum[1]\endnote{\lipsum[2]}\endnote{\lipsum[3]}\endnote{\lipsum[4]}\endnote{\lipsum[5]}\endnote{\lipsum[6]}\endnote{\lipsum[7]}\endnote{\lipsum[8]}
\endnote{\lipsum[5]}

\theendnotes
\end{document}

with output:

QUESTION: I would like the page number on the second page of output (i.e., the first page of the endnotes) to appear at the bottom of the page with no header on that page. How may I do this? If the algorithm cannot be applied to the first page of the endnotes, how may I accomplish what I am trying to do? (I compile the actual document with lualatex.)
Thank you.

A: Put \renewcommand{\notesname}{\thispagestyle{nohead}Notes}
before \begin{document}
to make the page number appear at the bottom of the page of Notes.
Another chapter added (without [nohead]).


text:
Q: Deleting user permissions from document library instead of site level I wanted to delete a user permission from ONE of the various document libraries in a SharePoint site.
But when i deleted the permission, it seemed to have deleted the user permission at a much higher level (site level?)
This caused the user not being able to access ALL the document libraries instead.
How do i delete the user permission from one of the document library only?

A: You need to go to Document Library Ribbon -> Under Library -> Library Settings -> Permissions for this document library  OR simply Document Library Ribbon -> Under Library -> Library Permissions
By default the document library will be inheriting permissions from Site, you need to click "Stop Inheriting permissions" ribbon button to stop that..

Than you can delete the users and it won't affect the Site..

A: If you need to remove permissions programmatically you should first break inheritance:
list.BreakRoleInheritance(true);

After that you can for example remove all role assignments for list or library and it does not effect for higher levels:
SPRoleAssignmentCollection roleAssignmentCollection = list.RoleAssignments;
for (int i = roleAssignmentCollection.Count - 1; i >= 0; i--)
{
   roleAssignmentCollection.Remove(i);
}

A: Follow this steps
got to Library Permission
by default, library inherits permissions from parent. Just click on Stop Inheriting permissions.
after that, Delete the users or groups which you don't want.
Add the users or groups that you want library to be accessible. and save.
library will than have unique permissions

redpajama_set_name: RedPajamaStackExchange


text:
Q: Matplotlib add_subplot does not add to the expected position fig = plt.figure(figsize=(10,30))
ax1 = fig.add_subplot(1,1,1)
ax2 = fig.add_subplot(2,1,2)
ax3 = fig.add_subplot(3,1,3)

ax1.imshow(np.ones((100,200,3))) # white
ax2.imshow(np.zeros((100,200,3))) # black
ax3.imshow(np.zeros((100,200,3))) # black

The above code yields the below image
ax1 the white image is where I expected to be. the ax2, ax3, the black images are overlapped with each other

A: Figured it out!
Turns out add_subplot requires the overal dimensions. So the correct way to write it this
fig = plt.figure(figsize=(10,15))
ax1 = fig.add_subplot(3,1,1)
ax2 = fig.add_subplot(3,1,2)
ax3 = fig.add_subplot(3,1,3)


text:
Q: Image warping with Python I need to warp an image of relatively large size (1679x1475) in Python. I have the transformed coordinates. How can I efficiently warp the image to transformed coordinate system. I tried scipy.interpolate.griddata, but soon my computer runs out of memory.

A: You want scipy.ndimage.map_coordinates. You can configure the interpolation method and how it handles points that are outside the original image.
An example:
import numpy as np
from scipy import misc
#create a 2D array that has a grayscale image of a raccoon
face = misc.face(gray=True)

import matplotlib.pyplot as plt
plt.imshow(face,cmap=plt.cm.gray)

the unwarped image looks like this
#set up our new coordinate system
rows,cols = np.mgrid[0:768, 0:1024]
rows = rows**(1/2) * 767**(1/2)
cols = cols**(2) / 1023
rows = np.roll(rows,150,0)

from scipy import ndimage
#warp the image using a 3rd order (cubic) spline interpolation
new_img = ndimage.map_coordinates(face,[rows,cols], order=3)
plt.figure()
plt.imshow(new_img,cmap=plt.cm.gray)

the image after warping

A: OpenCV comes with a function cv2.resize() for this purpose. The size of the image can be specified manually, or you can specify the scaling factor. Different interpolation methods are used. Preferable interpolation methods are cv2.INTER_AREA for shrinking and cv2.INTER_CUBIC (slow) & cv2.INTER_LINEAR for zooming. By default, interpolation method used is cv2.INTER_LINEAR for all resizing purposes. You can resize an input image either of following methods:
import cv2
import numpy as np

img = cv2.imread('messi5.jpg')

res = cv2.resize(img,None,fx=2, fy=2, interpolation = cv2.INTER_CUBIC)

#OR

height, width = img.shape[:2]
res = cv2.resize(img,(2*width, 2*height), interpolation = cv2.INTER_CUBIC)


text:
Q: I want to understand why the data i am passing as props into the React functional component is showing as undefined? I have been given a ready made react component, in which I need to pass data as props but somehow I am not able to see the props data when I console log it. Can someone help me understand if I am passing the prop correctly .I am not aware what type of functional component is being used here and if the prop I am passing is correctly entered. I pass the same prop to other class based components which do show the data properly.
    import React from 'react';
    import { withStyles } from '@material-ui/core/styles';
    import Button from '@material-ui/core/Button';
    import Dialog from '@material-ui/core/Dialog';
    import MuiDialogTitle from '@material-ui/core/DialogTitle';
    import MuiDialogContent from '@material-ui/core/DialogContent';
    import MuiDialogActions from '@material-ui/core/DialogActions';
    import IconButton from '@material-ui/core/IconButton';
    import CloseIcon from '@material-ui/icons/Close';
    import Typography from '@material-ui/core/Typography';

    const styles = (theme) => ({
        root: {
            margin: 0,
            padding: theme.spacing(2),
        },
        closeButton: {
            position: 'absolute',
            right: theme.spacing(1),
            top: theme.spacing(1),
            color: theme.palette.grey[500],
        },
    });

    const DialogTitle = withStyles(styles)((props) => {

        const { children, classes, onClose, routeHappyData, ...other } = props;
        console.log(routeHappyData);
        return (
            <MuiDialogTitle disableTypography className={classes.root} {...other}>
                <Typography variant="h6">{children}</Typography>
                {onClose ? (
                    <IconButton aria-label="close" className={classes.closeButton} onClick={onClose}>
                        <CloseIcon />
                    </IconButton>
                ) : null}
            </MuiDialogTitle>
        );
    });

``

```The prop I want to pass is "routeHappyData" which is showing undefined when console logged.
In the Parent class component i am passing the prop this way given below```

        render() {
            let {
              routeHappyData

                } = { ...this.props };
            return (

         <div>{noOfStops}</div>
                                {<CovidHealthSafety routeHappyData={this.props.routeHappyData}/>}
                    </div>
    )

A: You console.log it before your routeHappyData variable is assigned. Try putting it one line below.
const DialogTitle = withStyles(styles)((props) => {
    const { children, classes, onClose, routeHappyData, ...other } = props;
    console.log(routeHappyData);
    return (
        <MuiDialogTitle disableTypography className={classes.root} {...other}>
            <Typography variant="h6">{children}</Typography>
            {onClose ? (
                <IconButton aria-label="close" className={classes.closeButton} onClick={onClose}>
                    <CloseIcon />
                </IconButton>
            ) : null}
        </MuiDialogTitle>
    );
});


text:
Q: SQL problem, LEFT JOIN [..] IN() This small SQL error is bugging me. It doesn't seem to be a problem with the query, just the scope(?), examples work best:
SELECT ocp.*, oc.*, GROUP_CONCAT( u.username SEPARATOR ', ') AS `memjoined`
FROM gangs_ocs_process ocp, gangs_ocs oc
LEFT JOIN users u ON u.userid IN ( ocp.membersin )
WHERE ocp.ocid =1 AND ocp.gangid =1 AND oc.oc_name = ocp.crimename
GROUP BY ocp.ocid
LIMIT 0 , 30

Theres a column (gangs_ocs_process.membersin) which has a list of IDs that have joined (ie 1,2,5). I'm trying to get the usernames for each of these IDs (from the users table) in one go.
The problem is LEFT JOIN users u ON u.userid IN ( ocp.membersin )
If I substitue 1,2,4 in for ocp.membersin (putting the literal list instead of column name), it works ok. It returns a column that has the usernames (image). However, if I leave in the ocp.membersin, I get this error:
#1054 - Unknown column 'ocp.membersin' in 'on clause'
This is the first time I've even used IN in left joins so I'm a bit lost.
Any help would be great :)

A: I don't think that "IN" will work for this syntax.  MySQL expects IN to be something akin to a dataset, not a delimited string.  I think you need to find a way to take membersin, expand it into a dataset MySQL can work with (maybe a temporary table), and join on that.

A: If you have delimited strings in your table, you have a design problem in your database.  Add a new table to hold these values.

A: The reason you can't get it to work is because first you need to get your database NORMALIZED. You should NEVER, EVER have a list of ID's in a single column.

A: This is a bad way to keep membership.
But if you still need to live with it, you may try REGEXP matching to test for membership:
SELECT ocp.*, oc.*, GROUP_CONCAT( u.username SEPARATOR ', ') AS `memjoined`
FROM gangs_ocs_process ocp
LEFT JOIN users u ON (ocp.membersin RLIKE CONCAT('(^|,)[[:blank:]]?', userid, '[[:blank:]]?($|,)'))
JOIN gangs_ocs oc ON (ocp.ocid = 1 AND ocp.gangid = 1 AND oc.oc_name = ocp.crimename)
GROUP BY ocp.ocid
LIMIT 0 , 30

A: After taking another look, I think your problem is trying to aggregate at the wrong point as well as the IN syntax and that you should aggregate in a subquery restricted by the contents of the IN. I don't know enough about your schema to make this out of the box correct, but you want something like this. SomeKeyfield should relate back to gangs_ocs_process
SELECT ocp.*, oc.*, u.Memjoined
FROM gangs_ocs_process ocp, gangs_ocs oc
LEFT JOIN (Select SomeKeyField, GROUP_CONCAT( u.username SEPARATOR ', ') as memjoined
            from  users where userid in
            (select membersin from gangs_ocs_process
             where [whatever conditions] )
             Group By SomeKeyField) u on ocp.SomeKeyField = u.SomeKeyField

WHERE ocp.ocid =1 AND ocp.gangid =1 AND oc.oc_name = ocp.crimename
GROUP BY ocp.ocid
LIMIT 0 , 30

A: Are you sure 'membersin' is in the 'gangs_ocs_process' table, and not the 'gangs_ocs' table?


text:
Q: Is this Code Exploitable? (PHP) I paid someone to code basic PHP scripts for me, so bare in mind for my dumb questions. I just want to keep my users safe.
Is this code exploitable, and if so, how can I fix it?
if(isset($_POST['serial'])){
    $serial = $_POST['serial'];
    $count=$db->prepare("SELECT * FROM users WHERE serial=:serial LIMIT 1");
    $count->bindParam(":serial",$serial);
    $count->execute();
    $no=$count->rowCount();

    if($no >0 ) {
        echo "User Found";
    } else {
        echo "User Not Found";
    }
}

I am guessing I need to sanitize 'serial' to ensure there are no injection attempts. Is there any code to do this for me? Will something like this work?
$name = strip_tags(trim( $_POST[ 'name' ] ) );

A: If you mean more specifically the SQL Injection, then this statement is good enough to prevent it, since it uses prepared statement, i.e. it passes parameter :serial and later on it will fill it by calling $count->bindParam(":serial",$serial);.
The risk of SQL Injection is when you make your statement by concatenating SQL queries with user input directly, without sanitization, example:
DO NOT USE SUCH KIND OF CODING
$count=$db->prepare("SELECT * FROM users WHERE " . $_POST['serial'] .  " LIMIT 1");


text:
Q: How to roll back a transaction on error in PostgreSQL? I'm writing a script for PostgreSQL and since I want it to be executed atomically, I'm wrapping it inside a transaction.
I expected the script to look something like this:
BEGIN
-- 1) Execute some valid actions;
-- 2) Execute some action that causes an error.
EXCEPTION
    WHEN OTHERS THEN
        ROLLBACK;
END; -- A.k.a. COMMIT;

However, in this case pgAdmin warns me about a syntax error right after the initial BEGIN. If I terminate the command there by appending a semicolon like so: BEGIN; it instead informs me about error near EXCEPTION.
I realize that perhaps I'm mixing up syntax for control structures and transactions, however I couldn't find any mention of how to roll back a failed transaction in the docs (nor in SO for that matter).
I also considered that perhaps the transaction is rolled back automatically on error, but it doesn't seem to be the case since the following script:
BEGIN;
-- 1) Execute some valid actions;
-- 2) Execute some action that causes an error.
COMMIT;

warns me that: ERROR: current transaction is aborted, commands ignored until end of transaction block and I have to then manually ROLLBACK; the transaction.
It seems I'm missing something fundamental here, but what?
EDIT:
I tried using DO as well like so:
DO $$
BEGIN
-- 1) Execute some valid actions;
-- 2) Execute some action that causes an error.
EXCEPTION
    WHEN OTHERS THEN
        ROLLBACK;
END; $$

pgAdmin hits me back with a: ERROR: cannot begin/end transactions in PL/pgSQL. HINT: Use a BEGIN block with an EXCEPTION clause instead. which confuses me to no end, because that is exactly what I am (I think) doing.
POST-ACCEPT EDIT:
Regarding Laurenz's comment: "Your SQL script would contain a COMMIT. That ends the transaction and rolls it back." - this is not the behavior that I observe. Please consider the following example (which is just a concrete version of an example I already provided in my original question):
BEGIN;

-- Just a simple, self-referencing table.
CREATE TABLE "Dummy" (
    "Id" INT GENERATED ALWAYS AS IDENTITY,
    "ParentId" INT NULL,
    CONSTRAINT "PK_Dummy" PRIMARY KEY ("Id"),
    CONSTRAINT "FK_Dummy_Dummy" FOREIGN KEY ("ParentId") REFERENCES "Dummy" ("Id")
);

-- Foreign key violation terminates the transaction.
INSERT INTO "Dummy" ("ParentId")
VALUES (99);

COMMIT;

When I execute the script above, I'm greeted with: ERROR: insert or update on table "Dummy" violates foreign key constraint "FK_Dummy_Dummy". DETAIL: Key (ParentId)=(99) is not present in table "Dummy". which is as expected.
However, if I then try to check whether my Dummy table was created or rolled back like so:
SELECT EXISTS (
    SELECT FROM information_schema."tables"
    WHERE "table_name" = 'Dummy');

instead of a simple false, I get the same error that I already mentioned twice: ERROR: current transaction is aborted, commands ignored until end of transaction block. Then I have to manually terminate the transaction via issuing ROLLBACK;.
So to me it seems that either the comment mentioned above is false or at least I'm heavily misinterpreting something here.

A: You cannot use ROLLBACK in PL/pgSQL, except in certain limited cases inside procedures.
You don't need to explicitly roll back in your PL/pgSQL code. Just let the exception propagate out of the PL/pgSQL code, and it will cause an error, which will cause the whole transaction to be rolled back.
Your comments suggest that this code is called from an SQL script. Then the solution would be to have a COMMIT in that SQL script at some place after the PL/pgSQL code. That would end the transaction and roll it back.

A: I think you must be using an older version, as the exact code from your question works without error for me:

(The above is with PostgreSQL 13.1, and pgAdmin 4.28.)
It also works fine for me, without the exception block:

As per this comment, you can remove the exception block within a function, and if an error occurs, the transaction run within it will automatically be rolled back. That appears to be the case, from my limited testing.


text:
Q: Cytoscape won't let me upload table to a network collection the only option was to unassigned table. Does anyone know how to resolve this? the drop-down option isn't available so my table is automatically imported as unassigned table. Anybody come across this issue before? Or is there something wrong with my table setting?
cytoscape screenshot

A: Not sure what you were expecting.  According to the screenshot, you don't have any networks open, so an imported table can only be unassigned.  If, on the other hand, you are trying to import a network, you need to use import network from file, not import table from file.
-- scooter

A: I had the same issue, and ended up spending 3-4 hours on this.

This icon on the tool-bar allows loading of networks from tables without any issue. I was very lucky to find this solution in a video on YouTube(!): https://youtu.be/Z8jUmJL2HFw?t=52, but not in the Cytoscapes documentation.
To me, Cytoscape's file import system felt very un-intuitive. I am not sure why cytoscape does not have a unified import system for loading simple (csv/tsv) tables. Following are few ways that did not work in my case. I am using version 3.9.0. In both of these cases the table got imported as 'Unassigned table'.

*

*Drag and drop 'Edge Table'/'Network table'.

*File > Import > Import from file

I went through the documentation and I am still not sure what is the use of 'Unassigned table'. How to assign the columns as source, target etc in the 'Unassigned table'? Even the sample tables shown in the Cytoscape's manual did the same(!).
By the way, I am not sure why the Cytoscape's documentation is not intuitive. For example, I googled 'cytoscape import table' and this slide show showed up as a 1st result: https://cytoscape.org/cytoscape-tutorials/protocols/importing-data-from-tables/#/5 . From the title of the slideshow i.e. 'Importing data from tables', I assumed that it will guide me through how to generate network from tabular data. However, instead it shows how to load data for nodes, which does not create a network(!). Why not demonstrate how to load edge/network data and guide us through the process till the generation of the network? I hope this will improve in next versions of CytoScape.
Anyways, I hope the solution helps.


text:
Q: Web service vs. Office Automation I have ASP.NET Web Service, that works under IIS.
I use Microsoft.Interop DLL to convert file from XML Table format to Excel 2003.
In my code I have reference to Microsoft.Interop DLL version 12. When I try to use this web service from VS, everything working correct.
But when I move my web service to 64-bit Windows Server 2008 I have problem with this convertion.
I place my Microsoft.Interop DLL into bin folder of my web service.
I also tried to make build for 86x and 64x platforms, but nothing changed.
Without converting my web service working correct.
What may cause this problem?

A: You cannot use Office Automation in a server process like a web service. It's designed to automate the Office desktop applications. In a service, it doesn't work, or causes bugs that are difficult to reproduce, is unsupported, and may even be a violation of your license with Microsoft.


text:
Q: android Volley delete method, why will send empty parameters I work with android volley library! I have some don't understand problem with sending request with json and DELETE method from server. Request successfully connect to server but sended parameters server will receive is empty. But header request work normaly! Please help me!
public void deletePoint(String id) throws JSONException {
    dialog.show();
    queue = Volley.newRequestQueue(getActivity(), new ExtHttpClientStack(new SslHttpClient().getHttpClient()));
    String urlRequest = getUrl();
    JSONObject param = new JSONObject();
    param.put("id", id);
    JsonObjectRequest userRequest = new JsonObjectRequest(Request.Method.DELETE,
            urlRequest,
            param,
            deletePointRequestSuccessListener(),
            reqErrorListener()){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = super.getHeaders();
            if (headers == null || headers.equals(Collections.emptyMap())) {
                headers = new HashMap<String, String>();
            }
            if (ProgressFragment.this.headers != null) {
                headers.keySet().removeAll(ProgressFragment.this.headers.keySet());
                headers.putAll(ProgressFragment.this.headers);
            }
            headers.put("Content-Type", "application/json");
            return headers;
        }
    };

    userRequest.setRetryPolicy(new DefaultRetryPolicy(
            MY_SOCKET_TIMEOUT_MS,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    dialog.show();
    queue.add(userRequest);
}

private Response.Listener<JSONObject> deletePointRequestSuccessListener() {
    return new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            dialog.hide();
            Gson gson = new Gson();
            Success resp = gson.fromJson(response.toString(), Success.class);
            if(resp.isSuccess()){
                Toast.makeText(getActivity(), getString(R.string.success), Toast.LENGTH_SHORT).show();
                try {
                    getGraphData();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            dialog.hide();
        }
    };
}

A: Try to pass parameters with the URL as you would do with a GET request. Worked for me :)
Code sample (not tested):
url += "?";
for(String key : params.keyset()){
  url += URLEncode.encode(key,"UTF-8") +"="+ URLEncode.encode( params.get(key),"UTF-8") +"&";
}
url = url.substring(0, url.length()-1); // remove last '&' char

A: it's this issue that has been resolved
you can rewrite the HurlStack class
public class HurlStack implements HttpStack {
             break;
         case Method.DELETE:
             connection.setRequestMethod("DELETE");
             addBodyIfExists(connection, request); // here call addBodyIfExists method
             break;
         case Method.POST:
             connection.setRequestMethod("POST");

request with DELETE method will be easy as POST,for example
    mQueue = Volley.newRequestQueue(context);
StringRequest postRequest = new StringRequest(Request.Method.DELETE, HttpUtils.URL_MSG,
    new Response.Listener<String>()
    {
        @Override
        public void onResponse(String response) {
            if (mCallBack!=null) {
            mCallBack.success(response);
            }
        }
    },
    new Response.ErrorListener()
    {
        @Override
        public void onErrorResponse(VolleyError error) {
        if (mCallBack!=null) {
            mCallBack.fail(null);
        }
        }
    }
) {
    @Override
    protected Map<String, String> getParams()
    {
    return params;
    }

};

mQueue.add(postRequest);

that can only resolve android os 5.0 devices problem
there has new problem on android os 4.2.2 device
it will throw the following exception
java.net.ProtocolException: DELETE does not support writing

to rewrite Volley.newRequestQueue(Context context, HttpStack stack) method can resovle this problem
    public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    .
    .
    .

    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new OkHttpStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    .
    .
    .

    return queue;
}

OkHttpStack.java(okhttp-1.6.0.jar)
public class OkHttpStack extends HurlStack {
  private final OkHttpClient client;

  public OkHttpStack() {
    this(new OkHttpClient());
  }

  public OkHttpStack(OkHttpClient client) {
    if (client == null) {
      throw new NullPointerException("Client must not be null.");
    }
    this.client = client;
  }

  @Override protected HttpURLConnection createConnection(URL url) throws IOException {
    return client.open(url);
  }
}

it works for me, hoping that work for you as well


text:
Q: anyone know of a shared To-do list plugin for eclipse Does anyone know of shared TODO list plugin for Eclipse that allows users in a a development team to all view and edit the same list of tasks?

A: Mylyn can be used to integrate issue tracking systems into the IDE.

It does this by making tasks a first class part of Eclipse, and integrating rich and offline editing for repositories such as Bugzilla, Trac, and JIRA.

If you are not looking for a lightweight solution, then you might give it a try.

A: Other than the already built-in "Tasks"? It works by adding TODO, XXX or FIXME (in caps) in comments in the source code. I think this works pretty good and we use it at work all the time.

A: I don't know about such particular plug-in, but maybe that you could take a look to what the Communication framework or the Mylin feature offer you in term of collaborative work.

A: If you want to track a TODO-list among a couple of developer, you really want to use a issue-tracking system such as Bugzilla, Trac, or Jira. As soon as you've started to add tasks to it, you'll want features such as sorting on different fields, different kinds of views, etc.
That said, Mylyn is the best way to integrate it into Eclipse.

A: Ive just installed a plugin called fasttrack which is just the kind of thing I was looking for. Works best with SVN, but you can also use it with CVS.


text:
Q: Need to analyze data from Android Wear I want to know what is the best method to transfer data from Android wear for further analysis. Few options I found were to store data on wear's local database or store data on cloud using google cloud Apis. I need to collect data on wear continuously, transfer and analyze that data for further processing.

A: You could quite easily store the pertinent information on the internal storage of the device and then retrieve it manually when you plug the device into your computer. Something like the following would be quick and easy:
public static void AppendLog(String filename, String text)
{
    File log = new File("sdcard/" + filename);
    if (!log.exists())
    {
        try
        {
            log.createNewFile();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    BufferedWriter writer = new BufferedWriter(new FileWriter(log, true));
    String sLogEntry = Log.Tag(severity) + text;
    writer.append(sLogEntry);
    writer.newLine();
    writer.close();
    System.out.println(sLogEntry);
}

This method will create a text file, if one does not already exist, and add the specified information to said text file. Each time you want to add information/data for later retrieval, simply use AppendLog("YOUR_FILENAME.txt", "Information you wish to add") and the data will automatically be added to the log. Then when you plug in your device to the computer you simply retrieve the text file and the data therein. If you use this, make sure to add the WRITE_EXTERNAL_STORAGE permission to your manifest file.
If you do not have access to the wear device, you would need to send the data wirelessly. One possible option is to send a simple email with the text file as an attachment. An easy way to do this would be to integrate ACRA (Application Crash Report for Android) into your application. While this is library is mainly used to send information after a crash, you can use the framework to send information anytime you want. ACRA would make it easy to gather information about the device and send it to a specified email address. You could also manually add your text file to the ACRA report by using the ReportField.APPLICATION_LOG and then specifying:
applicationLogFile = "sdcard/YOUR_FILENAME.txt",
applicationLogFileLines = 1000,

Just make sure that the number you set using applicationLogFileLines is equal or greater than the number of lines you expect to have in your log/data file. I have attached the links to both the quick start guide for adding ACRA to your project, as well as the advanced user guide that discusses topics like manually sending reports without a crash and adding custom information to said report:
http://www.acra.ch/
https://github.com/ACRA/acra/wiki/AdvancedUsage


text:
Q: Mirroring a website with wget based on specific query-string I'm trying to mirror a website with the following URL format:
http://example.com/homepage?page=1
I want to mirror only the ones using the query string from page=1 to page=100. How do I do this as efficient as possible with wget?
I do not need to mirror recursively, only pages 1 to 100. Saving the CSS/JS will also be nice. Excluding images can be great too to keep it fast (only interested in the text).
Help?

A: Create a list of URLs:
seq 1 100 | xargs -n 1 -I {} echo http://example.com/homepage?page={} > URLS.txt

Then download all with wget:
wget -i URLS.txt


text:
Q: Running QField without a Google account I'd like to give QField a try but I can not install it from Google Play Store. I do not want to create a Google account for privacy concerns.
Is there a possibility to install QField without using Play Store and a Google account, for example by using F-Droid?

A: All releases can be downloaded directly from the github page, as stated in the documentation. All .apk packages there are signed.
If someone wants to make the effort of uploading it to F-Droid and keeping it up to date, that will be very welcome. If you want to dig into this best contact the user list or the github issue page to coordinate or for specific questions.


text:
Q: Multiple split equations I find myself again and again using a combination of the gather and aligned environments. So it would be nice to not have to write so much. In particular, it is often only clear after writing the formula, whether it needs splitting.
So the new environment should act like gather, only that when lines are separated by a special symbol/macro (\n for example) they should be put together into an aligned-environment. I tried the following
\documentclass{article}
\usepackage[fleqn]{amsmath}

\newenvironment{multeq}{%
    \let\n{\\}
    \let\\{\end{aligned}\\\begin{aligned}}
    \begin{aligned}
}{%
    \end{aligned}
    \let\\{\n}
}

\begin{document}

    \begin{gather}
        \begin{aligned}
            S(A) &= (I_{n-k, k}AI_{n-k,k})_{i,j} = (I_{n-k,k})_{i,i}A_{i,j}(I_{n-k,k})_{j,j}\\
            &= \begin{cases}A_{i,j}&\begin{aligned}&(i\leq n-k\wedge j\leq n-k)\\\vee&(i>n-k\wedge j>n-k)\end{aligned}\\-A_{i,j}&\text{otherwise}\end{cases}
        \end{aligned}\\
        \Rightarrow H = S(U(n-k)\times U(k))
    \end{gather}

    \begin{multeq}
        S(A) &= (I_{n-k, k}AI_{n-k,k})_{i,j} = (I_{n-k,k})_{i,i}A_{i,j}(I_{n-k,k})_{j,j}\n
        &= \begin{cases}A_{i,j}&\begin{aligned}&(i\leq n-k\wedge j\leq n-k)\n\vee&(i>n-k\wedge j>n-k)\end{aligned}\n-A_{i,j}&\text{otherwise}\end{cases}\\
    \Rightarrow H = S(U(n-k)\times U(k))
    \end{multeq}

\end{document}

where the output should be 2×

but it gives the error:
! LaTeX Error: There's no line here to end.
l.24    \begin{multeq}

How does this error come about and what is a good way to create such an environment?

So using David's corrections, and adding gather:
\newenvironment{multeq}{\begin{gather}%
    \def\n{\\}%
    \def\\{\end{aligned}\\\begin{aligned}}%
    \begin{aligned}%
}{%
    \end{aligned}%
    \end{gather}}

I got
! Paragraph ended before \gather was complete.

So I tried using \Collect@Body from environ:
\def\savebody#1{\def\BODY{#1}}
\usepackage{environ}
\makeatletter

\newenvironment{multeq}{
    \def\n{\\}%
    \def\\{\end{aligned}\\\begin{aligned}}%
    \Collect@Body\savebody
}{\begin{gather}%
    \begin{aligned}%
            \BODY%
    \end{aligned}%
    \end{gather}}

\makeatother

But now the redefinition of \\ is ignored. What else could I do?

A: You need \def not \let \nd you need to get into math mode:
\documentclass{article}
\usepackage[fleqn]{amsmath}

\newenvironment{multeq}{\[%
    \def\n{\\}%
    \def\\{\end{aligned}\\\begin{aligned}}%
    \begin{aligned}%
}{%
    \end{aligned}%
    \]}

\begin{document}

    \begin{gather}
        \begin{aligned}
            S(A) &= (I_{n-k, k}AI_{n-k,k})_{i,j} = (I_{n-k,k})_{i,i}A_{i,j}(I_{n-k,k})_{j,j}\\
            &= \begin{cases}A_{i,j}&\begin{aligned}&(i\leq n-k\wedge j\leq n-k)\\\vee&(i>n-k\wedge j>n-k)\end{aligned}\\-A_{i,j}&\text{otherwise}\end{cases}
        \end{aligned}\\
        \Rightarrow H = S(U(n-k)\times U(k))
    \end{gather}

    \begin{multeq}
        S(A) &= (I_{n-k, k}AI_{n-k,k})_{i,j} = (I_{n-k,k})_{i,i}A_{i,j}(I_{n-k,k})_{j,j}\n
        &= \begin{cases}A_{i,j}&\begin{aligned}&(i\leq n-k\wedge j\leq n-k)\n\vee&(i>n-k\wedge j>n-k)\end{aligned}\n-A_{i,j}&\text{otherwise}\end{cases}\\
    \Rightarrow H = S(U(n-k)\times U(k))
    \end{multeq}

\end{document}

You may need some other changes, depending quite wh\t input markup you want, the above produces

A: After looking at some macro expansions, I found the actual problem. amsmath defines \let\\\math@cr when it expands gather. So whatever I do to \\ beforehand, will not matter. Thus I changed \math@cr et voilá, it works. At least if I collect the body with NewEnviron.
\documentclass{article}
\usepackage[fleqn]{amsmath}
\usepackage{environ}

\makeatletter
\NewEnviron{multeq}{%
    \begingroup
        \let\n\math@cr
        \begin{gather}
            \def\math@cr{\end{aligned}\n\begin{aligned}}
            \begin{aligned}
                \BODY
            \end{aligned}
        \end{gather}
    \endgroup
}
\makeatother

is the needed definition. It also works with align instead of gather or split instead of aligned. And for a simpler usage example:
\begin{document}
\begin{multeq}
    0 + 0 = 0\n
    0 * 0 = 0\\
    1 + 1 = 2\n
    1 * 1 = 1
\end{multeq}
\end{document}

will be printed as


text:
Q: RPy2 robjects.r.pie gives curious error "'x' values must be positive" I'm feeling awfully silly, but I can't seem to work this out. I'm trying to make a pie chart, using rpy2 in Python.
from rpy2.robjects import r
import os.path

image = "test.png"
values = [0.5, 0.5]

print "using R"
r.png(image, width=100, height=100)
r.pie(values)
r.dev_off()

Now, to do the same thing directly in R I know I want this:
values <- (0.5, 0.5)
pie(values)

That works fine in the R interpreter. I've tried using tuples instead of lists in Python, but was told ValueError: Nothing can be done for the type <type 'tuple'> at the moment.
What Python type corresponds to the R vector? Do I need to use numpy?

A: [note: your R code does not appear correct. You probably mean
values <- c(0.5, 0.5)

The use of the function c() matters; see below]
Currently rpy2 does not try to guess how one wants to represent in R a Python list or tuple.
This can be found in the rpy2 documentation.
Use either the R function c() or the rpy2 class FloatVector.


text:
Q: UWP block some notifications when app is in the background I'd like to block some of notifications. I can do it when app is in foreground, using the code below:
var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
channel.PushNotificationReceived += Channel_PushNotificationReceived;

And later:
private void Channel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args)
{
    if (args?.NotificationType == PushNotificationType.Toast)
    {
        if (string.IsNullOrWhiteSpace(args.ToastNotification?.Content?.InnerText))
        {
            args.Cancel = true;
        }
    }
}

But I have no idea how to do it when app is turned off. I tried Notification Listener, but I get access to notifications only when they're already presented.
My question is, how to block some notifications, when app is in the background?

A: You could use Raw Push Notifications (see docs). These are special kind of notifications with no associated UI, but you can create a background task that is triggered whenever such notification arrives. In this task you can then decide if you want the notification to be displayed and in such case create and show the notification directly in code.

A: Because I'm using Azure Notification Hub, I can't use Raw Push Notifications. Eventually I added a tag with device family (uwp, android, ios), and send the notification from hub using syntax tag && !uwp that sends particular notification everywhere but not to uwp.


text:
Q: Transform string into IF argument How to transform a string into a logical argument in Python, to be inserted as an argument of the if() function?
For example:
string = "(A != 0) and (B >= 5)"

How can this string be transformed into the very logic that it represents so that it can be inserted into an if() function?

A: You can use the eval function to evaluate the string:
string = "(A != 0) and (B >= 5)"
if eval(string):
    doSomething()


text:
Q: Angular download SQLite file I have this code which is downloading a file from server, and its working for most of the files except of SQLite *.db file
download(node){
    this.service.downloadFile(node.data.path)
    .toPromise()
    .then(response => this.saveToFileSystem(response, node.data.name));
}

private saveToFileSystem(response, filename) {
    const blob = new Blob([response._body], { /*type: 'application/octet-stream'*/ });
    saveAs(blob ,filename);
}

The *.db file is being downloaded to my computer but when opening it getting:

I tried both, with/without: type: 'application/octet-stream'

A: Worked when I updated the get call in my service to this.http.get(url ,{responseType: ResponseContentType.Blob}):
downloadFile(path){
    var url = this.fileBrowseUrl + "download?path=" + path.replace(/\\/g,"%5C");

    return this.http.get(url ,{responseType: ResponseContentType.Blob})
    .do(/*this.showSpinner = true*/)
    .catch((response: Response) => this.errorHandler(response) );
}

A: This is how I'm downloading file, maybe that will help you:
Component:
this._service.export(column, date)
       .subscribe(
           (data) => { this.openFileForDownload(data);},
           error => { this.errorMessage = <any>error;  },
           () => {  });

openFileForDownload(data: HttpResponse<any>) {
        let filename = data.headers.get('filename');
        saveAs(data.body, filename);}

service:
export(column: string, date: Date) {
        let params = new HttpParams()
            .append('column', column)
            .append('date', date ? date.toISOString() : '')
        let headers = new HttpHeaders({ 'Content-Type': 'application/JSON' });
        return this._http.get<any>(url, { headers: headers, params: params, responseType: 'blob' as 'json', observe: 'response' as 'body' });
    }


text:
Q: Is it possible to turn my code into a list comprehension? also how can i improve my code? Is it possible to turn the part of my code where there is a nested for loop into a list comprehension? also how can i improve my code. What it does is takes a input and displays all the permutations/combos
N = "123123"
s = []
def combos():
    global s
    for i in range(len(N)):
        for j in range(i+1,len(N) + 1):
            s.append(N[i:j])
    s = list(set(s)) # converting to set to remove duplication

combos()

A: Yes, it should be possible to turn this function to a list comprehension. I used the itertools module for this (it's my first time using it, so it may not look "correct" to people more experiencied with it).
However, do you really want all the permutations? Because I'm don't think this is what your function currently does.
Anyways, here's what you could do using itertools.permutations :
s = list(set(["".join(i) for j in range(len(N)+1) for i in itertools.permutations(N, j)]))

Warning : it doesn't output the same result as your function.
Note: you can also try replacing itertools.permutations by itertools.combinations as I'm not quite sure of what you want. The syntax is exactly the same, you literally just have to replace "permutations" by "combinations".
Output for itertools.permutations:
271 substrings - ['', '231132', '122133', '1232', '23131','3', '312123', '131232', '313122', '123', '332', '223311','332211', '1321', '233121', '322113', '23123', '313221', '113223', '212133', '313', '2313', '3311', '311322', '321231', '22131', '2311', '31212', '1323', '1123', '32131', '3221', '32312', '211233', '21233', '321123', '32231', '13321', '323112', '31', '132', '2121', '122', '13122', '1', '232', '121233', '312312', '311232', '213321', '13123', '322131', '1313', '22133', '32112', '231213', '332112', '233211', '123321', '133', '1322', '123312', '132132', '21331', '3123', '131223', '21313', '133221', '21', '3211', '31322', '32213', '32321', '22113', '312132', '1312', '33112', '12231', '22311', '233112', '132123', '13221', '21321', '1213', '12312',
 '13', '1331', '2321', '221133', '23113', '3312', '31232','213132', '23321', '123132', '3322', '122331', '12', '3231', '12331', '321132', '32113', '21132', '323211', '3213', '33122', '113', '13213', '2123', '213', '12133', '21312', '312', '31221', '121323', '331212', '32132', '3121', '13223','223', '1212', '31312', '132321', '3212', '33211', '1223','133212', '221313', '113232', '121332', '231', '131', '12123', '132231', '213213', '121', '321', '33', '33121', '223131', '31231', '123213', '321321', '321312', '231321', '21133', '312321', '322', '11', '2133', '33212', '313212', '331122', '232131', '11232', '21213', '23121', '1233', '3113', '112233', '13322', '23311', '31213', '212331', '323121', '213231', '31321', '11332', '21323', '22331', '31223', '221331', '2312', '1332', '2231', '221', '1132', '23', '1133', '113
23', '2323', '3321', '231123', '1221', '2332', '331', '12233', '23112', '33221', '213123', '23132', '11233', '2233', '323', '312231', '32311', '32123', '211332', '113322', '231312', '132213', '212313', '11322', '223113', '2331', '2', '211', '23231', '332121', '3232', '23213', '322311', '12132', '2113', '233', '23312', '31122', '32121', '12332', '3122', '232311', '13232', '331221', '132312', '13132', '112', '12321', '231231', '3112', '3131', '212', '13212', '2112', '13312', '232113', '1122', '112323', '2132', '3223', '123123', '21231', '31132', '1231', '2211', '23211', '32', '21123','2131', '123231', '321213', '133122', '122313', '112332', '22', '12313', '2213', '131322', '3132', '13231', '311223','12213', '12323', '21332', '31123', '32211', '213312', '312213', '11223', '311', '22313', '211323']


text:
Q: Let SQL write a backup to a workstation's directory I need to write a backup to a workstation directory.
I've granted the sql service domain account read/write/modify rights to the directory.
Msg 3201, Level 16, State 1, Line 2
Cannot open backup device '\\ws10000\c$\temp\Auditor.bak'. Operating system error 5(Access is denied.).
Msg 3013, Level 16, State 1, Line 2
BACKUP DATABASE is terminating abnormally.

If I grant the service account admin rights to the machine it completes successfully.
What additional rights do I need to grant?
Thanks!
edit:  I'm thinking that maybe the account needs to be admin in order to use the c$ (admin) share.  I'll try creating a share.

A: The c$ share is a special administrative share.  Try creating a new share on your workstation and granting the account SQL is using access to it instead.

A: Scheduled backups run as the SQL Server Agent.  The agent needs rights to write to the machine that you want to store data on.  What user does the agent run as, compare and assign the appropriate permissions and you should be ready to go.


text:
Q: What to Use to Pick Multiple files (Media files) and retrieve them in a StorageFile collection at custom/desired index? I have a list in which i retrieve multiple mp3 files. Now when i want to add files again, i pick files from picker but they overwrite the previous files in IReadOnlyList filesList
i want that if i choose files again...then they should go to the next index of filesList
Ex: First time i pick 3 files and they go to filesList[0], filesList[1], filesList[2].
    Now I again click on addmusicbtn to pick files and i pick 2 files. Now what i want is to
    get these files on filesList[3] and filesList[4]. But IReadOnlyList is'nt allowing to do this, it
    starts storing from index 0.
I've also tried IList but it does'nt work with File Picker
    IReadOnlyList<StorageFile> fileList;
    private async void addmusicbtn_Click(object sender, RoutedEventArgs e)
    {
            var fop = new FileOpenPicker();
            fop.FileTypeFilter.Add(".mp3");
            fop.FileTypeFilter.Add(".mp4");
            fop.FileTypeFilter.Add(".avi");
            fop.FileTypeFilter.Add(".wmv");
            fop.ViewMode = PickerViewMode.List;

            fileList = await fop.PickMultipleFilesAsync();

                foreach (StorageFile file in fileList)
                {
                    mlist.Items.Add(file.Name);
                    stream = await file.OpenAsync(FileAccessMode.Read);
                }
                mediafile.SetSource(stream, file.ContentType);
                mediafile.Play();
    }

A: PickMultipleFilesAsync will return the files picked during that instance. If you want to add them to a list of previously picked files then add them to a separate list similar to how you add them to mlist (but save the StorageFile not the path. The StorageFile is much more useful).
Here's a modified version of your code which keeps a cumulative fileList:
List<StorageFile> fileList; // don't forget to initialize this somewhere!
private async void addmusicbtn_Click(object sender, RoutedEventArgs e)
{
        var fop = new FileOpenPicker();
        fop.FileTypeFilter.Add(".mp3");
        fop.FileTypeFilter.Add(".mp4");
        fop.FileTypeFilter.Add(".avi");
        fop.FileTypeFilter.Add(".wmv");
        fop.ViewMode = PickerViewMode.List;

        IReadOnlyList<StorageFile> pickedFileList;

        pickedFileList= await fop.PickMultipleFilesAsync();
        // add the picked files to our existing list
        fileList.AddRange(pickedFileList);

        // I'm not sure if you want fileList or pickedFileList here:
        foreach (StorageFile file in fileList)
        {
            mlist.Items.Add(file.Name);
            stream = await file.OpenAsync(FileAccessMode.Read);
            mediafile.SetSource(stream, file.ContentType);
        }
        mediafile.Play();

}


text:
Q: mysql while loop's the last value for example I have this while loop and gives 4 values:
while($get = mysql_fetch_assoc($result)) {
  echo $get['anything'];
  echo '

';
}

Question: I dont't want class separator to be shown after the last $get['anything'] value. How can I do it ?

A: $iii=1;
while($get = mysql_fetch_assoc($result)) {
  if ($iii!=1) {
    echo '

';
  }
  echo $get['anything'];
  $iii=$iii+1;
}


text:
Q: Why isn't this Linear Regression line a straight line? I have points with x and y coordinates I want to fit a straight line to with Linear Regression but I get a jagged looking line.
I am attemting to use LinearRegression from sklearn.
To create the points run a for loop that randomly crates one hundred points into an array that is 100 x 2 in shape. I slice the left side of it for the xs and the right side of it for the ys.
I expect to have a straight line when I print m.predict.
import numpy as np
import matplotlib.pyplot as plt
import random
from sklearn.linear_model import LinearRegression

X = []
adder = 0
for z in range(100):
    r = random.random() * 20
    r2 = random.random() * 15
    X.append([r+adder-0.4, r2+adder])
    adder += 0.6
X = np.array(X)

plt.scatter(X[:,0], X[:,1], s=10)
plt.show()

m = LinearRegression()
m.fit(X[:,0].reshape(1, -1), X[:,1].reshape(1, -1))

plt.plot(m.predict(X[:,0].reshape(1, -1))[0])

A: I am not good with numpy but, I think it is because the use of reshape() function to convert X[:,0] and X[:,1] from 1D to 2D, the resulting 2D array contains only one element, instead of creating a 2D array of len(X[:,0]) and len(X[:,1]) respectively. And resulting into an undesired regressor.
I am able to recreate this model using pandas and able to plot the desired result. Code as follows
import numpy as np
import matplotlib.pyplot as plt
import random
from sklearn.linear_model import LinearRegression
import pandas as pd
X = []
adder = 0
for z in range(100):
    r = random.random() * 20
    r2 = random.random() * 15
    X.append([r+adder-0.4, r2+adder])
    adder += 0.6
X = np.array(X)

y_train = pd.DataFrame(X[:,1],columns=['y'])
X_train = pd.DataFrame(X[:,0],columns=['X'])

//plt.scatter(X_train, y_train, s=10)
//plt.show()

m = LinearRegression()
m.fit(X_train, y_train)
plt.scatter(X_train,y_train)
plt.plot(X_train,m.predict(X_train),color='red')


text:
Q: Why using AS, while creating ALIAS in FROM causing an error for me? Can we use AS to create an ALIAS in FROM.If no,why? .If yes,is it limited to only few cases?(because I am getting an error in my case)
ALIAS in FROM without AS works perfectly fine
  SELECT a.id_employee FROM(SELECT id_employee FROM table1 union  SELECT id_employee FROM table2) a;

But why ALIAS in FROM using AS creates error 00933. 00000 - "SQL command not properly ended"
  SELECT a.id_employee FROM(SELECT id_employee FROM table1 union  SELECT id_employee FROM table2) as a;

NOTE: Also I came across the oracle: can you assign an alias to the from clause? explanations which used AS . So can ?

A: Oracle does not allow as in the FROM clause.  Oracle only supports as for column aliases.
However, you don't need a subquery for this.  It is simpler to use:
SELECT id_employee FROM table1
UNION
SELECT id_employee FROM table2


text:
Q: Can I use inner select that uses FOR xml Path inside a view SQL Server 2008 R2: can I use an inner select that uses FOR XML PATH inside a view? The purpose of 'relatedProductIDString' is to produce a comma delimited string of IDs in one field.
Here is the inner select
(SELECT
     CAST(productRelated.relatedProductID AS varchar) + ', '
 FROM
     productRelated
 WHERE
     productRelated.parentProductId = productWebSource.ProductWebID
 FOR XML PATH('')) AS relatedProductIDString

Note, it does work when you run it. It allows me to save the view and query the view. But when I open it  in design view three weird things happen:

*

*I get an error in where clause near '(' - Error in order by clause. Unable to pass query text

*the first section is missing, there are no tables in the diagram area

*the second section is missing, there are no fields in the filed list.
This said, click OK to the error described at 1, run my view and the correct results are showing.
Here is the full view for completeness:
SELECT TOP (100) PERCENT
    dbo.productWebSource.ProductWebID AS productID,
    dbo.productWebSource.ProductName AS productName,
    dbo.ProductType.ProductTypeName AS productType,
    dbo.ProductStatus.ProductStatusDesc AS productStatus,
    dbo.productWebSource.metaData,
    dbo.productWebSource.metaDescription,
    dbo.productWebSource.classification,
    dbo.productWebSource.trademarkName,
    dbo.trademarkOwner.title AS trademarkOwnerName,
    dbo.productWebSource.RegCountry AS country,
    dbo.productWebSource.vetExclusive,
    dbo.productWebSource.ProductDesc AS basicDescription,
    dbo.productWebSource.UVPNumber AS uvpNumber,
    (SELECT CAST(productRelated.relatedProductID AS varchar) + ', '
     FROM productRelated
     WHERE productRelated.parentProductId = productWebSource.ProductWebID FOR XML PATH('')) AS relatedProductIDString
FROM
    dbo.ProductType
RIGHT OUTER JOIN
    dbo.productWebSource ON dbo.ProductType.ProductTypeID = dbo.productWebSource.ProductTypeID
LEFT OUTER JOIN
    dbo.ProductStatus ON dbo.productWebSource.ProductStatusID = dbo.ProductStatus.ProductStatusID
LEFT OUTER JOIN
    dbo.trademarkOwner ON dbo.productWebSource.trademarkOwnerId = dbo.trademarkOwner.trademarkOwnerId
WHERE
    (dbo.productWebSource.ProductStatusID < 4)
ORDER BY
    productName

Very weird. It appears to work, can be queried but does not behave in design view and has this error every time I open the view (in design view).  Have I done something that works but is not supposed to?


text:
Q: PHP debugging breakpoint not hit when somebody hits the URL from a different machine I have enabled XDebug and configured PhpStorm like this:

This is my PHP.ini configuration file:
zend_extension = "c:\wamp\bin\php\php5.5.12\zend_ext\php_xdebug-2.2.5-5.5-vc11-x86_64.dll"
[xdebug]
xdebug.remote_enable = on
xdebug.profiler_enable = off
xdebug.profiler_enable_trigger = off
xdebug.profiler_output_name = cachegrind.out.%t.%p
xdebug.profiler_output_dir = "c:/wamp/tmp"
xdebug.show_local_vars=0
xdebug.remote_port=9000

I have put my WAMP online. So anybody could type in my IP:Port combination and the website gets loaded fine. When I visit a URL like my IP:port from my machine the debug breakpoints hit fine. But when somebody else from a different machine hits my IP:port the page is loaded fine but the breakpoints don't get hit on my machine.
I want that whenever somebody hits the URL from a different machine as well my breakpoints should get hit on my machine.
Is there any extra setting that I need to do for that?

A: Try setting remote_host in your php.ini
https://xdebug.org/docs/all_settings#remote_host
I'm guessing this is for testing only, but be aware that it will make you page hang if it's trying to serve more than one request at a time.


text:
Q: url matching /app, /app/.* but not /app-foo Trying to use Java's regexp
I want to match /app, /app/.* , but not /app-foo  .. any hints ?
The  '/app/?.'  doesn't work    and '/app\b/?.' matches /app-foo
any quick soln ?

A: Try this:
/app(?:/.*)?

Explanation:

*

*/app match the "/app" string

*(?: start of a optional group (non capturing)

*

*/.* match any string starting with /

*)? end the optional group


text:
Q: Why don't p-type seismic waves propagate along straight lines in the lower mantle? Can you tell me why seismic waves (p-type shock wave) passing through the earth's lower mantle don't propagate along straight lines in particular?

A: The density and modulus of the Earth changes with depth (as Earth is hotter inside), and this affects the speed of propagation. Just as light refracts when it encounters a change in refractive index, you can think of this change in speed of propagation to change the "refractive index of pressure waves".


text:
Q: How to get nondirectory part of absolute file name? I would like to ask how to get the file name from interactive command in lisp.
Btw, this is taken from another stackoverflow thread.
Paste an image on clipboard to Emacs Org mode file without saving it
(defun markdown-insert-clipboard-image (&optional file)
  (interactive "G")
  (shell-command (concat "pngpaste " file))
  (insert (concat "![" file "](" file ")")))

My problem is the file is using absolute path instead of just the filename causing the file to have an error when pushed to the server.
Instead of yahoocom.png only,
I get
/Users/test/test/test/test/yahoocom.png
I would only want to get
yahoocom.png
Is there anyway that I can modify the code so that it only uses the filename.

A: I think what you are looking for is file-name-nondirectory:

Return file name FILENAME sans its directory.
  For example, in a Unix-syntax file name,
  this is everything after the last slash,
  or the entire name if it contains no slash.

Note that you probably do not want to pass the base name to shell-command (use either the original absolute path or file-relative-name)
PS. I suggest that you replace "G" with "fImage file name: " in your interactive form because your function will fail if the file does not exist.

A: While sds's answer indeed gives what you directly asked for, I think what you're really looking for might be to have the relative name of the file (which will be just the same if the file is in the current working directory).  If so, try file-relative-name:

Convert FILENAME to be relative to DIRECTORY (default: default-directory).
  This function returns a relative file name that is equivalent to FILENAME
  when used with that default directory as the default.
  If FILENAME is a relative file name, it will be interpreted as existing in
  default-directory.
  If FILENAME and DIRECTORY lie on different machines or on different drives
  on a DOS/Windows machine, it returns FILENAME in expanded form.


text:
Q: A commutative ring whose all localizations are fields If $A$ is a ring such that $A_{p}$ is a field for every prime ideal $p\subseteq A$, is $A$ a field?

A: The answer is no.  Take $A$ to be a product of two fields.  Notice that, here, $A$ isn't even a domain.  So, we've shown not only that being a field isn't a local property, but being a domain isn't a local property, either.


text:
Q: Unable to use Laravel Eloquent findOrFail method using call_user_func_array function I have searched how to use call_user_func_array with Eloquent method. But didn't find any clue about it.
I want to make my code more flexible using call_user_func_array method in my Eloquent query.
Code not working:-
$object = call_user_func_array($this->object_type . '::findOrFail', [$this->object_slug]);

Error:-
ErrorException (E_UNKNOWN)
call_user_func_array() expects parameter 1 to be a valid callback, class 'Friendship' not found.
But if I am not using call_user_func_array method, then my below code is running fine:-
$object = Friendship::find($this->object_slug);

Please guide me whether static callback method  be used in call_user_func_array function? If not then please suggest any alternate approach.

Problem Solved:-
call_user_func_array method don't care about use namespaces. So in case of namespaces add full path of class.
Updated code:-
call_user_func_array('\SiteApp\Friendship\\' . $this->object_type . '::findOrFail', [$this->object_slug]);
Thanks for help :)

A: Apparently call_user_func_array() doesn't care about use statements for importing classes so you have to use the fully qualified class name:
call_user_func_array('\SiteApp\Friendship\Friendship::findOrFail', [$this->object_slug]);

It depends on your case but the simplest would probably be to store the full name in $this->object_type.
// $this->object_type = '\SiteApp\Friendship\Friendship';
call_user_func_array($this->object_type . '::findOrFail', [$this->object_slug]);


text:
Q: FullCalendar: how to get data from db and show in events (as a json feed) I am a newbie to fullcalendar and ajax. I have difficulty in fetching data from the database and those data should be shown up in my fullcalendar.
    I have tried a code to do the same. but i am not able to get data through ajax as a json feed.
    So far i am getting data from the database through codeigniter MVC. but i
    coulnt pass data to the fullcalendar event.
 The following is my view file: calendar.php

<script>
$(document).ready(function() {

$.ajax({
    url: "<?php echo base_url() ?>/common/calendar/show_holidays",
    type: 'POST', // Send post data
    data: 'type=fetch',
    async: true,
    success: function(s){
          freshevents = s;//alert(s);
    }
});

$('#calendar').fullCalendar('addEventSource', JSON.parse(freshevents));

    /* initialize the calendar
    -----------------------------------------------------------------*/

    $('#calendar').fullCalendar({
        //events: JSON.parse(json_events),
        //events: [{"id":"14","title":"New Event","start":"2015-01-24T16:00:00+04:00","allDay":false}],
        utc: true,
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        editable: true,
        droppable: true,
        events: {

        }

    });

   });
    </script>

A: First you need to parse SQL resultset to JSON, you can do that with the next PHP functions:
Connect to DB function:
function connectDB(){
   $con = mysqli_connect("HOST", "USER", "PASS", "DB");
    if($con){
        echo 'OK';
    }else{
        echo 'KO';
    }
    return $con;
}

Function to disconnect from DB:
function disconnectDB($con){
    $close = mysqli_close($con);

    if($close){
        //echo 'OK';
    }else{
        //echo 'KO';
    }
    return $close;
}

Function to get JSON parse from one resultset:
function getArraySQL(){
    $conexion = connectDB();
    //generate SQL query
    if(!$result = mysqli_query($conexion, "SELECT title,color,start FROM events")) die();

    $rawdata = array();

    while($row = mysqli_fetch_array($result))
    {
        $title=$row['title'];
        $color=$row['color'];
        $start=$row['start'];

        $rawdata[] = array('title'=> $title, 'color'=> $color, 'start'=> $start);
    }
    disconnectDB($conexion);
    //Parse to JSON and return
    $rawdata=json_encode($rawdata);
    return $rawdata;
}

After this step, you can include JSON returned into your events calendar script:
$(document).ready(function() {
    $('#calendar').fullCalendar({
        header: {
          left: 'prev,next today',
          center: 'title',
          right: 'month,agendaWeek'
        },
        events: <?php
        $result = array();
        $result=getArraySQL();
        if(isset($result)){
            echo $result;
        }
        ?>,
        eventRender: function (event, element) {
        element.attr('href', 'javascript:void(0);');
        element.click(function() {
            alert(event.title);
        });
    }
    });

});

Hope this can help you.


text:
Q: How to reorder a CSV's rows based on order of appearance of unique values with bash/unix tools? I've used Python to parse a large test result file of flight data, but need to reorder its rows by grouping the same values together, in order of appearance.
The CSV is currently ordered:
 (Flight ID)                  (Trajectory Data)
20110117559515, , , , , , , , ,2446,6720,370,42  (Time 0)
20110117559572, , , , , , , , ,2390,6274,410,54  (Time 0)
20110117559574, , , , , , , , ,2391,6284,390,54  (Time 0)
20110117559587, , , , , , , , ,2385,6273,390,54  (Time 0)
20110117559588, , , , , , , , ,2816,6847,250,32  (Time 0)
...

where every unique ID is listed with its current trajectory data at one point in time.  This order then repeats with new trajectory data for every minute these flight are in the air.
The way I need it reordered is:
20110117559515, , , , , , , , ,2446,6720,370,42  (Time 0)
20110117559515, , , , , , , , ,24xx,67xx,3xx,42  (Time 1)
20110117559515, , , , , , , , ,24xx,67xx,3xx,42  (Time 2)
20110117559515, , , , , , , , ,24xx,67xx,3xx,42  (Time 3)
20110117559515, , , , , , , , ,24xx,67xx,3xx,42  (Time N)
20110117559572, , , , , , , , ,2390,6274,410,54  (Time 0)
20110117559572, , , , , , , , ,23xx,62xx,4xx,54  (Time 1)
20110117559572, , , , , , , , ,23xx,62xx,4xx,54  (Time 2)
... and so on

I've written another Python script to handle this job, but because of the large file size, it takes 3-4 hours.  I would like to find the way of doing this with bash/unix tools, which I am unfamiliar with in this context, and was looking at something along the lines of the sort utility:
sort -n -s -t, -k1,1 infile.csv > outfile.csv

-t sets the delimiter, -k sets the sort key, -s stabilizes the sort, and -n uses numeric comparison.
Any ideas?  (I'll look to add rep if you can use a one-liner).
Clarification:
I want all the details for the first flight that appears in the input data file grouped together at the start of the output file; then you want all the details for the second flight number that appears in the input file grouped together next, and repeat ad nauseam. – Jonathan Leffler

A: I think you'll need to preprocess the file to impose an ordering, sort it using the imposed ordering, and then remove the ordering information.  The awk script has spaces removed so it fits on one line in SO without the horizontal scroll bar — it hurt to remove the spaces.
awk -F, '{if(order[$1]==0)order[$1]=++counter;print order[$1]","$0;}' infile.csv |
sort -t, -s -k1,1n |
sed 's/^[^,]*,//'

This looks to see whether the flight number (field $1) has been seen before.  If not, it is allocated a new sequential number.  The record is then output with the sequential number at the start of the line, followed by a comma and the original record.  The output is sorted stably (it would be possible to modify the awk so that you got stable sorting even if the sort program did not support that).  Then the sorted output has the sequential number removed; I chose to use sed but cut or awk or a number of other programs could be used instead.
I tested with the input file shown below, which is based on the data in the question, but I've reordered things so that the file '587 and '588 appear before '572 in the input (so it is a more acid test of the sorting) and I also made each line unique by setting the last digit in the fourth trajectory column to a distinct value for each record (but the values were in descending order so that if the sort was working on the data, it would be out of order).
20110117559515, , , , , , , , ,2446,6720,370,42
20110117559587, , , , , , , , ,2385,6273,390,54
20110117559588, , , , , , , , ,2816,6847,250,32
20110117559572, , , , , , , , ,2390,6274,410,54
20110117559574, , , , , , , , ,2391,6284,390,54
20110117559515, , , , , , , , ,24xx,67xx,3xx,49
20110117559515, , , , , , , , ,24xx,67xx,3xx,48
20110117559572, , , , , , , , ,2390,6274,410,59
20110117559515, , , , , , , , ,2446,6720,370,47
20110117559515, , , , , , , , ,24xx,67xx,3xx,46
20110117559515, , , , , , , , ,24xx,67xx,3xx,45
20110117559572, , , , , , , , ,23xx,62xx,4xx,58
20110117559572, , , , , , , , ,23xx,62xx,4xx,57

This output looks correct to me:
20110117559515, , , , , , , , ,2446,6720,370,42
20110117559515, , , , , , , , ,24xx,67xx,3xx,49
20110117559515, , , , , , , , ,24xx,67xx,3xx,48
20110117559515, , , , , , , , ,2446,6720,370,47
20110117559515, , , , , , , , ,24xx,67xx,3xx,46
20110117559515, , , , , , , , ,24xx,67xx,3xx,45
20110117559587, , , , , , , , ,2385,6273,390,54
20110117559588, , , , , , , , ,2816,6847,250,32
20110117559572, , , , , , , , ,2390,6274,410,54
20110117559572, , , , , , , , ,2390,6274,410,59
20110117559572, , , , , , , , ,23xx,62xx,4xx,58
20110117559572, , , , , , , , ,23xx,62xx,4xx,57
20110117559574, , , , , , , , ,2391,6284,390,54

You could probably do the whole thing in Perl fairly fast, too.  66 MiB is hardly an exorbitant amount of data to keep in memory in a machine that has one or more GiB of RAM.
This Perl script (genflights.pl) creates about 69 MiB of data:
#!/usr/bin/env perl
use strict;
use warnings;

my $seq = 1000000;

for my $time (0..1500)
{
    for my $flight (0..1000)
    {
        my $r0 = int(rand(1000)) + 20110117559000;
        my $r1 = int(rand(10000));
        my $r2 = int(rand(10000));
        my $r3 = int(rand(1000));
        my $r4 = int(rand(100));
        printf "%s, , ,%07d, ,%04d,%04d,%03d,%02d\n", $r0, ++$seq, $r1, $r2, $r3, $r4;
    }
}

The first few lines of output from one run were:
20110117559486, , ,1000001, ,2670,6847,792,91
20110117559489, , ,1000002, ,0278,1929,972,25
20110117559845, , ,1000003, ,9169,4915,145,21
20110117559356, , ,1000004, ,3519,1660,106,97
20110117559976, , ,1000005, ,8988,7830,884,64
20110117559446, , ,1000006, ,7459,7458,791,93
20110117559442, , ,1000007, ,7265,5853,012,41
20110117559686, , ,1000008, ,4624,0682,859,32
20110117559081, , ,1000009, ,3624,0264,017,06
20110117559336, , ,1000010, ,6501,9033,329,33
20110117559869, , ,1000011, ,5020,3008,919,96
20110117559047, , ,1000012, ,5747,4140,693,83
20110117559531, , ,1000013, ,0591,1866,482,68
20110117559355, , ,1000014, ,2254,2731,946,99
20110117559952, , ,1000015, ,0941,0531,743,85

It took about 3 seconds to generate 69 MiB (file flights). I then ran the script above (with the output redirected to a file flights.out) under 'time' and got the output:
+ awk -F, '{if(order[$1]==0)order[$1]=++counter;print order[$1]","$0;}' flights
+ sort -t, -s -k1,1n
+ sed 's/^[^,]*,//'

real    0m8.658s
user    0m7.881s
sys     0m0.441s

Under 10 seconds for the processing of 69 MiB.
-rw-r--r--  1 jleffler  staff  69115046 Mar 13 09:04 flights
-rw-r--r--  1 jleffler  staff  69115046 Mar 13 09:06 flights.out

The output file started:
20110117559486, , ,1000001, ,2670,6847,792,91
20110117559486, , ,1001621, ,2274,5287,188,57
20110117559486, , ,1001642, ,2716,6983,778,49
20110117559486, , ,1002791, ,1704,9426,430,05
...
20110117559486, , ,2501369, ,4900,8239,048,70
20110117559486, , ,2501850, ,7114,8721,684,40
20110117559489, , ,1000002, ,0278,1929,972,25
20110117559489, , ,1000090, ,0114,7462,862,55
20110117559489, , ,1000904, ,7780,8559,121,47
20110117559489, , ,1001499, ,9320,8459,592,01
...
20110117559489, , ,2499635, ,5199,8313,668,30
20110117559489, , ,2499955, ,3386,6280,102,19
20110117559489, , ,2500748, ,5740,6370,594,15
20110117559489, , ,2501534, ,1222,9866,714,24
20110117559845, , ,1000003, ,9169,4915,145,21
20110117559845, , ,1000220, ,5341,8347,724,25
20110117559845, , ,1000295, ,5722,4031,045,11
...

This is running on a 2.3 GHz Intel Core i7 MacBook Pro, 16 GiB RAM, Mac OS X 10.7.5.

A: Here's my attempt at a solution.
#!/bin/bash
declare -a ids
declare -A flights
i=0
while IFS= read -r line;
do
   id=$(echo $line | cut -d, -f1)
   if [[ -z ${flights[$id]} ]]; then
       flights[$id]=$line
       ids[$i]=$id
       i=$((i+1))
   else
       flights[$id]=${flights[$id]}$'\n'$line
   fi
done < infile.csv
for id in "${ids[@]}"
do
    echo "${flights[$id]}"
done > outfile.csv

This uses an associative array flights to build a string containing all the info for each flight. Also, it uses a normal array ids that keeps track of the order in which flights appear in the file.
To output, we just iterate through the ids array and keep printing the strings from flights array.
This doesn't try to do any kind of sorting and also reads through the file only once.

A: Totally different approach
awk -F',' '{print $0 >> $1;close($1)}' ~/Downloads/newtrajectory.csv

Need to use close() on the file, since there are to many to keep them all open.
The awk-script above will output as many files as there are unique Flight IDs
i.e, the file 20110117559515 will contain all items for that id and so on.
Its almost as  fast as the sort approach, ~5s for a 200k-lines test file.
As a post-process-step, use cat and a for-loop to concatenate everything into a single file.
To get the first unique ids:
NR>1{
  a[$1]+=1
  if (a[$1] == 2) {
    exit
  }
  else {
    print $1
  }
}

Then you can use a simple while-loop to concatenate everyting
 while read line; do cat $line >> final.csv; done < cnt.txt

output:
$ head final.csv
20110117559572, , , , , , , , ,2390,6274,410,54
20110117559572, , , , , , , , ,2391,6268,410,101
20110117559572, , , , , , , , ,2392,6261,410,144
20110117559572, , , , , , , , ,2394,6254,410,183
20110117559572, , , , , , , , ,2395,6247,410,219
20110117559572, , , , , , , , ,2397,6240,410,251
20110117559572, , , , , , , , ,2399,6232,410,279
20110117559572, , , , , , , , ,2400,6223,410,304
20110117559572, , , , , , , , ,2402,6215,410,326
20110117559572, , , , , , , , ,2404,6207,410,347

which looks ok to me.
Some timings:
$ time awk -F',' '{print $0 >> $1;close($1)}' ~/Downloads/newtrajectory.csv

real    0m14.534s
user    0m4.096s
sys     0m10.101s

$ time awk -F',' -f u.awk ~/Downloads/newtrajectory.csv > cnt.txt

real    0m0.008s
user    0m0.000s
sys     0m0.008s

$ time while read line; do cat $line >> final.csv; done < cnt.txt

real    0m4.282s
user    0m0.236s
sys     0m1.028s


text:
Q: Making Konsole to be login shell by default I don't know why there are "login" and "non-login" shells in the first place, and i'm not very eager to know.
The fact is that the RVM and NVM software that i use frequently require login shells, and Konsole starts a non-login shell.
This forces me to submit a  bash -l command every time i start a Konsole.
How do i make Konsole start in login shell mode by default?

A: The Konsole Handbook:

Konsole doesn't provide convenience for running login shell, because
  developers don't like the idea of running login shell in a terminal
  emulator.
Of course, users still can run login shell in Konsole if they really
  need to. Edit the profile in use and modify its command to the form of
  starting a login shell explicitly, such as "bash -l" and "zsh -l".


text:
Q: Adding textboxes over the panel height So I need to add textboxes to a panel with a click of a button. Every click adds one textbox under the last one and so on. But when it goes over the panel height it suddenly makes bigger space between the texboxes even though the int is still the same.
Here's my code so far.
List<TextBox> textboxes = new List<TextBox>();
private void button1_Click(object sender, EventArgs e)
{
    tbY += 30;
    TextBox tb = new TextBox();
    tb.Left = 3;
    tb.Top = tbY;
    tb.Font = new Font("Verdana", 12, FontStyle.Bold);
    tb.Size = new Size(325, 25);
    tb.BorderStyle = BorderStyle.None;
    button1.Top = tbY;
    panel1.Controls.Add(tb);
    textboxes.Add(tb);
    ScrollToBottom(panel1);
}

A: The Top of a Control is calculated relative to the scroll position of its Parent.
You are always scrolling to the bottom of your Panel, so you need to set it like this, taking the curent scroll position into account:
tb.Top = tbY + panel1.AutoScrollPosition.Y;

Note that the AutoScrollPosition.Y is negative when you have scrolled downward, so we need to add it!

A: You might as well use a flowLayoutPanel for this purpose. Use the following properties on your flowLayoutPanel and it'll work as you intend. (without having to do the manual calculation)
        List<TextBox> textboxes = new List<TextBox>();
        public Form1()
        {
            InitializeComponent();
            flowLayoutPanel1.FlowDirection = FlowDirection.TopDown;
            flowLayoutPanel1.WrapContents = false;
            flowLayoutPanel1.AutoScroll = true;
        }
        private void button1_Click(object sender, EventArgs e)
        {

           TextBox tb = new TextBox();
            tb.Left = 3;
            tb.Font = new Font("Verdana", 12, FontStyle.Bold);
            tb.Size = new Size(325, 25);
            tb.Text = tb.Top.ToString();
            tb.BorderStyle = BorderStyle.None;
            flowLayoutPanel1.Controls.Add(tb);
            textboxes.Add(tb);

        }


text:
Q: Connect TSOP to prolifc serial I have a prolifc USB to serial cable that I want to use to recieve infrared signals coming from a TSOP Sensor
I saw it is possible to connect a classic rs232 connector with TSOP here.
How can I connect it without damaging something ?

A: You most probably can't do that. The standard software for a TSOP-RS232 combo relies on the ability to read the hardware serial port very fast. An usb-to-serial cable does not offfer this option, it only offers a windows serial port interface, not the serial port hardware (register level) interface.
One option is to have a microcontroller read out the TSOP and send the decoded information to the PC, like shown here.


text:
Q: Using Indeterminate Progressbar with Backgroundworker in WPF I created a little tool for importing and converting data from one database to another. Since this takes a lot of time, I wanted to display some kind of progress for the user with a indeterminate progressbar.
As long as the import is running, the progressbar should be running too.
I used this site as reference : The ProgressBar control but I got trouble understanding the role of the DoWork-Method since the option for a indeterminate progressbar is set once.
I came up with a solution that works halfway, I can't stop the animation after the import's done.
Could someone help me out?
XAML:
 <ProgressBar Minimum="{Binding Path=Minimum}" Maximum="100" IsIndeterminate="{Binding Path=IsIndeterminate}" Height="20" Grid.Column="2" Grid.Row="5" Grid.ColumnSpan="2"/>

ViewModel:
public void StartImportThread()
    {
        ButtonsEnabled = false;
        var th = new Thread(new ThreadStart(StartImport));
        th.IsBackground = true;
        th.Start();
    }
public void StartImport()
    {
        _threadDispatcher = Dispatcher.CurrentDispatcher;
        BackgroundWorker worker = new BackgroundWorker();
        worker.WorkerReportsProgress = true;
        worker.WorkerSupportsCancellation = true;
        worker.DoWork += worker_DoWork;
        worker.RunWorkerCompleted += worker_Complete;

        worker.RunWorkerAsync();

        // Doing Import Stuff
        worker.CancelAsync(); // Import finished
        ButtonsEnabled=true;
    }
    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
       // while(true)
     //  {
          Minimum = 0;
          IsIndeterminate = true;
    //   }

    }

    private void worker_Complete(object sender, RunWorkerCompletedEventArgs e)
    {
       // if (e.Cancelled)
       // {
            IsIndeterminate = false;
            Minimum = 100;
       // }

    }

A: Here is what works for me. RelayCommand and ViewModelBase are from MvvmLight library, the DoWorkCommand is called by a button:
        <Button Name="BtnReload" Command="{Binding DoWorkCommand}" Width="75" Height="25"/>
        <ProgressBar Minimum="{Binding Path=Minimum}" Maximum="100" IsIndeterminate="{Binding Path=IsIndeterminate}" Height="20"/>

   public class MainViewModel : ViewModelBase {

    private RelayCommand _doWorkCommand;
    private bool _isIndeterminate;
    private int _minimum;
    private Dispatcher _threadDispatcher;

    public int Minimum {
        get { return _minimum; }
        set {
            _minimum = value;
            RaisePropertyChanged(nameof(Minimum));
        }
    }

    public bool IsIndeterminate {
        get { return _isIndeterminate; }
        set {
            _isIndeterminate = value;
            RaisePropertyChanged(nameof(IsIndeterminate));
        }
    }

    public MainViewModel(IDataService dataService) {

    }

    public void StartImportThread() {
        //  ButtonsEnabled = false;
        var th = new Thread(new ThreadStart(StartImport));
        th.IsBackground = true;
        th.Start();
    }

    public void StartImport() {
        _threadDispatcher = Dispatcher.CurrentDispatcher;
        BackgroundWorker worker = new BackgroundWorker();
        worker.WorkerReportsProgress = true;
        worker.WorkerSupportsCancellation = true;
        worker.DoWork += worker_DoWork;
        worker.RunWorkerCompleted += worker_Complete;

        worker.RunWorkerAsync();

        // Doing Import Stuff
        worker.CancelAsync(); // Import finished
        //   ButtonsEnabled = true;

    }

    void worker_DoWork(object sender, DoWorkEventArgs e) {
        Minimum = 0;
        IsIndeterminate = true;
        //for (int i = 0; i < 30; i++) {
        //    Thread.Sleep(100);
        //}
    }

    void worker_Complete(object sender, RunWorkerCompletedEventArgs e) {
        IsIndeterminate = false;
        Minimum = 100;
    }

    public RelayCommand DoWorkCommand => _doWorkCommand ??
        (_doWorkCommand = new RelayCommand(() => StartImportThread()));

}


text:
Q: How to access/expose Inventory Item Locations sublist fields in Suitescript I have the multiple locations feature enabled and multi-location inventory. I need a way to set or retrieve location-specific values, such as Location On Hand, Location Next Count Date, Location Last Count Date, Location Inventory Count Interval.
These fields are accessible through the Saved Search interface, but there is no documentation on SuiteAnswers on how to get at them through SuiteScript APIs. The SuiteScript Records browser does not have entries for accessing this sublist. How can I set or retrieve values with the SuiteScript API without using searches?
Specifically, I want to be able to load a record, set the Next Inventory Count date for a specific location, and then submit and close and actually see the changes in Netsuite. Currently the only workaround I've found is awkwardly building a CSV file in suitescript and submitting that with the job manager, but that has its own limitations.

A: The sublist name is undocumented and not officially supported, but you can still access it with the sublist ID "locations", IE
//load arbitrary item record
var itemRec = nlapiLoadRecord('inventoryitem', 655009)

//find the line with location internal ID 1
var line = itemRec.findLineItemValue('locations','location',1);
//get that line's location count interval
var countinterval = itemRec.getLineItemValue('locations', 'invtcountinterval', line);

//calculate the next count date as today + interval, set up the
//last count date as a string
var lastCountDate = nlapiDateToString(new Date());
var nextCountDate = new Date() + countInterval*MILLISECONDS_IN_DAY;
nextCountDate = nlapiDateToString(nextCountDate);

//set the values on the item
itemRec.setLineItemValue('locations','lastinvtcountdate', line, lastCountDate);
itemRec.setLineItemvalue('locations','nextinvtcountdate', line, nextCountDate);

nlapiSubmitRecord(itemRec);

You can discover the field names for the sublist by using something like "Inspect Element" in chrome on the sublist interface. For example, right click on the "Next Inventory Count Date" header on the locations sublist of any item, and click "Inspect Element". Looking at the div.listheader that comes up, right above that you will see something like

.elements['locationssortfld'].value='nextinvtcountdate'

The 'nextinvtcountdate' would be the field ID that you plug in to the field argument of nlapiSetLineItemValue.
Hope that helps someone. I had a hell of a time figuring this out by myself  the first time around, although it seems more obvious now.

A: You can also access the fields you want from a search using these field ids.
new nlobjSearchColumn("locationquantityavailable",null,null)
new nlobjSearchColumn("locationquantityonhand",null,null)
new nlobjSearchColumn("locationlastinvtcountdate",null,null,
new nlobjSearchColumn("locationnextinvtcountdate",null,null)
new nlobjSearchColumn("locationinvtcountinterval",null,null)


text:
Q: overlaying text on image with flickity? using flickity, how do i overlay vertically and horizontally aligned text on some images?
here is my jade:
.gallery
  .cell
    h2 One
    img(src="01.jpg")
  .cell
    h2 Two
    img(src="02.jpg")
  .cell
    h2 Three
    img(src="03.jpg")

and my js:
$(document).ready(function(){

$('.gallery').flickity({
autoPlay: 3000,
prevNextButtons: false

});
});

I tried this but the second and third images appear shrunk. Any clues?


text:
Q: Visual studio - running X number of instances of a project I know in VS 2013 it is possible to run multiple projects at once, but I need to start a single project with multiple instances (would like to be able to set the number).
The purpose for this requirement is I need to test code that interacts with a server component and want to test its safety if multiple clients are picking at it at, if they make concurrent requests, etc.
To clarify, I want to start X number of project instances at once.

A: You just start the instance without debugging: DEBUG -> Start Without Debugging (or Ctrl+F5). You can start another instance without debugging while one is already running. This way you can have several instances at the same time.
EDIT:
You can always invoke the exe from a command line and have a script looping through it several times. The command below did the trick for me:
for %i in (1 2 3 4 5) DO myApp.exe

If you are running a command line program to have it in separate command line windows you start it with start cmd /k
for %i in (1 2 3 4 5) DO start cmd /k myApp.exe

Only probably use an absolute path to run your program because the new command line dialog is oppened in a default directory. And apply /k switch which will execute the program after the command line is opened.

A: You can use Process.Start() from the System.Diagnostics namespace, and within Main(string[] args) check if args has any data.  One of those elements, depending how the arguments are passed in, would be the number of times the program needs to launch itself.  Use that argument in a loop and launch the program again without startup arguments
public static void Main(string[] args)
{
    if (args.Length > 0)
    {
        // First element is the number of times to launch itself
        int numberOfClients = Convert.ToInt32(args[0]);

        // Launch the same application multiple times
        for (int i = 0; i < numberOfClients; i++)
        {
            Process.Start(System.Reflection.Assembly.GetEntryAssembly().Location);
        }
    }

    Console.WriteLine("I've been launched");
    Console.ReadLine();
}

Setting command line arguments from Command Prompt
MyApp.exe 5

Setting command line arguments within Visual Studio


text:
Q: How do you prevent DHT spill with Bittorrent? I have a small network that I want to serve with a Bittorent tracker. It's important, though, that information shared in this network doesn't accidentally spill out with Distributed Hash Tables, allowing unknown peers to accumulate. I have at my disposal all the regular features of a tracker, but I don't know of a way to enforce the clients connecting to disable certain controls (namely, DHT) and expose others in the swarm to outside connections.
Does a control like that exist in the protocol specification? If not, what would be involved in implementing it?

A: If you can't trust the client, then you can't trust the client!
That said, if you can trust the clients to a certain extent, then there is a feature that does what you want. From the wikipedia article:

After the DHT was adopted, a "private" flag — analogous to the broadcast flag — was unofficially introduced, telling clients to restrict the use of decentralized tracking regardless of the user's desires. The flag is intentionally placed in the info section of the torrent so that it cannot be disabled or removed without changing the identity of the torrent. The purpose of the flag is to prevent torrents from being shared with clients that do not have access to the tracker. The flag was requested for inclusion in the official specification in August, 2008, but has not been accepted. Clients that have ignored the private flag were banned by many trackers, discouraging the practice.

If you are willing to trust the clients to honor the "private" flag, then all you need to do is set that flag.


text:
Q: Zend\Mail headers: Call to a member function setType() on a non-object When trying to set content-type in Zend\Mail message:
use Zend\Mail\Message;
.
.
.
// create the message
$message = new Message();
$message->getHeaders()->get('content-type')->setType('multipart/alternative');
.
.
.

I get the following error:
Fatal error: Call to a member function setType() on a non-object in /var/www/jt_sso/website/app/library/Mail/Manager.php on line 125

Is there something I should do if this header is missing. I notice Zend\Mail\Headers (result of getHeaders() ) has a ::has(headerName) method so I could check if this method exists, but I can't see a method to set a new header if it's missing. Also, can't I just set the message (and create one if it doesn't exist)? When I look at examples online, I just see the get()->setType(..) method chain.

A: This is happening becuase the header 'content-type' is not defined, so you have to define it.
For example :
$message->getHeaders()->addHeaderLine('content-type', 'multipart/alternative');

This should add the missing header and set the
type you want for it.


text:
Q: Get the text value of OCI-LOB in PHP I have a column in the DB which is of type CLOB and I can't get the value in PHP as it is shown as

"resource id='204' type='"oci8 descriptor"'".

My adapter code:
 $this->_db->fetchRow(
                    $this->_db->select()
                        ->from(self::TABLE_NAME, array(
                            'BODY'
                        ))

A: This is covered in The Underground PHP and Oracle Manual, page 234 "Fetching LOBs". Here's the example from that page:
<?php
$c = oci_connect('hr', 'welcome', 'localhost/XE');

$myblobid = 123;

$query = 'select blobdata from mybtab where blobid = :myblobid';
$s = oci_parse($c, $query);
oci_bind_by_name($s, ':myblobid', $myblobid);
oci_execute($s);
$arr = oci_fetch_array($s, OCI_ASSOC);
if (is_object($arr['BLOBDATA'])) { // protect against a NULL LOB
    $data = $arr['BLOBDATA']->load();
    $arr['BLOBDATA']->free();
    echo $data;
}
?>

I would advise reading the manual page yourself as there is important advice about avoiding memory leaks and returning LOB data as a string.


text:
Q: Solve for $z$ in $4z^2+8|z|^2-3=0$ $$4z^2+8|z|^2-3=0$$
I have to find $z$.
$|z|^2 = z\cdot \bar{z}$, but I don't know if this helps in this situation.

A: You can prove first that $z^2$ is real, and then use the fact that $|z|^2=|z^2|$.
Can you find $z^2$ then?


text:
Q: Export "Local" Excel File to a SQL Server Table I want to import data from excel to SQL SERVER using queries,not by using wizard. I tried this query
Select PerCode,'1395/01',Day1,Day2,Day3,Day4,Day5,...,Day30,Day31
From OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                'Excel 12.0;Database=D:\TimeSheet.xls;',
                'SELECT PerCode,Day1,Day2,Day3,Day4,Day5,...,Day30,Day31 FROM [Sheet1$]')

The important point is, I can use a local Path on a client, not on server.
Is there any way?


text:
Q: How to ration amount in purely functional style I need to distribute certain amounts to array of people according to their score. The rule is that their demands are met according to their position with whatever remains.
In JavaScript using Lo-Dash (JSBin):
var amount = 1000,
  people = [
    { name : 'Joe', score: 40, demand: 400},
    { name : 'Sue', score: 30, demand: 350},
    { name : 'Kim', score: 25, demand: 300},
    { name : 'Ron', score: 20, demand: 250}
  ];

function  distribute(people, amount){
   return _.map(_.sortBy(people,'need'),function(person){
     var ration = Math.min(person.demand,amount);
     amount -= ration; // This is the state (mutation) that I want to avoid
     return _.assign(person,{ ration: ration})
 });
}
console.log(distribute(people, amount));

Result:
[{  demand: 400,  name: "Joe",  ration: 400,  score: 40},
 {  demand: 350,  name: "Sue",  ration: 350,  score: 30},
 {  demand: 300,  name: "Kim",  ration: 250,  score: 25},
 {  demand: 250,  name: "Ron",  ration:   0,  score: 20}]

Since the solution depends on the order,  is it possible to change this code to make it purely functional?

A: The functional solution is a fold:
function distribute(people, amount) {
  return _.foldl(_.sortBy(people, 'score'), function(result, person) {
    var ration = Math.min(person.demand, result.remaining);
    var resultPerson = _.assign(person, { ration: ration });
    return { people: result.people.concat(resultPerson),
             remaining: result.remaining - ration };
  }, { people: [], remaining: amount }).people;
}


text:
Q: Why is {key : "value"} different from {"key" : "value"}? Directly from the node REPL:
> d1 = {key : "value"}
{ key: 'value' }
> d2 = {"key" : "value"}
{ key: 'value' }
> d1 == d2
false

Why is d1 different from d2 ?

A: It isn't, you'd get the same result if you just repeated the first line with d2 instead of d1. However, the two objects you're creating are different objects, and so they are not ==. == with object references checks to see if the two operands refer to the same object (Section 11.9.3 of the spec). What you have there is two objects which both have a property called key with the value "value".

A: Because they are two different objects. It's not comparing the members of the object.

A: They aren't the same object. You're doing a reference equality comparison, not a value comparison.


text:
Q: Command for paragraph indentation after equations I want to write two new commands \eqend and \eqcntd so that when I put the command at the end of an equations,

*

*The \eqend command puts a "." after the equation and forces the next paragraph to indent, regardless of the number of blank lines after the equation.

*The \eqcntd command puts a "," after the equation and forces the next paragraph not to indent, regardless of the number of blank lines after the equation.

This is a sample usage,
\begin{equation}
f(x) = x^2 + 1 \eqend
\end{equation}
Some text here, but it's gonna get indented.

and another one,
\begin{equation}
f(x) = x^2 + 1 \eqcntd
\end{equation}

Some text here, but it's not gonna get indented.

Here is my NOT-WORKING solution,
\newcommand{\eqend}{\,. \mbox{\par}}
\newcommand{\eqcntd}{, \mbox{\noindent}}

A: This is not an answer to your question, but perhaps it might help.
I would redefine the equation environment itself. For example, with plain TeX
you could define something like (didn't test though)
\def\eqindent#1{$$#1\,.$$\indent\ignorespaces}

and use it like this:
\eqindent{f(x) = x^2 + 1}
Some text here, but it's gonna get indented.

And similarly for the \noindent case.
And there ought to be a similar way to do that with LaTeX.

A: As Barbara Beeton has commented, forcing the first paragraph after an equation environment to indent can be achieved with \aftergroup -- use this command to add a \par after the group established by the environment.
Forcing the first paragraph after an environment not to indent isn't that straightforward. I came up with the following:

*

*I defined a new macro \@doendeq that will redefine \everypar so that it a) removes the indentation from the first paragraph following it b) reverts to its original (empty) definition. (\@doendeq is an abridged version of LaTeX's \@doendpe which is used after paragraph-making environments.)

*To change every instance of the equation environment to remove indents after it, one could simply add \aftergroup\@doendeq to the definition of \endequation. As you are looking for a command to modify only some instances of equation, I used \csappto from the etoolbox package to locally add\aftergroup\@doendeq to \end<\@currenvir> (\@currenvir being the name of the current environment).
I suspect that there are more elegant ways to do this.
\documentclass{article}

\usepackage{etoolbox}

\makeatletter
\newcommand*{\@doendeq}{%
  \everypar{{\setbox\z@\lastbox}\everypar{}}%
}
\newcommand*{\eqend}{\,.\aftergroup\par}
\newcommand*{\eqcntd}{%
  \,,%
  \csappto{end\@currenvir}{%
    \aftergroup\@doendeq
  }%
}
\makeatother

\begin{document}

\begin{equation}
f(x) = x^2 + 1 \eqend
\end{equation}
Some text here, but it's gonna get indented.

\begin{equation}
f(x) = x^2 + 1 \eqcntd
\end{equation}

Some text here, but it's not gonna get indented.

\end{document}


text:
Q: Association in cakephp multiple databases Cakephp 2 How to get data form multiple databases.
Example-
two database -> db_1 and db_2.
two tables -> users in db_1 database and countries in db_2
    users table -> id , username, country_id, status
    countries table -> id, name, status

and Association is -
App::uses('AppModel', 'Model');

class User extends AppModel
{
var $name = 'User';
var $useDbConfig = 'bd_1';
var $belongsTo = array('Country'=>array('className'=>'Country'), );
}

And in Controller when I use this Query then get a error
    $data = $this->User->find('all', array('conditions' => array('Country.status' => 1)));

    $this->set('data', $data);

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'Country.status' in 'where clause

A: You can´t do this out of the box because if you configured the two databases in Config/database.php they will be in different connections.
What you can do is make two separated finds and join the array data in php or, if you really need to do this and the databases are in the same server, make a custom query:
$db = $this->User->getDataSource();
$data = $db->fetchAll('SELECT * from db_1.users User LEFT JOIN db2.countries Country');