text:
Q: Ruby combinations with ruleset & speed optimization? Hey iam trying to figure out how i could limit my combinations of objects.
My problem:
I want to generate x teams with the most "point" outcome of 432 players, max team size is 7 players. Each player has an "position" attribute, every team must have each position one time and max 3 times. Also an player has an "worth" attribute. Each team cant be more worth than 70. Every player can only be one time in an team.
Data example:
{ name: 'James Harden', position: 'PG', weight: 15.9, points: 62.63 },
{ name: 'Russell Westbrook', position: 'PG', weight: 14.9, points: 56.12 },
{ name: 'LeBron James', position: 'SF', weight: 15.9, points: 55.67 },
{ name: 'Bradley Beal', position: 'SG', weight: 14.8, points: 52.69 },
{ name: 'Anthony Davis', position: 'PF', weight: 14.6, points: 52.16 },
{ name: 'Damian Lillard', position: 'PG', weight: 13.5, points: 49.34 },
{ name: 'Nikola Vucevic', position: 'C', weight: 12.9, points: 47.97 },
{ name: 'Domantas Sabonis', position: 'PF', weight: 12.8, points: 47.6 }

My try:
Well i tried to use the combination method from ruby:
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
print b.combination(7).to_a

that take 52 minutes for my laptop so solve all combinations. so i search for a way to do it faster an to apply more options like mentioned above to limit the result of teams.
Later if i find an solution i want to build this thing into an rails app with picture of the players and so on. Hopefully someone can give me an hint or has done something similar to give advices.
Also how would i controll to use more cpu kernels to speed up the proccess ?


