text:
Q: How do I pass the dropdown select value to a button click in the controller and search against the value in data base? here is the controller
@RequestMapping(value = "/submitrule", method = RequestMethod.POST)
public String addruleSerch(@ModelAttribute("SpringWeb") Rule obj2, ModelMap  model) {
model.addAttribute("Select", obj2.getId());
System.out.println("********" + obj2.getId());
ruleApi.getRule(obj2.getId());
model.addAttribute("listrule", ruleApi.getRule(obj2.getId()));
return "redirect:/hello";
}

here is the html....
<form action="/CommissionTool/submitrule" method="post">

        <select name="Select"><c:forEach items="${listRules}" var="rule">
                                    <option value="${rule.id}">
                                        <c:out value="${rule.id}" />
                                    </option>
                    </c:forEach>
                </select>

        <input type="submit" onClick="addRow('in_tbl_name')" VALUE="Add New">

</form>

How could i fix this.. please help me
Thanks in Advance...

A: Well you need to do several changes in your code, but is pretty near.

*

*You need to send the object you want to use as modelAttribute to the view the first time.

*In your html you need to say to the form which is the object to render, your model attribute

*Create a POST method in your controller to retrieve the object
Lets put all together in this this example. I have a class called RuleForm, which contains an attribute of type Rule.
public class RuleForm {
    ...
    @Getter @Setter    //here use lombok, but you could create your getters-setters methods
    private Rule rule;
    ...
}

Now in the controller, into the GET method, we set the view resolver(JSP) and the object we will send to there. In this case an object of type FormRule
@RequestMapping(value = "/submitrule", method = RequestMethod.GET)
      public ModelAndView addruleSerch() {
     ModelAndView model = new ModelAndView("yourView");
     //here you choose the name you will use in your view, is up to you the name to choose
     model.addObject("formRule", new FormRule());
     return model;
}

Now we need to pick up that object we sent to the view and use it into our form tag.
<form action="/CommissionTool/submitrule" method="post" model="formRule">
...
<select name="rule.id"><c:forEach items="${listRules}" var="rule">
                                <option value="${rule.id}">
                                    <c:out value="${rule.id}" />
                                </option>
                </c:forEach>
            </select>

In this point when we send the form to the Controller, we will send the RuleForm object with a value into rule.id object, then in the controller we have to get that id value and add out business logic.
@RequestMapping(value = "/submitrule", method = RequestMethod.POST)
      public String addruleSerch(@ModelAttribute RuleForm ruleForm) {
     //Here you will have access to your  object
     ruleForm.getRule().getId();// rule selected in the form
     ... your business logic
     return "redirect:/someUrl";
}


text:
Q: Arduino/C++: Access specific header file of structs from library (Not sure whether this is exclusively a C/C++ issue)
I'm currently fragmenting elements of a large Arduino project into reusable libraries - so far soo good.
However, a number of methods in the libraries return special structs which are declared in a data-types.h file contained in each library. The problem I have now is I'm unable to import/utilise these structs in my main sketch. I've tried declaring a variable of the DataTypes class in the main library header file and accessing the structs through it, but I get error error: invalid use of 'struct DataTypes::_theStructNameHere_t'
How would I go about accessing these structs from the library in my main sketch to declare as a variable type? I don't want to have to copy the header file which contains the structs from the library into my sketch, and I also don't want to have to create a separate library just for this single header file of structs!
Here's a quick example of what I mean:
Main.cpp:
#include <Arduino.h>
#include <MyLibrary.h>

MyLibrary myLib;

void setup() {
    (This is declared in the library) myLib.dataTypes._theStructNameHere_t response = myLib.getASpecialValueWhichIsOfType_theStructNameHere_t()// Gives "error: invalid use of 'struct DataTypes::_theStructNameHere_t'""

    // Example usage of the struct:
    Serial.print("\n Loop Card Status: ");Serial.print(response.loop_status, HEX);
    if (response.number_allocated > 0) {
        Serial.print("\n Devices Allocated: ");Serial.print(response.number_allocated, HEX);
    } else {
        if (response.loop_status != 0x123) {
            // Some condition
        } else {
            // Something else
        }
    }
}

void loop() {
    ...
}

Library Structure:
    src/
    - /data-types/
    - - data-types.h
    - MyLibrary.cpp
    - MyLibrary.h

Library Header MyLibrary.h:
#ifndef   _MYLIBRARY_H_
#define   _MYLIBRARY_H_

#include <Arduino.h>

#include "./helpers/helpers.h"
...
#include "./data-types/data-types.h"

class MyLibrary {

    public:
        Uart *_commPort;
        Helpers helpers;
        ...
        DataTypes dataTypes;

        DataTypes::_theStructNameHere_t getASpecialValueWhichIsOfType_theStructNameHere_t();

      ...

    protected:
    private:

};

#endif // _MYLIBRARY_H_

DataTypes Class data-types.h:
#ifndef   _RESPONSE_TYPES_H
#define   _RESPONSE_TYPES_H

class DataTypes
{
    public:
      struct _theStructNameHere_t
        {
            bool successful;
            uint8_t loop_status;
            uint8_t number_allocated;
            uint8_t highest_address;
            uint8_t number_inputs;
            uint8_t number_outputs;
        }
        ..even more..
    private:
}
#endif // _RESPONSE_TYPES_H

A: I was able to obtain a MCVE from your example:
class DataTypes
{
    public:
    struct _theStructNameHere_t
    {

    };
};

class Library
{
    public:
        DataTypes dataTypes;
        DataTypes::_theStructNameHere_t getMyDataType();
};

int main(int argc, char *argv[])
{
    Library myLib;
    myLib.dataTypes._theStructNameHere_t response;
}

which gives a similar error as your code:
~$ g++ test.cpp
test.cpp: In function 'int main(int, char**)':
test.cpp:20:21: error: invalid use of 'struct DataTypes::_theStructNameHere_t'
     myLib.dataTypes._theStructNameHere_t response;

The problem is that you use an instance to access the struct type/name. To fix it, replace
myLib.dataTypes._theStructNameHere_t response = ...;

with
DataTypes::_theStructNameHere_t response = ...;

Notes:

*

*Instead of using classes to create separate namespaces, please consider using namespaces directly. This is a feature of C++ which is available under Arduino.

namespace Library {

namespace DataTypes {

struct _theStructNameHere_t
{
    ...
};

...

} /*** namespace Library::DataTypes ***/

} /*** namespace Library ***/

*

*Please read StackOverflow guidelines concerning how to ask a good question, in particular the section about Mininimal, Complete and Verifiable Example.

*Sooner or later someone will tell you that there is no such thing as C/C++; C is C and C++ is C++; Arduino lives in its own world, even if is based on C++. Thus, you might want to remove C and C++ tags from your question.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Node (express.js) next() is called before end of stream I have the following middleware function
var bodyParser = require('body-parser'),
  fs = require('fs');
module.exports = function(req, res, next) {
  // Add paths to this array to allow binary uploads
  var pathsAllowingBinaryBody = [
    '/api2/information/upload',
    '/api2/kpi/upload',
  ];

  if (pathsAllowingBinaryBody.indexOf(req._parsedUrl.pathname) !== -1) {
    var date = new Date();
    req.filePath = "uploads/" + date.getTime() + "_" + date.getMilliseconds() + "_" + Math.floor(Math.random() * 1000000000) + "_" + parseInt(req.headers['content-length']);

    var writeStream = fs.createWriteStream(req.filePath);
    req.on('data', function(chunk) {
      writeStream.write(chunk);
    });
    req.on('end', function() {
      writeStream.end();
      next();
    });
  } else {
    bodyParser.json()(req, res, next);
  }
};

The files is being transfered correctly however sadly the next() in the
req.on('end', function() {
  writeStream.end();
  next();
});

is called before it is done writing all data to the new file.
My question is what am i doing wrong? And how can i fix it?

A: Use the writable file stream's close event to know when the file descriptor has been closed.
Replace this:
var writeStream = fs.createWriteStream(req.filePath);
req.on('data', function(chunk) {
    writeStream.write(chunk);
});
req.on('end', function() {
    writeStream.end();
    next();
});

with this:
req.pipe(fs.createWriteStream(req.filePath)).on('close', next);


text:
Q: AppleScript and Numbers: Can't add value to cell I'm trying to merge data from various sources into Numbers.
I keep receiving this error message:
Can't set «class NMCv» of "C30" to 8302.0.

This is the subroutine I am using:
on addViewsToNumbersSheet(userViews, numbersRow)
    tell application "Numbers"
        tell front document
            tell table 1 of sheet "Doc Data"
                log "Row: " & numbersRow
                log "Value: " & userViews
                set cellC to ("C" & numbersRow as string)
                set cellValue to userViews
                set value of cellC to cellValue
            end tell
        end tell
    end tell
end addViewsToNumbersSheet

The data prints to the log:
(*Row: 30*)
(*Value: 8302.0*)

I tried to just place a string in the cell and I received the same error message. What am I missing? I have a separate script and I am able to add values to this same sheet with it.
So then I logged the class, it was a real. After various conversion efforts failed I added a subroutine that returned an integer. I feel like I am killing a fly with a bazooka here.
on convertNumber(userViews)
    set aString to userViews as string
    set AppleScript's text item delimiters to "."
    set aNumber to text item 1 of aString as number
    return aNumber
end convertNumber

and my previous script now looks like so:
on addViewsToNumbersSheet(userViews, numbersRow)
    tell application "Numbers"
        tell front document
            tell table 1 of sheet "Prebid Docs"
                set convertedNum to my convertNumber(userViews)
                set cellC to ("C" & numbersRow as string)
                set value of cellC to convertedNum
            end tell
        end tell
    end tell
end addViewsToNumbersSheet

I did confirm that convertedNum is an integer.
And still getting the error message. Sigh. Any help would be great.
Bigger picture:
I am pulling view data from Google Analytics as an Excel file. In my Numbers file I have the doc path and date it was added to the repo in cols A and B. I now want col C to contain this view data. I match paths (from GA (in Excel) to repo path (in Numbers)), save the row that matched (from Numbers) and the value from Excel and want to add that value to the Numbers row, col C.

A: set cellC to cell ("C" & numbersRow as string)


text:
Q: Change text back and forth using a key My assignment is to use events and navigate the DOM.
I have to create a script so that when i press Q while on my webpage, (>p<)A(>/p<) has to change to the letter Q, when i press Q again, the letter has to return to A.
Thanks, in advance! :-)

document.body.addEventListener("keydown", function(event) {
  if (event.keyCode == 81) {
    document.getElementById('A').innerText = "Q";
  }
});

A

A: Check, whether the current value already is "Q": p.innerText=="Q"?"A":"Q"

const p=document.getElementById('A');
document.body.addEventListener("keydown", function(event) {
  if (["q","Q"].includes(event.key)) {
    p.textContent = p.textContent=="Q"?"A":"Q";
  }
});

A

A: Create an array of your letters and use the % Reminder Operator to loop over the index

const letters = ["A", "Q"];  // Use as many as you like
const tot = letters.length;  // How many letters we have
let i = 0;                   // Start at letter index 0

const elA = document.querySelector('#A');

addEventListener("keydown", (evt) => {
  if (evt.key === "q") { // or use evt.code === "KeyQ" (if you don't care about Shift key)
    i += 1;    // increment
    i %= tot;  // loop
    elA.textContent = letters[i];
  }
});
Click here to focus and use the keyboard letter "Q"

A


