text:
Q: How do I configure an additional context path for tomcat-maven-plugin? I'm using Maven 3.0.3 with the Tomcat plugin. Using Maven and Tomcat, I would like to deploy an embedded instance of the site. My question is how do I configure an additional context path in my embedded Tomcat server?  Below is my Tomcat configuration, but either my <contextFile> specification is invalid or the contents of that file (below) are invalid:
<Context path="/all-new-jx-web" docBase="/Users/davea/Documents/workspace/NissanUSA2/Technology/nna/mycousa/jx/target/web">
</Context>

because when I invoke
mvn clean -Dmaven.test.skip=true verify -Ptomcat tomcat:run

none of the URLs mapped to /all-new-jx-web (my additional context path) are getting mapped (assets aren't being served by Tomcat). Any ideas why?  Below is my tomcat profile from my pom.xml file:
<profile>
  <id>tomcat</id>
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>tomcat-maven-plugin</artifactId>
        <version>1.1</version>
        <configuration>
          <contextFile>config/tomcat/context.xml</contextFile>
          <mode>context</mode>
          <addContextWarDependencies>true</addContextWarDependencies>
          <charset>UTF-8</charset>
          <path>/all-new-jx</path>
          <update>true</update>
          <warDirectory>target/${project.artifactId}-${project.version}.${project.packaging}</warDirectory>
          <systemProperties>
            <JAVA_OPTS>-Xms256m -Xmx512m -XX:MaxPermSize=256m -XX:NewRatio=6
                -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled
                -verbose:gc"
            </JAVA_OPTS>
          </systemProperties>
        </configuration>
      </plugin>
    </plugins>
  </build>
</profile>

A: I had the same issue.I tried giving location to external server xml but I could get my project to run. Ultimately I ended up modifying the tomcat plugin code to include the additional static context path.
// Snippet from AbstractRunMojo.java

            String appBase = new File(configurationDir, "webapps")
                    .getAbsolutePath();
            Host host = container.createHost("localHost", appBase);

            host.addChild(context);
            // Adding static context
            createStaticContext(container, context, host);//More code after this

    private void createStaticContext(final Embedded container, Context context,
        Host host) {
    if (null != staticContextDocbase) {
        Context ctx1 = container.createContext(staticContextPath,
                staticContextDocbase);
        ctx1.setPrivileged(true);
        Wrapper servlet = context.createWrapper();
        servlet.setServletClass(DefaultServlet.class.getName());
        servlet.setName("staticContent");
        ctx1.addChild(servlet);
        ctx1.addServletMapping("/", "staticContent");
        host.addChild(ctx1);
    }
}

A: You've got the right idea with your contextFile xml element, but try being explicit instead of using a relative path.
<contextFile>${basedir}/config/tomcat/context.xml</contextFile>

${basedir} is the folder your pom.xml lives in. You might need to change this part if that's not correct for your project.

A: Use the serverXml configuration for that.

A: We needed the same in order to run in dev mode our app, which uses Apache solr. The following seemed to work:

*

*declare solr as type=war, scope=tomcat dependency

*use the tomcat maven plugin (version 1.1) with addContextWarDependencies

*add system property for solr home as example below

then one can run maven like: mvn tomcat:run. Keep in mind that java will require lots of memory in this scenario, so before running maven do export MAVEN_OPTS="-Xmx1536m -XX:MaxPermSize=512m" for example.
The pom.xml is like, where we assume there are some properties -including one called solr.home- read from a config file:
<project>
  ...
  <dependencies>
  ...
    <dependency>
      <groupId>org.apache.solr</groupId>
      <artifactId>solr</artifactId>
      <version>3.3.0</version>
      <type>war</type>
      <scope>tomcat</scope>
    </dependency>
  </dependencies>
  <build>
  ...
    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>tomcat-maven-plugin</artifactId>
      <version>1.1</version>
      <configuration>
        <addContextWarDependencies>true</addContextWarDependencies>
        <systemProperties>
          <property.you.need>${example.property.yours}</property.you.need>
          <solr.solr.home>${solr.home}</solr.solr.home>
        </systemProperties>
      </configuration>
    </plugin>
    ...
  </build>
</project>

Solr can then be reached in:
http://localhost:8080/solr/admin

and your application in
http://localhost:8080/your-app-id/


text:
Q: Can't get the values of the checkbox in my Lightning component when I sent an Object I have the following code:
HTML:
<lightning-card title="CHOOSE THE INFORMATION TO SHARE" icon-name="">

        <template for:each={treatments} for:item="treatment">
            <lightning-input key={treatment.Id} type="checkbox" label={treatment.Diagnostic__r.Name} value={treatment}> </lightning-input>
        </template>

        <lightning-button variant="confirm" label="Share Information" title="Share Information"
            onclick={handleShareButton} class="slds-m-right_x-small">
        </lightning-button>

</lightning-card>

JavaScript:
handleShareButton(){
    const infoToShare = [...this.template.querySelectorAll('lightning-input')].filter(input => input.checked);
    infoToShare.forEach(info => {
        this.arrayInfo.push(JSON.stringify(info.value));
    });
    console.log(this.arrayInfo);
}

When I try sending a parameter like treatment.Name it works but not when I sent the object itself, someone knows why?
Thank you in advance...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Minimum number of boxes we need to pack the items We have $N$ items of the same size and we want to them in boxes. We have boxes of different sizes $\{M_1,\ldots , M_k\}$, how many we want from each size. Each box has be fully filled.
Design an algorithm that calculates the minimum number of boxes we need to pack the items.
We consider $M_1=1$ to have always fully boxes independent of $N$.
$$$$
It looks like Knapsack problem. So do we have to apply the algorithm of Knapsack problem for each box?
So we could sort the boxes in increasing order as for the size.
Then we starting packing items in that box, if it gets full we go to the next box.
We do that till no items are left.
Is the idea correct?

A: We indeed can solve it as Knapsack problem - for each $n \leq N$ calculate $a_n$ - minimum number of boxes we need for $n$ items by recurrent
$$a_n = \begin{cases}
\infty, & n < 0 \\
0, & n = 0 \\
1 + \min_i a_{n - M_i}, & n > 0
\end{cases}$$
Greedy algorithm doesn't work, as usual: let $N = 10$, $M_2 = 6$, $M_3 = 5$. Then greedy algorithm uses one box of size $6$ and $4$ boxes of size $1$ for a total of $5$ boxes, while optimal solution is to use two boxes of size $5$.


text:
Q: What is the problem of my h1 tag on iphone? I have my mobile only website. I am testing on my Iphone 6. The problem is with my title h1 tag no showing when you load. It reappears after you resize the screen and scroll past it. Can anyone help? Please and Thanks.              Code:
https://github.com/SEGACD32XMODEL1/Websiteland/blob/master/mobile.html
Site:
https://segacd32xmodel1.github.io/Websiteland/mobile.html

 Websiteland

        Cornhub

        Federal Crimes

        GamesAndMore

        KahootSpam

        Reload

        Roasted Beef 420

        School

        Time

        Uno Special Cards

        Websites


text:
Q: Will a PCI Universal card work in a PCI-E X16 slot? I have a will a PCI Universal card but not slot. Will it work in a PCI-E X16 slot?

A: Possibly ...
They do make pci to pcie adapters and I think you can put them in an x16 slot.

You'd have to get creative with some case modding but if it's a full height pci card you'd need something like this:

A: It will not

Typical PCI cards have either one or two key notches, depending on
  their signaling voltage. Cards requiring 3.3 volts have a notch 56.21
  mm from the card backplate; those requiring 5 volts have a notch
  104.47 mm from the backplate. "Universal cards" accepting either voltage have both key notches. This allows cards to be fitted only
  into slots with a voltage they support.

PCIe devices communicate via a logical connection called an
  interconnect or link. A link is a point-to-point communication
  channel between two PCIe ports, allowing both to send/receive ordinary
  PCI-requests (configuration read/write, I/O read/write, memory
  read/write) and interrupts (INTx, MSI, MSI-X). At the physical level,
  a link is composed of 1 or more lanes

Various PCI slots. From top to bottom:

*

*PCI Express x4

*PCI Express ×16

*PCI Express ×1

*PCI Express ×16

*Legacy    PCI (32-bit)

PCI Express - Source
Legacy PCI - Source

A: Totally different and incompatible standards.
It won't even physically fit.
So the answer is: NO.

A: To summarize and expand upon what has been already stated (to produce a more comprehensive single answer), there are 3 main variants of the over-arching PCI standard that you have to look out for:

*

*32-bit PCI (simply called 'PCI')

*64-bit PCI (usually called 'PCI-X')

*PCI-e (the newer version of the overall PCI standard)

Conventional PCI (anything before PCI-e) came in 4 flavours:

*

*PCI 3.3 v

*PCI 5 v

*PCI-X 3.3 v

*PCI-X 5 v

For anything to work properly, you need to check the PCI slots on your motherboard, to see what bit-ness and voltage your slots require. In the best-case scenario, your board will be a Universal PCI/PCI-X bus, allowing for 3.3v, 5v, and Universal cards to be plugged in. You still need to match the bit-ness, however.
In addition to this, you also cannot plug PCI conventional cards into the newer PCI-e slots and vice versa. You mentioned that you have a Universal PCI card, and a PCI-e x16 slot. You would also need to know the bit-ness. Assuming that you have a 32-bit Universal card, a viable option has been mentioned on this page. You will need an adapter, as LawrenceC mentioned in his answer. For more on these topics, please see the following resources:

*

*32-Bit PCI Bus Definition | Orbit Micro News

*Conventional PCI - Wikipedia
A Google Image Search using any of the pictures used in LawrenceC's post should also provide shopping results for what you may need.
Good Day to you all.

A: You are confusing PCIe with PCI-X.  PCI-X slots were 64-bit (as opposed to regular PCI slots, which were only 32-bit), and came in a 3.3V and 5V variety.  They were keyed differently so that a 5V card could not be plugged into a 3.3V slot or vice versa.  A "Universal" PCI card simply means that the card can be inserted into any type of PCI or PCI-X slot.
PCI-X slots were only ever found in servers.  They (like PCI) disappeared once PCIe took over.  Neither standard is compatible with PCIe, nor will they fit into a PCIe slot.


text:
Q: Asp.Net Core not seeing files added to project during docker build I have an asp.net core application that has nothing inside of it's wwwroot folder at build time but during docker build I have a stage that compiles my Angular application and then in a later stage copies the compiled files into the wwwroot folder. When the application launches and I directory browse nothing is there. I can run code that reads the directory and sees the files so what am I doing wrong here?
FROM microsoft/dotnet:2.2-aspnetcore-runtime AS base
WORKDIR /app
EXPOSE 80

FROM node:10.15-alpine as webbuild
COPY ["ShareWeb/Angular", "ShareWeb/web"]
WORKDIR /ShareWeb/web
RUN npm install
RUN npm install -g @angular/cli
RUN npm install -g sass
RUN npm rebuild node-sass
RUN ng build --prod

FROM microsoft/dotnet:2.2-sdk AS hostbuild
WORKDIR /src
COPY ["ShareWeb/ShareWeb.csproj", "ShareWeb/"]
RUN dotnet restore "ShareWeb/ShareWeb.csproj"
COPY . .
WORKDIR "/src/ShareWeb"
COPY --from=webbuild ShareWeb/web/dist wwwroot/ # Copies my files in
RUN dotnet build "ShareWeb.csproj" -c Release -o /app

FROM hostbuild AS publish
RUN dotnet publish "ShareWeb.csproj" -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
RUN rm -r Angular
ENTRYPOINT ["dotnet", "ShareWeb.dll"]

A: On this line:

COPY --from=webbuild ShareWeb/web/dist wwwroot/ # Copies my files

Try: /ShareWeb/web/dist as the path instead of ShareWeb/web/dist


text:
Q: How to extract numbers from mixed strings I have a character vector of strings, that are either integers or of the form "Pn[ab]?"
> figc
 [1] "3"   "2"   "7"   "8"   "10"  "3"   "4"   "6"   "P3a" "P3b" "5"   "P9"
[13] "1"   "13"  "15"  "18"  "21"  "22"  "5"   "6"   "9"   "1"   "13"  "14"
[25] "15"

I want to convert these to numbers, where, for "P3a" the result is 3, and "P9" gives 9.
I tried:
fig <- ifelse(substr(figc, 1, 1)=="P",
              as.numeric(substr(figc, 2, 1)),
              as.numeric(figc))

giving:
> fig <- ifelse(substr(figc, 1, 1)=="P",
+               as.numeric(substr(figc, 2, 1)),
+               as.numeric(figc))
Warning message:
In ifelse(substr(figc, 1, 1) == "P", as.numeric(substr(figc, 2,  :
  NAs introduced by coercion
>
> fig
 [1]  3  2  7  8 10  3  4  6 NA NA  5 NA  1 13 15 18 21 22  5  6  9  1 13 14 15

But I get NAs for the non-numeric ones.  How to fix this? I looked at the stringr package, but couldn't see anything that would help with this simple problem

A: We can use parse_number
library(readr)
parse_number(figc)
 [1]  3  2  7  8 10  3  4  6  3  3  5  9  1 13 15 18 21 22  5  6  9  1 13 14 15

data
figc <- c("3", "2", "7", "8", "10", "3", "4", "6", "P3a", "P3b", "5",
"P9", "1", "13", "15", "18", "21", "22", "5", "6", "9", "1",
"13", "14", "15")

A: Use str extractand the character class \\d:
library(stringr)
str_extract(string, "\\d+")
[1] "3" "2" "6" "3" "3" "5" "9"

Alternatively, in base R, you can use the negative character class \\D, which matches any character that is not a digit, and remove it:
gsub("\\D", "", string)

Data:
string <- c("3","2", "6", "P3a", "P3b", "5", "P9")

A: We could use gsub removing all letters:
as.numeric(gsub("[[:alpha:]]", "", figc))

[1]  3  2  7  8 10  3  4  6  3  3  5  9  1 13 15 18 21 22  5  6  9  1 13 14 15


text:
Q: What is socket variable in socket.io I'm new to Node.js and socket.io.
I go official site of socket.io, and try a tutorial.
http://socket.io/get-started/chat/
It work correctly on my computer. But I can't understand essence of its code at all.
QUESTION:what is "socket variable" in below code. And Where is it from?
io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

Maybe "msg variable" is String type variable. And it is from client side, right?

A: The socket variable is basically a socket to a client. The io.on('conection') will be called each time a new client connects and give a socket to subscribe to.
socket.on('chat message' will subscribe on events sent by client associated with that socket instance.
Here is the different parts of your program explained:
io.on('connection', function(socket){ // Waiting for new clients to connect, then return a socket instance
// msg can be any javascript object like a string or array ect.
  socket.on('chat message', function(msg){ // Subscribe on event 'chat message' will be called when client do io.emit
    io.emit('chat message', msg); // Server send to clients
  });
});

A: Type of the variable msg is not exactly String but more like whatever emitted in the 'chat message' event. You don't have to emit only strings, you can emit objects too. In the context of the example, yes. It is from the client side.
The variable socket though, socket is the connection between client and the server. If the server receives a 'chat message' event from that connection, or rather 'socket', it emits a 'chat message' event on all the sockets that it has. The content of the 'chat message' event that server emits to all sockets that are connected to it is the same as the content of the 'chat message' event that client, which sent the chat message, emitted to the server in the first place.


text:
Q: Show that there is a bijection between $[S^0,X]$ and $\pi_0(X)$ for a topological space X So I've been asked to show that there is a bijection between $\pi_0(X)$ and $[S^0,X]$ for a topological space X but the definition given in my notes is:  $\pi_n(X) = [S^n,X]$, so I'm finding this a bit confusing. The question is part b of the below image:

A: Let $S^0 = \{0, 1 \}$ and denote the basepoint of $X$ by $x_0$.
By definition, $[S^0, X]$ is the set of equivalence classes of maps from $S^0 $ to $X$ sending $0$ to the basepoint $x_0$ modulo homotopy.
So let's ask ourselves: how can we classify such maps up to homotopy?
First of all, since all of our maps send $0$ to $x_0$, our maps are uniquely specified by where they send the point $1$.
So suppose you have two maps $f_1, f_2: S^0 \to X$, defined by
$$ f_1 : 0 \mapsto x_0, \ \ 1 \mapsto x_1,$$
$$ f_2 : 0 \mapsto x_0, \ \ 1 \mapsto x_2.$$
These maps are homotopic iff there exists a continuous function $F: S^0 \times I \to X$ such that
$$ F(t , 0) = f_1(t), \ \  F(t , 1) = f_2(t),$$
for $t \in S^0$.
If such a continuous function $F$ exists, then $s \mapsto F(1, s)$ is a continuous path between $x_1$ and $x_2$, so $x_1$ and $x_2$ are in the same path component.
Conversely, if $x_1$ and $x_2$ are in the same path component, then there exists a continuous path $\gamma : I \to X$ with $\gamma(0) = x_1$ and $\gamma(1) = x_2$, so we can define such a function $F$ by
$$ F(0,s) = x_0, \ \ F(1,s) = \gamma (s).$$
The conclusion is that $[S^0, X]$ can be identified with the set of path components of $X$, which is precisely $\pi_0(X)$, by definition.


text:
Q: Android: Project structure for opensource projects (GitHub) I've mostly been a consumer in the open source world, but now want to start contributing.
Generally the projects hosted on GitHub (Talking about android here) are seen to have the following structure (with a library and a sample module):

I was wondering if this structure can be generated using an existing template when creating a new project in Android Studio. I intend to put my existing code in the library module and a few samples in the sample module. I know it is obvious but just stating.
I tried adding a new project with no activity but it generated a regular android app project with app folder. Is there a way to get the structure as seen in screenshot using Android Studio itself, or I'll need to manually add modules as seen?


text:
Q: Can a script be automated after a commit on Perforce? We use Perforce at work, and routinely keep software projects in the repository.  In general creators follow the normal Perforce flow, BUT we also have a class of users, who doesn't have any need to edit the files but only read them.  Currently we use P4Web but that requires the user so download each file individually to reassemble the project directory.  Ideally I would like to have a process where when a user does a commit/submit in Perforce, the script would automatically run to generate a single zip file of the project directory and files, so that it was a one-click download that was guaranteed to be correct against current state of the source files.  I know Git has a post-commit hook which could be used for this, but I can't figure out an equivalent function in Perforce.

A: Short answer: Yes, read the documentation, page 103.
Here is a link to all of the documentation available from Perforce.
Long answer, you can edit the triggers by typing p4 triggers from the command line. You provide the name of the trigger (i.e. "my_archive"), the type of trigger (i.e. change-commit in your case), path (i.e. the //depot/path/to/the/directory/that/contains/the/files/to/zip/...), and the command_path (your script), plus any variables to pass along to your script.
Really, take a look at the docs, it is really quite simple and powerful.

A: If they just need read access, then just give them read access in the p4protect table. That way you avoid having to mess around with snapshots of your repository.


text:
Q: What to do with a build "dist" folder So I finished a very small angular2 project, and build it trough angular-cli with the command "ng build --prod".
I get a "dist" folder out of this. But what should I do with this dist folder in order to make it run ? Publish it to a server ?
Regards.

A: Yes! Upload the contents of the dist folder to your webserver to host it live. This step where you take your finished, built project and send it to the server is often called "deployment".
Depending on where you host your site you may have command line tools available to make deploying your app just as easy as building it (for example, upload to an Amazon S3 bucket with AWS command line tools, firebase deploy with firebase-tools, and even the Angular CLI can deploy to Github's gh-pages with ng github-pages:deploy)


text:
Q: Ember.js QT w/ Javascript Bridge We have a full desktop application based in QT C++ (mac & windows). We utilize webkit to serve up the UI based in HTML and Javascript. We also interact with the C++ via a javascript bridge. I'm doing quite the overhall and incorporating Ember.js as the MVC for a much more modular UI.
My question pertains to the best method for persistance. Should I stick with the Javascript objects we currently utilize, or transition to Ember Data for persistence, and read/write via a function in Ember Data(translation layer)?
Also we utilize webkit, but should I see about instead utilising Node.js rather than strait html/js?
I'd like to not do drastic changes, but I want to do this right. Any advice?

A: From the Ember side, there's no reason to use Ember Data, because Ember works fine without it.  But Ember's infrastructure relies heavily on the API provided by Ember.Observable, which is available to all subclasses of Ember.Object. Similarly, JavaScript arrays will support more Ember features if you use Ember.Array and Ember.MutableArray, although this will happen automatically unless you disable Ember.EXTEND_PROTOTYPES.
So one very reasonable approach would be to port your existing model classes to Ember.Object. That would require, among other things, using get and set to access properties. If you do this, then your objects will be first class Ember citizens, and you'll have access to all the neat features of Ember, including automatic view updates and data bindings.
Here's what Ember.Object looks like, and how it integrates with the rest of Ember:
MyApp.Person = Ember.Object.extend({
  firstName: null,
  lastName: null,

  init: function () {
    // You can put more initialization code here.
  },

  // Compute fullName based on firstName and lastName.
  // This will automatically propagate updates when
  // firstName or lastName changes.
  fullName: function () {
    return this.get("firstName") + " " + this.get("lastName");
  }.property("firstName", "lastName")
});

var person = MyApp.Person.create({ firstName: "Jane", lastName: "Doe" })

Then, in an Ember view, you could write something like:
<p>{{person.fullName}}</p>

…and the view would automatically updated whenever firstName or lastName changed. Similarly, you could edit firstName using the following code:
{{view Ember.TextField valueBinding="person.firstName"}}

In this example, changes to the text field will be automatically propagated back to the underlying object. (Though you can get clever and build a text field that only propagates changes when the user is done editing.)
If you need to pass property updates from Ember to QT, see the guide to building getters and setters with computed properties or use observers. A lot depends on exactly how you're exposing your C++ APIs via your JavaScript bridge. But as long as you can tie into Ember.Observable somehow, you'll have full access to all of Ember's features.


text:
Q: This end tag has no matching start tag. I messed up somewhere. Please look at it for me?

    <title></title>

    <form id="StudentList" runat="server">

        <asp:ListBox ID="lstStudents" runat="server"
            onselectedindexchanged="lstStudents_SelectedIndexChanged">
        </asp:ListBox>

        <asp:Label ID="lblOutput" runat="server" Text=""></asp:Label>

    </form>

Warning 4   This end tag has no matching start tag.

Is it that my tags are out of order? I am stumped.

A: Do you have a doctype defined?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Just for the record, you can use the great W3C validator to check the validity of HTML, XHTML and more.


text:
Q: How to find a control (textbox) that was created during rowCommand and get its value I have added a GridView to my webform. I then bounded data to the gridview programatically, followed by adding a RowDataBound function so that I can have each cell, in the gridView selectable as such:
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
            string clickInfo = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");
            // Add events to each editable cell
            for (int columnIndex = 3; columnIndex < e.Row.Cells.Count; columnIndex++)
            {
                // Add the column index as the event argument parameter
                string jsClick = clickInfo.Insert(clickInfo.Length - 2, columnIndex.ToString());
                // Add this javascript to the onclick Attribute of the cell
                e.Row.Cells[columnIndex].Attributes["onclick"] = jsClick;
                // Add a cursor style to the cells
                e.Row.Cells[columnIndex].Attributes["style"] += "cursor:pointer;cursor:hand;";
            }
        }
    }

...So then what i wanted to do is that whenever a cell is selected, turn that cell red and add a textbox so i can enter a value.. Shown below
<Columns>
<asp:ButtonField CommandName="CellClick" Visible="false" ControlStyle-   CssClass="redCell"></asp:ButtonField>
</Columns>

codebehind:
  public void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.ToString() == "CellClick")
        {
            //INDEX INFO
            int selectedRowIndex = Convert.ToInt32(e.CommandArgument.ToString());
            int selectedColumnIndex = Convert.ToInt32(Request.Form["__EVENTARGUMENT"].ToString());
            //TRIGGERS EVENT FOR SELECTED CELL
                    GridView1.Rows[selectedRowIndex].Cells[selectedColumnIndex].Attributes["style"] += "background-color:Red;";
                    TextBox scheduleBox = new TextBox();
                    scheduleBox.CssClass = "redCell";
                    scheduleBox.ID = "ActiveCell";
                    scheduleBox.Width = 35;
                    this.GridView1.Rows[selectedRowIndex].Cells[selectedColumnIndex].Controls.Add(scheduleBox);
                    scheduleBox.Focus();
            //LABEL INDEX INFO
            lblCell.Text = (selectedColumnIndex - 2).ToString();
            //LABEL HEADER & ROW TITLES
            lblStartTime.Text = GridView1.Rows[selectedRowIndex].Cells[1].Text;

        }
    }  GridView1.DataBind();
    }

what I want to do now is once I press enter, get the value that currently resides in the texbox that was created programmatically and for now just display that value on a messagebox or whateevr (what Im really going to do is update a database but first I just need to find out how to get that value)
<asp:Panel runat="server" DefaultButton="Button1">
<asp:Button ID="Button1" CssClass="ActiveCell" runat="server" Style="display: none"     OnClick="Button1_Click1" /></asp:Panel>

and the function Im using is this:
protected void Button1_Click1(object sender, EventArgs e)
    {

        var schedule = FindControl("ActiveCell") as TextBox;
        ScriptManager.RegisterStartupScript(this, typeof(Page),
             "alert", "alert('VALUE GOES HERE FROM TEXTBOX');", true);
    }

So now my question: How can i get the value from ScheduleBox?

A: If I understand your question correctly, you should be able to use:
<%=schedule.ClientID %>.value

I am admittedly not a javascript expert, so let me know if that helps.
also, is the
var schedule = FindControl("ActiveCell") as TextBox;

returning the textbox correctly?
EDIT: if that doesn't work, try
<%=ActiveCell.ClientID %>.value

A: Have you tried looking into the controls of the cell of the selected row?
To work around the lack of a selectedColumnIndex in the GridView, I had to change your "GridView1_RowCommand" event to replace one line (to set the ID) and add one more:
            scheduleBox.ID = "ActiveCell_" + selectedRowIndex.ToString() + "_" + selectedColumnIndex.ToString();
            scheduleBox.TextChanged += scheduleBox_TextChanged;

It would look something like this:
int selectedColumnIndex = 0;
int selectedRowIndex = 0;
string lastUserInputText = string.Empty;

    public void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.ToString() == "CellClick")
        {
            //INDEX INFO
            selectedRowIndex = Convert.ToInt32(e.CommandArgument.ToString());
            selectedColumnIndex = Convert.ToInt32(Request.Form["__EVENTARGUMENT"].ToString());
            //TRIGGERS EVENT FOR SELECTED CELL
            GridView1.Rows[selectedRowIndex].Cells[selectedColumnIndex].Attributes["style"] += "background-color:Red;";
            TextBox scheduleBox = new TextBox();
            scheduleBox.CssClass = "redCell";

            //This formats the ID so its unique, and now the TextBox contains the row and colummn indexes:
            scheduleBox.ID = "ActiveCell_" + selectedRowIndex.ToString() + "_" + selectedColumnIndex.ToString();
            scheduleBox.TextChanged += scheduleBox_TextChanged;

            scheduleBox.Width = 35;

            this.GridView1.Rows[selectedRowIndex].Cells[selectedColumnIndex].Controls.Add(scheduleBox);
            scheduleBox.Focus();
            //LABEL INDEX INFO
            lblCell.Text = (selectedColumnIndex - 2).ToString();
            ////LABEL HEADER & ROW TITLES
            lblStartTime.Text = GridView1.Rows[selectedRowIndex].Cells[1].Text;

        }
        GridView1.DataBind();
    }