text:
Q: Maven JAX-WS WSGEN "Class not found error" When i try to Compile my program.  I get the following error message:
Failed to execute goal org.jvnet.jax-ws-commons:jaxws-maven-plugin:2.2:wsgen (generate-wsdl) on project SimpleWebServices: Error executing: wsgen [-keep, -s, etc..........

So, I begin poking around and further up the error, I see this:
Class not found: "com.test.ws.services.SimpleServiceImpl"

It would appear that for some reason, the WSGEN cannot find my  value.  Does anyone have any ideas?
Here's my POM if interested...
        <plugin>
            <groupId>org.jvnet.jax-ws-commons</groupId>
            <artifactId>jaxws-maven-plugin</artifactId>
            <version>2.2</version>
            <executions>
                <execution>
                    <id>generate-wsdl</id>
                    <phase>process-classes</phase>
                    <goals>
                        <goal>wsgen</goal>
                    </goals>
                    <configuration>
                        <sei>com.test.ws.services.SimpleServiceImpl</sei>
                        <genWsdl>true</genWsdl>
                        <verbose>true</verbose>
                    </configuration>
                </execution>
            </executions>
        </plugin>

User Edit:
I think i got it (based on @Thomas suggestion).  It appears that I didn't specify the source folder in the POM Build area.  Resulting in my source not being compiled.
Adding:
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>

Did the trick for me.
@Thomas if you post your answer, I'd be happy to give you answer credit.
Thanks for your reply,

A: just use
mvn clean compile jaxws:wsgen

instead of
mvn clean jaxws:wsgen

the problem is, that there is no compiled version available. wsgen will work for classpaths like JARs with ByteCode.
sourceDirectory ${project.basedir}/src/main/java is maven default, so you doesn't have to set it necessarily.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Glass : Launch AVD Manager I want to run the sample app of Google Glass. I am using the Eclipse environment. I have already downloaded SDK platform and Glass Development Kit - Sneak Peak. But when I try to launch the Android Virtual Device Manager and select target as Glass Development Kit Sneak Peak, it does not launch.
What should I do ?

A: The Android Virtual Device Manager is for emulators; it may not help because there is no officially supported Google Glass emulator. You may want to check this post for more information.


text:
Q: Regex for matching a name followed by numbers The problem i have with this task is:

*

*If there is a : or / between the name and the number there CAN be a whitespace bevore and after the symbol

*If there is non of the symbols there MUST be a whitespace between the name and the number.
So far i came to this:
^\s*[^/:\d]*\s*?[/:]?\s*([0-9]{6,10})\s*$

But that matches Name1234567 wrong. It should be wrong but is true. (there MUST be a whitespace between)
1234567, Name 1234567 or Name/1234567 works everything perfectly fine. But i can't get that one specific task working.
Hope someone can fix that problem.
Greetz

A: How about
[a-zA-Z]*(?:\s|(?:\s?[:\/]\s?))\d+

for example http://regex101.com/r/dD3lP4/1
How it matches
[a-zA-Z]* matches any number of alphabets
(?:\s|(?:\s?[:\/]\s?))matches a space \s or \s?[:\/]\s? space followed by : or / again followed by space \s. The quantifies ? makes \s occurence as zero or one (can part in the question)
\d+ matches any number of digits


text:
Q: Python - Parse text file and create lists based on some criteria I've been searching for a solution to this question for a while without any luck.  I'm wanting to use Python to read a text file and create some lists (or arrays) based on the data in the file.  An example will best illustrate my goal.
Consider the following text:
NODE
1.0, 2.0
2.0, 2.0
3.0, 2.0
4.0, 2.0
ELEMENT
1, 2, 3, 4
5, 6, 7, 8
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
5, 6, 7, 8
5, 6, 7, 8
5, 6, 7, 8

I would like to read through the file (ideally once as the files can be large) and once I find "NODE" take each line between "NODE" and "ELEMENT" and put into a list.  Then, once I reach "ELEMENT" take each line between "ELEMENT" and some other break (maybe another "ELEMENT" or end of file, etc…) and put that into a list.  For this example,it would result in two lists.
I've tried various things but they all require knowing information about the file beforehand.  I'd like to be able to automate it.  Thank you very much!

A: With that example data, and assuming that the labels follow the pattern in your example, you can use a regex:
import re, mmap, os

def conv(s):
    try:
        return float(s)
    except ValueError:
        return s

data_dict={}
with open(fn, 'r') as fin:
    size = os.stat(fn).st_size
    data = mmap.mmap(fin.fileno(), size, access=mmap.ACCESS_READ)
    for m in re.finditer(r'^(\w+)$([\d\s,.]+)', data, re.M):
        data_dict[m.group(1)]=[[conv(e) for e in line.split(',')]
                        for line in m.group(2).splitlines() if line.strip()]

print data_dict

Prints:
{'NODE': [[1.0, 2.0], [2.0, 2.0], [3.0, 2.0], [4.0, 2.0]],
 'ELEMENT': [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [1.0, 2.0, 3.0, 4.0], [1.0, 2.0, 3.0, 4.0], [1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [5.0, 6.0, 7.0, 8.0], [5.0, 6.0, 7.0, 8.0]]}

So, how does this work:

*

*We use mmap to apply a regex to a file

*We assume that the labels are the form of ^\w+$ (ie, labels made up of letters and numbers on a line)

*Then capture all the numbers and spaces following that

*Create a dict with the label as the key, the parsed numbers as the list of floats following.

Done!

A: If you want this to be fully general and automated, you need to come up with the rule that distinguishes section headers from rows. I'll invent one, but it's probably not the one you want, in which case my invented code won't work for you… but hopefully it will show you what you need to do, and how to get started.
def new_section(row):
    return len(row) == 1 and row[0].isalpha() and row[0].isupper()

Now, we can just group the rows by whether or not they're section headers by using itertools.groupby. If you printed out each group, you'd get something like this:
True, [['NODE']]
False, [['1.0', '2.0'], ['2.0', '2.0'], …, ]
True, [['ELEMENT']]
False, [['1.0', '2.0', '3.0', '4.0'], …, ]

We don't care about the first value in each of those, so drop it.
And we want to batch up each pair of adjacent groups into a (header, rows) pair, which we can do by zipping our iterator with itself.
And then just put it in a dict, which will look something like this:
{'NODE': [['1.0', '2.0'], ['2.0', '2.0'], …],
 'ELEMENT': [['1.0', '2.0', '3.0', '4.0'], …]}

Here's the whole thing:
import csv
import itertools

def new_section(row):
    return len(row) == 1 and row[0].isalpha() and row[0].isupper()

with open(path) as f:
    rows = csv.reader(f)
    grouped = itertools.groupby(rows, new_section)
    groups = (group for key, group in grouped)
    pairs = zip(groups, groups)
    lists = {header[0][0]: rows for header, rows in pairs}

A: def getBlocks(fname):
    state = 0
    node = []
    ele = []
    with open(fname) as f:
        for line in f:
        if "NODE" in line:
            if state == 2:
            yield (node,ele)
            node,ele = [],[]
            state = 1
        elif state == 1 and "ELEMENT" in line:
            state = 2
        elif state == 1:
            node.append(list(map(float,line.split(","))))
        elif state == 2 and re.match("[a-zA-Z]+",line):
            yield (node,ele)
            node,ele = [],[]
            state = 0
        elif state == 2:
            ele.append(list(map(int,line.split(","))))
        yield (node,ele)

for node,ele in getBlocks("somefile.txt"):
    print "N:",node
    print "E:",ele

might be about what your looking for its kinda gross... im sure you can do it better

A: For the simpler problem in the updated question, you really don't need regexps, or groupby, or a complex state machine, or anything beyond what a novice should be able to understand easily.
All you need to do is accumulate rows into one list until you find the row 'ELEMENT', then start accumulating rows into the other one. Like this:
import csv
result = {'NODES': [], 'ELEMENTS': []}
current = result['NODES']
with open(path) as f:
    for row in csv.reader(f):
        if row == ['NODE']:
            pass
        elif row == ['ELEMENT']:
            current = result['ELEMENTS']
        else:
            current.append(row)


text:
Q: How can I enable a #define automatically in XCode when the simulator is selected? I have a few files that I want compiled differently when I'm testing my iPhone app on the simulator, so I'm using a #define simulator macro in those files.  I'm trying to figure out how I can comment out this #define statement and tell XCode to define this macro when the simulator is selected.  How can I do this?
I read a couple other similar questions on here and tried adding a conditional assignment in the "Other C Flags" build settings for the "Any iOS Simulator SDK" architecture with the value set to "-simulator=1", but that doesn't seem to do anything.
Thanks in advance for your wisdom!

A: #if TARGET_IPHONE_SIMULATOR should do the trick.

A: You don't need your own #define for this: Apple provides one for you. Just use
#if TARGET_IPHONE_SIMULATOR

around the code you want specific to the simulator. (You'll need to include the TargetConditionals.h header for this, but it's probably already included if you import the frameworks.)


text:
Q: Prove any number $c \in [a, b]$ is a subsequential limit if $\lim\inf x_n = a$, $\lim \sup x_n = b$, $a\ne b$, $\lim(x_n -x_{n+1})=0$ I'm trying to solve the following problem:

Let $\{x_n\}$ denote a bounded sequence. Prove that any number $c \in [a, b]$ is a subsequential limit of $\{x_n\}$ if:
  $$
\begin{cases}
\lim_{n\to\infty} (x_n - x_{n+1})=0\\
\lim\inf x_n = a\\
\lim \sup x_n = b\\
a\ne b
\end{cases}
$$

Here are some of my thoughts. We know that $x_n$ is bounded. Then by Bolzano-Weierstrass we may choose some subsequence such that it has a finite limit:
$$
\exists c \in [a, b] : \lim x_{n_k} = c \iff \forall \epsilon_1 > 0 \exists N_1\in\Bbb N: \forall n_k > N_1 \implies |x_{n_k} - c| < \epsilon_1
$$
We are also given that limsup and liminf exist and therefore:
$$
\exists N_2 \in \Bbb N : \forall n_k > N_2 \implies x_{n_k} \ge a \\
\exists N_3 \in \Bbb N : \forall n_k > N_3 \implies x_{n_k} \le b
$$
If we now choose $N$ to be $\max\{N_2, N_3\}$ we obtain:
$$
\exists N = \max\{N_2, N_3\}: \forall n_k > N \implies a \le x_{n_k} \le b \tag1
$$
Also we are given the fact that $\lim (x_n - x_{n+1}) = 0$:
$$
\forall \epsilon_2 > 0, \exists N_4 \in \Bbb N: \forall n_k > N_4\implies |x_n - x_{n+1}| < \epsilon_2
$$
But if $\lim (x_n - x_{n+1}) = 0$, then it is also true for the subsequences:
$$
\forall \epsilon_3 > 0, \exists N_5 \in \Bbb N: \forall n_k > N_5\implies |x_{n_k} - x_{n_k+1}| < \epsilon_3 \tag 2
$$
Now I'm struggling to combine that facts in order to show that any $c \in [a, b]$ is a subsequential limit of $\{x_n\}$, how do I proceed? Feels like i have to consider $(1)$ and $(2)$ in tandem in order to finish the proof.

A: Pick $c\in (a,b)$ and enumerate $L=\{x_n:x_n\le c\}$ by $\{y_n\}$ and $U=\{x_n:x_n\ge c\}$ by $\{z_n\}$. Notice $\{x_n\}=\{y_n\}\cup\{z_n\}$ and that both $y_n$ and $z_n$ are infinite because $\liminf x_n=a$ and $\liminf x_n=b$. If either $\limsup y_n =c$ or $\liminf z_n=c$ we are done, so suppose neither holds. Then there exists some $N$ s.t. for $m,n\ge N$, $y_m < c-\epsilon<c<c+\epsilon<z_n$ for some \
$\epsilon>0$. If there were only finitely many $k$ s.t. $x_k\le c\le x_{k+1}$, we could not have $\liminf x_n=a$ and $\limsup x_n=b$. Therefore there are infinitely many $k$ s.t. $x_k=y_{n_k}$ and $x_{k+1}=z_{m_k}$. For $k$ large enough, $x_{k+1}-x_k\ge 2\epsilon$, so we can not have $\lim( x_n-x_{n+1})=0$.

A:
Claim: Let $A,B$ be subsets of $\Bbb R$ such that $\delta:=\inf B-\sup A>0$. Let $x_n\in A\cup B$ be a sequence such that $\lim_{n\to\infty} (x_n-x_{n+1})=0$, then $\exists M\in\Bbb N$ such that either $x_n\in A$ for all $n\ge M$ or $x_n\in B$ for all $n\ge M$.
Proof: Let $n_0\in\Bbb N$ be such that $|x_n-x_{n+1}|<\delta/2$ for all $n\ge n_0$. Suppose for contradiction that such an $M$ cannot be found, then $\exists N>n_0$ such that $x_N\in A$ but $x_{N+1}\in B$. This, however, implies that
$$
\delta\le |x_N-x_{N+1}|<\delta/2,
$$
a contradiction.

Let's apply the above to your problem:
Assume that $\exists c\in (a,b)$ such that $c$ is not a subsequential limit of $x_n$, then there is an $\varepsilon>0$ and $N\in\Bbb N$ such that for all $n\ge N$, $x_n\notin (c-\varepsilon,c+\varepsilon)$. This splits the set in which the sequence $x_n$ (for $n\ge N$) lies into two parts, i.e.
$$
A=[a,c-\varepsilon], B=[c+\varepsilon,b].
$$
The sets $A$ and $B$ satisfy the conditions above.
Without loss of generality, let's say $x_n\in A$ for all $n\ge M$. Then we have
$$
\limsup_{n\to\infty} x_n \le \sup_{n\ge M} x_n \le c-\varepsilon < b,
$$
which contradicts $\limsup_{n\to\infty} x_n = b$.

A: Here's my very informal answer.
The lim sup and lim inf info
says that the sequence
gets infinitely often
arbitrarily close to
a and b.
The difference info
says that
successive terms
get eventually arbitrarily close.
So,
on the way between a and b,
the successive terms
are arbitrarily close
and so will be,
somewhere,
arbitrarily close to c.
Since this happens
infinitely often,
choose these terms close to c
as the subsequence.

A: The answer has already been given, but I will try to add my own thoughts on this, hopefully valid. Please let me know whether the reasoning below is wrong and I will either edit it or delete it completely.
Choose some $c \in [a, b]$. If $c = a$ or $c = b$ then we are done since:
$$
\lim\sup x_n = b = c \\
\text{or}\\
\lim\inf x_n = a = c
$$
Suppose $ c \notin \{a, b\}$. Then by Bolzano-Weierstrass (and the fact that $x_n$ is bounded and hence $x_{n_k}$ is also) we may choose a convergent subsequence $\{x_{n_k}\}$ from $\{x_n\}$. Suppose its limit is $c$:
$$
\lim x_{n_k} = c
$$
Using the definition of a limit:
$$
\forall \epsilon_1 > 0\ \exists N \in \Bbb N: \forall n_k > N \implies |x_{n_k} - c| < \epsilon_1 \tag1
$$
On the other hand we have the following property:
$$
\lim_{n\to\infty} (x_n - x_{n+1}) = 0
$$
This property also applies to subsequences so for $\{x_{n_k}\}$:
$$
\lim_{k\to\infty} (x_{n_k} - x_{n_k + 1}) = 0
$$
Rewriting it by definition we obtain:
$$
\forall \epsilon_2 > 0\ \exists N \in\Bbb N: \forall n_k > N \implies |x_{n_k} - x_{n_k + 1}| < \epsilon_2 \tag2
$$
Based on $(1)$ and $(2)$ we may choose $N$ such that both statements are satisfied. Since both inequalities in $(1)$ and $(2)$ become valid we may sum them up:
$$
\forall \epsilon = \max\{\epsilon_1, \epsilon_2\} > 0\ \exists N = \max\{N_1, N_2\}: n_k > N \implies |x_{n_k} - c| + |x_{n_k} - x_{n_k + 1}| < \epsilon
$$
By trialnge inequality:
$$
|x_{n_k} - c| + |x_{n_k} - x_{n_k + 1}| \ge |x_{n_k} - c + x_{n_k} - x_{n_k + 1}| = |2x_{n_k} - x_{n_k + 1} - c|
$$
Going from definition to a limit we get:
$$
\lim_{k\to\infty}(2x_{n_k} - x_{n_k + 1}) = c
$$
We've chosen $\{x_{n_k}\}$ such that $\lim x_{n_k} = c$ exists and we know that $\lim({x_{n_k} - x_{n_k + 1}}) = 0$ also exists, so:
$$
\lim_{k\to\infty}(2x_{n_k} - x_{n_k + 1}) = \\
\lim_{k\to\infty}(x_{n_k} + x_{n_k} - x_{n_k + 1}) = \\
\lim_{k\to\infty}x_{n_k} + \lim_{k\to\infty}(x_{n_k} - x_{n_k + 1}) = \\
= \lim_{k\to\infty}x_{n_k} + 0 = \\
= \lim_{k\to\infty}x_{n_k} = c
$$
Since $c$ is arbitrary in $[a, b]$ and $x_{n_k}$ is a subsequence of $x_n$ this shows that every $c\in[a, b]$ appears to be a subsequential limit.


text:
Q: Consuming Rest service with SSL certificate in C# I am trying to consume a rest service to read Active MQ messages in C#. The service has a SSL certificate with no password. I can successfully get the response when I use the service url in browser (chrome, restlet client) but not in postman. I had added the certificate to Chrome before accessing the url.
This is a HTTPS service.
I have to call the service with the SSL cert along with my http request. I have tried WebRequestHandler, HttpWebRequest, HttpClient with no luck.
When I do that, I received the following error.

The underlying connection was closed: Could not establish trust
  relationship for the SSL/TLS secure channel.

string url =  System.Configuration.ConfigurationManager.AppSettings["ActiveMQDev"].ToString();
string certFileName = System.Configuration.ConfigurationManager.AppSettings["SSLCertPath"].ToString();

// create HTTP web request with proper content type
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json;charset=UTF8";
X509Certificate2 cert = new X509Certificate2(certFileName);
request.ClientCertificates.Add(cert);
request.PreAuthenticate = true;
WebResponse response;

using (new ServerCertificateValidationScope(request, delegate { return true; }))
{
    // call the web service and get response
    response = request.GetResponse();
}

if (response != null)
{
    //handle the response
}

this suppresses the exception but I get

RemoteCertificateNameMismatch

error in the callback(sender, certificate, chain, errors).
When I dont have the call to suppress the SSL error, I get a

401 unauthorized response from the server.

Any help is much appreciated. Thank you!

A: So we went back to the team that gave us the cert and it was faulty! We got a cert with password and its a pfx file now. We are directly accessing the queue now attaching the cert in the request. This seems to have resolved the issue with getting to the queue and accessing the messages in it. The only problem we have now is the messages are not dequeuing but i guess thats the AMQ team's headache. If anyone requires the code to access the AMQ directly using the NMS api, please send me a message. I can send a sample. Thanks all for your help. Really appreciate it.!


text:
Q: new bean for every wicket session I was creating my first application using Apache wicket and am stuck on a problem. After the user logs in through the authentication method I have a new session which is created for that user. Now if I wanted to have data stored for just that user how would I use bean to implement that?
At the moment i created an interface and a class with get and set methods for the variables i wanted stored and created a bean such as <bean id="springApplicationContext" class="com..util.SpringApplicationContext"/> but what happens is the data gets overwritten but when i change the scope to "session" everyone has the same data in the bean still.
Thanks

A: The correct way is to use Session scoped Spring bean. There must be some error in your config if the data is visible to all users.
Using Spring has nothing to do with Wicket though!
Alternative approach is to store your data in Wicket's Session class.
Override MyApplication#newSession() method and return MySession class. The instance of MySession will be stored as an attribute in the HTTP session by Wicket. You can put any member fields inside MySession, e.g.;
public class MySession extends WebSession {
  ...
  private MyBean myBean;
  // setter and getter
  ...
}

Then in your Wicket code use it with: MySession.get().getMyBean().setSome(thing);


text:
Q: Help to fix jquery sortable for ordered list Please see the demo here
http://trainee4.afixiindia.com/pratap/ui/shopping_cart.html
When I click on the number and try to drag for sortable,its not happening.But when I drag the li ,its working
"It mayn't be done with an ordered list because the numbers aren't represented in HTML. I have to use an unstyled, unordered list and manage the numbers myself.":-Its a solution I think
Is there any solution.?

A: Just add this to your #cart ol style:
list-style-position: inside;


text:
Q: Replacing an item in an object? I'm looping through an object:
foreach ($data as $asset) {

    $asset->test = 'test';
}

test exists in $data and is set to something else, I wish to replace it with 'test'.
The above fails to work. Where am I going wrong?

A: You should use referenced loop with & like foreach ($data as &$asset)
foreach ($data as &$asset)
{
    $asset->test = 'test';
}

Referenced loop will have an effect to $data, otherwise only current $asset object changes.

A: You can think about using a function that already exists, like array_walk that would execute your function.
function test_exists(&$asset) {
    $asset->test = "test";
}

array_walk($data, "test_exists");


text:
Q: android studio, how to disable action bar menu opening on drag I wonder how to disable action bar menu opening on drag.
@Override
public void onResume() {
    super.onResume();
    if(getActivity() != null)
        ((AppCompatActivity)getActivity()).getSupportActionBar().hide();
}
@Override
public void onStop() {
    super.onStop();
    if(getActivity() != null)
        ((AppCompatActivity)getActivity()).getSupportActionBar().show();
}

I used this code to hide the bar in my fragment, but it still can be opened by dragging the left side of the screen.


text:
Q: Hide table content if value is null in PDFMake I want to hide a table content if a certain variable is null.
The table design code :
{
          color: '#000000',
          margin: [25, 10, 0, 0],
          table: {
            body: [
              [
                {
                  text: 'STRUCTURAL/FOUNDATION',
                  alignment: 'center',
                  style: 'subheader',
                },
              ],
            ],
          },
          layout: {
            hLineColor: function (i, node) {
              return 'black';
            },
            vLineColor: function (i, node) {
              return 'black';
            },
            paddingLeft: function (i, node) {
              return 100;
            },
            paddingRight: function (i, node) {
              return 100;
            },
            paddingTop: function (i, node) {
              return 2;
            },
            paddingBottom: function (i, node) {
              return 2;
            },
          },
        },

If this.StoredData.structureDescription is null, then this above code should be hidden (i.e, nothing to be displayed on the pdf).


text:
Q: Attempting to find the next div element from the current one I have html code like this:

**CRED ID:**

**11111972**

**CAQH ID:**

**11189685**

if something shows as two stars for you it is supposed to be bold.  I made the text bold so it shows up better.  Anyway I can use //div[contains(text(),'CRED ID:')] to get the div element containing "CRED ID".  The actual cred id value is "11111972".  I am wondering how, when I use the above xpath, I can tell it to get the text value of the next div (i.e., 11111972).  I can't really use a ../div because there are earlier and later divs at this level.  Can anyone suggest?
I could use a @FindBy and make a List, find the index if "CRED ID" and add 1 I suppose, but it seems like there should be another way?
Thanks
p.s. I never really understodd following-sibling but I do not know whether that would work here?

A: You can use the following-sibling axis:
WebElement credId = driver.findElement(By.xpath("//div[contains(text(),'CRED ID:')]"));
WebElement credIdValue = credId.findElement(By.xpath("following-sibling::div"));

Or, you can reach it in one go:
WebElement credIdValue = credId.findElement(By.xpath("//div[contains(text(),'CRED ID:')]/following-sibling::div"));


text:
Q: Instance class with "Global" settings Coming from a scripting background, I've started working with c# and .net. I've created a class that creates a text file notice that a process is complete. I instantiate this class in a console application and call the write process at the end.  What I'm trying to do is keep track through all my other classes when an error or warning has occurred, and reflect that event in the notice.
I've implemented this with public static bools, so that no matter what class is running, when a catch occurs, I can update a bool to true. I get the feeling though that this is wrong, and I don't know enough at this point to find what I should be doing.
Can anyone help?
Code example:
namespace Logging
{
public class Notice
{
    public static bool HasWarning { get; set; }
    public static bool HasError { get; set; }

    public string ProcessName {get; set;}

    public enum Status
    {
        [Description("Complete Success")]
        Complete_Success,
        [Description("Complete with Warnings")]
        Complete_With_Warnings,
        [Description("Error Incomplete")]
        Error_Incomplete
    }

    public void EndProcess(Status status)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append(string.Format("{0} is Complete!", ProcessName));
        sb.Append(Environment.NewLine);
        sb.Append(Environment.NewLine);
        sb.Append(string.Format("Completion Status: {0}", ToStringEnums(status)));
        sb.Append(Environment.NewLine);
        sb.Append(string.Format("Completion Time: {0}", DateTime.Now.ToString("MM/dd/yy H:mm:ss")));

        File.WriteAllText(string.Format(@"{0}\EndProcess.txt", Directory.GetCurrentDirectory()), sb.ToString());
    }

This is where I call it:
        private static void WriteNotice()
    {
        Notice newNotice = new Notice();
        newNotice.ProcessName = "NCOA";
        if (Notice.HasError == true)
            newNotice.EndProcess(Notice.Status.Error_Incomplete);
        else if (Notice.HasWarning == true)
            newNotice.EndProcess(Notice.Status.Complete_With_Warnings);
        else
            newNotice.EndProcess(Notice.Status.Complete_Success);

    }

A: I suggest using a Try Catch statement around your code and trace like following:
    try
        {
            //your code goes here

        }
        catch (Exception ex)
        {
            //write exception detail to output window using .Net Tracing Tools
            System.Diagnostics.Debug.WriteLine(ex.Message);
        }

for a more advanced logging mechanism i would recommend using NLOG as following:
    static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
    try
    {
    //your code
    }
    catch (Exception ex)
    {
    logger.Error(ex.Message + System.Reflection.MethodBase.GetCurrentMethod());
    }


text:
Q: NullPointerException from random index for populated array list? I am trying to pull a random string from an ArrayList. I make sure to populate it before pulling from it yet it still acts as if it empty. I even printed the list out after populating it and it is indeed populated, leaving me to believe the problem must be elsewhere in my code. Any ideas?
Oh, and yes, my code is hilarious. I'm creating a console game for fun about a gross dude who works in my office. (Might as well make practice fun, right?) Enjoy. :P
here is the object class
import java.util.ArrayList;
import java.util.Random;

public class Meg {

    private String name = "Meg";
    private int weight = 300;
    private int annoyanceLevel = 1000;

    static ArrayList<String> randomBoringTopics = new ArrayList<String>();

    public static void populateRandomBoringTopics(){
    randomBoringTopics.add("women's underwear");
    randomBoringTopics.add("men with backhair");
    randomBoringTopics.add("tucked in shirts");
    randomBoringTopics.add("shaving at one's desk");
    randomBoringTopics.add("pot bellies");
    }

    public void Fart(){
        System.out.println("Meg let's out a huge fart with zero consideration for who hears it");
    }

    public static void startBoringConversation(){
        Random randomGenerator = null;
        int index = randomGenerator.nextInt(randomBoringTopics.size());
        String randomBoringTopic = randomBoringTopics.get(index);
        System.out.println("Meg begins to talk to you about his thoughts regarding " + randomBoringTopic);
    }

    public void creep(){
    System.out.println("Meg suddenly appears behind you, breathing heavily and rubbing his stomach while fingering his belly button");
    }

    public void interject(){
    System.out.print("Meg hears you talking and butts into your conversation, making it instantly boring");
    }

    public void disappear(){
    System.out.print("Meg leaves his desk and is gone for an extended period of time, relieving those in his row but "
    + "tormenting the rest of the office");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public int getAnnoyanceLevel() {
        return annoyanceLevel;
    }

    public void setAnnoyanceLevel(int annoyanceLevel) {
        this.annoyanceLevel = annoyanceLevel;
    }

}

And here is my main...
public class Main {

    public static void main(String args[]){

        Meg.populateRandomBoringTopics();
        Meg.startBoringConversation();
    }
}

A: What you are doing here is guaranteed to throw a NPE:
public static void startBoringConversation(){
    Random randomGenerator = null;
    // randomGenerator can only be null at this location
    int index = randomGenerator.nextInt(randomBoringTopics.size());
    String randomBoringTopic = randomBoringTopics.get(index);
    System.out.println("Meg begins to talk to you about his thoughts regarding " + randomBoringTopic);
}

You need to actually create a Random object to get your random numbers from:
public static void startBoringConversation(){
    Random randomGenerator = new Random();
    int index = randomGenerator.nextInt(randomBoringTopics.size());
    String randomBoringTopic = randomBoringTopics.get(index);
    System.out.println("Meg begins to talk to you about his thoughts regarding " + randomBoringTopic);
}

A: Random randomGenerator = null;
int index = randomGenerator.nextInt(randomBoringTopics.size());

I sure don't know what else you were expecting to happen here...
(randomGenerator is null)
Just like for any other object, you have to instantiate it before you use it:
Random randomGenerator = new Random();
int index = randomGenerator.nextInt(randomBoringTopics.size());

A: Here is how you fix it.
    Random randomGenerator = new Random();

A: Strange program aside, think you have to instantiate Random...
Random randomGenerator = new Random();

versus what you have...
Random randomGenerator = null;


text:
Q: source(..., chdir=TRUE) does not seem to change the directory I'm pretty new to R and I'm trying to source a file which is again sourcing files. So I have a file, lets call it mother.R which contains a source call:
source ("grandmother.R")

mother.R and grandmother.R are in the same directory.
I would now like to source mother.R:
source ("C:/Users/whatever/R/mother.R", chdir=T)

My assumption was that the chdir=T would cause the source within the source to be looked for under C:/Users/whatever/R/, but it does not find grandmother.R when sourcing like this. Do I missunderstand chdir? Is there a way to do this without have to use absolute paths in mother.R?

A: Your understanding of how source works seems correct to me. But let's write an example so you can compare with your setup and maybe find where you went wrong.
Let the /Users/me/test/mother.R file contain the following:
print("I am the mother")
print(paste("The current dir is:", getwd()))
source("grandmother.R") # local path

and let the /Users/me/test/grandmother.R file contain the following:
print("I am the grandmother")

Where you start will help understand:
> getwd()
[1] "/Users/me"

This does not work:
> source("/Users/me/test/mother.R")
[1] "I am the mother"
[1] "The current dir is: /Users/me"
Error in file(filename, "r", encoding = encoding) :
  cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file 'grandmother.R': No such file or directory

because R is looking for grandmother.R in the getwd() dir...
Instead,
> source("/Users/me/test/mother.R", chdir = TRUE)
[1] "I am the mother"
[1] "The current dir is: /Users/me/test"
[1] "I am the grandmother"

works because source() temporarily changes the current directory to /Users/me/test/ where it can find grandmother.R.
When source gives you the handle back, you end up where you started, meaning the chdir is local to the source call like @CarlWitthoft pointed out.
> getwd()
[1] "/Users/me"


text:
Q: Angular4 http get parse error Request mydomain/request returns json string like "accepted" or "declined"
I would use request in angular to get this string :
  getStatus(jobOfferId): Promise<string> {
    const url = "someurl";

    return this.httpClientService.get(url)
      .toPromise()
      .then(response => response as string);
  }

This would work in angular 2, but I've just upgraded to angular 4 and this request returns an error instead
"Http failure during parsing for https://mydomain/request"

A: JSON is the default expected response type. You can try forcing using "text" instead and print the result just to understand what is happening:
httpClient.get('http://some.com/endpoint/', { responseType: 'text' }).subscribe(result => {
    console.log(result);
});


text:
Q: Openpyxl - Writing from dictionary to excel rows and columns So what im trying to do is writing to an existing excel-file from a dictionary:
wb = load_workbook(filename='test.xlsx')
ws2 = wb.get_sheet_by_name("Blad3")
tuple(ws2.iter_rows('A2:I1000'))
for i in ws2.iter_rows('A2:I1000'):
    print str(row[0].value)
    for i in Candidates:
        row[0].value = i['Start Location']
        row[1].value = i['Distance']
        row[2].value = i['End Location']
    for p in Potential_candidates:
        row[4].value = p['Start Location']
        row[5].value = p['Distance']
        row[6].value = p['End Location']
    for n in No_coords:
        row[8].value = No_coords
print 'Saving to file "test.xlsx"'
wb.save('test.xlsx')

the "print str(row[0].value)" get the correct value from the worksheet, but when i instead try to set the value it says:
TypeError: 'NoneType' object has no attribute 'getitem'.
The error occurs at row[0].value = i['Start Location']
Ive been trying to figure out why and either ive just missed the most obvious thing or im completely lost. Shouldnt you be able to write to the cell if you
can read from it?
So i figured out what was wrong with the NoneType error, apparently the list had a None element at [0].
So i added a function to remove such elements from all the lists and now i have a new error:
TypeError: 'tuple' object does not support item assignment

A: So i figured out what i did wrong, which was alot, first of, my code tried to fill each row with the entire dictionary instead of just the first element.
Secondly row[0]= didnt work because of... reasons. So i did a messy solution (but that works):
def write_excel():
wb = load_workbook(filename='test.xlsx')
ws = wb.get_sheet_by_name("Blad3")
count = 0
for row in ws.iter_rows('A2:I500'):
    x = str(row[0].coordinate)
    x1 = str(row[1].coordinate)
    x2 = str(row[2].coordinate)
    x3 = str(row[4].coordinate)
    x4 = str(row[5].coordinate)
    x5 = str(row[6].coordinate)
    x6 = str(row[8].coordinate)
    try:
        Start = Candidates[count]['Start Location']
        Dist = Candidates[count]['Distance']
        End = Candidates[count]['End Location']
        ws[x] = Start
        ws[x1] = Dist
        ws[x2] = End
    except IndexError:
        pass
    try:
        Pstart = Potential_candidates[count]['Start Location']
        Pdist = Potential_candidates[count]['Distance']
        Pend = Potential_candidates[count]['End Location']
        ws[x3] = Pstart
        ws[x4] = Pdist
        ws[x5] = Pend
    except IndexError:
        pass
    try:
        NoCoo = No_coords[count]
        ws[x6] = NoCoo
    except IndexError:
        pass
    count=count+1
print 'Saving to file "test.xlsx"'
wb.save('test.xlsx')

I know it can be cleaned up alot, but it helped me to understand what went poopoo so hopefully it might help someone else as well :)
Ill be cleaned up when i create a better codestructure for the whole program.


text:
Q: Allure gradle conflict using custom gradle wrapper At our firm we're supposed to user proprietary gradle wrapper and I think this issue is related to it.
This is the part of my build.gradle related to Allure:
 apply plugin: 'io.qameta.allure'

 buildscript {
    dependencies {
        ...
        classpath 'io.qameta.allure:allure-gradle:2.5'
    }
}

allure {
    autoconfigure = true
    version = '2.5.0'
}

And here is the error I get every time I'm trying to build project:

Unable to find method
  'org.gradle.api.tasks.TaskOutputs.files([Ljava/lang/Object;)Lorg/gradle/api/tasks/TaskOutputFilePropertyBuilder;'.
  Possible causes for this unexpected error include:
*
*Gradle's
  dependency cache may be corrupt (this sometimes occurs after a network
  connection timeout.) Re-download dependencies and sync project
  (requires network)
*The state of a Gradle build process
  (daemon) may be corrupt. Stopping all Gradle daemons may solve this
  problem. Stop Gradle build processes (requires restart)
*Your
  project may be using a third-party plugin which is not compatible with
  the other plugins in the project or the version of Gradle requested by
  the project.In the case of corrupt Gradle processes, you can
  also try closing the IDE and then killing all Java processes.

Is there any workaround for that?

A: I think the plugin resolution should be:
 buildscript {
     dependencies {
         classpath 'io.qameta.allure:allure-gradle:2.5'
     }
 }

 apply plugin: 'io.qameta.allure'

 // apply to project
 allure {
    autoconfigure = true
    version = '2.5.0'
 }


text:
Q: Removing header/footer/other elements from an HTML Object page? I am currently using the HTML Object element to embed a page within another page on my application by passing the link of the page I wish to embed to the object element's data property like so:
<object data="www.someurl.com"></object>

To make things clear, let's say I am passing the link of page A to an object element to embed page A within page B. What I am wondering is if there is any way to remove the header and footer of page A within the object element? It sort of looks repetitive because page B also holds the same header and footer, so I am wondering if it is possible to remove the header and footer from the object element.
If it helps, the application is using jQuery in case there is some solution there.


text:
Q: Show/Hide column in Power BI Table/Matrix visual Is there any possibility to show or hide the column in Table/Matrix visual in Power BI report by user dynamically?
For Example, I have a table view with columns COLUMN-1, COLUMN-2, COLUMN-3. Now I may have filter drop down to list all the column headers, so based on user selection (Multiple selections) Table view should get adjusted to show column values.
Since Power BI was developed based on Excel, curious to know if we are having Hide/Show column based on any condition or available in visual by default (Maybe by right-clicking on column header then show/hide it).

A: You can do this with the following workaround:

*

*Create your page with the table showing both columns.

*Create a bookmark, uncheck "Data"

*Duplicate the page and remove the column you want to conditionally hide. Set the page as hidden.

*Create a bookmark, uncheck "Data"

*Add a button to the first page pointing to the 2nd bookmark

*Add a button to the second page pointing to the 1st bookmark

*Ensure your slicers are synced

The end user experience is they will feel like they are conditionally hiding and unhiding the column.
A bit crap and a lot of extra work but I have it working well in my implementation.

A: Currently it is not possible to hide columns in visual based on slicer selection, there is an idea about this issue, please vote it up.
https://ideas.powerbi.com/forums/265200-power-bi-ideas/suggestions/19435267-conditional-visibility-of-a-visual-based-on-slicer
Thanks!

A: This is now available in Power BI with preview feature "Field Parameter". Check the May 2022 update.


text:
Q: question on struct with char array Below is my code snippet
struct encode
{

   char code[MAX];

}a[10];

int main()
{
char x[]={'3','0','2','5','9','3','1'};

  for(i=0;i<1;i++)
  {

      printf("%c",x[i]);

//This will printout like 3025931 now I want this to be stored in structure.
  }

strcpy(a[0].code,x);
// or
a[0].code=x;//neither works

display();

}

void display()
{
printf("%c",a[0].code);
}

I want the output to be like:3025931.
Which I am not getting due to incompatible assign type. Please tell me where am i going wrong.

A: I see two problems here. The first is that the source of the strcpy is a where it probably should be x.
The second is that x is not null-terminated. Strings in C are null-terminated character arrays.
I would change the two lines:
char x[] = {'3','0','2','5','9','3','1'};
strcpy(a[0].code, a);

to:
char x[] = {'3','0','2','5','9','3','1', '\0'};
strcpy(a[0].code, x);

Here's a complete program that gives you what you want (it actually prints out the number twice, once in your inner loop character by character and once with the printf so that you can see they're the same):
#include <stdio.h>
#include <string.h>
#define MAX 100
struct encode {
    char code[MAX];
} a[10];

int main() {
    int i, j;
    char x[] = {'3','0','2','5','9','3','1','\0'};

    for(i = 0; i < 1; i++) {
        for(j = 0; j < 7; j++) {
            printf("%c", x[j]);
        }
        printf("\n");

        strcpy(a[0].code, x);
    }
    printf("%s\n",a[0].code);
    return 0;
}

Update based on comment:

I am sorry. I am new to C. My apologies for not pasting the code snippet correctly in the beginning: "printf("%c",a[0].code);" doesn't display "3025931".

No, it won't. That's because a[0].code is a character array (string in this case) and you should be using "%s", not "%c". Changing the format specifier in the printf should fix that particular issue.

A: Here,
strcpy(a[0].code, a);
did you mean
strcpy(a[0].code, x);
...?
Also, x needs to be null terminated, or you need to replace strcpy with strncpy or memcpy and pass in a length.

A: This line doesn't make much sense:
   strcpy(a[0].code, a);

Perhaps you want this:
    memcpy(a[0].code, x, sizeof x);
    a[0].code[sizeof x] = '\0';

(The second line is necessary to nul-terminate code, making it a proper C string).

A: A lot of things are wrong in your program. The most offending line is this:
strcpy(a[0].code, a);

but there are other oddities as well, e.g.

*

*display is never called

*a is only assigned (kind of), but never read (except in display, which is never called)

*the i loop makes no sense

Basically, this program looks like copy-pasted by someone who has no clue.


text:
Q: Editing questions, not allowed to fix single char mistakes that kills the formatting and makes the question near unreadable, what gives?
Possible Duplicate:
We're discouraged from fixing typos and misspellings on SE sites?

I just tried to edit a question to fix a single char mistake that killed the formatting of the question and thus made it near unreadable, but i was not allowed, because "surely i could fix more than one char".
To me that seems pretty detrimental to the process. How can the system possibly have a clue what is needed to be fixed? Why would it force me to make more changes to allow me to correct the one big error that was needed?
To me the system seems broken.


text:
Q: how to display » in ajax.actionlink in an ajax.actionlink the first argument is the "text to display" which takes a string value, however I'd like to display a » (which displays a nice '>>') however ajax.actionlink is displaying a literal '& raquo;' how can I make it display the symbol?

A: You can directly use it, HTML helper will encode it automatically:-
@Ajax.ActionLink("« Previous","Test",new AjaxOptions
{
     OnSuccess = "Test"
})

@Ajax.ActionLink("Next »","Test",new AjaxOptions
{
     OnSuccess = "Test"
})

A: An » is U+00BB, so the C# escape is \u00BB.


text:
Q: Counting sundays appears in first day of month I wrote this code above to get number of sundays appears in first day of the month. I don't get a correct result and dont have idea why? any suggestion?
import java.util.Calendar;

    public class Test{
          public static void main(String args[]) {
            int counter = 0;
            Calendar c = Calendar.getInstance();

            for (int i = 1900; i<=2000; i++){
                for (int j = 0; j <=11; j++){
                    c.set(i, j, 1);
                    int day_of_week = c.get(Calendar.DAY_OF_WEEK);
                    if(day_of_week==1){
                        counter++;
                    }
                }
            }
            System.out.println(counter);
          }
    }

A: The 20th century includes years from 1901 to 2000. By amending your for-loop...
for (int i = 1901; i <= 2000; i++){

You will get 171 months.

In addition, using hard-coded values in code is generally a bad thing; look at some of PearsonArtPhoto's suggestions

A: First of all, there's several things to make the code clearer that could be done. But I suspect the crux of the question is that you should start from the year 1901, as that's technically the first day of the century. As far as code clean up, here's a few tips:

*

*Use variable names that mean something, like year and month.

*Use constants, instead of just enumerating the value (Calendar.DAY_OF_WEEK.SUNDAY)

Put everything together, and you've got:
public class Test{
      public static void main(String args[]) {
        int counter = 0;
        Calendar c = Calendar.getInstance();
        int Day_Of_Month=1; //This makes it easier in case you want to tweak the test, to say,

        for (int year = 1901; year<=2000; year++){
            for (int month = 0; month <12; month++){
                c.set(year, month, 1);
                int day_of_week = c.get(Calendar.DAY_OF_WEEK);
                if(day_of_week==Calendar.DAY_OF_WEEK.SUNDAY){
                    counter++;
                }
            }
        }
        System.out.println(counter);
      }
}


text:
Q: Как правильно закрыть поток ввода/вывода BufferedReader? Подскажите как правильно закрыть поток ввода/вывода BufferedReader
вот код:
BufferedReader reader;
    try {
        reader = new BufferedReader(new InputStreamReader(System.in));
    }
    catch (Exception e){
        e.getStackTrace();
    }
    finally {
        reader.close();
    }

так не работает, т.к. он может и не существовать
в каком месте правильно будет вставить код его закрытия или можно как-то проверить , что он существует?

A: try( BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)) ) {
    ...
catch (Exception e){
    e.getStackTrace();
}


text:
Q: TypeScript class declaration error with private variable If I have a TypeScript class declaration like this:
export class myClass {
  constructor(public aVariable: number) {}
  private aPrivateVariable: number;
}

and then try to initialize it with:
let someVar: myClass[] = [{
  aVariable: 3
}, {
  aVariable: 2
}];

I get an error (at least in VS Code) saying:
Property 'aPrivateVariable' is missing in type '{ aVariable: number; }'.
Why can't I do this?
Thanks.

A: Imagine your class also has a method that uses this field:
 export class myClass {
  constructor(public aVariable: number) {}
  private aPrivateVariable: number;
  test(){  }
 }

Now if you would do the following:
 const instance: myClass = {
    aVariable: 1,
    test() {
      alert.aPrivateVariable + 1);
    }
 };

 instance.test();

It would fail. Therefore, you also need to add private properties.
 let someVar: myClass[] = [{
  aVariable: 3,
  aPrivateVariable: 2,
 }, {
  aVariable: 2,
  aPrivateVariable: 3
 }];

A: Type { aVariable: number; } isn't compatible with myClass
As the manual states,

Private and protected members in a class affect their compatibility. When an instance of a class is checked for compatibility, if the target type contains a private member, then the source type must also contain a private member that originated from the same class. Likewise, the same applies for an instance with a protected member. This allows a class to be assignment compatible with its super class, but not with classes from a different inheritance hierarchy which otherwise have the same shape.

If myClass is supposed to be used as interface to assign plain objects that are structurally compatible with myClass class, separate interface should be provided:
interface IMyClass {
  aVariable: number;
}

export class myClass implements IMyClass {...}

let someVar: IMyClass[] = [{
  aVariable: 3
}];

and then try to initialize it

It should be noticed that the code above doesn't initialize the class. It's unclear what were the reasons to assign plain objects instead of class instances, but if someVar should contain instances of myClass, type error indicates the problem. Instances should be explicitly instantiated with new:
let someVar: myClass[] = [new myClass(3)];

A: Defining the objects in the way you did ({ aVariable: 2}) does not instantiate them as myClass objects. This is a problem since aPrivateVariable is not being instantiated because myClass constructor is never called and the object you add does not match what myClass contains.
As this excerpt from the typescript handbook on type compatibility states:

Private and protected members in a class affect their compatibility. When an instance of a class is checked for compatibility, if the target type contains a private member, then the source type must also contain a private member that originated from the same class. Likewise, the same applies for an instance with a protected member. This allows a class to be assignment compatible with its super class, but not with classes from a different inheritance hierarchy which otherwise have the same shape.

One way to deal with this is to instantiate every object using something such as map()

const someVar: myClass[] = [2,3,1].map(num => myClass(num)) ;

Or, if you're confident of the shape of the object, you can use type coercion:

let someVar: myClass[] = [] as myClass[]

Be careful with this approach though since it does not guarantee that what's contained in the array matches the model of the class.

A: export class myClass {
   constructor(public aVariable: number) {}
   private aPrivateVariable: number;
}

The correct way would be really initializing your class like this:
const someVar: myClass[] = [
    new myClass(3),
    new myClass(2),
]

If you don't initialize your class then you want to get any methods from myClass, you will end up with object cast as myClass.

A: You forgot to declare the class. You can do it like this
const someVar: myClass[] = [new myClass(3), new myClass(2)];

A: Correct way to initialize this class is -
export class myClass {
  constructor(public aVariable: number) {}
  private aPrivateVariable: number;
}

let someVar: myClass = new myClass(3);


text:
Q: Using \label within a figure float
Possible Duplicate:
Where to put the \label on a figure environment?

My question is rather simple. I have noticed that when I use \label like this
\begin{figure}[h]
\centering
\includegraphics[width=0.5\textwidth]{Leslie_Lamport}
\label{fig:LL}
\caption{Leslie Lamport}
\end{figure}

and then refer to this label it refers rather to the section number than to the figure (I've seen it been refered as section.figurenumber but that was due to a package I believe - possibly hyperref). But when using it after the caption
\begin{figure}[h]
\centering
\includegraphics[width=0.5\textwidth]{Leslie_Lamport}
\caption{Leslie Lamport}
\label{fig:LL}
\end{figure}

it really refers to the figure number.
Can someone explain the mechanic behind \label to me?

A: Use the \label{fig:LL} inside the \caption{} tag.
\begin{figure}[h]
\centering
\includegraphics[width=0.5\textwidth]{Leslie_Lamport}
\caption{Leslie Lamport\label{fig:LL}}
\end{figure}


text:
Q: Browser going in a loop while using the 301 redirection I am using WordPress and I have to redirect the some URLs like
https://test.com/demo to https://test.com/demo/a/b/c/
https://test.com/example to https://test.com/example/a/b
https://test.com/xyz to https://test.com/xyz/a/b/c/d/

https://test.com/xyz/a/ to https://test.com/pqr/

I tried the below 301 code but it's not working, My browser is going in a loop, and the URL showing multiple times.
Redirect 301 http://test.com/demo http://test.com/demo/a/b/c/
Redirect 301 http://test.com/example http://test.com/example/a/b
Redirect 301 https://test.com/xyz https://test.com/xyz/a/b/c/d/
Redirect 301 https://test.com/xyz/a/ https://test.com/pqr/

.htaccess code
# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

RewriteRule ^demo$ /demo/a/b/c/ [R=301,L
RewriteRule ^example$ /example/a/b/c/ [R=301,L]

</IfModule>
# END WordPress

A: The directives you've posted won't do anything since the Redirect directive takes a root-relative URL-path as the source URL, not an absolute URL (with scheme + hostname). You may be seeing the result of a cached redirect (301 - permanent - redirects are cached persistently by the browser. Test first with 302s to avoid caching issues.)
However, the Redirect directive is not the correct tool for the job, for a couple of reasons:

*

*The mod_alias Redirect directive is prefix-matching, so matches anything that starts with the stated URL-path. (So, in your example, the first three redirects would indeed result in a redirect-loop and the 4th would never be processed.)

*You should avoid mixing mod_rewrite (part of the WordPress code block) and mod_alias in the same context since you can get unexpected conflicts. mod_rewrite always executes first, despite the apparent order of the directives.
Try the following instead, using mod_rewrite, at the top of your .htaccess file. Before the # BEGIN WordPress code block.
RewriteRule ^demo$ /demo/a/b/c/ [R=301,L]
RewriteRule ^example$ /example/a/b/c/ [R=301,L]
RewriteRule ^xyz$ /xyz/a/b/c/ [R=301,L]
RewriteRule ^xyz/a/$ /pqr/ [R=301,L]

NB: There is no slash prefix on the URL-path matched by the RewriteRule pattern.


text:
Q: Change amchart bullet placement using inputs Say I have an amchart lineWithScrollAndZoom graph.  I want to allow a user to change a bullet point location on the y-axis by letting them click the bullet point, then they can use a dropdown input or some other input form to allow them to change the y-axis value.  The bullet point and corresponding lines would then change based on where the bullet point was moved.
Is this even possible?


text:
Q: Can we insert Unicode Characters using Robot Class in Java? I am developing a Real time English-Sinhala Unicode translator in java.I did the translation part.But now I want to add the Final output Unicode characters to the currently active window (like a web browser).There's a way to add characters via java Robot class with
 Robot.keyPress(//keyInput) method.But is there any way to do this with java Unicode characters like u0200 hex value.If it can't be done with this way what solutions I have to resolve this.Please anyone help me ?

A: Yes, you can simulate key presses using Robot, as suggested here. No, Robot can't see what's printed on the user's key caps. You're probably going to have to develop a virtual keyboard. When available, Unicode glyphs make usable button labels, as shown here.
Addendum: Note that a KeyEvent represents a keystroke, while Unicode encodes graphemes represented by glyphs. The mapping depends on the keyboard layout, e.g. Sinhala.


text:
Q: Help building a scheme (involves L293D H-bridge) I'm making a bluetooth-controlled fire truck for my son based on an old wire-controlled truck I bought at a yard sale. It didn't have its wire-remote.
I already got Arduino Nano to drive 2 motors using a L293D (wheels forwards-backwards, steering left-right). It is being controlled from my phone via HC-05. Works like a charm.
Here's my problem. There are three wires sticking out that control the truck's siren and water pump. By using a battery pack, I tested different combinations and found two that make the truck do what I want. When I connect battery '+' to purple and '-' to black wire, siren sounds. When I connect battery '+' to purple and '-' to orange wire, water pump works.
My question is, how do I control (switch on and off) these two functions using another L293D? See attached picture. I need to understand which of Outputs 1,2,3,4 should be connected to Purple, Black and Orange and enabled for it to work.
Appreciate your help! It was far easier with the two motors :)

A: You do not need a full H bridge, just a couple of relays.
You can connect the purple wire to your positive power supply, while the other two wires should be connected to the negative via two separate relays. To hook a relay to an arduino just search the web, there literally are dozen of tutorials.
If for some reason you want to use the H bridge you can proceed as follows:
Hook the purple wire to your positive power supply, then power the L293D as usual. As Vcc you do not need a stiff power supply, as if you were powering the motors, you just need the digital Vcc.
Enable 1 and 2 drivers connecting pin 1 to Vcc, then hook the black and orange wires to the outputs (1 and 2). Now you can control your alarm and water pump via in1 and in2, please note that the device will turn on when the input is low, i.e. a digital zero.
When you turn off the devices there is a sim chance of damage since you are putting Vcc on a terminal that is probably meant for ground or high impedance. If you are concerned about this problem please add a protection diode in series, pointing towards the L293D.
See the schematic:

simulate this circuit – Schematic created using CircuitLab
Please note that I connected pin9 to gnd to disable the 3 and 4 drivers.

A: It is not practical to control non-motor devices (example:siren & pump) using H-bridge IC. For simpler solution, you can use a simple transistor circuit that work as a switch.
But if for a specific reason you want to control the non-motor devices using H-bridge, you can use this circuit:

Note:

*

*original picture from here

*siren = motor 1 (forward/backward), pump = motor 2 (left/right)

*Diode: 1N4001/1N4002, maximum load 600 mA for L293D

With this circuit:

*

*Forward: siren ON, backward: siren OFF.

*Left: Pump ON, right: Pump OFF (or vice versa).


text:
Q: Can not find the methods at different Paypal Rest API classes I have downloaded Paypal-Java-SDK-Master and built it with the Gradle plugin in Eclipse. I made a jar-archive of the classes and included it in my project. And I copied some code from somewhere. Below is an extract:
The problem is that the methods called on the Amount, Payer and all the other classes do not exist. Inspection of the java-files confirms this. Have I downloaded and installed the wrong archive or is the example to old?
Is there someone that can give me some help?
import java.util.ArrayList;
import java.util.List;

import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Payer;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.RedirectUrls;
import com.paypal.api.payments.Transaction;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;

public class JavaSampleOne {
    String clientId = "some id I not want to share";
    String clientSecret = "some id I not want to share";

public static void main(String[] args) {
    Amount amount = new Amount();
    amount.setCurrency("USD");
    amount.setTotal("1.00");

    Transaction transaction = new Transaction();
    transaction.setAmount(amount);
    List<Transaction> transactions = new ArrayList<Transaction>();
    transactions.add(transaction);

    Payer payer = new Payer();
    payer.setPaymentMethod("paypal");

I changed to implementation in the gradle.build file. When I refreshed the project I got this error:Errormessage
This is my file structure: Filestructure
This is how it looks like in Eclipse navigator: Eclipse navigator projects
I choosed Wrapper when I imported the project.

A: delete (or move) the local jar and add this to your build.gradle:
repositories {
    mavenCentral()
}

dependencies {

     // paypal-core should be automatically fetched
     // implementation "com.paypal.sdk:paypal-core:1.7.2"

     // that's the one you actually may need
     implementation "com.paypal.sdk:rest-api-sdk:1.14.0"
}

then synchronize the Gradle project, in order to fetch the dependencies.
there are some more artifacts available for com.paypal.sdk.


text:
Q: CQ5.6.1- Log4j in Osgi bundle not detecting I am using a jar file given by my client in CQ5.6.1. Some classes in the jar file requires log4j. So I created a Osgi bundle having the client jar and log4j jar files using Eclipse. I installed this into the Osgi Bundles of CQ and activated the bundle. The class from the client jar is correctly invoked from my components jsp, but the client jar is not able to locate the log4j classes. I am getting the error java.lang.ClassNotFoundException: org.apache.log4j.PropertyConfigurator not found. I also tried putting the log4j jar into the install folder under my app\ in CQ, but that also didn't help. I searched in google but couldn't find a suitable solution yet. Any help to resolve is highly appreciated. Thank you.

A: Your log4j bundle needs to export the org.apache.log4j package, and the client bundle needs to import it. Sling scripts see all exported packages.
You can use the OSGi console at /system/console/bundles to verify that those exports and imports are correct, the client bundle's status page should show that it imports the package from the log4j bundle.
If the exports are correct, the cause might also be some log4j or client code loading the PropertyConfigurator using a thread context class loader (TCCL) or another mechanism that does not play well with OSGi. If it's TCCL you can work around the issues by setting that TCCL yourself around code that loads the PropertyConfigurator.
CQ does provide the slf4j logging APIs out of the box, so if you can convince your client to switch to those that's probably easier.


text:
Q: how can i create automatic file backup to save to cloud storage? I have 4 workstations (windows) that I need to backup and save to gloud storage, I would like it to be automatically. it is possible?

A: You can imagine to set up, on each workstation a planned task that performs a gcloud rsync regularly in dedicated folder on Google Cloud Storage (and that get the correct folder from the local workstation)


text:
Q: sonata_type_date_picker somehow makes -1 day after saving entity Did someone experience this? I have date in datepicker.
https://monosnap.com/file/MfiUeANHvBjQjypTfW3jZqBbxKKCRU
After saving: https://monosnap.com/file/9nLR0yRYfccCVoGcRHkR1KST1zIUMJ
And everytime like this!
edit: Guys, somehow problem was related to php version. I had 7.0, now 7.1
The thing is... Default format for datepicker changed in php7.1 version and it was incorrect, so I changed option 'format' => 'dd.MM.yyyy' and now everything is fine, but! What does php version to do with this thing? How can it change default datepicker format? Can somebody explain this? Did anyone experience this type of problem?


text:
Q: How to access a protected json array in php I am using the facebook sdk for php. And it is returning a protected json array which I cannot use. Can There Be Another Way of using the protected array.

This is My Code:
<?php
  require 'phpInsight-master/autoload.php';
  require_once 'autoload.php';

  use Facebook\FacebookSession;
  use Facebook\FacebookRedirectLoginHelper;
  use Facebook\FacebookRequest;
  use Facebook\FacebookResponse;
  use Facebook\FacebookSDKException;
  use Facebook\FacebookRequestException;
  use Facebook\FacebookAuthorizationException;
  use Facebook\GraphObject;
  use Facebook\Entities\AccessToken;
  use Facebook\HttpClients\FacebookCurlHttpClient;
  use Facebook\HttpClients\FacebookHttpable;

  $sentiment = new PHPInsight\Sentiment();

  FacebookSession::setDefaultApplication('APP ID', 'APP SECRET');

  /*$helper = new FacebookRedirectLoginHelper('http://123.63.13.117/');
  try
  {
    $session = $helper->getSessionFromRedirect();
  }
  catch(FacebookRequestException $e)
  {
    echo 'Failure: ' . $e->getMessage();
  }
  catch(Exception $e)
  {
    echo 'Failure: ' . $e->getMessage();
  }
  */
  $raw_id = $_GET['id'];
  $id = '/' . $raw_id;
  echo $id;
  $session = new FacebookSession('ACCESS TOKEN');

  if(isset($session))
  {
    $request = new FacebookRequest($session, 'GET', '/me');
    $response = $request->execute();

    $graphObj = $response = $response->getGraphObject();

    echo '
';
     var_dump($graphObj);
    echo '
';
    $bio = $graphObj->backingData->bio;
    $sentu = $sentiment->categorise($bio);
  }
  else
  {
    echo 'getLoginUrl() . '"> Login: ';
  }
?>

And On the line of $bio it shows :
Fatal error: Cannot access protected property Facebook\GraphObject::$backingData
in C:\xampp\htdocs\facebook\facebook-php-sdk-v4-4.0-dev\facebook.php on line 50

A: The property you're try to access $backingData is protected, which means you can't access it directly. To get it change your code from:
$bio = $graphObj->backingData->bio;

to:
$bio = $graphObj->getProperty('bio');
// Or, if you need the whole array:
$data = $graphObj->asArray()
$bio = $data['bio'];

It might be a good idea to read up on property visibility in objects.


text:
Q: Adding animation delay does not change effects Here is a simple slider and I have added animation: slide 0.5s forwards; animation-delay: 2s; to buttons but it doesn't change anything. My goal is to make transition effects on images, to show next image slowly from right side to left. And when showing back image from left side to right slowly. I hope you understand what I mean. But it doesn't change anything. https://jsfiddle.net/9t3cbese/7/
js:
var imageCount = 1;
var total = 10;

function photo(x) {
    var image = document.getElementById('image');
    imageCount = imageCount + x;
    if(imageCount > total){imageCount = 1;}
    if(imageCount < 1){imageCount = total;}
    image.src = "http://buhehe.de/wp-content/uploads/2018/02/"+ imageCount +".jpg";
    clearInterval(time);
    time =  window.setInterval(function photoA() {
    var image = document.getElementById('image');
    imageCount = imageCount + 1;
    if(imageCount > total){imageCount = 1;}
    if(imageCount < 1){imageCount = total;}
    image.src = "http://buhehe.de/wp-content/uploads/2018/02/"+ imageCount +".jpg";
    },1000);
    }
 var time = window.setInterval(function photoA() {
    var image = document.getElementById('image');
    imageCount = imageCount + 1;
    if(imageCount > total){imageCount = 1;}
    if(imageCount < 1){imageCount = total;}
    image.src = "http://buhehe.de/wp-content/uploads/2018/02/"+ imageCount +".jpg";
    },2500);

CSS
@media only screen and (max-width: 600px) {
   #image{
        width: 400px !important;
height:300px !important;
    }
  #slider {
        width: 400px !important;
height:300px !important;
    }
}
 @media only screen and (max-width: 500px) {
   #image{
        width: 300px !important;
height:200px !important;
    }
  #slider {
        width: 300px !important;
height:200px !important;
    }
}
#slider {
    width: 500px;
    height: 400px;
    margin-left: 3px;
 margin-top: 7px;
margin-bottom: 7px;
     padding: 10px;
    position: relative;
    background: #eceded;

    border-radius: 7px;
    }