text:
Q: asp.net fileupload control time-out on big files Getting ERR_CONNECTION_RESET after more or less 2 minutes of uploading a rather big file (90 MB) through asp.net fileupload control.
Testing this on a shared host environment so I don't know exactly what policies are enforced on me.
web.config settings are sufficient I think:
 <httpRuntime requestValidationMode="2.0" maxRequestLength="1000000" executionTimeout="45000" />

Should I be looking at other async file-upload controls? Am I missing a web.config setting? Is the upload control simply not sufficient for large files on slow connections?

A: There can be a number of reasons why the connection is reset and upping the max request length works to a point but you are right about looking into async file uploaders. The most important part is using one which "chunks" the files into smaller pieces and so avoids request limits etc. I have had the best experience with plupload:
http://www.plupload.com/
Here is some code for receiving the files (this is MVC but you can refactor to use a handler in .NET classic):
       [HttpPost]
        public ActionResult UploadImage(int? chunk, int? chunks, string name)
        {
            var fileData = Request.Files[0];

            if (fileData != null && fileData.ContentLength > 0)
            {
                var path = GetTempImagePath(name);
                fileSystem.EnsureDirectoryExistsForFile(path);

                // Create or append the current chunk of file.
                using (var fs = new FileStream(path, chunk == 0 ? FileMode.Create : FileMode.Append))
                {
                    var buffer = new byte[fileData.InputStream.Length];
                    fileData.InputStream.Read(buffer, 0, buffer.Length);
                    fs.Write(buffer, 0, buffer.Length);
                }
            }

            return Content("Chunk uploaded", "text/plain");
        }


text:
Q: WSR Show Numbers In Windows Speech Recognition (WSR), there is a command called "Show Numbers" that pulls up transparent boxes over every clickable item on the active window.
I'm not looking for a full program but more of what identifies clickable items on an active screen, if something like that even exists. I hope this question makes sense. Thank You! If it's important, I'm using c#.

A: While I'm not familiar with WSR, UI items can be identified through the UI Automation framework. It's able to see controls on windows and able to interact with them. The primary intent is for accessibility purposes(Screen readers and the like) but it has also been coopted for UI Automation tasks and is the backbone behind portions of the Coded UI Framework. http://msdn.microsoft.com/en-us/library/ms747327.aspx


text:
Q: Not sure about image on JButton I have already tried the following =
ImageIcon clear = new ImageIcon ("icons\delete1.png");
JButton clearBT = new JButton(clear);

And it works perfectly, I just have a question to make. The directory of the image is into my hard disk, but I want to deliver my project to my professor, so I am not sure if the image will still show up when in his computer. The thing is that I am not sure if the directory that I've put in my code (which exactly is "C:\\Users\\George\\Desktop\Giorgos\\icons\\delete1.png") will have something to show on my professor's pc.
Thank you in advantage for your answers, and if I am not clear enough, I am willing to rephrase.

A: If Your Professor's PC has internet access then you can use something like
(Please upload your file somewhere on internet like imgur and pass that url of your image  new URL(here))
URL lenna =
            new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png");

ImageIcon clear = new ImageIcon (URL);
JButton clearBT = new JButton(clear);

A: If icons folder is in project directory folder and in code you are calling the image with :
ImageIcon clear = new ImageIcon ("icons\delete1.png");
And It's working perfectly ,then It will work anywhere.
Just Make sure you are not calling the image location address as its complete address that is referring to  your computer hard disk.

A: Put the picture in you projects and you will have to change your code to
JButton clearBT = new JButton(new ImageIcon(getClass().getResource(image_path)));