//The following event gets the current index of the Row and the column where the user is changing the text
    void scheduleBox_TextChanged(object sender, EventArgs e)
    {
        TextBox txtSelected = (TextBox)sender;
        string[] selectedValues = txtSelected.ID.Split(new char[] { '_' });
        selectedRowIndex = int.Parse(selectedValues[1]);
        selectedColumnIndex = int.Parse(selectedValues[2]);
        //you could also use it to get the text directly while the user is editing it:
        lastUserInputText = txtSelected.Text;
    }

//This gets the text for the selected row and column. But if you only have 1 column with a TextBox it would be easier to just use the column index constant instead of doing it dynamically. However, remember you already have this value in the "lastUserInputText" variable. If you use that the following code may not be necessary:
string GetTextFromSelectedRowTextBox()
{
    string textBoxValue = string.Empty;
    foreach (Control curControl in this.GridView1.Rows[selectedRowIndex].Cells[selectedColumnIndex].Controls)
    {
        if (curControl is TextBox)
        {
            TextBox txtScheduleBox = (TextBox)curControl;
            textBoxValue = txtScheduleBox.Text;
            break;
        }
    }
    return textBoxValue;
}


text:
Q: MS Access 2016 - table - lookup values I can do a simple lookup field in a table to choose values from another table field. Suppose my new table has the first field as a lookup field (Surname). It gives you a long dropdown menu of all the surnames available.
Now, how do I limit the dropdown menu in the second field to restrict only to first names available, matching the above selected surname (not all the first names available)
The third field should automatically result in an unique ID (taken from another table that is assigned to this particular combination (Surname + First name) (Assuming there are no multiple people with the same surname + first name)
Thank you

A: What you describe is known as 'cascading' or 'dependent' combobox. This requires code behind a form. This is a common topic How can i filter a combobox selection list based on another combobox selection
Advise never build lookups in table. Build combobox on form. http://access.mvps.org/Access/lookupfields.htm
Should not be saving name parts into another data table, save only EmpID.
Don't separately select surname and firstname. Concatenate name parts to a single value listed in combobox dropdown:
SELECT EmpID, Surname & ", " & Firstname AS Fullname FROM Employees ORDER BY Surname, Firstname;
To handle possibility of multiple people with same name (e.g. John Smith), include another identifying field in the concatenation, such as job title.
Set combobox properties to hide EmpID column and users see the descriptive info column but EmpID is value of combobox.


text:
Q: Why is this not printing to standard output (stdout)? I'm currently creating my own command line shell, and I'm having problems when trying to take in pipes. My program starts with the parent process. It checks to see if the user puts in exit or history. If so it uses those commands, but this is not important. If the user puts in anything other than exit or history, then it creates a child who executes the current task.
However, if the user puts in a command that has a single pipe, then we start at the parent and it creates a child process, call this child, child 1. child 1 see's that there is a pipe and uses fork to create another child, call this child 2. Child 1 creates another child, call it child 3 (Note: child 2 and 3 use shared memory). Now, child 2 executes the first command, and child 3 executes the command using child 2's output. But I'm not getting any output for some reason.
I'm not sure if this is the most efficient way of executing my task, but this is what my professor said to do.
If you want to see all of my code here it is: http://pastebin.com/YNTVf3XP
Otherwise here is my code starting at child 1:
            //Otherwise if we have a single pipe, then do
            else if (numPipes == 1) {

                char *command1[CMD_MAX];        //string holding the first command
                char *command2[CMD_MAX];        //string holding the second command
                int fds[2];                     //create file descriptors for the parent and child
                pid_t new_pid;                  //create new pid_t obj

                onePipeSplit(tokens, command1, command2, numTokens);    //Getting each command for pipe

                if (pipe(fds) < 0) {            //use the pipe command. If < 0
                    perror("Pipe failure.");    //we have an error, so exit
                    exit(EXIT_FAILURE);
                }

                //Creating child 2
                new_pid = fork();

                //if pid < 0 then we have an error. Exit.
                if (new_pid < 0) {
                    perror("Fork failure.");
                    exit(EXIT_FAILURE);
                }

                //Else we have the child (2) process
                else if (new_pid == 0) {

                    close(fds[0]);      //Close read

                    //sending stdin to the shared file descriptor
                    if (dup2(fds[1], STDOUT_FILENO)<0) {
                        perror("Can't dup");
                        exit(EXIT_FAILURE);
                    }

                    execvp(command1[0], command1);  //Execute the next command
                    perror("Exec failure");
                    exit(EXIT_FAILURE);
                }

                //Else if we have the parent process
                else {

                    pid_t child = fork();           //Creating child 3
                    if (new_pid < 0) {              //if pid < 0, error, exit
                        perror("Fork failure.");
                        exit(EXIT_FAILURE);
                    }

                    //else if pid > 0 we have the parent wait until children execute
                    else if (new_pid > 0) {
                        wait(NULL);
                    }

                    //else we have the child (3)
                    else {

                        close(fds[1]);      //Close write

                        //Sending stdout to the shared file descriptor
                        if (dup2(fds[0], STDIN_FILENO) < 0) {
                            perror("Can't dup");
                            exit(EXIT_FAILURE);
                        }

                        execvp(command2[0], command2);  //Execute the command
                        perror("Exec failure");
                        exit(EXIT_FAILURE);
                    }
                }
            }

Here is an image that my professor gave me to show how it should work.

A: The problem is here:
                   pid_t child = fork();           //Creating child 3
                    if (new_pid < 0) {
       ... you keep checking `new_pid` here on down,
       ... but you should be checking `child` here on down...

Also in onePipeSplit you need to put a NULL at the end of both command lists because execvp needs that.  After the first loop add:
command1[i] = NULL;

and after the second:
command2[i] = NULL;

OK, a few more fixes:
after each dup2() you need to close the original fd.  One example:
                    if (dup2(fds[1], STDOUT_FILENO)<0) {
                        perror("Can't dup");
                        exit(EXIT_FAILURE);
                    }
                    close(fds[1]);      /* ADD ME */

and in the parent process:
                    //else if pid > 0 we have the parent wait until children execute
                    else if (child > 0) {
                        close(fds[0]);   /* we don't use */
                        close(fds[1]);   /* the pipe */
                        wait(NULL);
                        exit(0);         /* when 2 & 3 are done, we are too */
                    }


text: Q: My sprites in p5.play continue to have a strange halo surrounding them Does anyone know why all of my sprites (images) have strange halos drawn around them whenever I run my sketch? Am I using the wrong filetype or transparency settings?


text:
Q: Protection Cells in Google Sheets That's my first pot here as I have some Idea about creating some Sheet paper on Google Sheets.
To be hones with all of you - Im not a programer and just creating something by using your knowladge on Stack and using Macros ( then changing scripts)
I have issue with authorization for blocked Cells.
The Idea :
When our person that will be Confirming the Checkbox to TRUE Value, then I have a timestamp to be set with a note that is Stamped. After this process I want to have the cells locked by Script for that user that is editing sheet values(ChcekBox), but the main issue is that when Im on the Account I can't by script LockMyself from the Editing.
SO my question is : Is there any chance to call for Admin Account to lock that ?
Code:
 if (driverconfirm == "true")
    {

        spreadsheet.getRange(celladdress).setValue(new Date()).setNumberFormat("MM/dd/yyyy hh:mm")
        stampedDriver.setValue('stamped')

        // - Lock Range
        var protection = spreadsheet.getRange('G57:J57').protect();
         protection.removeEditors([dem]);  // here is the issue as im on my account, and can't get rid off myself - DEM is the email address as Var
    };


text:
Q: "wrong ELF class: ELFCLASS32", but only when using GDB I'm trying to run dfhack in a debugger. I'm running 64-bit Ubuntu Trusty, but Dwarf Fortress does not have a 64-bit build so I'm running 32-bit Dwarf Fortress. I have installed gdb via apt-get install gdb:i386.
Here's what happens when I start dfhack with gdb:
ben@australium:~/df_linux$ xvfb-run -a ./dfhack --gdb
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./libs/Dwarf_Fortress...(no debugging symbols found)...done.
(gdb) start
Temporary breakpoint 1 at 0x804bdec
Starting program: /home/ben/df_linux/libs/Dwarf_Fortress
ERROR: ld.so: object './hack/libdfhack.so' from LD_PRELOAD cannot be preloaded (wrong ELF class: ELFCLASS32): ignored.
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/i386-linux-gnu/libthread_db.so.1".

Temporary breakpoint 1, 0xf7598b53 in main ()
   from /home/ben/df_linux/libs/libgraphics.so
(gdb)

Here's what happens when I run it without gdb:
ben@australium:~/df_linux$ xvfb-run -a ./dfhack
Xlib:  extension "RANDR" missing on display ":99".
Loading bindings from data/init/interface.txt
New window size: 1280x720
Font size: 10x12
Resizing grid to 128x60
Resizing font to 10x12

Resetting textures
DFHack is ready. Have a nice day!
Type in '?' or 'help' for general help, 'ls' to see all commands.
[DFHack]#

The executable, the preloaded library, and gdb are all 32-bit:
ben@australium:~/df_linux$ readelf -h /home/ben/df_linux/libs/Dwarf_Fortress
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           Intel 80386
  Version:                           0x1
  Entry point address:               0x804c980
  Start of program headers:          52 (bytes into file)
  Start of section headers:          18192664 (bytes into file)
  Flags:                             0x0
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         8
  Size of section headers:           40 (bytes)
  Number of section headers:         28
  Section header string table index: 27
ben@australium:~/df_linux$ readelf -h /home/ben/df_linux/hack/libdfhack.so
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 03 00 00 00 00 00 00 00 00
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - GNU
  ABI Version:                       0
  Type:                              DYN (Shared object file)
  Machine:                           Intel 80386
  Version:                           0x1
  Entry point address:               0x1b7e40
  Start of program headers:          52 (bytes into file)
  Start of section headers:          43686636 (bytes into file)
  Flags:                             0x0
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         7
  Size of section headers:           40 (bytes)
  Number of section headers:         37
  Section header string table index: 34
ben@australium:~/df_linux$ readelf -h /usr/bin/gdb
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           Intel 80386
  Version:                           0x1
  Entry point address:               0x808cb95
  Start of program headers:          52 (bytes into file)
  Start of section headers:          5089368 (bytes into file)
  Flags:                             0x0
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         9
  Size of section headers:           40 (bytes)
  Number of section headers:         28
  Section header string table index: 27

A:
ERROR: ld.so: object './hack/libdfhack.so' from LD_PRELOAD cannot be preloaded (wrong ELF class: ELFCLASS32): ignored.

This error comes from GDB starting your (64-bit) shell, which in turn execs your (32-bit) dfhack program.
You should only care about preloading into the target program. The fact that libdfhack.so was not preloaded into your shell is of no consequence, and you should simply ignore it.


text:
Q: how to handle RxAndroid errors in the main thread I'm new to rxJava/Android and surprised that my onError lambda is  sometimes called on the main-thread and sometimes not, although I use .observeOn(AndroidSchedulers.mainThread())
Example 1: onError on main-thread
this works as expected: onError is called on the main-thread
Observable.error(new RuntimeException("RTE"))
    .subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(s -> {
                Log.e(TAG, "onNext("+s+")-thread: " + Thread.currentThread().getName());
            },
            throwable -> {
                Log.e(TAG, "onError()-thread: " + Thread.currentThread().getName());
            });

log-output:
onError()-thread: main

Example 2: onError NOT on main-thread
Observable.create(new Observable.OnSubscribe<String>() {
    @Override
    public void call(Subscriber<? super String> subscriber) {
        subscriber.onNext("one and only");
    }
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.timeout(1, TimeUnit.SECONDS)
.subscribe(s -> {
        Log.e(TAG, "onNext("+s+")-thread: " + Thread.currentThread().getName());
    },
    throwable -> {
        Log.e(TAG, "onError()-thread: " + Thread.currentThread().getName());
    });

the output is something like this:
onNext(one and only)-thread: main
onError()-thread: RxComputationScheduler-4

I thought that after calling observeOn(AndroidSchedulers.mainThread()), ALL emissions should be done on the main-thread.
so I have these questions:

*

*I could not find any documentation that specifies under what circumstances onError is called in which thread. Anyone knows a link?

*I do of course want to display some error-indication in the GUI: so how can I force onError to be ALWAYS called in the main-thread?

A: Because .timeout(1, TimeUnit.SECONDS) by default operates on Schedulers.computation().

A: I just found out that I only need to change the order of calls. When I call observeOn after timeout it works as expected:
.timeout(1, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())

log-output
onNext(one and only)-thread: main
onError()-thread: main

The reason is, that observeOn will only affect everything below the call, and only until some other operator changes the thread again. In the example above, timeout() will change to the computation thread.
Note, that subscribeOn works differently. It does not matter where in the chain you call it.
You should only call it once (when you call it multiple times the first call wins: see "Multiple subscribeOn" in this Blog)
Here is a nice blog-post with more details: RxJava- Understanding observeOn() and subscribeOn()


text:
Q: Javascript For Loop To Slow for Progress Event Listener Fireing I am trying to change a element background color according the the progress of an upload. The problem I am having is the for loop is way to slow compared to the progress event listener that fires off. Is there anything I can do about this?
var colors = [
    "#fff2f2",
"#ffe6e6",
"#ffd9d9",
"#ffcccc",
"#ffbfbf",
"#ffb3b3",
"#ff9999",
"#ff7373",
"#ff8080",
"#ff5959",
"#ff4d4d",
"#ff4040",
"#ff3333",
"#ff2626",
"#ff1919",
"#ff0d0d",
"#ff0000",
]

var first = 0;
var last = 5;
var xhr = new XMLHttpRequest();

xhr.upload.addEventListener("progress", updateProgress, false);

var foo = document.getElementById("uploadScreen");
var form = document.getElementById("uploadForm");
var percentComplete;

xhr.open("POST", "php/upload.php", true);
xhr.send(new FormData(form));

function updateProgress(event) {
    if (event.lengthComputable) {
        percentComplete = Math.round(event.loaded / event.total * 100);
        for (i=0; i < colors.length; i++) {
            if (percentComplete > first && percentComplete < last ) {
                console.log(foo.style.backgroundColor = colors[i]);
                break;
            }
        }
        first = first +5;
        last = last +5;
    } else {
        alert("no no");
    }
}

A: Rather than getting a whole number as a percent, leave it as a value between 0 and 1. Then just multiply that by the length of your array to get the correct index.
var percentComplete = event.loaded / event.total;
var index = Math.round(percentComplete * (colors.length - 1)); // Subtract 1 to account for zero based indexing
foo.style.backgroundColor = colors[index];

http://jsfiddle.net/h6bsU/

A: var colors = [
    "#fff2f2",
"#ffe6e6",
"#ffd9d9",
"#ffcccc",
"#ffbfbf",
"#ffb3b3",
"#ff9999",
"#ff7373",
"#ff8080",
"#ff5959",
"#ff4d4d",
"#ff4040",
"#ff3333",
"#ff2626",
"#ff1919",
"#ff0d0d",
"#ff0000",
]

var first = 0;
var last = 5;
var xhr = new XMLHttpRequest();

xhr.upload.addEventListener("progress", updateProgress, false);

var foo = document.getElementById("uploadScreen");
var form = document.getElementById("uploadForm");
var percentComplete;

xhr.open("POST", "php/upload.php", true);
xhr.send(new FormData(form));

function updateProgress(event) {
    if (event.lengthComputable) {
        percentComplete = Math.round(event.loaded / event.total * 100);
        var i=praseInt(percentComplete/5);
        console.log(foo.style.backgroundColor = colors[i]);
    } else {
        alert("no no");
    }
}

I think there is no need to use for loop in this case.


text:
Q: Threading simple calculations I've been trying to parallelize the following function but cannot figure out how to.
public static Cell GetClosestCell (Cell cell)
{
    // The four calls below should be run in parallel.
    Cell temp1 = new FindNorth(cell);
    Cell temp2 = new FindSouth(cell);
    Cell temp3 = new FindWest(cell);
    Cell temp4 = new FindEast(cell);

    // Return smallest cell based on [X].
    if ((temp1.X < temp2.X) && (temp1.X < temp3.X) && (temp1.X < temp4.X))
    {
        return (temp1);
    }
    else if ((temp2.X < temp3.X) && (temp2.X < temp4.X))
    {
        return (temp2);
    }
    else if (temp3.X < temp4.X)
    {
        return (temp3);
    }
    else
    {
        return (temp4);
    }
}

Each of the four function calls should run in parallel but without having to initiate a thread. In other words, there should be 4 threads already running waiting for input to which I can dispatch each call.
I'm used to the normal paradigm of parallel loops and not sure how to approach this (at least not in a clean way).

A: using System;
using System.Threading.Tasks;

public class Program {
    public static void Main() {

        Task<Cell> task1 = new Task<Cell>(n => FindNorth((Cell)n), cell);

        Task<Cell> task2 = new Task<Cell>(n => FindSouth((Cell)n), cell);
        Task<Cell> task3 = new Task<Cell>(n => FindSouth((Cell)n), cell);
        Task<Cell> task4 = new Task<Cell>(n => FindEast((Cell)n), cell);

        task1.Start();
        task2.Start();
        task3.Start();
        task4.Start();
        Console.WriteLine("Main method complete. Press <enter> to finish.");
        Console.ReadLine();
    }

}


text:
Q: Pass a class, instantiate it and and use the right method I have a wrapper method for sending a Get request:
public CloseableHttpResponse sendGetWithHeaders(String url, Map<String, String> headers) {

    HttpGet httpget = new HttpGet(url);

    // loop over entrySet() and httpget.setHeader(key, value);

    return client.execute(httpget); // client instantiated elsewhere
}

It works.
But I don't want to create another 5+ almost identical methods for Head, Put, Options, etc.
Can I generify this method by passing in a Class? Meaning
sendRequestWithHeaders(HttpGet.class, "url", someMap)

The below attempts fail:
CloseableHttpResponse sendRequestWithHeaders(Class<?> clazz, String url, Map<String, String> headers) {

    Object request = clazz.newInstance();
    // request.setHeader(key, value); doesn't compile because it's of type Object
}

or
<T> CloseableHttpResponse sendRequestWithHeaders(Class<T> clazz, String url, Map<String, String> headers) {

    Object request = clazz.newInstance();
    T t = clazz.cast(request);

    // setHeader(key, value); doesn't compile either because T is generic
}

P.S. I have an alternative solution using Apache's RequestBuilder anyway, I'm just interested if there is a solution for the above.

A: The request classes for Get, Post... extend HttpRequestBase so you can limit T accordingly:
public <T extends HttpRequestBase> CloseableHttpResponse sendRequestWithHeaders(Class<T> clazz, String url, Map<String, String> headers) throws IOException {
    CloseableHttpResponse response = null;
    try {
        HttpRequestBase request = clazz.getConstructor(String.class).newInstance(url);
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                request.setHeader(header.getKey(), header.getValue());
            }
        }
        response = client.execute(request);
    } catch (Exception ex) {
        // handle exception
    }
    return response;
}

A: For the exact described case, you may want to use a factory function (Function<String, HttpRequestBase> requestFactory) and method references (HttpGet::new, HttpPost::new, etc.) to achieve the desired result.
Please consider the following draft implementation using Apache HttpClient 4.5.3:
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

public class Program {
    public static void main(String[] args) throws IOException {
        try (final CloseableHttpResponse response = CustomHttpClient.sendRequestWithHeaders(
            HttpGet::new,
            "http://apache.org/",
            new HashMap<>())) {
            System.out.println(response.getStatusLine());
            final HttpEntity entity = response.getEntity();
            final String bodyAsString = EntityUtils.toString(entity);
            System.out.println(bodyAsString);
            EntityUtils.consume(entity);
        }
    }

    private static class CustomHttpClient {
        private CustomHttpClient() {
        }

        public static CloseableHttpResponse sendRequestWithHeaders(
            final Function<String, HttpRequestBase> requestFactory,
            final String url,
            final Map<String, String> headers) throws IOException {
            final CloseableHttpClient client = HttpClients
                .custom()
                .setDefaultHeaders(createHeaders(headers))
                .build();
            return client.execute(requestFactory.apply(url));
        }

        private static Collection<Header> createHeaders(final Map<String, String> headers) {
            return headers.entrySet()
                .stream()
                .map(entry -> new BasicHeader(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
        }
    }
}


text:
Q: Digium card shows green and red light after each second after configuration My digium card and pri was working fine in other system but i removed and installed that digium card in other system .I have configured it but its showing only 24 channels but i have 30 channels .My digium card shows green light then red light then green and than red light and so on.
I have been follwing this tutorial
I tried to reinstall asterisk,dahdi,and configured dahdi many times following above tutorial but it still shows me 24 channels.
the card and pri were worked perfectly in the previous system.
But what could be the reason of showing 24 channels rather than 30 and changing of card light from green to red the to green  aftersome seconds??
Any help would be appreciated.


text:
Q: Show compactness of an operator with Arzelà–Ascoli We have $K\colon L^{2}(a,b) \rightarrow L^{2}(a,b)$ such that $ Kf(t)=\sum_{j=1}^{n}\phi_{j}(t) \int_{a}^{b} \psi_{j}(S) f(s)ds$ where $\phi_{j} ,\psi_{j} \in L^{2}(a,b)$. We want to show that K is compact. I tried to use the Arzelà–Ascoli theorem  and I started by trying to show that for a sequence $f_{n}$ in the unit ball of $L^{2}(a,b)$ $K(f_{n})$ is uniformly bounded but I failed to prove this point. Can anyone help?
Thanks.

A: Notice that the range of the unit ball is contained in the compact set
$$K:=\left\{\sum_{j=1}^na_j\phi_j, |a_j|\leqslant \lVert \psi_j\rVert_2\right\}.$$


text:
Q: How to set the rotation rate of a pymunk SimpleMotor to reach a specific angle? I am trying to create a function (for deep learning) in which I can control my angle values for a robot by sending a specific list with the difference of angle, and then the motor should rotate till it reaches that angle . Setting the SimpleMotor.rate works inside the while loop when I am using keyboard controls, but it doesn't work when I am trying to use it in a function outside the while loop. Can anyone please suggest? Here is the code:
    def change_angle(angles):
        chassis_angle = self.chassis_b.angle*180/np.pi
        cur_angles = [self.leftLeg_1b_body.angle*180/np.pi- chassis_angle,self.leftLeg_1a_body.angle*180/np.pi-chassis_angle,self.rightLeg_1a_body.angle*180/np.pi-chassis_angle,self.rightLeg_1b_body.angle*180/np.pi-chassis_angle]
        target_angles = [cur_angles[0]+angles[0],cur_angles[1]+angles[1],cur_angles[2]+angles[2],cur_angles[3]+angles[3]]
        #time = angle/omega
        if target_angles[0]-cur_angles[0]>0:
                self.motor_ba1Left.rate = -2
                print("1")
        else:
                self.motor_ba1Left.rate = 2
                print("2")
        if target_angles[1]-cur_angles[1]>0:
                self.motor_ac1Left.rate = -2
                print("3")
        else:
                self.motor_ac1Left.rate = 2
                print("4")
        if target_angles[2]-cur_angles[2]>0:
                self.motor_ac1Right.rate = 2
                print("5")
        else:
                self.motor_ac1Right.rate = -2
                print("6")
        if target_angles[3]-cur_angles[3]>0:
                self.motor_ba1Right.rate = 2
                print("7")
        else:
                self.motor_ba1Right.rate = -2
                print("8")
        while (target_angles[0]!=cur_angles[0]) or (target_angles[1]!=cur_angles[1]) or (target_angles[2]!=cur_angles[2]) or (target_angles[3]!=cur_angles[3]):
            if target_angles[0]-cur_angles[0]==0:
                self.motor_ba1Left.rate = 0
            if target_angles[1]-cur_angles[1]==0:
                self.motor_ac1Left.rate = 0
            if target_angles[2]-cur_angles[2]==0:
                self.motor_ac1Right.rate = 0
            if target_angles[3]-cur_angles[3]==0:
                self.motor_ba1Right.rate = 0
            cur_angles = [self.leftLeg_1b_body.angle*180/np.pi- chassis_angle,self.leftLeg_1a_body.angle*180/np.pi-chassis_angle,self.rightLeg_1a_body.angle*180/np.pi-chassis_angle,self.rightLeg_1b_body.angle*180/np.pi-chassis_angle]

        self.motor_ba1Left.rate = 0
        self.motor_ac1Right.rate = 0
        self.motor_ac1Left.rate = 0
        self.motor_ba1Right.rate = 0

    simulate = True
    rotationRate = 1
    while running:
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYDOWN and event.key in (K_q, K_ESCAPE)):
                sys.exit(0)
            elif event.type == KEYDOWN and event.key == K_z:
                # Start/stop simulation.
                simulate = not simulate
            elif event.type == KEYDOWN and event.key == K_r:
                # Reset.
                self.reset_bodies()
            elif event.type == KEYDOWN and event.key == K_h:

                self.chassis_b.angular_velocity = -2
            elif event.type == KEYDOWN and event.key == K_u:
                self.chassis_b.apply_force_at_local_point([0,-1500000])
            elif event.type == KEYDOWN and event.key == K_j:
                self.chassis_b.apply_force_at_local_point([0,1500000])

            elif event.type == KEYDOWN and event.key == K_k:
                self.chassis_b.angular_velocity = 2
            elif event.type == KEYDOWN and event.key == K_w:
                self.motor_ba1Left.rate = -rotationRate
            elif event.type == KEYDOWN and event.key == K_s:
                self.motor_ba1Left.rate = rotationRate
            elif event.type == KEYDOWN and event.key == K_a:
                self.motor_ac1Left.rate = -rotationRate
            elif event.type == KEYDOWN and event.key == K_d:
                self.motor_ac1Left.rate = rotationRate
            elif event.type == KEYDOWN and event.key ==K_UP:
                self.motor_ba1Right.rate = rotationRate
            elif event.type == KEYDOWN and event.key ==K_DOWN:
                self.motor_ba1Right.rate = -rotationRate
            elif event.type == KEYDOWN and event.key ==K_LEFT:
                self.motor_ac1Right.rate = -rotationRate
            elif event.type == KEYDOWN and event.key ==K_RIGHT:
                self.motor_ac1Right.rate = rotationRate
            elif event.type == KEYUP:
                print("keyup")
                self.motor_ba1Left.rate = 0
                self.motor_ac1Left.rate = 0
                self.motor_ba1Right.rate = 0
                self.motor_ac1Right.rate = 0
                self.chassis_b.angular_velocity = 0
                #self.chassis_b.velocity = 0d
        self.draw()
        change_angle([30,40,-30,-40])

        ### Update physics
        fps = 50
        iterations = 25
        dt = 1.0/float(fps)/float(iterations)
        if simulate:
            for x in range(iterations): # 10 iterations to get a more stable simulation
                self.space.step(dt)
        #self.rotation()
        self.check_collide()
        #self.arm_collide_check()
        #self.printinfo()
        pygame.display.flip()
        clock.tick(fps)

    if __name__ == '__main__':
sim = Simulator()
sim.main()

A: I do not think the while loop within change_angle works as intended.
Every frame you call change_angles from the while running: loop. Within that function you first decide a rate for the motor with the if statements. So far so good. After this the rate will be set to some value, but the motor has not yet rotated anything, because that happens in the step function: self.space.step(dt) which is the part that actually move the simulation forward, run the motor, apply gravity, resolves collisions etc.
After this part there is a while loop where I think the idea was to figure out if the angles had updated to the target angles. However, that will never happen, since the simulation only happens in the step function as I described above.
I think you can try to remove that while loop, and instead put a big if statement in the beginning of change_angle that checks if the target angles are reached and if so reset rate of motor to 0 and return. (And otherwise continue the existing if-statements).
One last tip: The angles are floating point numbers, e.g. 42.234567.... It is almost never a good idea to try to compare if to such numbers are exactly equal, since they might never become equal because of rounding errors. Instead its better to check if the difference is smaller than some delta, e.g. target_angles[0]!=cur_angles[0] becomes abs(target_angles[0]-cur_angles[0]) < delta where delta is a small number (e.g. delta=0.01)


text: Q: 3rd Party App with Interactive Canvas on Nest Hub Max [Conversational Actions Sunset | Alternatives] we are developing 3rd-party apps on Nest Hub Max and currently using Interactive Canvas that triggers webhook HTTP requests. But Interactive Canvas won't be supported as part of the Conversational Actions Sunsets. The suggested alternatives App Actions doesn't support visual screens, so what are the alternatives for developing 3rd-party apps with visuals on the Nest Hub Max (in replace of Interactive Canvas and webhooks)?


text:
Q: Efficient way to construct this array in numpy? I need to construct an N x M x N array A such that A[i, j, k] == (0 if i != k else x[j]). I could write:
A = np.zeros((N, M, N))
for i in range(N):
    for j in range(M):
        A[i,j,i] = x[j]

Or, alternatively:
A = np.zeros((N, M, N))
for i in range(N):
    A[i,:,i] = x

But both are most likely too slow for my purposes. Is there a faster way?

A: Approach #1
Using broadcasting to create all those linear indices where x's are to be assigned and then simply assign into its flattened view, like so -
# Initialize
Aout = np.zeros((N, M, N))

# Comput all linear indices
idx = (np.arange(N)*(N*M+1))[:,None] + N*np.arange(M)

# In a flattened view with `.ravel()` assign from x
Aout.ravel()[idx] = x

Approach #2
Using views based element access supported by np.lib.stride_tricks.as_strided -
Aout = np.zeros((N, M, N))
s0,s1,s2 = Aout.strides
Aoutview = np.lib.stride_tricks.as_strided(Aout,shape=(N,M),strides=(s0+s2,s1))
Aoutview[:] = x

Approach #3
Another approach would be to use integer array indexing along the first and third axes, closely simulating the second approach from the question, but in a vectorized manner -
Aout = np.zeros((N, M, N))
Aout[np.arange(N),:,np.arange(N)] = x

Runtime test
Approaches -
def app0(x,A):
    for i in range(N):
        for j in range(M):
            A[i,j,i] = x[j]
    return A

def app1(x,A):
    for i in range(N):
        A[i,:,i] = x
    return A

def app2(x,Aout):
    idx = (np.arange(N)*(N*M+1))[:,None] + N*np.arange(M)
    Aout.ravel()[idx] = x
    return Aout

def app3(x,Aout):
    s0,s1,s2 = Aout.strides
    Aoutview = np.lib.index_tricks.as_strided(Aout,shape=(N,M),strides=(s0+s2,s1))
    Aoutview[:] = x
    return Aout

def app4(x,Aout):
    r = np.arange(N)
    Aout[r,:,r] = x
    return Aout

Verification -
In [125]: # Params
     ...: N, M = 100,100
     ...: x = np.random.rand(M)
     ...:
     ...: # Make copies of arrays to be assigned into
     ...: A0 = np.zeros((N, M, N))
     ...: A1 = np.zeros((N, M, N))
     ...: A2 = np.zeros((N, M, N))
     ...: A3 = np.zeros((N, M, N))
     ...: A4 = np.zeros((N, M, N))
     ...:

In [126]: print np.allclose(app0(x,A0), app1(x,A1))
     ...: print np.allclose(app0(x,A0), app2(x,A2))
     ...: print np.allclose(app0(x,A0), app3(x,A3))
     ...: print np.allclose(app0(x,A0), app4(x,A4))
     ...:
True
True
True
True

Timings -
In [127]: # Make copies of arrays to be assigned into
     ...: A0 = np.zeros((N, M, N))
     ...: A1 = np.zeros((N, M, N))
     ...: A2 = np.zeros((N, M, N))
     ...: A3 = np.zeros((N, M, N))
     ...: A4 = np.zeros((N, M, N))

In [128]: %timeit app0(x,A0)
     ...: %timeit app1(x,A1)
     ...: %timeit app2(x,A2)
     ...: %timeit app3(x,A3)
     ...: %timeit app4(x,A4)
     ...:
1000 loops, best of 3: 1.49 ms per loop
10000 loops, best of 3: 53.6 µs per loop
10000 loops, best of 3: 150 µs per loop
10000 loops, best of 3: 28.6 µs per loop
10000 loops, best of 3: 25.2 µs per loop


text:
Q: Using ASPNETDB.mdf in a real application. How can it be used with another database? Firstly, I'm new. I'm creating a website in .NET and am getting confused by a few things.
When using a CreateUserWizard control, a database file called aspnetdb.mdf is created automatically.
I am creating a Blackjack game and thus need to initialise values such as totalWins, totalGamesPlayed etc. for each user.
My question is, what is the best method to do so in .NET? Should I add fields to the Users table in aspnetdb.mdf or create a seperate file with a Users table?
Eitherway, how do I populate this table adding a new record for each new user?

A: You want to use the Profiles feature, also built-in to .NET.

A: I would not mess around with the Users table in aspnetdb.mdf since it's meant to contain personal information such as username, etc. You should create a separate table called User_Score and work off of that one. You can create a foreign key to the Users table using the user_id (or whatever the suitable key should be).
As far as populating the data initially, there are many approaches to this, one could be having a trigger that will initialize a record in the User_Score table as soon as a record is created in the User table.
One approach would be creating a trigger similar to this in the User table:
CREATE TRIGGER myTrigger
   ON User
   AFTER INSERT
AS BEGIN
   -- INSERT RECORD IN THE User_Score table here
   -- populating the appropriate fields. Example:
  INSERT INTO User_Score (username,columna, columnb, columnc)
  SELECT username, 0,0,0 from inserted
END


text:
Q: Authentication for a webpage I'm having a webpage on which I will try to make a nice authentication..
At the best I would like that only the users allowed should be able to visit it, without any password or stuff. Is that possible and how can I do that?
If it matters the application is written in c#
Otherwise anyone has any smooth tip?

A: There are 2 parts involved here:

*

*Identifying the user and making sure it is what it tells to be (Authentication);

*Allowing only some of the users to access your page (Authorization).

For your case, the second one should be easy, once you have done the first one. A good starting point would be The definitive guide to form-based website authentication


text:
Q: Windows Server 2012 AD DC/DNS/DHCP in single server I have to say I am not a system admin but I had to setup the development environment in my company and I ran into many issues and after searching for many hours I hope somebody can help me out here!
My Setup consist of an ADSL modem/router connected to NIC1 of server and NIC2 connected to switch!
I set static IP for NIC1 192.168.15.100 and add AD DC to server which added DNS then added DHCP to server! right now PCs connected to switch can get IP from switch but no internet access. I have internet on server but the NIC2 shows limited connectivity!
on PCs I get this
IP: 10.10.200.111
Subnet Mask: 255.0.0.0
Gateway: 10.10.200.1
DNS: 192.168.15.100
DHCP: 10.10.200.1
I cant join PCs to domain too, I get the error message that "The specified domain does not exist or could not be contacted"
on AD DC I get warnings for 2886, 1400 and 4013
on DNS I get warning for 4013
on DHCP I get warning for 10020
In DNS Manager I have 2 DNS servers, 1 for DEV-SERVER and another for dev-server.hq.mycompany.com.
Here is Server IP config details, any sort of help would be appreciated!
Windows IP Configuration

   Host Name . . . . . . . . . . . . : dev-server
   Primary Dns Suffix  . . . . . . . : hq.mycompany.com
   Node Type . . . . . . . . . . . . : Hybrid
   IP Routing Enabled. . . . . . . . : No
   WINS Proxy Enabled. . . . . . . . : No
   DNS Suffix Search List. . . . . . : hq.mycompany.com

Ethernet adapter Ethernet 2:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Broadcom BCM5716C NetXtreme II GigE (NDIS
 VBD Client) #33
   Physical Address. . . . . . . . . : 78-2B-CB-26-97-D3
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::450b:7913:9c5e:4be9%13(Preferred)
   IPv4 Address. . . . . . . . . . . : 10.10.200.1(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.0.0.0
   Default Gateway . . . . . . . . . :
   DHCPv6 IAID . . . . . . . . . . . : 326642635
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-18-B9-BC-E6-78-2B-CB-21-97-D2

   DNS Servers . . . . . . . . . . . : ::1
                                       127.0.0.1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Ethernet adapter Ethernet:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Broadcom BCM5716C NetXtreme II GigE (NDIS
 VBD Client) #32
   Physical Address. . . . . . . . . : 78-2B-CB-26-97-D2
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::393f:b832:6fb6:1216%12(Preferred)
   IPv4 Address. . . . . . . . . . . : 192.168.15.100(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.15.1
   DHCPv6 IAID . . . . . . . . . . . : 259533771
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-18-B9-BC-E6-78-2B-CB-21-97-D2

   DNS Servers . . . . . . . . . . . : ::1
                                       127.0.0.1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Tunnel adapter isatap.{8A7DB7D3-7E12-4A4B-9885-34080BF56936}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter Local Area Connection* 12:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Teredo Tunneling Pseudo-Interface
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter isatap.{2ED762D8-71D0-40D3-9568-D9CA45135595}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter #2
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

A: This setup is a mess.

*

*Don't multihome your Domain Controller.

*Don't have just one Domain Controller for a domain.

*You can't just use a server as a router (what you're trying to do) without explicitly configuring it to be one. You need to install RRAS, in this case.

*Don't run RRAS or any other roles on a Domain Controller. Get another server or a hardware router/L3 switch.

*Your clients need to point to the server for DNS to join the domain. It also has to be able to actually reach that interface. Your current config doesn't allow this.
There is really a lot here that is configured wrong. I'd throw it away and start from scratch with a new design. A design that doesn't involve multi-homing a DC and doesn't attempt to use it as a router.


text:
Q: AWS: dynamically allocate & associate new IP addresses to EC2 instance? I am running some web crawling jobs on an AWS hosted server. The crawler scrapes data from an eCommerce website but recently the crawler gets "timeout errors" from the website. The website might have limited my visiting frequency based on my IP address. Allocating a new Elastic-IP address solves the problem, but not for long.
My Question: Is there any service that I can use to automatically and dynamically allocate & associate new IPs to my instance? Thanks!

A: To change the EIP you can just use Python boto
Something like this:
#!/usr/bin/python

import boto.ec2

conn = boto.ec2.connect_to_region("us-east-1",
    aws_access_key_id='<key>',
    aws_secret_access_key='<secret>')

reservations = ec2_conn.get_all_instances(filters={'instance-id' : 'i-xxxxxxxx'})
instance = reservations[0].instances[0]

old_address = instance.ip_address
new_address = conn.allocate_address().public_ip

conn.disassociate_address(old_address)
conn.associate_address('i-xxxxxxxx', new_address)

A: If you want use TOR network just execute:
sudo apt-get install tor
sudo /etc/init.d/tor start

 netstat -ant | grep 9050 #  Tor port

and in your java project you set the proxy as:
public static void main(String[] args) {
    System.setProperty("socksProxyHost", "127.0.0.1");
    System.setProperty("socksProxyPort", "9050");

you can scheduler a cron job that each XX time reboot your application and tor.
Easy and secure.


text:
Q: Unit test which asserts that current thread is the main thread The question is does it make sense to write a unit test which asserts that the current thread is the main thread? Pros/cons?
Recently I've seen the unit test which asserts the current thread for the callback of service. I'm not sure, that it's a good idea, I believe it's more kind of integration test. In my opinion, the unit test should assert method in isolation and should not know about the nature of the consumer of service.
For example, in the iOS, the consumer of this service is intended to be a UI which by default has a constraint to run a code at the main thread.

A: Should you write a unit test which tests if a thread is the main thread?  Depends, but probably not a good idea.
If the point of a unit test is meant to verify proper functioning of a method, then testing this aspect is almost certainly not testing this aspect.  As you said yourself, it is conceptually more of an integration test, since the proper functioning of a method is not likely to change based on which thread is running it, and the one responsible for determining which thread gets used is the caller and not the method itself.
However, this is why I say it depends, because it may very well depend on the method itself, should the method spawn new threads.  Though in all likelihood this isn't your case.
My advice would be to leave this check out of the unit test and port it to a proper integration test for this aspect.

A:
should not know about the nature of the consumer of service.

When a consumer consumes a service there is a "contract" express or implied about what functionality is provided and how. Restrictions on what thread the callback can happen in are part of that contract.
I presume that your code runs in a context where there is some sort of "event engine" that runs in the "main thread" and a way for other threads to request that the event engine schedules code is run in the main thread.
In the purest view of unit tests you would mock absoloutely every dependency. In the real world very few people do that. The code under test is allowed to use the real versions of at least basic platform features.
So the real question IMO is do you consider the event engine and the runtime threading support to be part of the "basic platform features" that unit tests are allowed to depend on or not? If you do then it makes perfect sense to check if a callback happens on the "main thread". If you are mocking the event engine and threading system then you would design your mocks so they can determine if the callback would have happened on the main thread. If you are mocking the event engine but not the runtime threading support you would want to test if the callback happens on the thread where your mock event engine runs.

A: Let me show you my favorite unit test principles:

A test is not a unit test if:

*

*It talks to the database

*It communicates across the network

*It touches the file system

*It can't run at the same time as any of your other unit tests

*You have to do special things to your environment (such as editing config files) to run it.

  A Set of Unit Testing Rules - Michael Feathers

If your unit test insists that it be the "main thread" it's hard not to run afoul of number 4.
This may seem harsh but remember that a unit test is just one of many different kinds of tests.

You're free to violate these principles. But when you do, don't call your test a unit test. Don't put it with the real unit tests and slow them down.

A: I can see why it would be an attractive test. But what would it actually be testing? say we have the function
showMessage(string m)
{
    new DialogueBox(m).Show(); //will fail if not called from UI thread
}

Now I can test this and run it in a non UI thread, proving that an error is thrown. But really for that test to have any value the function needs to have some specific behaviour that you want it to do when run in a non UI thread.
showMessage(string m)
{
    try {
        new DialogueBox(m).Show(); //will fail if not called from UI thread
    }
    catch {
        Logger.Log(m); //alternative display method
    }
}

Now I have something to test, but its unclear that this kind of alternative would be useful in a real life

A: Arrange
Act
Assert
Should a unit test assert that it's on a specific thread?  No, because it's not testing a unit in that case, it's not even an integration test, as it doesn't say anything about the configuration taking place in the unit...
Asserting which thread the test is on, would be like Asserting the name of your test server, or better yet the name of the test method.
Now, it might make sense to Arrange for the test to be run on a specific thread, but only when you want to be sure that it will return a specific result based on the thread.

A: If you have a function that is documented to only run correctly on the main thread, and that function is called on a background thread, that's not the functions fault. The fault is the caller's fault, so unit tests are pointless.
If the contract is changed so that the function will run correctly on the main thread, and report a failure when run on a background thread, you can write a unit test for that, where you call it once on the main thread and then on a background thread and check that it behaves as documented. So now you have a unit test, but not a unit test checking that it is run on the main thread.
I would very much suggest that the first line of your function should assert that it runs on the main thread.

A: Unit testing is only useful if it's testing correct implementation of said function, not correct usage, because a unit test can't say that a function is not going to be called from another thread in the rest of your codebase, just as it can't say that functions won't be called with parameters that violate their preconditions (and technically what you're trying to test is basically a violation of a precondition in usage, which is something you can't effectively test against because the test can't restrict how other places in the codebase use such functions; you can test if violations of preconditions result in approriate errors/exceptions, however).
This is an assertion case to me in the implementation of the relevant functions themselves as some others have pointed out, or even more sophisticated is to make sure the functions are thread-safe (though this is not always practical when working with some APIs).
Also just a side note but "main thread" != "UI thread" in all cases. Many GUI APIs are not thread-safe (and making a thread-safe GUI kit is damned hard), but that doesn't mean you have to invoke them from the same thread as the one which has the entry point for your application. That might be useful even in implementing your assertions inside the relevant UI functions to distinguish "UI thread" from "main thread", like capturing the current thread ID when a window is created to compare against instead of from the application main entry point (that at least reduces the amount of assumptions/usage restrictions the implementation is applying to only what is truly relevant).
Thread safety was actually the "gotcha" tripping point in a former team of mine, and in our particular case I would have labelled it the most counter-productive "micro-optimization" of them all of a kind that incurred more maintenance costs than even handwritten assembly. We had rather comprehensive code coverage in our unit tests, along with rather sophisticated integration tests, only to encounter deadlocks and race conditions in the software that eluded our tests. And that was because the developers haphazardly multithreaded code without being aware of every single side effect that could possibly occur in the chain of functions calls that would result from their own, with a rather naive idea that they could fix such bugs in hindsight by just throwing locks around left and right, and perhaps even getting a false sense of confidence from their test coverage*.

I was skewed in the opposite direction as an old school type that distrusted multithreading, was a real latecomer to embracing it, and thought correctness beats performance to the point of rarely ever getting use out of all these cores we have now, until I discovered things like pure functions and immutable designs and persistent data structures which finally allowed me to fully utilize that hardware without a worry in the world about race conditions and deadlocks. I must admit that all the way up until 2010 or so, I hated multithreading with a passion except for a few parallel loops here and there in areas that are trivial to reason about thread-safety, and favored much more sequential code for the design of products given my grief with multithreading in former teams.

To me that way of multithreading first and fix bugs later is a terrible strategy to multithreading to the point of almost making me hate multithreading initially; you either make sure your designs are rock-solid thread-safe and that their implementations only use functions with similar guarantees (ex: pure functions), or you avoid multithreading. That might come across a bit dogmatic but it beats discovering (or worse, not discovering) difficult-to-reproduce issues in hindsight which elude tests. There's no point optimizing a rocket engine if that's going to result in making it prone to unexpectedly explode out of the blue halfway along its journey to out of space.
If you inevitably have to work with code which is not thread safe, then I don't see that as an issue to solve with unit/integration testing so much. Ideal would be to restrict access. If your GUI code is decoupled from business logic, then you might be able to enforce a design which restricts access to such calls from anything other than the thread/object which creates it*. That's far mode ideal to me is to make it impossible for other threads to call those functions than to try to make sure they don't.

*

*Yes, I realize that there's always ways around whatever design restrictions you enforce typically where the compiler can't protect you. I'm just speaking practically; if you can abstract "GUI Thread" object or whatever, then it might be the only one handed a parameter to the GUI objects/functions, and you might be able to restrict that object from having access to other threads. Of course it might be able to bypass and dig deep and work its way around such hoops to pass said GUI functions/objects to other threads to invoke, but at least there's a barrier there, and you can call anyone who does that an "idiot", and not be in the wrong, at least, for clearly bypassing and seeking loopholes for what the design obviously was attempting to restrict. :-D That's actually a very practical litmus test to me is like how confidently you can call someone an "idiot" in misusing a design, without the risk of you actually being the idiot for designing something prone to misuse.

A: If the callback is documented to not be thread-safe to invoke on any other than, say, the UI thread or main thread, then it seems perfectly reasonable in a unit test of a code module which causes the invocation of this callback to make sure it isn't doing something that is not thread-safe by working outside the thread that the OS or application framework is documented to guarantee safe.


text:
Q: Creating iOS plist based on another I'm very new to iOS development and am having an issue.  I have a plist that contains a lot of information for a bunch of different animals.  The plist is an array of dictionaries, and each dictionary is an animal.  Each dictionary has a key called "type", which is the type of animal (cat, dog, bird, etc).  I want my application to first display a table view that lists all of the possible types.    When the user selects the type, they will then go to another table view that lists all of the animals of that selected type.  They can then select that specific animal and another view will be displayed that has all the detailed information about that specific animal.

I suppose the best way to approach this is that when a user selects the "type" of animal, a new plist will be generated containing the directory entries from the original plist that have a "type" key that matches what the user selects.  How can I implement this?  Would this logic be in the viewDidLoad method for the second table view?  Once the plist is created that contains only the animals of interest, the cellForRowAtIndexPath method would display the list of animals?

Thanks for any assistance!

David

A: First: You shouldn't generate any new plists in this situation... If you want to store a list of dictionaries based on a query of your data, it should go into an NSMutableDictionary/NSDictionary. Before creating each table, you should construct one of these dictionaries with the filtered data, and pass it to the table as the data source.
Second: I'd try using a database instead of a plist to make your queries a little easier to manage.
Third: Normalize your data as much as possible, hence, have a database table (or plist if you go that route) of "animal types," and a db table/plist of "animals" ... then reference the animal's type by id, instead of by name. If you change that name in the future, you'll have a hell of a time trying to find every occurrence. In addition, it's less buggy that way; one accidental misspelling will leave you wondering why one animal is causing an error and the others aren't.


text:
Q: How could i rename android studio package I have a problem - I am trying to rename the packages of my Android application with Android Studio, but it turns out that following the steps of other guides after giving refactor does not give me the option to rename the package.
Instead it gives me to rename the directory directly and I don't know what to do with that.
There is screenshot


text:
Q: pip fails everytime I try to install any packages My pip didn't work for any package:
 regex_3/_regex.c:46:20: fatal error: Python.h: No such file or directory
     #include "Python.h"
                        ^
    compilation terminated.
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

when I tried to fix this by
sudo apt-get install python3-dev

I got this:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 python3-dev : Depends: python3 (= 3.5.1-3) but 3.5.1-4 is to be installed
               Depends: libpython3-dev (= 3.5.1-3) but it is not going to be installed
               Depends: python3.5-dev (>= 3.5.1-2~) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

and i can't install any of these dependencies!Could someone help me out.

A: You should be able to see the list of held packages by:
apt-mark showhold

and then un-hold them by
sudo apt-mark unhold <package name>

After that, you should be able to remove the conflicting packages and then reinstall all.
Try removing all the unmet dependencies and then reinstalling.


text:
Q: Script bash merge directories recursively and execute function for common files I need to bash script the merging of several directories recursively into one, however when copying an already existing file I want to execute a specific function.
I was thinking, as a start :
    mkdir merge
    cp -r dir1/* dir2/* merge/

but when a file already exists with the same name, I don't want to overwrite or discard, I want to execute my function, something like:
    if [-f $file]
    do myfunction() done

Any idea what my script should look like ?
Thanks

A: You could use a simple script like that:
#!/usr/bin/env bash

myfunction()
{
    printf "Omit %s\n" "$i"
}

dst=merge
mkdir -p "$dst"

# put a list of directories you want to copy here
for i in dir{1..10}
do
    if [ -e "$dst"/"$i" ]
    then
    myfunction "$i"
    continue
    fi

    cp -r "$i" "$dst"
done

It should work for simple cases but it could be optimized.  For
example, instead of calling cp multiple times one could create a
list of directories that should be copied and run cp only once or
using xargs to avoid Argument list too long issue.

A: You could use this script:
#!/usr/bin/env bash

# make destination directory
dest=merge
mkdir -p $dest

# If file exists in target directory call `some_function`
# Do not overwrite existing files
for f in dir{1,2,3}/*; do
    [ -f "$dest/$(basename $f)" ] && some_function
    cp -rn "$f" "$dest"
done


text:
Q: Better way to pass userInfo data with NSNotificationCenter in iOS [[NSNotificationCenter defaultCenter] postNotificationName:@"TapNewProduct" object:self.productID];

(or)
NSDictionary *dict = @{@"productID":self.productID};

[[NSNotificationCenter defaultCenter] postNotificationName:@"TapNewProduct" object:nil userInfo:dict];

Which is better method from above two?

A: Your first option abuses the 'sender' parameter of the notification because it's simple. It'll work, but it isn't correct. The idea with that parameter is that you can use it to filter the notifications that you receive. If you'll use it like that then fine, but it isn't for passing user info.
So, the second option is the correct one.
Imagine someone else coming to help on your project in the future - the more your code is written to follow standards the easier it'll be for them to help you.

A: In both the methods you are gonna get same output. you will fetch the object by notification.object.
but in this,
[[NSNotificationCenter defaultCenter] postNotificationName:@"TapNewProduct" object:self.productID];

there is no need to create a dictionary. it can reduce the code.

A: The object parameter is the "notificationSender", that is, the object posting the notification.  The userInfo parameter is intended to contain information about the the notification and it may be nil.
More details in Apple's reference documentation.

A: postNotificationName:object: method invokes postNotificationName:object:userInfo: with a userInfo argument of nil.So basically there is no reason to argue with which one is better than the other.


text:
Q: SQL server 2005 - query aribitrary time interval in date range I have a DateTime column. I want to extract all records, lets say, from 8:30 to 16:15 within a certain date range. My problem is that I need to compare hour and minute as a single time value. I can test the DATEPART for Greater or Less than some hours value, but if I then do that for minutes my query will fail if the later-in-the-day time has a smaller minutes value.
I have looked at INTERVAL, BETWEEN, DATEPART, DATEDIFF etc, but don't see quite how to to this without a "TimeOfDay" value that I can use across records of different dates.
I have tried subtracting the year, month and day parts of the date so that I can compare just the time of day, but when attmpting to subract, say, the year part of a date I get an overlfow error:
This part works:
select - cast( DATEPART(YEAR, CallTime) as integer) from history

This fails:
select DATEADD(YEAR, - cast( DATEPART(YEAR, CallTime) as integer), CallTime)
from history where calltime is not null

I have also tried casting the hours and minutes parts to chars, concatenating them and comparing to my target range, but this also fails.
I believe newer versions of SQL server may have a function to deal with this situation, but that's not available to me.
I hope and imagine there is a simple, obvious solution to this, but it's eluding me.

A: Try creating a "MinuteOfDay" function that calculates how many minutes have passed in the day based on a datetime.
CREATE FUNCTION dbo.[MinuteOfDay]
(
    @dt datetime
)
RETURNS int
AS
BEGIN
    RETURN (datepart(hh,@dt)*60) + datepart(mi,@dt)
END

then use the result of that function to filter.
select *
from MyTable t
where dbo.MinuteOfDay(t.SomeDateTimeColumn) between dbo.MinuteOfDay('1900-1-1 08:30:00') and dbo.MinuteOfDay('1900-1-1 16:15:00')

A: give this a shot:
DECLARE @StartDateTime  datetime
       ,@EndDateTime    datetime

--date range is ALL of January 1st up to & including 31st
SELECT @StartDateTime='2011/01/01'
      ,@EndDateTime='2011/01/31'

SELECT
    *
    FROM TableName  t
    WHERE
        t.ColumnDate>=@StartDateTime AND t.ColumnDate<@EndDateTime+1 --date range
        AND LEFT(RIGHT(CONVERT(char(19),t.ColumnDate(),120),8),5)>='08:30' --time range start
        AND LEFT(RIGHT(CONVERT(char(19),t.ColumnDate(),120),8),5)<='16:15' --time range end

if you have an index on t.ColumnDate, this should be able to take advantage of it.
the "date range" part of the WHERE throws away rows that are not within the intended date range.  The "time range start" part of the WHERE throws away rows that are to early in time and the "time range end" throws away rows that are to late.

A: DATETIME values can be cast as FLOAT.  Actually, a DATETIME is stored as a FLOAT.
The whole part of the FLOAT is the days since '12/31/1899' (or something close).  The fractional part is the number of hours divided by 24.  So 0.5 = 12 Noon.
08:30 is 0.3541666667
16:15 is 0.6770833333
SELECT CAST(CAST('2011-03-25 08:30:00' AS DATETIME) AS FLOAT) = 40625.3541666667
SELECT CAST(CAST('2011-03-25 16:15:00' AS DATETIME) AS FLOAT) = 40625.6770833333
So you could write
SELECT * FROM users WHERE hire_date < 40625.3541666667
Using a DATETIME as FLOAT you can use whichever mathematical functions work best for your query.