#image {
    width: 500px;
        height: 400px;
    }

.left {
    height:50px;
    width:50px;
    position:absolute;
    top:80%;
    transform: translateY(-50%);
    left:15px;
    opacity:1;
    animation: slide 0.5s forwards;
    animation-delay: 2s;
  }
  .right {
    height:50px;
    width:50px;
    position:absolute;
    top:80%;
    transform: translateY(-50%);
    right:15px;
    opacity:1;
    animation: slide 0.5s forwards;
    animation-delay: 2s;;
  }
.right:hover ,  .left:hover {
    opacity:0.6; cursor: pointer;
    }


text:
Q: Connecting to a remote database in Informix We have Informix database setup in 2 environments.
TEST
host1:1528/d7main:INFORMIXSERVER=m7uatserver

PROD
host2:1528/d7main:INFORMIXSERVER=m7server

I tried to run a query on customer table in PROD connecting from UAT.
select  * from d7main@m7server:customer where active = 'Y';

I get below error.
Attempt to connect to database server (m7server, conerr=-931, oserr=0) failed.
[SQL State=08004, DB Errorcode=-908]

Is there something wrong with the way the query is written? Or does the DBA need to setup something else for this connection to happen?
The syntax seems correct based on
Access remote tables in the IBM Informix 12.10 Manual.