A: Another option would be to ship the image bundled with your source code. For instance, create a "package" / directory inside your project hierarchy and store images there.
Then, you can load them this way:
ImageIcon image = new ImageIcon(getClass().getResource("/path/to/the/image");

For instance, if the image is under org/example/program then the above will be:
ImageIcon image = new ImageIcon(getClass().getResource("/org/example/program/image.png");


text:
Q: Replace all characters except for the last occurrence I am performing a replace of characters on a string like this:
result = strings.ReplaceAll(result, ".", "_")

This works as expected, but I want to preserve the last occurence of the . and not replace it, just leave it alone.
Is there a fancy way doing this?

A: Split into []string, then Join all but last ;)
func ReplaceAllButLast(data, old, new string) string {
    split := strings.Split(data, old)
    if len(split) < 3 {
        return data
    }
    last := len(split) - 1
    return strings.Join(split[:last], new) + old + split[last]
}

https://go.dev/play/p/j8JJP-p_Abk
func main() {
    println(ReplaceAllButLast("a", ".", "_"))
    println(ReplaceAllButLast("a.b", ".", "_"))
    println(ReplaceAllButLast("a.b.c", ".", "_"))
    println(ReplaceAllButLast("a.b.c.d", ".", "_"))
}

produced
a
a.b
a_b.c
a_b_c.d

UPDATE
That was a joke, just to be fancy
Best way is to count the number of matches and replace Count()-1, the second it to ReplaceAll until last match position and using Join to be the slowest
func ReplaceAllButLast_Count(data, old, new string) string {
    cnt := strings.Count(data, old)
    if cnt < 2 {
        return data
    }
    return strings.Replace(data, old, new, cnt-1)
}

func ReplaceAllButLast_Replace(data, old, new string) string {
    idx := strings.LastIndex(data, old)
    if idx <= 0 {
        return data
    }

    return strings.ReplaceAll(data[:idx], old, new) + data[idx:]
}

func ReplaceAllButLast_Join(data, old, new string) string {
    split := strings.Split(data, old)
    if len(split) < 3 {
        return data
    }
    last := len(split) - 1
    return strings.Join(split[:last], new) + old + split[last]
}

Benchmark using a.b.c.d -> a_b_c.d
goos: windows
goarch: amd64
pkg: example.org
cpu: Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
Benchmark_Count-8       16375098            70.05 ns/op        8 B/op          1 allocs/op
Benchmark_Replace-8     11213830           108.5 ns/op        16 B/op          2 allocs/op
Benchmark_Slice-8        5460445           217.6 ns/op        80 B/op          3 allocs/op

A: The most obvious way to handle this would be to combine Replace and Count:
func ReplaceAllExceptLast(d string, o string, n string) string {
    strings.Replace(d, o, n, strings.Count(d, o) - 1)
}

I don't think this would be the most optimal solution, however. For me, the best option would be to do this:
func ReplaceAllExceptLast(d string, o string, n string) string {
    ln := strings.LastIndex(d, o)
    if ln == -1 {
        return d
    }

    return strings.ReplaceAll(d[:ln], o, n) + d[ln:]
}

This works by getting the index of the last occurrence of the value you want to replace, and then doing a replace-all on the string up to that point. For example:
println(ReplaceAllExceptLast("a", ".", "_"))
println(ReplaceAllExceptLast("a.b", ".", "_"))
println(ReplaceAllExceptLast("a.b.c", ".", "_"))
println(ReplaceAllExceptLast("a.b.c.d", ".", "_"))

will produce:
a
a.b
a_b.c
a_b_c.d

A: The first solution comes to my mind is Positive Lookahead of regular expression
[.](?=.*[.])
However, the (?=re) is not supported in Golang re2

We can use Non-capturing group to implement it in this way

*

*First use
(?:[.])( Match a single character present in the list below [.]) to find all dot indexes.

*Then replace dot with '_' except the last one.
Sample
func replaceStringByIndex(str string, replacement string, index int) string {
    return str[:index] + replacement + str[index+1:]
}

func replaceDotIgnoreLast(str string, replacement string) string {
    pattern, err := regexp.Compile("(?:[.])")
    if err != nil {
        return ""
    }

    submatches := pattern.FindAllStringSubmatchIndex(str, -1)
    for _, submatch := range submatches[:len(submatches)-1] {
        str = replaceStringByIndex(str, replacement, submatch[0])
    }

    return str
}

func main() {
    str := "1.2"
    fmt.Println(replaceDotIgnoreLast(str, "_"))
    str = "1.2.3"
    fmt.Println(replaceDotIgnoreLast(str, "_"))
    str = "1.2.3.4"
    fmt.Println(replaceDotIgnoreLast(str, "_"))
}

Result
1.2
1_2.3
1_2_3.4

A: *

*Use strings.Count to count the occurrence of the string you want to replace

*Pass count-1 to strings.Replace to omit the last occurrence

func ReplaceAllButLast(input string, find string, replace string) string {
    occurrencesCount := strings.Count(input, find)
    return strings.Replace(input, find, replace, occurrencesCount-1)
}


text:
Q: inner product of eigenfunctions of different operators I have these two Sturm-Liouville problems:
$$\Phi''+\omega^2\Phi=0$$
$$(\mu\Theta')'+\lambda^2\mu\Theta=0$$
In the first problem, $\Phi(\theta)$ is the eigenfunction and $\omega$ is the eigenvalue and in the second problem $\Theta(\theta)$ and $\lambda$ are the eigenpairs with $\mu(\theta)>0$ the weighting function. Both are in the interval $\theta\in[0,2\pi]$ and with the periodic boundary condition.
As we know, the eigenfunctions of each problem create an orthonormal basis:
$$\langle \Phi_n , \Phi_k \rangle=\delta[n,k]$$
$$\langle \mu\Theta_n , \Theta_k \rangle=\delta[n,k]$$
where $\langle\rangle$ is the notation of inner product and $\delta$ is the Kronecker delta.
The question arises: what happens for the inner product of these eigenfunctions when they do not belong to a common operator,
$$\langle \Phi_n , \Theta_k \rangle=?$$
$$\langle \mu\Theta_n , \Phi_k \rangle=?$$
Can some of them be orthogonal? Is there an identity to compute these inner products with less computational complexity?


text:
Q: where to place duplicate controller methods in rails 3 I am working on refactoring a rails 3 project. Lets say that i have controllers A, B, C and  D. Below are the methods that are reside in the controllers. Now, if we have common methods in models, we place them in module and include that module in the model. But how do we solve code repetition problem for controllers?
 A     B     C     D
----------------------
 m1    m1    m1
 m2    m2    m2    m2
       m3    m3

Here, m1, m2, m3 and m4 are some methods that are repeated in the above controllers. I dont want to move them to ApplicationController cause that will make the controller heavy and they will become global. Also, some of the method are private. Whats the ideal solutions?

A: Refactor the common functionality into helper methods and then just call those methods from the Controller. See this: http://api.rubyonrails.org/classes/ActionController/Helpers.html
If you have a case where the methods are exactly the same (BTW, that'd be weird and signals other problems with your code more insidious than repetition ), you can still put them into modules and include each module in your controller. Modules are a feature of the Ruby language and not the Rails framework.

A: This depends on a million things, but we'll start small. Firstly, there's no reason you can't include a module in the controller because, after all, it's just a Ruby class.
As was also briefly mentioned, you should look at why there is all this duplicated code before deciding how to clean it up. Maybe the code belongs in a helper/presenter/decorator because it has something to do with presentation logic. Maybe the code belongs in a model because it is not presentation logic but it does have to do with representing the real world.
Maybe the code does in fact belong in the ApplicationController like m2 in your example. If it's a controller-specific helper used in 4 of your controllers, the ApplicationController is probably not a bad place for it.
As you said in one of your comments, this could be as simple as placing the module in your lib directory and including it everywhere you need it. Don't forget you can also test modules (and you should) in a similar fashion:
class MyModuleTest < ActiveSupport::TestCase
  class ModuleIncluder
    include MyModule
  end

  test "some method should do a thing" do
    ... test content ...
  end
end


text:
Q: Cardinality of the Set of all finite subset of $\mathbb{R}$ Find the cardinality of the set of all finite subsets of $\mathbb{R}$.
I have proved that the set of all finite subsets of $\mathbb{N}$ is countable . But I cannot find the cardinality of the set in case of $\mathbb{R}$ .
My Attempt:
First I have considered the set $$A_k=\{\{a_1, a_2, ..., a_k\}| a_i \in \mathbb{R}  \ and\ a_1<...<a_k  \}$$
Then $S=$ The set of all finite subsets of $\mathbb{R}=\bigcup_{n=1}^{\infty}A_{n}$,
and now in the case of $\mathbb{N}$, I could show that this $A_k$ is countable and consequently the set of all finite subset of $\mathbb{N}$ is countable.
But in this case I cannot say anything like this...In this case the set will be of the cardinality as that of $\mathbb{R}$ (I think). But cannot prove it.
I appreciate your help.  Thank you.

A: We can show that $\#S \ge {c}$ via the injection $f: \mathbb{R} \rightarrow S$, $f(x) = \{x\}$.
If you show $\#S \le c$ then you can conclude $\#S = c$ invoking Bernstein's theorem.

Let's prove the following: let $X = \{X_k,\ k \in \mathbb{N}\}$ be a family of subsets such that $\#X_i \le c$,  $\ \forall i \in \mathbb{N}$, and let $V = \bigcup_{k\in \mathbb{N}}X_k$. Then $\#V \le c$.
Because $\#X_i \le c$, we have for each $i$ a surjective $f_i: \mathbb{R} \rightarrow X_i$. We define $g: \mathbb{N} \times \mathbb{R} \rightarrow V$, $g(n,x) = f_n(x)$.
$g$ is an surjective function: let $x \in V$, then $x \in X_i$ for some $i$, then we have $a \in \mathbb{R}$ such that $f_i(a) = x$ because $f_i$ is surjective. Then $g(i,a) = f_i(a) = x$, with $(i,a) \in \mathbb{N}\times\mathbb{R}$.
We conclude that $g$ is surjective.
Thus $\#V \le \#(\mathbb{N}\times\mathbb{R})$, this is, $\#V \le c$.

Your set $S$ satisfies the hypotheses, so we have $\#S \le c$, and thus $\#S = c$.

A: Let $A$ be an element of the set of all the finite subsets of $\mathbb{R}$, which we shall denote simply by $\mathcal{P}_{<\omega}(\mathbb{R})$
Assertion: $\mathcal{P}_{<\omega}(\mathbb{R})\preccurlyeq\,^\omega\mathbb{R}$
We will identify $A$ with a $\omega$-sequence of elements of $\mathbb{R}$, that is, and element of $^\omega\mathbb{R}$, in the following way:
Assume that $A=\{a_0,\dots,a_n\}$. Then we can construct a $\omega$-sequence $(b_k)_{k\in\omega}$ defined by:
$$b_k=\begin{cases}
  a_k\qquad\qquad\text{if }k\le n \\
  a_n+1\qquad\text{ if }k>n
\end{cases}$$
It is clear that the correspondence $A\longmapsto(b_k)_{k\in\omega}$ is injective.
Now, on the one hand we have that $\mathbb{R}\preccurlyeq\mathcal{P}_{<\omega}(\mathbb{R})$, because the function $r\in\mathbb{R}\longmapsto\{r\}\in\mathcal{P}_{<\omega}(\mathbb{R})$ is obviously injective.
On the other hand, $\mathcal{P}_{<\omega}(\mathbb{R})\preccurlyeq\mathbb{R}$, since $\;\mathcal{P}_{<\omega}(\mathbb{R})\preccurlyeq\,^\omega\mathbb{R}\;$ and $\;^\omega\mathbb{R}\preccurlyeq\mathbb{R}$: in fact, $|^\omega\mathbb{R}|=\big(2^{\aleph_0}\big)^{\aleph_0}=2^{\aleph_0\times\aleph_0}=2^{\aleph_0}=|\mathbb{R}|$
From the Cantor-Bernstein therem, we obtain that $|\mathcal{P}_{<\omega}(\mathbb{R})|=|\mathbb{R}|=2^{\aleph_0}$


text:
Q: reCAPTCHA is accepting random values I'm using Greg Gilbert's reCAPTCHA validator for Laravel 4 (https://github.com/greggilbert/recaptcha).
I know that reCAPTCHA only needs one word on two to validate forms but my problem is different. I actually have a single word displayed on my reCAPTCHA, the second one is missing. And unfortunately, the displayed word is the "pictured-word", you know, the word for which you can write whatever you like and it will be accepted.

So if it shows number 109, I can write "108" and my form will be accepted.
How to fix that please ?

A: After some tests, I've found that if I use Firefox's "Private navigation" window, my reCAPTCHA is displaying 2 words instead of 1 as I described here.
It means that if you are connected to your Google account on your web browser, reCAPTCHA "trusts" you a little bit more than a not-connected user and shows you only one word/number.


text:
Q: Wide Voltage Automotive Status To Microcontroller Input I need to monitor the status of a wire in an automotive application that can have 10-40VDC on it at any time. What is a good approach to limit the voltage to a microcontroller input across such a wide range? I plan to use a 10nF cap and TVS for ESD and other transients but I'm not sure the best approach to limit the expected voltage. If I can reliably detect 10V, 40V may burn up the input resistors (or resistor and zener?) or I can limit for 40V and not sense 10V.
The signal is a simple on off status line that I'm tapping into. It won't be carrying any data or change state very often. I will be sampling it occasionally in the micro to determine if it's high (1V to 40V) or low (GND to under 1V).
Thanks.
Edited to add that my microcontroller will be running at 3.3V and a logic low needs to be under 1V. Any solution I use must include a low value cap between the input and GND and either diode clamps to Vdd and GND or a Transil.

A: Using a resistor and Zener diode will work fine.  The simulation below shows what you get with a 4.7V zener.
You can use a very large resistor, because the microcontroller I/O pin draws virtually no current.  With a 100kOhm resistor and approximately 5V output voltage, the power dissipation is (40-5)^2 / (100,000) = 12mW, well within what the resistor can handle.

simulate this circuit – Schematic created using CircuitLab

A: I'd be inclined to use something simple and dirty like this

simulate this circuit – Schematic created using CircuitLab
Vary the value of R3, or omit it, depending on what you want the lower threshold to be.
Note that base emitter junctions are pretty tough, and tend to fail short circuit when they do. If it dies, it will save the protected circuit, and can be easily replaced.
D1 is to protect from negative voltage. Car electrics are supposed to be able to tolerate the reverse connection of a jump start battery without damage, as well as 160v load dumps and 24v truck battery jump starts, pretty harsh!

A: Selvek's answer should work. I would add that another simple alternative to the zener is to clamp the voltage to VDD using a diode.

simulate this circuit – Schematic created using CircuitLab
In fact, most ICs already include such a diode internally so if you get the resistor right you don't even need to add a diode.
One thing you need to be careful of when you use this method is that the minimum power draw of your circuit must always be greater than the current through D1 at 40v. In this case, the current is 0.7ma. R2 in this case creates a minimum load of 1ma, which will protect the supply from being raised over 5v.


text:
Q: Why am I not able to load my custom CSS? function file
<?php

   function test_theme(){
    wp_enqueue_style("customestyle", get_stylesheet_uri() )

   }

add_action( 'wp_enqueue_scripts', 'test_theme' );

and I added wp_head to my header. I also have stylesheet file in my root folder.


text:
Q: update listbox on textbox change asp.net could any one please help me how to accomplish in asp.net my problem? I have a server control textbox and listbox. What I want to happen is than when I type something on the textbox, on keypress, the contents of the listbox is also updated(realtime) and will filter the result accordingly. If textbox has been cleared, all original values from the listbox will come back.

A: use JQuery for textbox
$("#<%=txtboxID.ClientID %>").keydown(function (e) {
    e.preventDefault();
    //your action
});


text:
Q: How do I use rugged to add and commit all files in a repository I am initializing a git repository that already has some files in it
repo = Rugged::Repository.init_at(".")

I need to stage the files already in that folder and commit them. This is what I've tried:
repo = Rugged::Repository.new(".")
    index = repo.index
    index.add_all()

    options = {}
    options[:tree] = index.write_tree(repo)

    options[:author] = { :email => "testuser@github.com", :name => 'Test Author', :time => Time.now }
    options[:committer] = { :email => "testuser@github.com", :name => 'Test Author', :time => Time.now }
    options[:message] ||= "Making a commit via Rugged!"
    options[:parents] = repo.empty? ? [] : [ repo.head.target ].compact
    options[:update_ref] = 'HEAD'
    Rugged::Commit.create(repo, options)

However if I look into the directory and run a git status all I get is:
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    deleted:    .editorconfig
    deleted:    .gitignore
    deleted:    Procfile
    deleted:    README.md

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    .editorconfig
    .gitignore
    Procfile
    README.md


text:
Q: Method definition not found What am I doing wrong?  This is the .h file:
#import <UIKit/UIKit.h>
#import <sqlite3.h>

@class ReaderViewController;

@interface ReaderAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    ReaderViewController *viewController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet ReaderViewController *viewController;

- (void)checkForDatabase;
//- (void)SQLiteConnection: (NSString *)defaultDBPath;
@end

The error is shown here:

A: You are calling the [self checkForDatabase] method which doesn't appear to exist in the .m file.

The Incomplete Implementation warning is because you have declared the checkForDatabase method in your interface
The Method Definition error is because you are attempting to call the missing method in the application:didFinishLaunchingWithOptions: method.

A: You have failed to implement checkForDatabase in ReaderAppDelegate.m (or in any other file you're linking into the project). You said you would in the header, and then you didn't.


text:
Q: PHP, Line break when writting to a file I am trying to keep a running total of all the responses to a form I have written, but I am having trouble making it so that each response takes a new line. I have my code down below. I just want it so that it is easier to read because right now what happens is that all the responses are jammed together would like to have each one on a new line. I tried a few things and have them commented in the code and what the result was. Thanks in Advance.
<?php
if (isset($_POST['sometext']))
    {
    $myFile = "testFile.txt";
    $thetext=$_POST['sometext'] ;//added + "\n" here but all response turned to 0
    writemyfile($myFile,$thetext,"a");
    } else
    {
    $thetext="Enter text here";
    }

function readmyfile($thefile)
    {
        $file = fopen($thefile, "r") or exit("Unable to open file!");
        //Output a line of the file until the end is reached
        while(!feof($file))
        {
            echo fgets($file). "
";
        }
        fclose($file);
    }

function writemyfile($thefilename,$data,$mode)
    {
        $myfile=fopen($thefilename,$mode);
        fwrite($myfile, $data); // added + "\n" here and responses turned 0
        fclose($myfile);
    }
?>

        <title> Zain's Test Site</title>

        <form method="post" action="<?php echo $php_self ?>">
            <input type="text" name="sometext" value="<?php echo $thetext ?>" >
            <input type="submit" name="Submit" value="Click this button">
        </form>
        <?php readmyfile("testFile.txt"); ?>

A: $thetext."\n"

in php you concatenate strings using ".", you use "+" in javascript.

A: Can you try appending the newline character (\n) to the $thetext variable like this:
$thetext=$_POST['sometext'] . "\n";

Remember to use '.' as the concatenation operator, and use double-quotes around the newline character.

A: Use newline "\n" instead of the br's which is for html

A: $text = $text."\n" ?
Err here's some more text to fill out the answer

A:  fwrite($myfile, $data); // added + "\n" here and responses turned 0

the concat string operator is (.) not (+)
you can also simplify your script thusly
 echo nl2br(get_file_contents($file));


text:
Q: Como recuperar uma base de dados em MySQL Tive um problema num cliente que o sistema operativo deixou de funcionar.
Consegui aceder ao disco e nele está uma base de dados MySQL dentro da pasta C:\ProgramData\MySQL\MySQL Server 5.7\Data\BDados que contém os ficheiros .FRM e .IDB.
Como é que consigo recuperar essa base de dados?
Já copiei os ficheiros dessa pasta para a pasta do meu computador mas não consigo aceder. Quando entro pelo MySQL Workbench as tabelas aparecem mas não consigo aceder ao conteúdo. Dá sempre o erro:

Error Code: 1812. Tablespace is missing for table bdados.clientes

Gostaria de ter a vossa ajuda para resolver esta situação.

A: Tem uma dica nesse site que pode te ajudar:
Primeiro você cria uma nova base de dados com as tabelas.
Depois exclua os arquivos recém criados usando a instrução DISCARD
ALTER TABLE newdb.table1 DISCARD TABLESPACE;

Em seguida, copie todos os arquivos .ibd e .frm do backup para a pasta do banco de dados, depois acesse o banco de dados.
Peça ao MySQL para aceitar os novos arquivos usando a instrução IMPORT.
ALTER TABLE newdb.table1 IMPORT TABLESPACE;

Isso pode ajudar a recuperar as tabelas do banco de dados.


text:
Q: Hash param is missing in payU payment gateway android integration I need to integrate payU payment gateway in my android app. But when app is trying to to get hash key it gives me error saying that
Hash param is missing
In demo app there are two option to generate hash
if(null == salt)
        generateHashFromServer(mPaymentParams);
    else
        generateHashFromSDK(mPaymentParams, intent.getStringExtra(PayuConstants.SALT));

In demo app there are note saying that hash key generation should be done
on server side
so I am passing salt as null
but Now the question is Which server url I have to use to generate hash?
Demo app is using this url
https://payu.herokuapp.com/get_hash

A: PayU money doesn't give any kind of API, So, people use a webview instead.

A: I got solution by doing little search.
Just generate all required hashes using own server.
After getting all required hashes we need to make PayuHashes Obj using this hashes
and pass this Obj in intent like this
Intent intent= new Intent(this, PayUBaseActivity.class);
intent.putExtra(PayuConstants.PAYU_CONFIG, payuConfig);
intent.putExtra(PayuConstants.PAYMENT_PARAMS, mPaymentParams);
intent.putExtra(PayuConstants.PAYU_HASHES, payuHashes);
intent.putExtra(PayuConstants.SALT, salt);

PayU SDK will take care of rest

A: You have to use your own server URL to generate hash keys.
In android app there are 3 mandatory hash keys you have to set else you will get error "mandatory hash key is missing".
Make sure you have set this 3 keys to payuHashes object.

*

*payuHashes.setPaymentHash(response.getString("payment_hash"));

*payuHashes.setVasForMobileSdkHash(response.getString("vas_for_mobile_sdk_hash"));

*payuHashes.setPaymentRelatedDetailsForMobileSdkHash(response.getString("payment_related_details_for_mobile_sdk_hash"));

Below three hashes are mandatory for payment flow and needs to be generated at merchant server:
1. Payment hash is one of the mandatory hashes that needs to be generated from merchant's server side.
Below is formula for generating payment_hash -
                                             sha512(key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5||||||SALT)

*vas_for_mobile_sdk_hash is one of the mandatory hashes that needs to be generated from merchant's server side.
Below is formula for generating vas_for_mobile_sdk_hash -

sha512(key|command|var1|salt)
here, var1 will be "default"

*payment_related_details_for_mobile_sdk_hash is one of the mandatory hashes that needs to be generated from merchant's server side.
Below is formula for generating payment_related_details_for_mobile_sdk_hash -

sha512(key|command|var1|salt)
here, var1 will be user credentials. If you are not using user_credentials then use "default".
Refer sample sdk from here:
https://github.com/payu-intrepos/Android-SDK-Sample-App/releases/
For server side code refer this:
https://github.com/payu-intrepos/Documentations/wiki/4.-Server-Side

A: i hope its useful to others i found a php script for generating hash in below link
https://docs.google.com/document/d/1wby1TStudKuOtIRmUIc3ZqDVOg20mks8q5mT40i60qw/edit
<?php

function getHashes($txnid, $amount, $productinfo, $firstname, $email, $user_credentials, $udf1, $udf2, $udf3, $udf4, $udf5,$offerKey,$cardBin)
{
      // $firstname, $email can be "", i.e empty string if needed. Same should be sent to PayU server (in request params) also.
      $key = 'XXXXXX';
      $salt = 'YYYYY';

      $payhash_str = $key . '|' . checkNull($txnid) . '|' .checkNull($amount)  . '|' .checkNull($productinfo)  . '|' . checkNull($firstname) . '|' . checkNull($email) . '|' . checkNull($udf1) . '|' . checkNull($udf2) . '|' . checkNull($udf3) . '|' . checkNull($udf4) . '|' . checkNull($udf5) . '||||||' . $salt;
      $paymentHash = strtolower(hash('sha512', $payhash_str));
      $arr['payment_hash'] = $paymentHash;

      $cmnNameMerchantCodes = 'get_merchant_ibibo_codes';
      $merchantCodesHash_str = $key . '|' . $cmnNameMerchantCodes . '|default|' . $salt ;
      $merchantCodesHash = strtolower(hash('sha512', $merchantCodesHash_str));
      $arr['get_merchant_ibibo_codes_hash'] = $merchantCodesHash;

      $cmnMobileSdk = 'vas_for_mobile_sdk';
      $mobileSdk_str = $key . '|' . $cmnMobileSdk . '|default|' . $salt;
      $mobileSdk = strtolower(hash('sha512', $mobileSdk_str));
      $arr['vas_for_mobile_sdk_hash'] = $mobileSdk;

// added code for EMI hash
      $cmnEmiAmountAccordingToInterest= 'getEmiAmountAccordingToInterest';
      $emi_str = $key . '|' . $cmnEmiAmountAccordingToInterest . '|'.checkNull($amount).'|' . $salt;
      $mobileEmiString = strtolower(hash('sha512', $emi_str));
     $arr['emi_hash'] = $mobileEmiString;

      $cmnPaymentRelatedDetailsForMobileSdk1 = 'payment_related_details_for_mobile_sdk';
      $detailsForMobileSdk_str1 = $key  . '|' . $cmnPaymentRelatedDetailsForMobileSdk1 . '|default|' . $salt ;
      $detailsForMobileSdk1 = strtolower(hash('sha512', $detailsForMobileSdk_str1));
      $arr['payment_related_details_for_mobile_sdk_hash'] = $detailsForMobileSdk1;

      //used for verifying payment(optional)
      $cmnVerifyPayment = 'verify_payment';
      $verifyPayment_str = $key . '|' . $cmnVerifyPayment . '|'.$txnid .'|' . $salt;
      $verifyPayment = strtolower(hash('sha512', $verifyPayment_str));
      $arr['verify_payment_hash'] = $verifyPayment;

      if($user_credentials != NULL && $user_credentials != '')
      {
            $cmnNameDeleteCard = 'delete_user_card';
            $deleteHash_str = $key  . '|' . $cmnNameDeleteCard . '|' . $user_credentials . '|' . $salt ;
            $deleteHash = strtolower(hash('sha512', $deleteHash_str));
            $arr['delete_user_card_hash'] = $deleteHash;

            $cmnNameGetUserCard = 'get_user_cards';
            $getUserCardHash_str = $key  . '|' . $cmnNameGetUserCard . '|' . $user_credentials . '|' . $salt ;
            $getUserCardHash = strtolower(hash('sha512', $getUserCardHash_str));
            $arr['get_user_cards_hash'] = $getUserCardHash;

            $cmnNameEditUserCard = 'edit_user_card';
            $editUserCardHash_str = $key  . '|' . $cmnNameEditUserCard . '|' . $user_credentials . '|' . $salt ;
            $editUserCardHash = strtolower(hash('sha512', $editUserCardHash_str));
            $arr['edit_user_card_hash'] = $editUserCardHash;

            $cmnNameSaveUserCard = 'save_user_card';
            $saveUserCardHash_str = $key  . '|' . $cmnNameSaveUserCard . '|' . $user_credentials . '|' . $salt ;
            $saveUserCardHash = strtolower(hash('sha512', $saveUserCardHash_str));
            $arr['save_user_card_hash'] = $saveUserCardHash;

            $cmnPaymentRelatedDetailsForMobileSdk = 'payment_related_details_for_mobile_sdk';
            $detailsForMobileSdk_str = $key  . '|' . $cmnPaymentRelatedDetailsForMobileSdk . '|' . $user_credentials . '|' . $salt ;
            $detailsForMobileSdk = strtolower(hash('sha512', $detailsForMobileSdk_str));
            $arr['payment_related_details_for_mobile_sdk_hash'] = $detailsForMobileSdk;
      }

      // if($udf3!=NULL && !empty($udf3)){
            $cmnSend_Sms='send_sms';
            $sendsms_str=$key . '|' . $cmnSend_Sms . '|' . $udf3 . '|' . $salt;
            $send_sms = strtolower(hash('sha512',$sendsms_str));
            $arr['send_sms_hash']=$send_sms;
      // }

      if ($offerKey!=NULL && !empty($offerKey)) {
                  $cmnCheckOfferStatus = 'check_offer_status';
                        $checkOfferStatus_str = $key  . '|' . $cmnCheckOfferStatus . '|' . $offerKey . '|' . $salt ;
                  $checkOfferStatus = strtolower(hash('sha512', $checkOfferStatus_str));
                  $arr['check_offer_status_hash']=$checkOfferStatus;
            }

            if ($cardBin!=NULL && !empty($cardBin)) {
                  $cmnCheckIsDomestic = 'check_isDomestic';
                        $checkIsDomestic_str = $key  . '|' . $cmnCheckIsDomestic . '|' . $cardBin . '|' . $salt ;
                  $checkIsDomestic = strtolower(hash('sha512', $checkIsDomestic_str));
                  $arr['check_isDomestic_hash']=$checkIsDomestic;
            }

    return $arr;
}

function checkNull($value) {
            if ($value == null) {
                  return '';
            } else {
                  return $value;
            }
      }

$output=getHashes($_POST["txnid"], $_POST["amount"], $_POST["productinfo"], $_POST["firstname"], $_POST["email"], $_POST["user_credentials"], $_POST["udf1"], $_POST["udf2"], $_POST["udf3"], $_POST["udf4"], $_POST["udf5"],$_POST["offerKey"],$_POST["cardBin"]);

echo json_encode($output);

?>

copy the php code and edit key and salt.


text:
Q: How To Detect Ctrl+V In AHK? I am trying to detect Ctrl+V. Then, make Xbutton1act as Enter for a few seconds, but I can't get it working.
Transform, CtrlV, Chr, 3
Input, OutputVar, L1 M

XButton1::
    if OutputVar = CtrlV
    {
        SetTimer, SendEnter, 0
        Sleep, 2000
        SetTimer, SendEnter, Off
    }
    else
    {
        Send  ^t
    }
Return

SendEnter:
    Send {Enter}
Return

A: ~^v::lastPaste := A_TickCount ;stores counter when ctrl+v is pressed
    Xbutton1::
        If A_TickCount - lastPaste < 2000 ;checks if 2 seconds gone after ctrl+v was clicked
        {
            Send, {Enter} ;sends enter
            Return
        }
        else
        {
            Send, ^t ;sends ctrl+t
            Return
        }


text:
Q: Building an absolute URL from a relative URL in Java I'm having trouble building an absolute URL from a relative URL without resorting to String hackery...
Given
http://localhost:8080/myWebApp/someServlet

Inside the method:
   public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}

What's the most "correct" way of building :
http://localhost:8080/myWebApp/someImage.jpg

(Note, must be absolute, not relative)
Currently, I'm doing it through building the string, but there MUST be a better way.
I've looked at various combinations of new URI / URL, and I end up with
http://localhost:8080/someImage.jpg

Help greatly appreciated

A: Using java.net.URL
 URL baseUrl = new URL("http://www.google.com/someFolder/");
 URL url = new URL(baseUrl, "../test.html");

A: How about:
String s = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/someImage.jpg";

A: Looks like you already figured out the hard part, which is what host your are running on. The rest is easy,
String url = host + request.getContextPath() + "/someImage.jpg";

Should give you what you need.

A: this code work will on linux, it can just combine the path, if you want more, constructor of URI could be helpful.
URL baseUrl = new URL("http://example.com/first");
URL targetUrl = new URL(baseUrl, Paths.get(baseUrl.getPath(), "second", "/third", "//fourth//", "fifth").toString());

if you path contain something need to escape, use URLEncoder.encode to escape it at first.
URL baseUrl = new URL("http://example.com/first");
URL targetUrl = new URL(baseUrl, Paths.get(baseUrl.getPath(), URLEncoder.encode(relativePath, StandardCharsets.UTF_8), URLEncoder.encode(filename, StandardCharsets.UTF_8)).toString());

example:
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
    public static void main(String[] args) {
        try {
            URL baseUrl = new URL("http://example.com/first");
            Path relativePath = Paths.get(baseUrl.getPath(), "second", "/third", "//fourth//", "fifth");
            URL targetUrl = new URL(baseUrl, relativePath.toString());
            System.out.println(targetUrl.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

output
http://example.com/first/second/third/fourth/fifth

baseUrl.getPath() are very important, don't forget it.
a wrong example:
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
    public static void main(String[] args) {
        try {
            URL baseUrl = new URL("http://example.com/first");
            Path relativePath = Paths.get("second", "/third", "//fourth//", "fifth");
            URL targetUrl = new URL(baseUrl, relativePath.toString());
            System.out.println(targetUrl.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

output
http://example.com/second/third/fourth/fifth

we have lost our /first in baseurl.


text:
Q: XML not being deserialized into object I posted a question very similar to this with a different XML/object model and it was resolved by suggestions to add missing {set; } on my properties of the class. While that worked there, with the class I'm trying to get to deserialize a different XML file, the {set; } are not missing.
The XML that I'm currently trying to deserialize looks like this:
<?xml version='1.0'?>
    <BillOfMaterials xmlns='http://www.manh.com/ILSNET/Interface' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.manh.com/ILSNET/Interface'>
        <BillOfMaterial>
            <Active>Y</Active>
            <Company>XYZ</Company>
            <InterfaceEntity>
                <Action>NEW</Action>
            </InterfaceEntity>
            <Item>PM6000035437</Item>
            <QtyUm>EA</QtyUm>
            <RevisionNum>1</RevisionNum>
            <BillOfMaterialDetails>
                <BillOfMaterialDetail>
                    <BuildLevel>1</BuildLevel>
                    <BuildSequence>1</BuildSequence>
                    <Company>XYZ</Company>
                    <InterfaceEntity>
                        <Action>NEW</Action>
                    </InterfaceEntity>
                    <Item>DP000351</Item>
                    <QtyNeededPerItem>3.0</QtyNeededPerItem>
                </BillOfMaterialDetail>
                <BillOfMaterialDetail>
                    <BuildLevel>1</BuildLevel>
                    <BuildSequence>2</BuildSequence>
                    <Company>XYZ</Company>
                    <InterfaceEntity>
                        <Action>NEW</Action>
                    </InterfaceEntity>
                    <Item>DP000354</Item>
                    <QtyNeededPerItem>1.0</QtyNeededPerItem>
                </BillOfMaterialDetail>
     </BillOfMaterial>
</BillOfMaterials>

My first class is the parent BillOfMaterial class, below:
[XmlRoot(ElementName = "BillOfMaterials", Namespace = "http://www.manh.com/ILSNET/Interface")]
public class BOMList
{
    [XmlElement("BillOfMaterial")]
    public BOM[] BOMs { get; set; }
}

public class BOM
{
    [XmlElement("BillOfMaterialDetails")]
    public BOMDetail[] Details { get; set; }

    [XmlElement("Active")]
    public string ActiveFlag { get; set; }

    [XmlElement("Company")]
    public string Company { get; set; }

    [XmlElement("Item")]
    public string Id { get; set; }

    [XmlElement("QtyUm")]
    public string QtyUOM { get; set; }

    [XmlElement("RevisionNum")]
    public string RevisionNumber { get; set; }
}

Then, the BOMDetail class which the BOM contains a collection of is below:
public class BOMDetail
{
    [XmlElement]
    public int BuildLevel { get; set; }
    [XmlElement]
    public int BuildSequence { get; set; }
    [XmlElement]
    public string Company { get; set; }
    [XmlElement("Item")]
    public string ItemId { get; set; }
    [XmlElement("QtyNeededPerItem")]
    public decimal Qty { get; set; }
}

My issue is that when testing this, the BOM parent object is correctly pulling data from the XML file, but the BOMDetails collection inside of it is null, when it should (in this example) contain two BOMDetail elements.
My code that does the deserialization is below:
XmlSerializer serializer = new XmlSerializer(typeof(BOMList));

using (FileStream fileStream = new FileStream(Filename, FileMode.Open))
{
    this.CreatedObjects = (BOMList)serializer.Deserialize(fileStream);
}

Thanks for any advice you may be able to provide, if there's any other info you need from me to try and help, please let me know.


text:
Q: Why doesn't backbone use module.exports? It looks like it uses just plain
exports instead of module.exports
in this line here.
if (typeof exports !== 'undefined') {
    Backbone = exports;

However this tutorial shows the module.exports being used.

A:
Why doesn't backbone use module.exports?

Because it doesn't have to. exports and module.exports refer to the same object:

In particular module.exportsis the same as the exports object.

If you can save a couple of characters to type, then why not do it?
You are doing the same when you use document.getElementById instead of window.document.getElementById. It's more to type and doesn't add any benefit.

In the tutorial they are using module.exports because they want to show the difference between exporting a symbol why exports, i.e.
exports.foo = bar;

and overwriting the exports object
module.exports = bar;

for which you have to use module.exports (exports = bar; would not work).

A: Think of module like window in a browser. In actuality, they're basically the same thing.
So, in the same way that window.location === location in javascript executed in the browser, module.exports === exports in a node environment.


text:
Q: How to get the relationship data from casted toArray Eloquent I'm trying to get the data without using eager loading in a Eloquent Model but I needed to cast it into Array to use in some part of the code.
In order words, I wanna just get the data like this example:
$invoice->invoice_type_id->name;

Since it's an array what I'm writing is: nfe['invoice_type_id']['name']
But I'm getting this error (because it's an array):
Trying to get property of non object

So, my query is:
Invoice::query()->where('order_id', $order_id)->get()->toArray();

And my model I already have the relationship declared:
public function invoiceType()
{
   return $this->belongsTo(InvoiceType::class);
}


text:
Q: Getting menu items in a wordpress site with javascript I'm trying to see if I can query the wordpress API to get all of the items in the menu of the site using Javascript.
I can see that there is a post here on how to do this in php but I don't know how to translate this to javascript as it seems to be using the internal wordpress PHP API.
There is a great library here and I can see that with the following code I can query the site:
var site = Site('<id>', WPCOM);
site.get(function(err, info){
  // `info` data object
});

But I don't know how to query the menu items or if this is at all possible?
Any help would be appreciated.

A: I don't have the rep to put this link in a comment.  I have not used it and don't know if it will do what you need but how about this page: https://wordpress.org/plugins/wp-api-menus/
Since I am posting as an answer, here is some info from that page:
This plugin extends the WordPress JSON REST API with new routes for WordPress registered menus.

The new routes available will be:

       /menus list of every registered menu.
       /menus/<id> data for a specific menu.
       /menu-locations list of all registered theme locations.
       /menu-locations/<location> data for menu in specified menu in theme location.

I also found this similar post on wordpress.stackexchange: https://wordpress.stackexchange.com/questions/209381/get-wp-navigation-menu-from-rest-api-v2.  It ends up pointing to the same 'wp-api-menus/' link.


text:
Q: Open() and codecs.open() in Python 2.7 behave strangely different I have a text file with first line of unicode characters and all other lines in ASCII.
I try to read the first line as one variable, and all other lines as another. However, when I use the following code:
# -*- coding: utf-8 -*-
import codecs
import os
filename = '1.txt'
f = codecs.open(filename, 'r3', encoding='utf-8')
print f
names_f = f.readline().split(' ')
data_f = f.readlines()
print len(names_f)
print len(data_f)
f.close()
print 'And now for something completely differerent:'
g = open(filename, 'r')
names_g = g.readline().split(' ')
print g
data_g = g.readlines()
print len(names_g)
print len(data_g)
g.close()

I get the following output:
<open file '1.txt', mode 'rb' at 0x01235230>
28

7

And now for something completely differerent:

<open file '1.txt', mode 'r' at 0x017875A0>

28

77

If I don't use readlines(), whole file reads, not only first 7 lines both at codecs.open() and open().
Why does such thing happen?
And why does codecs.open() read file in binary mode, despite the 'r' parameter is added?
Upd: This is original file: http://www1.datafilehost.com/d/0792d687

A: Because you used .readline() first, the codecs.open() file has filled a linebuffer; the subsequent call to .readlines() returns only the buffered lines.
If you call .readlines() again, the rest of the lines are returned:
>>> f = codecs.open(filename, 'r3', encoding='utf-8')
>>> line = f.readline()
>>> len(f.readlines())
7
>>> len(f.readlines())
71

The work-around is to not mix .readline() and .readlines():
f = codecs.open(filename, 'r3', encoding='utf-8')
data_f = f.readlines()
names_f = data_f.pop(0).split(' ')  # take the first line.

This behaviour is really a bug; the Python devs are aware of it, see issue 8260.
The other option is to use io.open() instead of codecs.open(); the io library is what Python 3 uses to implement the built-in open() function and is a lot more robust and versatile than the codecs module.


text:
Q: Google Drive desktop client not updating existing files from other users I've looked around and there doesn't really seem to be any troubleshooting information for the Google Drive desktop client. It all assumes you are using Google Docs on the web.
Anyway, my team is trying to use Google Drive like Dropbox, where multiple people are editing files shared amongst them through the desktop, such as images.
Dropbox is really good at noticing when a checksum for a file is changed, and syncing it. Google Drive's desktop client seems not to do this at all. Google Drive desktop client seems to only sync newly created files and not giving any notification at all that there is a modified version, it will never sync it, even though going online and opening that file will show the modified version.
Is there any way to fix this? and the answer has nothing to do with proxy or firewall configurations. Team is using computers running OSX and Windows.

A: Google Drive works similar when dealing with non-google-doc files. However, for google doc files, it only stores a link to the google doc on web. Thus your actual copy is always only available online.


text:
Q: Spark how to union two arrays column without removing duplicates There is function array_union, that union two arrays without duplicates. How can I union two arrays without removing duplicates?
+---------+---------+
|field    |field1   |
+---------+---------+
|[1, 2, 2]|[1, 2, 2]|
+---------+---------+

.withColumn("union", array_union(col("field"), col("field1")))

Result:
+---------+---------+------------------+
|field    |field1   |union             |
+---------+---------+------------------+
|[1, 2, 2]|[1, 2, 2]|[1, 2, 2, 1, 2, 2]|
+---------+---------+------------------+

A: Just use concat instead,
import org.apache.spark.sql.functions.{concat}

df1.withColumn("NewArr", concat("Array1","Array2")).show()

Input:

Output:


text:
Q: Can I change facebook timeline actions after submission I am in the process of adding timeline integration in an app by defining a couple custom actions, but there is a chance that we may change these later on (adding optional parameters, changing the box visualization, wording etc).
Is this possible to do after we have submitted the actions for approval, and after they are eventually approved? I expect them to need to go through approval again but I am not sure.
What happens to already published actions?
What happens during the eventual re-approval process?

A: Of course your actions have to go through approval again if you change them.
For existing and approved actions, those should stay in place as they are when you change them and submit them for approval again, they will show their "old" behavior until the changes are approved.


text:
Q: How can I avoid my selected row being a null when it's a concatenation of fields? I have this row that is part of my SQL Select:
REPLACE(STR(temp.AdminTestId,5),' ','0') + '-' +
REPLACE(STR(A.UserTestId,5),' ','0') + '-' +
REPLACE(STR(A.Sequence,2),' ','0') as TestId,

When Sequence is null then TestId returns as null. If Sequence is null what I would like is for just the zero padded AdminTestID the "-" and the zero padded UserTestId to appear.

A: You can use CASE to branch between two scenarios when Sequence is null or not.
You can also use ISNULL and COALESCE for null checking
Added code sample, as requested in comments
REPLACE(STR(temp.AdminTestId,5),' ','0') + '-' +
REPLACE(STR(A.UserTestId,5),' ','0') +
ISNULL('-' + REPLACE(STR(A.Sequence,2),' ','0'),'') as TestId,

A: Concatenating null values to a string will return a null string in Sql server.
The solution is usually to use Sql server's built in function to convert null values to empty strings, so your code would look like this:
REPLACE(COALESCE(STR(temp.AdminTestId,5), ''),' ','0') + '-' +
REPLACE(COALESCE(STR(A.UserTestId,5), ''),' ','0') + '-' +
REPLACE(COALESCE(STR(A.Sequence,2), ''), ''),' ','0') as TestId,

The COALESCE function is Sql server will return the first argument it receives that is not NULL.
Edit
To answer your comment, taking advantage of the fact that concatenating null to a string will return null, you can simply concatenate the hyphen to A.Sequence:
REPLACE(COALESCE(STR(temp.AdminTestId,5), ''),' ','0') + '-' +
REPLACE(COALESCE(STR(A.UserTestId,5), ''),' ','0') +
REPLACE(COALESCE('-' + STR(A.Sequence,2), ''),' ','0') as TestId,


text:
Q: Send one subdomain to subdirectory, everything else to file with parameter Hoo-boy I've been struggling with this one all day.
The redirect from the subdomains to the script files with subdomain passed in as a parameter work fine.
When one particular subdomain is actually a real folder (phpmyadmin), I can't seem to make it work, at least not with the previously mentioned rule in place.
Here's my stuff:
<VirtualHost *.domain.com:443>
ServerName *.domain.com
ServerAlias *.domain.com
DocumentRoot /home/domain/web
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.* [NC]
RewriteCond %{HTTP_HOST} ^(phpmyadmin)\.domain\.com
RewriteCond %{REQUEST_URI} !^phpmyadmin
RewriteRule ^(.*)$ /phpmyadmin [L]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.com
RewriteRule ^\/script2$ /public/script2.php?param1=%1 [L]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.com
RewriteRule ^(.*) /public/script1.php?param1=%1 [L]
<Directory /home/domain/web>
Options -Indexes IncludesNOEXEC FollowSymLinks -MultiViews
AllowOverride All
Order allow,deny
Allow from all
</Directory>
SSLEngine on
SSLCertificateFile /home/domain/crt
SSLCertificateKeyFile /home/domain/key
</VirtualHost>

Any ideas?

A: 2 problems with:
RewriteCond %{HTTP_HOST} !^www.* [NC]
RewriteCond %{HTTP_HOST} ^(phpmyadmin)\.domain\.com
RewriteCond %{REQUEST_URI} !^phpmyadmin
RewriteRule ^(.*)$ /phpmyadmin [L]

*

*In your target redirect, you do not change the domain. By just using /phpmyadmin, you're not directing to www.domain.com/phpmyadmin, you're directing to phpmyadmin.domain.com/phpmyadmin, which is likely to cause an infinite redirect loop since it will keep matching the phpmyadmin subdomain each redirect. Use:
RewriteRule ^(.*)$ http://www.domain.com/phpmyadmin [L]

*Unlike RewriteRule where the initial / is not used, RewriteCond %{REQUEST_URI} does need the leading slash like so:
RewriteCond %{REQUEST_URI} !^/phpmyadmin
Failing to do so means its not matching the directed /phpmyadmin, leading to another potential self-matching infinite redirect loop.
Also you don't need
RewriteCond %{HTTP_HOST} !^www. [NC]
since your url would never start with www and also start with phpmyadmin. Matching
RewriteCond %{HTTP_HOST} ^(phpmyadmin)\.domain\.com
automatically implies the NOT www match condition is also true


text:
Q: Matlab - Splitting a column into two (efficiently) I had previously wrote some code to split 3 columns into 4, however the code was very inefficient and time consuming. As I am working with millions of rows it wasn't suitable. (Below is my previous code)
tline = fgetl(fid);

ID=tline(1:4);
IDN = str2double(ID);

Day=tline(6:8);
DayN = str2double(Day);

HalfHour=tline(9:10);
HalfHourN = str2double(HalfHour);

Usage=tline(12:end);
UsageN = str2double(Usage);

There must be a more efficient and quicker way of doing this?
Going back to basics, I have produced a x by 3 matrix. but require an x by 4 matrix
To show what I am trying to do, examining one row -
I am trying to change
1001 36501 1005

to
1001 365 01 1005

Any help would be much appreciated!
Edit:
The second column I am trying to divide into two, is always composed of 5 characters. I am trying to get the first 3 characters into their own column, likewise for the remaining characters.

A: What might take time in your case is actually the use of the str2double function. It is known that this built-in function becomes very slow when the data set is large. You might try to get rid of it if possible.

A: you can use modulo
ans = (36501 - mod(36501,100))/100
This would give you 365
if you want the 1, it is mod(36501,100)
so this would effectively split your second column into 2 different numbers, you can then re name them etc.
hmmm on second thoughts, if all your numbers on your second column are 5 digits, this can be extremely efficient, since mod is computed in matlab by b = a - m.*floor(a./m);
check http://uk.mathworks.com/help/matlab/ref/mod.html it should work for vectors (i.e. your second column)


text:
Q: Derive a formula for a function F
Let $S$ := {$(x, y) ∈ \mathbb R^2: x^2 + y^2 = 1$} be the unit circle. Let $p = (0, -1)$ ∈ $S$.
Define a map $F$ from $\mathbb R$ × {$0$} to $S$ as follows: Given $(t, 0)$, let $F((t, 0)) = (x, y)$ ∈ $S$ be the intersection of $S$ with the line through $p$ and $(t, 0)$.
Derive a formula for $F$.
Show that $t$ → $F((t, 0))$ is a bijective map from $\mathbb R$ to $S$ \ {$p$}, and also derive a formula for its
inverse.

How to derive a formula for $F$? If I get the line passing through $p$ and $(t,0)$, I get $(D): y = at-1$, right?
And I know that to show that $\phi$ : $\mathbb R$ →  $S$ \ {$p$}, I have to show that $\phi$ is injective and surjective.
Please I need help solving this

A: For a start: From the intercept theorem we have
$$\frac y1=\frac{\sqrt{(x-t)^2+y^2}}{\sqrt{t^2+1}}.$$
Squaring and using $x^2+y^2=1$ we arrive in
$$y^2=\frac{(t-1)^2}{1+t^2}.$$

A: If we express $S$ in polar coordinates:
$$S:=\{(r,\varphi):r=1,\varphi∈(-\frac\pi{2},\frac{3\pi}{2})\}$$
then, from simple trigonometric relations, the inverse function $\Phi$ is:
$$\Phi(\varphi)=\tan\frac{\frac\pi2-\varphi}2$$
and its inverse $F$ is:
$$F(t)=\frac\pi{2}-2\arctan t$$
After changing coordinates back to cartesian, $F$ will look like:
$$F(t)=(\cos(\frac\pi{2}-2\arctan t),\sin(\frac\pi{2}-2\arctan t))$$
which can be further simplified to:
$$F(t)=(\frac{2 t}{t^2 + 1},\frac{1 - t^2}{t^2 + 1})$$


text:
Q: Fabric JS setting fill on an image is not working I am trying to set fill on an image using Fabric JS.
To demonstrate my problem I refer to the Kitchensink demo on fabricjs.com
http://fabricjs.com/kitchensink
On the image below I am trying to fill the image with a green color RGB(69,242,81) but when I set the color, nothing happens. Are there any workaround to this issue?
I have had a look at floodFilling but that is unfortunately too performance heavy for my use case.
Thanks!

Possible Solution
I might have found a possible solution when playing around with this demo: `http://fabricjs.com/image-filters`
I select an object and choose the mode tint and increase the alpha to maximum (see image below)

And I get the desired result (see image below)
Is there anything wrong with using this approach?

A: Fill isn't currently a recognized property for images. One reason for this is because drawing a solid color behind an image that isn't transparent causes that color to appear along the edges of an image. Since the image class inherits the default fill color of rgb(0,0,0) (black) from the Object class, that would mean that every image would have an outline like this, unless the fill color is manually changed to transparent.

If however you really want your images to respect the fill property, you can do this with a simple override to the _renderFill method of the Image class. Just be sure to set the fill of any images that don't need a background color to transparent.
fabric.Image.prototype._renderFill = function(ctx) {
      var elementToDraw = this._element;
      if (!elementToDraw) {
        return;
      }
      var scaleX = this._filterScalingX, scaleY = this._filterScalingY,
          w = this.width, h = this.height, min = Math.min, max = Math.max,
          // crop values cannot be lesser than 0.
          cropX = max(this.cropX, 0), cropY = max(this.cropY, 0),
          elWidth = elementToDraw.naturalWidth || elementToDraw.width,
          elHeight = elementToDraw.naturalHeight || elementToDraw.height,
          sX = cropX * scaleX,
          sY = cropY * scaleY,
          // the width height cannot exceed element width/height, starting from the crop offset.
          sW = min(w * scaleX, elWidth - sX),
          sH = min(h * scaleY, elHeight - sY),
          x = -w / 2, y = -h / 2,
          maxDestW = min(w, elWidth / scaleX - cropX),
          maxDestH = min(h, elHeight / scaleY - cropY);

      //fill override start
      ctx.beginPath();
      ctx.rect(x, y, sW, sH);
      ctx.fill();
      //fill override end

      elementToDraw && ctx.drawImage(elementToDraw, sX, sY, sW, sH, x, y, maxDestW, maxDestH);
    };


text:
Q: Increment/Decrement byte (char) in c++ with over/under-flow What is the best way to increment/decrement a byte in c++ while taking into consideration the overflow and underflow? For example, I have:
char c = random byte;
c += 0xB;

In case c <= 0xF4, this will work well, but any value above that would cause an overflow. Likewise, if it was c -= 0xB; and c < 0xB, an underflow would occur.
Let's say c =  0xFF, after the addition, will it be 0xA? Likewise with the underflow, if c = 0, will the result be 0xF5?
Also, for some odd, reasons, when I increase specific numbers, weird results occur. For example, if I increase 0x0 by 0xA, using the code:
c = (c + 0xA) & 0xFF;

the result is: 0x0D 0x0A and not just 0x0A... just as shown in the following image:

While all the rest of the bytes increase correctly.

A: I can at least explain your results with 0x0 by 0xA: On Windows, a newline in text files is typically represented as \r\n rather than \n and the file I/O functions will helpfully make this translation for you. In this case you don't desire the conversion though so you could open the file in binary mode which will inhibit the automatic conversion.
As for handling overflow, if you are able to use unsigned char instead of char, it's guaranteed to have well-defined modulo arithmetic for overflow and underflow.
If you need to handle signed over/under flow you're going to have to carefully code up all the logic you want.


text:
Q: Getting weird numbers from array pointer I made function that splits given values(from array pointer) into bytes. For simplicity I use one byte values.
Why I'm getting weird numbers when I print values?
void writePage(uint16_t address, uint64_t *data, uint8_t const len, uint8_t const bPD)
{
    uint8_t pageBuffer[32];
    uint8_t bytes2Write = len * bPD;

    for (uint8_t dataIndex = 0; dataIndex < len; dataIndex++)
    {
        std::cout << int(dataIndex) << std::endl;
        std::cout << data[dataIndex] << std::endl;
        for (uint8_t i = 0; i < bPD; i++)
        {
            pageBuffer[i + (dataIndex * bPD)] = ((data[dataIndex] >> 8 * i) & 0xFF);
            std::cout << int(pageBuffer[i + (dataIndex * bPD)]) << std::endl << std::endl;
        }
    }
}

int main()
{
    uint8_t array[3] = { 255, 20, 30 };
    std::cout << int(array[0]) << int(array[1]) << int(array[2]) << std::endl;
    writePage(0, (uint64_t*)array, 3, 1);

    getch();
    return 0;
}

Output

2552030
0
119944479905023
255
1
70453687222272
0   2
0
0

A: If your goal is to take any type,and to break up the bytes, the way it is almost always done is to cast a pointer to that type to a char * and work with the char *.
Here is an example using a stripped down version of your code.
#include <iostream>

struct foo
{
    int x;
    double y;
    char z;
};

void writePage(uint16_t address, char *data, uint8_t const len)
{
    for (uint8_t dataIndex = 0; dataIndex < len; dataIndex++)
    {
        std::cout << (int)data[dataIndex] << std::endl;
    }
}

int main()
{
    uint8_t array[3] = { 255, 20, 30 };
    std::cout << int(array[0]) << " " << int(array[1]) << " " << int(array[2]) << std::endl;
    writePage(0, reinterpret_cast<char *>(&array[0]), sizeof(array));
    foo f;
    f.x = 10;
    f.y = 20;
    f.z = 'g';
    std::cout << "Here are the bytes of foo, which has a sizeof(foo) as " << sizeof(foo) << "\n" ;
    writePage(0, reinterpret_cast<char *>(&f), sizeof(f));
    return 0;
}

Output:
255 20 30
-1
20
30
Here are the bytes of foo, which has a sizeof(foo) as 24
10
0
0
0
0
0
0
0
0
0
0
0
0
0
52
64
103
-54
-117
-54
-2
127
0
0


text: Q: How to enable Java Run Time Environment on Windows 7? Currently, I am working on mini java applet. However, when I opened my applet in my FireFox, it said Java is disabled and there is no option to enable it at all. I am aware of the vulnerability of the JVM. If enabling JVM is not possible, how can I test my java applet.


text:
Q: Adding http:// to URL still gets interpreted as incomplete URL I wrote a script that grabs the headers of any http or https website, and I wanted to add a feature that adds the protocol to the beginning of the URL if I don't specify myself. For some reason it still reads the finished URL as an invalid one and throws an error.
def headers(hosts)
uri = URI.parse(hosts)
http = Net::HTTP.new(uri.host, uri.port)

if !uri.scheme
    uri = "http://#{uri}"
    puts uri

elsif uri.scheme == 'https'
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
else
    false
end

begin
    Timeout::timeout(8) do
        http.start do
            resp = http.head('/')

            puts "#{resp.code} #{resp.message}"
            resp.each { |k, v| puts "#{k.capitalize}: #{v}" }
            puts "\n"

            http.finish
        end
    end

rescue SocketError
    puts "\nInvalid hostname: #{uri}"

rescue Timeout::Error
    puts "\n#{uri} doesn't seem to exist. Did you type the URL correctly?"

rescue Errno::ECONNREFUSED
    puts "\nERROR: #{uri}; Connection refused!"
end

end

begin
headers(ARGV[0])

rescue Interrupt
puts "\n"
end

You should be able to see that early on in the script, under; if !uri.scheme, I added puts uri. I wanted to be sure that I was creating the URL properly so I added that to test. Now, say for example I run the script and try to grab headers from google.com. The script adds http:// in front of it, and sure enough it puts: http://google.com. Yet it doesn't interpret it correctly somehow. Trying http://google.com works, but trying google.com and adding http:// on doesn't. I want to understand why. Thanks.

A: You have two errors: one, you are not reparsing the url string into an object. Two, you are not creating a new HTTP object if you added the schema. Try something like this:
if !uri.scheme
  uri = URI.parse "http://#{uri}"
end

http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == 'https'
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end

A: The problem
Because uri doesn't contain a string, it contains a URI::HTTP object:
uri = URI.parse("http://www.ruby-lang.org/")
p uri
# => #<URI::HTTP:0x202281be URL:http://www.ruby-lang.org/>

You are using this in your http variable when you initialize Net::HTTP. You simply have to create a new Net::HTTP object with the new URI.
An alternative
I noticed that's a lot of code for a simple task. Here's an alternative using rest-client:
RestClient.get("http://www.google.com/").headers

This also works with https or without a scheme.


text:
Q: Error : Multilingual App Toolkit build completed with errors I have a working project and it was working quite fine.
All of a sudden I am not able to build my Windows Phone project.
1>------ Build started: Project: win-ladenzeile, Configuration: Debug Any CPU ------
1>  Multilingual App Toolkit build started.
1>C:\Program Files (x86)\MSBuild\Microsoft\Multilingual App Toolkit\Microsoft.Multilingual.WindowsPhone.targets(9,5): error : The file exists.
1>C:\Program Files (x86)\MSBuild\Microsoft\Multilingual App Toolkit\Microsoft.Multilingual.WindowsPhone.targets(9,5): error :
1>C:\Program Files (x86)\MSBuild\Microsoft\Multilingual App Toolkit\Microsoft.Multilingual.WindowsPhone.targets(9,5): error : Update XLIFF build failed.
1>C:\Program Files (x86)\MSBuild\Microsoft\Multilingual App Toolkit\Microsoft.Multilingual.WindowsPhone.targets(9,5): error : Multilingual App Toolkit build completed with errors.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
========== Deploy: 0 succeeded, 0 failed, 0 skipped ==========

I tried the following:

*

*Disable and re-enable the Multilingual App Toolkit.

*Repair the Multilingual App Toolkit.

*Reinstall the Multilingual App Toolkit

*git reset head --hard

*Restart PC couple of times.

I am really confused and can't believe the Visual Studio suddenly started acting weird.
Any help is highly appreciated.
EDIT - (After 18 hours)
I am quite sure this has to do with the Multilingual App Toolkit.
I disabled it in the .csproj file
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Multilingual App Toolkit\Microsoft.Multilingual.WindowsPhone.targets" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\Multilingual App Toolkit\Microsoft.Multilingual.WindowsPhone.targets')" Label="MultilingualAppToolkitForWindowsPhone" />

Also disabled "Enable Code Analysis on Build" as I was getting some errors about Code Analysis.
I hope the next version of the toolkit will fix this bug.

A: You will see this when you hit the max number of temp files on your system.  See: http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&l=EN-US&k=k(System.IO.Path.GetTempFileName);k(GetTempFileName);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&rd=true
The Multilingual App Toolkit also uses this API and if you are already close to the limit, it can trigger the error.
To resolve this issues, please be sure to clean your %temp% folder to get unblocked.

A: Had this problem today and it seemed to be because the xlf files used by the Multiligual App Toolkit were not checked out of source control.
The actual problem appears to be the fact that the files are readonly on disk.


text:
Q: Invalid expression term 'int' - Casting object to primitive data type I have a class that is a dictionary of <string, string>, which is a collection of "variables", identified by their keys. I use MySQL to store them, so when I load/save them, I do it as a string, because there is no "generic data type" for sql.
When I want to retrieve a value, I need to cast it to whatever object I need. So what I did is:
protected object GetVariable(string key, Type type = null)
    {
        string result;

        this.Character.Variables.TryGetValue(key, out result);

        if (type == null)
        {
            return result;
        }

        object value = Convert.ChangeType(result, type);

        return value;
    }

Basically, you pass the key and the type you want to convert to. If it's null, it will return the default (string) immiediately. If it's not, it will attempt to convert to a primitive data type and return it. So, I tried calling:
int a = GetVariable("test", int);

However, when I tried to compile this file using CodeDomProvider, It said:
Invalid expression term 'int'

Why's that? How can I fix that?
I'm using C#.

A: You should pass in a type using the typeof operator. This will get you the actual Type instance of the int:
int a = GetVariable("test", typeof(int));

Optionally, you could change your code to use generics, as suggested in comments:
protected T GetVariable<T>(string key)
{
    string result;

    this.Character.Variables.TryGetValue(key, out result);

    if (result != null)
    {
        return Convert.ChangeType(result, typeof(T));
    }
    else
    {
        return default(T);
    }
}


text:
Q: If the product of two idempotents is idempotent, must the two idempotents commute? It is a basic fact that when two idempotents $e,f$ in a semigroup $S$ commute, then $ef$ is an idempotent. Is the converse true? Is it true for idempotents in rings?

A: No. In $M_2(\mathbb{C})$, let
$$
e=\begin{bmatrix}1&0\\ 0&0\end{bmatrix}, \ \
f=\begin{bmatrix}1&1\\ 0&0\end{bmatrix}.
$$
So
$$
e^2=e, \ \ f^2=f, \ \ ef=f, \ \ fe=e.
$$

A: Consider the semi-group of matrix $2\times 2$ with real entries and $A:=\pmatrix{0&1\\\ 0& 1}$, $B=\pmatrix{1&0\\\ 0&0}$. Then $A^2=A$, $B^2=B$, $AB=0$ but $BA=\pmatrix{0&1\\\ 0&0}\neq AB$.


text:
Q: Excluding Page from Release Build in ASP.NET Project I am using an "Inspector.aspx" to do some tests in my Debug build. In a Release build (and more importantly when creating an installer), I manually exclude the page (and it's related C# files) from the project.
Is there a way to automatically exclude files in a selected solution configuration in an ASP.NET project?
C++ projects give control on exclusion/inclusion per file per configuration

A: One option is to edit your msbuild (*.csproj) file to conditionally exclude certain files based on the Solution Configuration (ie. Debug, Release, etc). For instance:
<Compile
    Exclude="inspector.aspx"
    Condition="'$(Configuration)' == 'Release'" />

Similarly you could define an ItemGroup containing only the files that you want to be included in the Debug build:
<ItemGroup Condition="'$(Configuration)' == 'Debug'">
    <Compile Include="inspector.aspx" />
    <Compile Include="...other files..." />
</ItemGroup>


text:
Q: Typescript Compiler - Implement custom transformer Iv'e read alot of the Typescript github issues regarding implementation but there's little documentation or people working in this area.
My goal is to basically have typescript understand that..
[1,2,3,4,5].filter(_ % 2).map(_ + 2)
[{name: "test"}, {name: "test2"}].map(_.name).map(_.toUpperCase())

is the same as...
[1,2,3,4,5].filter((x) => x % 2).map((x) => x + 2)
[{name: "test"}, {name: "test2"}].map((x) => x.name).map((x) => x.toUpperCase())

i either want to define a SweetJS macro to convert all underscores to (x) => x at compile time or (peferably) have typescript apply that transformation for me since SweetJS is fairly hacky.
(For reference https://github.com/sweet-js/sweet-core)
How would i go about implementing something that allows typescript to at the bare minimum understand underscore syntax in the correct context \AND\ if possible transform underscores at compile time.
EDIT3: (Edit3 is here for readability) this is how far i have got with the problem, i have opted not to change the compiler to think it is a different type but instead do this....
declare const _: (<T>(arg: T) => T) & { [key: string]: () => any }
const test = [{name: "Shanon", age: 24}].filter(_.age);

which typescript is now happy with, but it is not typesafe so any help would be appreciated.
EDIT: With my minimal compiler skills, i think that i need typescript to understand that when i am within the context of a "CallExpression" underscore has a very unique meaning (CallExpression in the AST).
EDIT2:
this is the AST defintiion i need outputted (something like this) it's important to note, i don't want the underscore converted before it is typechecked but i want to controle how a underscore is type checked. It should only treat the underscore as this type inside a CallExpression AST type


text:
Q: Flutter StatefulWidget hierarchy I imagine this is by design, but when Navigate.Push'ing to a new Page from a StatefulWidget, the original page is rebuilt on rendering the second.  This is the sample code from https://flutter.io/cookbook/navigation/navigation-basics/, I have just added print statements to show activity and converted the first page to be Stateful.
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    title: 'Navigation Basics',
    home: FirstScreen(),
  ));
}

class FirstScreen extends StatefulWidget {
  @override
  FirstScreenState createState() {
    return new FirstScreenState();
  }
}

class FirstScreenState extends State<FirstScreen> {
  @override
  Widget build(BuildContext context) {
    print('Building Screen 1');
    return Scaffold(
      appBar: AppBar(
        title: Text('First Screen'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Launch screen'),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => SecondScreen()),
            );
          },
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext   context) {
    print('Building Screen 2');
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Screen"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Go back!'),
        ),
      ),
    );
  }
}

Output from this shows that on rendering the second page, the first is also then rebuilt:
I/flutter (20929): Building Screen 2
I/flutter (20929): Building Screen 1

I have an instance of this scenario where Screen 1 uses a FutureBuilder.  I don't want to have to reload all the data every time that Screen 2 is rebuilt.  Can't help but think I'm missing something fundamental as this seems illogical.


text:
Q: Differentiate between My SQL Queries What is the difference between the following queries? They give me the same result.
1
SELECT student. * ,
department.department_name,
semester.semester_name
FROM (
student
LEFT JOIN department ON student.student_id = department.department_id
LEFT JOIN semester ON student.student_id = semester.semester_id
)

2
SELECT student. * ,
department.department_name,
semester.semester_name
FROM (
student
LEFT JOIN department ON student.department_id = department.department_id
LEFT JOIN semester ON student.semester_id = semester.semester_id
)

3
SELECT student. * ,
department.department_name,
semester.semester_name
FROM (
student
LEFT JOIN department ON student.student_id = student.student_id
LEFT JOIN semester ON student.student_id = student.student_id
)

4
SELECT student. * , department.department_name, semester.semester_name
FROM (
student
LEFT JOIN department ON student.department_id = student.student_id
LEFT JOIN semester ON student.semester_id = student.student_id
)

A: You can't match this:
student.student_id = department.department_id

It doesn't make sense - you are saying that a student ID and a department number are interchangeable, but they are not. In this particular case, you probably have "student 1" and "department 1", and so in the case you are testing, it works. But it will not in general.
Equally, there is no value in doing this:
student.student_id = student.student_id

Here you are saying that you want the rows where something is equal to itself. Since all things are equal to themselves this will not apply any limitation, and so is redundant. If this is the only clause to a JOIN you will end up joining to all rows of the new table (a Cartesian product), which is definitely not what you want.
Only query (2) appears to be correct.

A: 2) (unless you have a weird schema) would be correct in that it would give a list of students and their courses and semesters.
3) would give a list of students against all courses and all semesters since student.student_id = student.student_id will always be true.
1 and 4) Will give random matchings between students and courses and semesters depending on which ids happen to tally between them (i.e. where they student id happens to be the same as the semester or department id).


text:
Q: how to seprate alphanumeric string into number and alphabets For example string is JD85DS8796
There are 4 text views and I want to set each text view like:
In 1st text-view JD, in 2nd text-view 85, in 3rd text-view DS, in 4th text-view 8796.

A: First of all, yes there is a crazy regex you can give to String.split:
"[^A-Z0-9]+|(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])"

What this means is to split on any sequence of characters which aren't digits or capital letters as well as between any occurrence of a capital letter followed by a digit or any digit followed by a capital letter. The trick here is to match the space between a capital letter and a digit (or vice-versa) without consuming the letter or the digit. For this we use look-behind to match the part before the split and look-ahead to match the part after the split.
However as you've probably noticed, the above regex is quite a bit more complicated than your VALID_PATTERN. This is because what you're really doing is trying to extract certain parts from the string, not to split it.
So finding all the parts of the string which match the pattern and putting them in a list is the more natural approach to the problem. This is what your code does, but it does so in a needlessly complicated way. You can greatly simplify your code, by simply using Pattern.matcher like this:
private static final Pattern VALID_PATTERN = Pattern.compile("[0-9]+|[A-Z]+");

private List<String> parse(String toParse) {
List<String> chunks = new LinkedList<String>();
Matcher matcher = VALID_PATTERN.matcher(toParse);
while (matcher.find()) {
    chunks.add( matcher.group() );
    }
return chunks;
}

If you do something like this more than once, you might want to refactor the body of this method into a method findAll which takes the string and the pattern as arguments, and then call it as findAll(toParse, VALID_PATTERN) in parse.

A: Try this way, this will gives you digits value, then remaining string can be separated as string
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("JD85DS8796");
m.find();
String inputInt = m.group();
textview.setText(inputInt);


text:
Q: not taking correct dimens folder for 7" and 10" tabs I have developed an app for phones. Now I need to support it to tablets as well. I need to change few dimensions of few views. I had kept 4 values folders for hdpi, xhdpi, xxhdpi and xxxhdpi. Now for a 7" tab I have kept values-sw600dp and for 10" inch tab I have kept values-sw720dp. But any changes I make in the dimens folders of the 600dp and 720dp does not change when I run in the tab. The 7" tab takes the values of values-hdpi folder. How do I support for both screens and tabs?
Please suggest.

A: If you actually have a tablet that has a smallest width of 600dp (values-sw600dp), then it should prioritize that over that over values-hdpi (see here). Are you sure your tablet is actually 600dp?

A: My 7" inch tap get resourses from sw320dp folder, You need use

dp = px / (dpi / 160)

to find right size qualifier.
This link have morе information:
Application Skeleton to support multiple screen
And answer from https://developer.android.com/guide/practices/screens_support.html?hl=ru#DeclaringTabletLayouts The proper way to declare tablet layouts was to put them in a directory with the xlarge configuration qualifier (for example, res/layout-xlarge/).


text:
Q: displaying file name, not content in text widget tkinter Python I've no idea why I haven't been able to find a good solution to this problem yet, it seems very elementary to me .. though not elementary enough to figure it out satisfactorily.
A chapter project in a cryptology book Im reading instructs to write a simple mono-alphabetic cipher in your preferred language ... I chose Python.
It starts with a simple tkinter app. with some widgets, lol ... duh. Anyways here's the relevant code:
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror

class Application(Frame):
    def __init__(self, master):
        """ Initialize Frame. """
        super(Application, self).__init__(master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """ Set all program widgets. """
        # set all labels
        Label(self, text = "Plaintext File: ")\
            .grid(row=0, column=0, sticky=W)
        Label(self, text = "Ciphertext: ")\
            .grid(row=3, column=0, sticky=W)
        Label(self, text = "Offset: ")\
            .grid(row=2, column=0, sticky=W)

    # set buttons
    Button(self, text = "Browse", command=self.load_file, width=10)\
        .grid(row=1, column=0, sticky=W)

    # set entry field
    self.file_name = Text(self, width=39, height=1, wrap=WORD)
    self.file_name.grid(row=1, column=1, columnspan=4, sticky=W)

    # set display field
    self.output_display = Text(self, width=50, height=5, wrap=WORD)
    self.output_display.grid(row=4, column=0, columnspan=4, sticky=W)

    # set offset amount spinbox
    self.offset_amt = IntVar()

    self.offset_amt = Spinbox(self, from_=1, to=13)
    self.offset_amt.grid(row=2, column=1, sticky=W)

    # set shift direction
    self.shift_dir = StringVar()
    self.shift_dir.set('r')

    Radiobutton(self, text="Shift Right", variable=self.shift_dir, value='r')\
        .grid(row=2, column=2, sticky=W)
    Radiobutton(self, text="Shift Left", variable=self.shift_dir, value='l')\
        .grid(row=2, column=3, sticky=W)

def load_file(self):

    self.filename = askopenfilename(initialdir='~')

    if self.filename:
        try:
            #self.settings.set(self.filename)
            self.file_name.delete(0.0, END)
            self.file_name.insert(0.0, open(self.filename, 'r'))
        except IOError:
            showerror("Open Source File", "Failed to read file \n'%s'"%self.filename)
            return

def main():
    root = Tk()
    root.title("simple mono-alpha encrypter")
    root.geometry('450x250')
    app = Application(root)

for child in app.winfo_children():
    child.grid_configure(padx=3, pady=3)

root.mainloop()

main()

There's only a very little of it that actually does anything besides create widgets right now, I decided to post it all since its not that involved yet and someone can get a good idea of where Im at.
My problem that I haven't solved is that when I press use the 'Browse' button to choose a file to encrypt and then choose the file, the file content is displayed in the 'file_name' text widget, rather than the file name itself.
Im thinking that I have to change the 'filename' variable to not the actual file name but the file instead and then load the content of the File Name field from the open file dialog box in a 'filename' variable. I just haven't been able to figure out how to do that yet.
Nor have I come across an appropriate method to do it.
Any guidance??
Thanks
F

A: Displaying the Filename
self.file_name.insert(0.0, self.filename)

Displaying the File Contents
You just need to read the data in from the file.  See http://docs.python.org/library/stdtypes.html#file-objects
with open(self.filename, 'r') as inp_file:
    self.file_name.insert(0.0, inp_file.read())


text:
Q: How to invoke a web service call using vbscript i am beginner in coding.
I have to call a web service below:
http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit
enter a value like 25 and click Invoke returns you the temperature in Fahrenheit.
For that i used below code:
url = "http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit&Celsius=25"
'Set oHttpReq = CreateObject("Microsoft.XMLHTTP") 'when i use XMLHTTP i am getting error saying "The download of the specified resource has failed."

Set oHttpReq = CreateObject("MSXML2.ServerXMLHTTP") 'If i use it, the response contains Root Element missing

oHttpReq.open "POST", url, False
oHttpReq.send

'Response
responseText = oHttpReq.responseText

WScript.echo responseText

Can anyone help me?

A: Create at file.vbs (visual basic script)
Compile with external tool to exe
In server task set this.
Const HOST = Sample service in IIS
Const URL = "wsPage.asmx"

Set xmlhttp = CreateObject("Microsoft.XMLHTTP")
xmlhttp.open "POST", HOST & URL & "/wsServiceTest", false

'Set the Content-Type header to the specified value
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"

' Send the request synchronously
xmlhttp.send ""
WScript.Echo "Load ok..."