A: The output from finderr -908 is:

-908  Attempt to connect to database server (servername) failed.
The program or application is trying to access another database server
  but has failed. Note the server name in the current statement.
The desired database server is unavailable, or the network is down or
  is congested. Ask your DBA and system administrator to verify that the
  server and network are operational. If the network is congested, use
  the environment variables INFORMIXCONTIME and INFORMIXCONRETRY to tune
  connection timing. For information on setting these environment variables,
  see the IBM Informix Guide to SQL: Reference.
This message appears in Version 6.0 and later versions.

Similarly, for error -931, the message means:

-931  Cannot locate servicename service/tcp service in /etc/services.
The service servicename is not listed in the network configuration file
  /etc/services (UNIX) or \etc\services (DOS). Check the
  $INFORMIXDIR/etc/sqlhosts file, and check that the service name for the
  desired server is correct. If so, contact your network administrator to
  find out why the service is not known. If you are using IBM Informix OnLine
  for NetWare, check the \etc\services file on the client for the
  required entries.

There are some quaintly archaic references there — OnLine for Netware is ancient history, as is version 6.00.  However, the basic gist is similar.
It would seem that there are network setup issues on one or both machines.
AFAICS, you have the test and production servers on the same machine.  Do they use a single INFORMIXDIR or does each have its own separate INFORMIXDIR?  (Both are possible; neither is wrong.)  Do they share the INFORMIXSQLHOSTS file?

*

*… Scratch that: you say host1 and host2 — two different machines, therefore, of necessity, each has its own INFORMIXDIR.

My guess from the -931 message is that they do not share the INFORMIXSQLHOSTS file (which in turn probably means each has its own INFORMIXDIR), and that the information in each file does not include the other server.
Make sure that if they are not using the same INFORMIXSQLHOSTS file (that is, the file $INFORMIXDIR/etc/sqlhosts by default, unless overridden by the $INFORMIXSQLHOSTS environment variable), that the information in the files is equivalent — or, at least, that each includes the entry for the other.

*

*… Are you on Windows or a Unix-based system?

*… Which version of Informix are you using?  (Running dbaccess -version or onstat -version should tell you if you don't know anyway.)

*… Is each host aware of the other — does the /etc/hosts file or its networking equivalent contain the relevant information so that each machine knows how to connect to the other?

If they're in the same INFORMIXDIR and using the same INFORMIXSQLHOSTS file, then come back and we'll think again.


text:
Q: Summing edges properties for order by in select statement I'm trying to do a select statement to order the result set by force of connections between them.
CREATE CLASS Entity EXTENDS V;
CREATE CLASS isConnectedTo EXTENDS E;

CREATE PROPERTY isConnectedTo.strength INTEGER;

'isConnectedTo' edges relate Entities to another Entities
The tricky part is I have double connections between the same entities as so:
CREATE VERTEX Entity SET name = "John";
CREATE VERTEX Entity SET name = "Mike";
CREATE VERTEX Entity SET name = "Susan";

CREATE EDGE isConnectedTo FROM (SELECT FROM Entity WHERE name = "Mike") TO (SELECT FROM Entity WHERE name = "John") SET strength = 3;
CREATE EDGE isConnectedTo FROM (SELECT FROM Entity WHERE name = "Mike") TO (SELECT FROM Entity WHERE name = "Susan") SET strength = 4;
CREATE EDGE isConnectedTo FROM (SELECT FROM Entity WHERE name = "John") TO (SELECT FROM Entity WHERE name = "Mike") SET strength = 2;

So Mike is connected to John which is connected to him too. Also Mike is connected to Susan.
In this case if I were to run my desired query on Mike it should return:

*

*John

*Susan
by this order because the sum of strength between Mike and John is 3 + 2 = 5 and between Mike and Susan is only 4.
I've iterated through many possible queries to no avail but I can't seem to figure why this last one refuses to work.
LET $main = SELECT FROM Entity WHERE name = "John";
LET $vset = SELECT expand(in('isConnectedTo')) FROM $main;
SELECT @rid, eval('$ei.strength + $eo.strength') as total_strength FROM $vset
   LET $ei = (SELECT expand(inE('isConnectedTo')) FROM $current WHERE $main.@rid IN out),
   LET $eo = (SELECT expand(outE('isConnectedTo')) FROM $current WHERE $main.@rid IN in)
ORDER BY total_strength DESC;

Note: I already got the Entities' names indexed with a hash dictionary and the 'isConnectedTo' edges are indexed with unique links between Entities (hence they cannot be repeated in the same direction)
All the other trials I did or help from the other answers here result in query times of >= 2 mins.

A: I'd like to propose a small change on your domain. Don't create 2 edges in case both people are connected, but use the same edge with 2 properties.
CREATE CLASS Entity EXTENDS V;
CREATE CLASS isConnectedTo EXTENDS E;
CREATE PROPERTY isConnectedTo.strengthOut INTEGER;
CREATE PROPERTY isConnectedTo.strengthIn INTEGER;

CREATE VERTEX Entity SET name = "John";
CREATE VERTEX Entity SET name = "Mike";
CREATE VERTEX Entity SET name = "Susan";

CREATE EDGE isConnectedTo FROM (SELECT FROM Entity WHERE name = "Mike") TO (SELECT FROM Entity WHERE name = "John") SET strengthOut = 3, strengthIn = 2;
CREATE EDGE isConnectedTo FROM (SELECT FROM Entity WHERE name = "Mike") TO (SELECT FROM Entity WHERE name = "Susan") SET strengthOut = 4;

In this was you have less edges and you can use this super fast query:
SELECT out.name as name1, in.name as name2, eval('strengthOut + strengthIn') as strength
FROM (
  SELECT expand( bothE('isConnectedTo') ) FROM Entity WHERE name = "Mike"
) ORDER BY strength

NOTE: Remember to create an index on Entity.name to speedup the inner query.

A: Try this query
select expand(rid) from (select @rid,sum($a[0].sum,$b[0].sum) as sum from Entity
let $a= (select sum(strength) as sum from isConnectedTo where in.name="Mike" and out.name=$parent.current.name),
$b= (select sum(strength) as sum from isConnectedTo where out.name="Mike" and in.name=$parent.current.name)
where name<>"Mike" order by sum desc)

A: Try this query:
select expand($a.rid) from (select from Entity where name="Mike")
let $a=(select @rid,sum(bothE().strength) as sum from Entity where both('isConnectedTo').name contains $parent.current.name group by name order by sum desc)


text:
Q: Как в конструктор поместить переменную enum У меня есть 2 переменные enum, которые обозначают пол человека.
public enum Gender {
    MAN("Мужчина"),
    WOMAN("Женщина");
    private String translation;

    Gender(String translation){
        this.translation = translation;

    }

    public String getGender(){
        return translation;

    }

}

И я хочу что бы пользователь выбирал какого пола создавать объект класса Person. Например ему выведется на консоль вопрос-"выберите пол человека 1-Муж, 2-Жен".
Он нажимает 1 и в конструктор объекта класса Person вставляется объект MAN.
public static void main(String[] args){

    Gender gen =  Gender.MAN;

    Person person1 = new Person(gen);
    ArrayList <Person> people = new ArrayList<>();
    people.add(person1);
    //вывод

}

public class Person {
    private  Gender gen;

    public Person ( Gender gen){
        this.gen = gen;
    }
}

A: Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
Person person1;
if (input == 1) {
     person1 = new Person(Gender.MAN);
} else {
    person1 = new Person(Gender.WOMAN);
}
ArrayList <Person> people = new ArrayList<>();
people.add(person1);


text:
Q: WebRequest Header Assistance I'm trying to post some XML to a an exposed service. I'm using System.Net.WebRequest to post the required info, and using Fiddler I can see that the result of my post is as follows:
 POST http://x.x.x.x:5010/FindReservationByRoom HTTP/1.1
 Content-Type: text/xml
 Transaction: 1
 Host: x.x.x.x:5010
 Content-Length: 29
 Expect: 100-continue

 <Room>103</Room>

Unfortunately the above does not appear to work. The instructions for communicating with this service indicate that the first line should actually read:
POST FindReservationByRoom HTTP/1.1

But WebRequest seems to be appending the entire URI to this first line. I'm not an HTTP guru so I'm not certain what I could be doing wrong here. Any suggestions would be much appreciated.
EDIT:
The error message returned from the call is:
 Unknown command verb '<Room>103</Room>POST'

EDIT:
The code I'm using to make the call is:
 System.Net.WebRequest req = System.Net.WebRequest.Create("http://x.x.x.x:5010/FindReservationByRoom");
        req.Headers.Clear();

        req.ContentType = "text/xml";
        req.Method = "POST";

        StringBuilder xml = new StringBuilder();
        xml.Append("<Room>103</Room>");

        byte[] bytes = System.Text.Encoding.ASCII.GetBytes(xml.ToString());

        StringBuilder header = new StringBuilder();
        req.Headers.Add("Transaction: 1");

        req.ContentLength = bytes.Length;
        Stream os = req.GetRequestStream();
        os.Write(bytes, 0, bytes.Length);

        System.Net.WebResponse resp = req.GetResponse();
        if (resp != null)
        {
            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
            string responsecontent = sr.ReadToEnd().Trim();
        }

A: As far as i know the status error : Unknown command verb is not a known http response.
You're treating this problem as if the http request is malformed but i'm getting the feeling there is no http layer problem.
Do you have the source code of this service you are trying to reach or is it a third party component?
I'm guessing they expect something more then just plain xml, maybe the service is scanning your xml for a command verb.


text:
Q: Firebase Android getting a child value of a child value I am using Google Firebase to back an Android Application which has parties that include guest list.
I have my data structured to have the users have a child node with the party unique key and true/false, then the parties have a child node with user unique keys and true/false to show the relations.
users:
    [unique userKey]
        userName: coffeeAddict
        parties:
            [unique partyKey]: true
            [unique partyKey]: false
parties:
    [unique partyKey]:
        partyName: Karen's 50th
        guests:
            [unique userKey]: true
            [unique userKey]: false

I followed what Firebase documentation shows as best practices, but my issue is I am trying to perform a query to get all the keys of the User's parties that are true.
I have been able to query the database to get particular users and parties based on having a value like a username be equal to a set value.
The last query I tried which returns null is
DatabaseReference database = FirebaseDatabase.getInstance().getReference(Constants.PARTIES);
Query userParty = database.orderByChild("guests/"+ userID).equalTo(true);

The main issue is I do not know how to check both sides are true and have a query based on that information. The goal is to create a list of a user's events based on their true/false status. Any help or guidance is greatly appreciated.

A: I make here the assumption that you know which party you are querying for guests. Try this :
final List<String> attendees = new ArrayList<>();
Query userParty = database.child(uniquePartyId).child("guests").orderByKey().equalTo(true);
userParty.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        String userKey = dataSnapshot.getRef().toString();
        attendees.add(userKey);
    }
    ...
}

or
final List<String> attendees = new ArrayList<>();
Query userParty = database.child(uniquePartyId).child("guests").orderByKey();
userParty.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        String userKey = dataSnapshot.getRef().toString();
        Boolean attendParty = (Boolean) dataSnapshot.getValue();
        if (attendParty) {
            attendees.add(userKey);
        }
    }
    ...
}


text:
Q: SQL Query - Match 1 to 1 in the list provided I have two tables (Table1 and Table2) such as this:
Table1:
id | X
1  | 12345
2  | 67890

Table2:
id | Y
1  | 'John Doe'
2  | 'John Doe'
2  | 'Jane Doe'

I want to produce a query such that the end result to be:
id | X     | Y
1  | 12345 | 'John Doe'
2  | 67890 | 'Jane Doe'

But with my query below, the output is as follows as it is matching T1.X IN ('12345', '67890')  with all the possible values in T2.Y IN ('John Doe', 'Jane Doe'):
id | X     | Y
1  | 12345 | 'John Doe'
1  | 67890 | 'John Doe'
2  | 67890 | 'Jane Doe'

This was the query:
SELECT *
FROM Table1 T1
INNER JOIN Table2 T2
ON T1.id=T2.id
WHERE T1.X IN ('12345', '67890')
AND T2.Y IN ('John Doe', 'Jane Doe')

What should the query be such that the result is first ('12345') in the list match with first ('John Doe') only, second ('67890') in the list match with second ('Jane Doe') only without me having to write out individual queries?

A: If you want specific pairs you can group your conditions in WHERE, use brackets to specify the order and grouping.
Here we want either 1 and 2 are true, which is the first line in your query or 3 and 4 are true which is the third line and we dont want to get 3 and 2 are true.
SELECT *
FROM Table1 T1
INNER JOIN Table2 T2
ON T1.id=T2.id
WHERE (T1.X = '12345' AND T2.Y = ('John Doe')
OR (T1.X ='67890' AND T2.Y = ('Jane Doe') ;

If you only want one value per id and you don't mind which you can use MIN or MAX. In this case we will use MIN because your want 'Jane Doe' in preference to 'John Doe'
SELECT T1.id, MIN(T1.X), MIN(T1.Y)
FROM Table1 T1
INNER JOIN Table2 T2
ON T1.id=T2.id
WHERE T1.X IN ('12345', '67890')
AND T2.Y IN ('John Doe', 'Jane Doe')
GROUP BY T1.id;


text:
Q: Is there an adjective meaning "dog like"? Feline is an adjective meaning "cat like". Then is there an adjective meaning "dog like"?

A: "Canine", or if you want to be infuriatingly erudite, you could use the noun "canid" in a metaphorical sense.

A: Canine.
http://www.merriam-webster.com/dictionary/canine
canine adj
1: of or resembling that of a dog
2: of or relating to dogs or to the family (Canidae) including the canids


text:
Q: Ember.js Why is an itemcontroller needed with Ember.Select option value After a lot of fiddling I realized that I needed to specify an itemcontroller in my ArrayController 'Markets'. It was needed to get access to a computed property in the ObjectController 'Market'.
My question is, why is this needed? Because the ObjectController is in my perception linked to the corresponding ArrayController?
I setup the controller in the application Route
// routes/application.js
model: function() {
    this.controllerFor('markets').set('model', this.store.find('market'));
}

The Ember.Select in a .hbs file
// views/article/someViewForARoute.hbs
{{view Ember.Select contentBinding="controller.controllers.markets"
optionLabelPath="content.nameWithTime" optionValuePath="content.id"}}

The Market ObjectController
// controllers/market.js
nameWithTime: function() {
    return this.get('name') + ' (' + this.get('time') + ')';
}.property('name', 'time')

The Markets ArrayController
// controllers/markets.js
itemController: 'market' // Why needed?

This question is only asking the reason why specifying itemcontroller this way is needed in Ember.js. Thanks for any clearification!

A:
the ObjectController is in my perception linked to the corresponding ArrayController?

In no way this is done, and such a behaviour isn't documented anywhere.
No ArrayController will have an itemController linked by default, The default value for itemController of an ArrayController is null Refer here.
If you don't want the computed property inside the marketController, better you can have that property in the marketModel.


text:
Q: Unsupported method Distinct in linq using the Mongodb driver I need to get the count of the distinct values in a select using the mongodb driver and linq. I made a groupby and then I'm trying to make the distinct but I'm always getting "unsupported method". How can I avoid it? I have no problems when I'm making other operations like average or sum. Is the problem that i'm making a select into another select?
queryGroupby = whereQuery.GroupBy(x => x.CheckinDate.ToString("yyyy MMM"));

var querySelect = queryGroupby
                  .Select(g => new Statistic()
                   {
                    HotelsCount = g.Select(g => g.HoId).Distinct().Count(),
                    Key = g.Key,
                    TotalBookingsAmount = g.Sum(g => g.GrossTotal) + g.Sum(g => g.Taxes),
                    BookingsCount = g.Count(g => true),
                    TotalBookedDays = g.Sum(g => g.StayDays),
                    AvgWindowStay = g.Average(g => g.StayDays),
                    AvgBookingsAmount = g.Average(g => g.GrossTotal) + g.Average(g => g.Taxes)
                    });

A: It is always better to use Mongodb aggregate for such complex queries, I am not sure what are you trying to do here, but I will show you how this should be done with c# mongodb driver.
Ideally, you should be using aggregate framework group by function, now if you find the doc hard to read, it is basically defining a extension method to IAggregateFluent, which takes two parameters, the first is an expression to your group key, the second is an expression that takes the group by original result, and return the projection for that result, in your case, the first expression is your queryGroupBy, and the second expression is your querySelect.
I am guessing your object type is Booking, hence the generic Aggregate<Booking> below
var result = await _collection.Aggregate<Booking>()
                .Group(e => e.CheckinDate.ToString("yyyy MMM"), // group by date
                            result => new Statistic()  //result is the group result, new Statistic is your projection of the result.
                   {
                    HotelsCount = g.Select(g => g.HoId).Distinct().Count(),
                    Key = g.Key,
                    TotalBookingsAmount = g.Sum(g => g.GrossTotal) + g.Sum(g => g.Taxes),
                    BookingsCount = g.Count(g => true),
                    TotalBookedDays = g.Sum(g => g.StayDays),
                    AvgWindowStay = g.Average(g => g.StayDays),
                    AvgBookingsAmount = g.Average(g => g.GrossTotal) + g.Average(g => g.Taxes)
                    })
                .ToListAsync();


text:
Q: Setting Provisioning Profile, Team, and Signing Certificate Without Opening XCode For unqiue reasons, I need to set the Provisioning Profile, the Team, and the Signing Certificate without opening XCode. Therefore, I would like to set these values at the command line using xcodebuild or fastlane. How would one do that?
Attached is a picture of the fields that I am trying to set without opening XCode.

A: I would use xcconfig files for that.
Let's say your build configuration is release.
Create a MyRelease.xcconfig file in Xcode and add the following lines:
#include "../Pods/Target Support Files/Pods-YourApp/Pods-YourApp.release.xcconfig"
DEVELOPMENT_TEAM = 12345678
CODE_SIGN_IDENTITY = iPhone Distribution: YourCompany (12345678)
PROVISIONING_PROFILE_SPECIFIER = YourApp Provisioning Name

You can easily copy those lines from the UI of your build settings in Xcode.
Then open the Tab General of your project in Xcode. Under configurations choose the name of your xcconfig file.
Then you delete the settings which you have set in Xcode directly so that only those from the xxconfig file are taken.
When you build, you can exchange the xcconfig file (i.e. cp someOther.xcconfig release.xcconfig) before running any other commands.


text:
Q: Transforming Esri JSON to Shapefile without using ArcPy? I have a large ESRI json (which I got from a request at an ESRI Rest API) that I need to convert to some sort of vector file, preferably a Shapefile.
It seems there are ways of doing this using ArcPy, but I do not own an ArcGIS license. Is there a way to work around this or is ArcGIS the only way to do it?


text:
Q: Does $\mbox{Im}\left ( z \right )\geq 0$ define an affine algebraic variety? Let $k=\mathbb{C}$ and $ A=\left \{z \in \mathbb{C} \mid \mbox{Im}(z)\geq 0  \right \}$.
I see intuitively that this cannot be expressed as the zero locus of a finitely number of polynomials, but how can you justify that it is not a variety with the following abstract definition of an affine variety?

A: Per your definition, an abstract affine variety over $k$ is a pair $(V,k[V])$ consisting of a set $V$ and a $k$-algebra $k[V]$ satisfying some conditions. You have not provided a candidate $k[V]$ to use with your given $V$, and in the comments you clarified that you were interested "if there exists a choice of $k[V]$ that makes it an algebraic variety".
With $k=\Bbb C$ and the definition of an abstract affine variety as given in the post, the only restrictions on when an arbitrary set (without any other structure) can be a $V$ such that there exists a $k[V]$ so that $(V,k[V])$ is an abstract affine variety are cardinality-related. That is, we can find a $\Bbb C[V]$ which makes $(V,\Bbb C[V])$ an abstract affine variety iff $|V|$ is finite or $|V|=|\Bbb C|$. To do this, take a bijection of $V$ with either a finite set $\{1,\cdots,n\}\subset\Bbb A^1_{\Bbb C}$ or the underlying points of $\Bbb A^1_\Bbb C$ and declare $\Bbb C[V]$ to be either $\Bbb C^n$ or $\Bbb C[x]$, respectively. For the other direction of the equivalence, there are two cases. If $|V|>|\Bbb C|$, then $|V| > |\Bbb A^n_\Bbb C|$ for any finite $n$, so there cannot be an injective map from $V$ to any $\Bbb A^n_\Bbb C$. If $|V|<|\Bbb C|$ but is not finite, this produces a contradiction because every $0$-dimensional affine variety is finite and every positive-dimensional affine variety has cardinality at least $|\Bbb C|$.
If your question was instead to show that the upper half-plane in the complex plane was not a Zariski-closed set, then this is much easier: the closed subsets of $\Bbb A^1_\Bbb C$ are either finite or the entire space, which you can easily derive from the fact that $\Bbb C[x]$, the coordinate algebra of $\Bbb A^1_\Bbb C$ is a PID with irreducible elements $0$ and $x-a$ for any $a\in\Bbb C$.


text:
Q: Specman Parametrized Unit I Need to verify a paramterized module in verilog, for example:
module A #(PAR1, PAR2, PAR3) (/*input, outputs*/);

This module is instantiated several times with different values of parameters.
I need to generate a SPECMAN Unit which can get PARAMETERs as constant for variable/port declaration.
Those parameters are also used for logic calculation.
I could not find a way to pass PARAMETERs to a specman unit as it can be done in verilog.
Is it possible?
If not - are there alternative solution?

A: There's no way to pass parameters to units in e. What you can do in your case, however, is used a template:
template unit some_unit of (<len'type>) {
  some_sig : in simple_port of <len'type> is instance;
    keep soft some_sig.hdl_path() == "some_sig";
};

The code above will define a template for a unit that contains a port, whose length is specified when declaring the unit instance. Here's how you can instantiate two units with different lengths:
extend sys {
  unit1 : some_unit of (uint(bits : 2)) is instance;
  unit2 : some_unit of (uint(bits : 4)) is instance;
};

You can find a working example on EDAPlayground.

A: Yes, in e you can define template struct or units. However, note that the parameters would be types rather than values.
For example, you can have a declaration like this:
template unit my_unit of (<first'type>, <second'type>) like base_unit {
    ......
};

and then you can instantiate it like this:
extend sys {
    foo: my_unit of (int(bits: 16), uint) is instance;
};

A: You can access Verilog parameters via simple_ports from e-code, just bind them like normal signals.
But it wouldn't help in this case because the values can't be used in other port declarations. I suggest to use the solutions offered here or make the ports wide enough to capture all requirements (MSBs would be filled with 1'b0 by Specman per default).


text:
Q: javax.media.NoPlayerException: Cannot find a Player for :vfw://0 I am getting error in the following code:
private void initCamera() throws IOException, NoPlayerException, CannotRealizeException
{
    MediaLocator ml = new MediaLocator("vfw://0");
    player = Manager.createRealizedPlayer(ml);
    this.tbCamera.add(player.getVisualComponent());
    player.start();
}

Following is the trace:
Jul 31, 2017 3:17:05 PM attendancemanagement.Student <init>
SEVERE: null
javax.media.NoPlayerException: Cannot find a Player for :vfw://0
at javax.media.Manager.createPlayerForContent(Manager.java:1412)
at javax.media.Manager.createPlayer(Manager.java:417)
at javax.media.Manager.createRealizedPlayer(Manager.java:553)
at attendancemanagement.Student.initCamera(Student.java:67)
at attendancemanagement.Student.<init>(Student.java:52)
at attendancemanagement.Student.main(Student.java:294)

this didn't help me.


text:
Q: Accessing object using method via this could you help me out with this code?
var mac = {
    notebook: "macbook",
    desktop: "imac",
    get_product: function (kind) {
        return this.kind;
    }
}

console.log(mac.get_product(notebook)); //ReferenceError: notebook is not defined

I expected "macbook" to log on the console.
Thanks for helping out.

A: So, this is the code which will do what you're trying to do:
var mac = {
    notebook: "macbook",
    desktop: "imac",
    get_product: function (kind) {
        return this[kind];
    }
}

console.log(mac.get_product('notebook'));

Looking at your original code:
var mac = {
    notebook: "macbook",
    desktop: "imac",
    get_product: function (kind) {
        // this.kind means mac.kind. You haven't defined mac.kind.
        // return this.kind;
        // instead, you want to look up the value of the property defined
        // at kind.

        // [] allow you to dynamically access properties in JavaScript
        // this["<something>"] means "get me the property named <something>
        // but because the contents of [] are determined before the overall
        // expression, this is the same as return this["<something>"];
        // var prop = "<something>";  return this[prop];
        return this[kind];
    }
}
// notebook (without quotes) is interpreted as a variable, but there is no
// variable by the name "notebook".
console.log(mac.get_product(notebook));

A: notebook is inner for mac so you cannot access it on console.log(mac.get_product(notebook));
Have a look at this article: http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

A: Just like get_product function, the notebook parameter is also defined inside the variable mac - so you'll need to refer to it as mac.notebook.

A: There are a few things up with this.

*

*There's no such thing as 'notebook' (it's 'mac.notebook'),

*There's no such thing as 'this.kind' (I presume you meant 'this.notebook').
var mac = {
    notebook: "macbook",
    desktop: "imac",
    get_product: function (kind) {
        return this.notebook;
    }
}

console.log(mac.get_product(mac.notebook));