text:
Q: AFNetworking HTTPClient subclass with XMLParser I am writing a small iOS app that queries a XML REST webservice. The networking framework in use is AFNetworking.
Situation
To query the webservice I subclassed AFHTTPClient:
@interface MyApiClient : AFHTTPClient

and in the implementation I make that available as a singleton:
+ (MyApiClient *)sharedClient {
    static MySharedClient *_sharedClient = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedClient = [[self alloc] initWithBaseUrl:[NSUrl URLWithString:@"http://url.to.the.webservice"]];
    });

    return self;
}

and in initWithBaseURL I tell AFNetworking to expect XML content:
[self registerHTTPOperationClass:[AFXMLRequestOperation class]];

Now I can call getPatch on the singleton from my ViewController and in the success block start parsing my returned XML. In NSXMLParserDelegate methods in the ViewController I can then pick the parts of the XML I am interested in and do stuff with it.
Problem
I want to have methods in my HTTPClient singleton that handle everything related to the webservice and return data models or list of models instead of XML.
For example I want to do something like this:
ServerModel *status = [[MyApiClient sharedClient] getServerStatus];

The ApiClient would then internally call the webservice, parse the XML and return the model.
How can I do that? Normally I would use a delegate that gets called once the XML is parsed, but due to the singleton nature of the ApiClient there could be multiple delegates?
Hope someone can shed light on this, thanks!

A: Use blocks instead of delegates.
From my ApiClient class:
- (void)getPath:(NSString *)path
     parameters:(NSDictionary *)parameters
        success:(void (^)(id response))success
        failure:(void (^)(NSError *error))failure
{
    NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters];
    [self enqueueHTTPOperationWithRequest:request success:success failure:failure];
}

-(void)fetchAllUsersSuccess:(void (^)(id))success
                     failure:(void (^)(NSError *))failure
{
    [self getPath:@"/api/mobile/user/"
       parameters:nil
          success:^(id response) {

                      if([response isKindOfClass:[NSXMLParser class]]){
                          //parse here to new dict
                          success(newDict);
                      } else
                          success(response);

          } failure:^(NSError *error) {
              failure(error);
          }];
}

Now I can use it like:
ServiceApiClient *apiClient = [ServiceApiClient sharedClient];

[apiClient fetchAllUsersSuccess:^(id dict) {
    for (NSDictionary *object in [dict objectForKey:@"objects"]) {
        [ServiceUser addUserFromDictionary:object
                                 inContext:self.managedObjectContext];
    }
    NSError *error= nil;
    [self.managedObjectContext save:&error];
    if (error) {
        NSLog(@"%@", error);
    }
} failure:^(NSError * error) {
    NSLog(@"%@", error);
}];

A: (Apologies in advance for this "sort-of" answer, but we're working towards a better solution...)
You need to take a step back and think about your design carefully.
You're having problems because you've got an idea that something in your design needs to be a singleton, but either:
1) that's not actually necessary,
2) something might already exist that does that job for you (e.g. the HTTP lib you're using),
or
3) You're making the wrong thing a singleton, or you haven't portioned out your design into the appropriate parts to work well with the singleton idea
So, can you tell me explicitly why you're going for a singleton approach? Is it just to ensure that only one network request can happen at once? Is there any notion of statefulness in your singleton object? Then I'll update this answer or comment, etc.
(Digression: I would also add that in some cases there might be a true need for a 'strong' singleton -- by which I mean that there really is only one possible instance, and that mechanism is baked right into your object, as you are doing - but this isn't it. The alternative is a 'weak' singleton, by which I mean your core object that actually does the work has a plain init method as usual, but shared access to a common object goes via another object, which is a kind of simple 'factory' that instantiates/holds the shared instance. The advantage of this weak singleton idea is that your code is more re-usable in different contexts - e.g. you could decide to do multiple HTTP requests/sessions concurrently at a later time - and it sometimes makes writing tests less problematic).


text:
Q: Amazon Cognito isn't delivering SMS text messages to my app's users I  have created a AWS Cognito user pool where user can login using

*

*Email

*Mobile number

I am verifying only "phone number" in attributes so all verification and forget messages going via mobile text SMS and It was working find few days and suddenly stopped sending messages.

Note :

*

*https://aws.amazon.com/premiumsupport/knowledge-center/cognito-troubleshoot-mfa-sms-delivery/

*My Amazon SNS limit is 100 $ and only 2$ is used .

*Graph shows only 2$ used

*I am able to send text SMS using SNS console

*No issue found in cloud watch matrix in cognoto and SNS

*https://github.com/aws-amplify/amplify-js/issues/6344
Updated :  I have created new region in Mumbai region and no SMS sent but when i have created in N Verginia SMS sent by pool.
Any information or  advice greatly appreciated

A: So after spending many hrs. to debug issue found Major "BUG" into AWS Cognito Let me explain Step by Step

*

*I have created an AWS Cognito pool in the Mumbai region Asia Pacific (Mumbai)
ap-south-1  which uses SNS text messages to send OTP messages.

*Requested Mumbai region SNS to increase Limit to 100 USD
Everything was working fine for a few days and suddenly all SMS text messages stopped.
Debug Steps :

*

*Uses following link and no issue found in 100 $ limit only 2 $ is used.

*

*https://aws.amazon.com/premiumsupport/knowledge-center/cognito-troubleshoot-mfa-sms-delivery/

*I have created a new Cognito pool with the same configuration into the same  Mumbai region and try to send message no message sent by AWS Cognito pool.

 3) I have created a new Cognito pool with the same configuration into the different  N Verginia region and try to send messages ,messages sent without issue.

*I have used the Mumbai region SNS and found no issue in the message.

So where is the issue ?
BUG :

*

*https://github.com/aws-amplify/amplify-js/issues/6344
In my case AWS Cognito internally uses Singapore region to send SMS text messages and where my Limit is 1$ since I am using Mumbai region Cognito should use Mumbai region not Singapore region.
Unfortunately, there is no public documentation available for users to know which is the closest region to the one they have selected. Upon sending SMS text messages. After raising request for all Asia Pacific  region issue is resolved .

*

*https://forums.aws.amazon.com/message.jspa?messageID=957242#957242

Since nothing explain in Doc should be documented by AWS.

A: Your Cognito verification sms are sent from different region than your infrastructure region. That's the key to resolve the problem.
For example:
My Frankfurt Cognito Service sends verification sms from Irland Region.
You could check this via Simple Notification Service (Mobile text messaging - Succes / Failure ratio).
That's the magic behind AWS and Cognito.

redpajama_set_name: RedPajamaStackExchange


text:
Q: A "strong" Galois-Tukey connection between orders with suborders (Background, may be skipped by the knowledgeable reader: A Galois-Tukey connection between two partial orders $(P,\le)$ and $(Q,\le)$ is a pair of maps $\varphi^+:P\to Q$ and $\varphi^-:Q\to P$ satisfying
$$ \forall p\in P \ \forall q\in Q: \left[ \varphi^-(q)\le p \Rightarrow q\le \varphi^+(p)\right]$$
for all $p\in P$, $q\in Q$.  (Note: Only "$\Rightarrow$", not "$\Leftrightarrow$" as in Galois connections.  Also, it's $\le$ on both sides, and the maps are not necessarily monotone.)
If there is such a Galois-Tukey connection, then $cf(P)\ge cf(Q)$, where
$cf(P)$ is the smallest cardinality of a cofinal (or: "dominating") set in $P$.  This is easy to see (and well known).  END OF BACKGROUND)
I am looking for a reference and/or a name for the following generalisation:
Let $P$, $Q$ be partial orders,  $P_0\subseteq P$ and $Q_0\subseteq Q$.
A pair of maps $\varphi^+:P\to Q$ and $\varphi^-: Q_0\to P_0$ is called a BLANK, if  we have
$$ \forall p\in P \ \forall q\in Q_0: \left[ \varphi^-(q)\le p \Rightarrow q\le \varphi^+(p)\right]$$
Is there a better name  than "strong GT connection", or perhaps even a well-established one?
My motivation is this: If we define (as in Bartoszyński-Judah 2.1.3.) the cardinal $cf(P_0, P)$ as the smallest size of a subset $D$ of $P$ which "dominates" $P_0$ (i.e., $\forall p_0\in P_0\ \exists d\in D: p_0\le d$), and dually the notion $add(P_0,P)$, then it is easy to see that the existence of a strong GT function as above will imply $add(P_0,P)\le add(Q_0,Q)$ and $cf(P_0,P)\ge cf(Q_0,Q)$.

Edit: Thanks to Peter Vojtas and Andreas Blass for pointing out that

*

*a (generalized) Galois-Tukey relation (or "morphism") does not have to be between two orders; any two  relations (subsets of $P_0\times P$ and $Q_0\times Q$,
where no inclusion relation is required between $P_0$ and $P$, or between $Q_0$ and $Q$) will do;

*Letting $\le'_P$, $\le'_Q$ be the restrictions of $\le_P$, $\le_Q$ to $P_0\times P$ and $Q_0\times Q$, respectively, my "strong GT relation" is just the usual generalized GT relation/morphism between $\le'_P$ and $\le'_Q$. Both relations happen to be partial orders, but that is irrelevant.

A: Martin, first definition is just J.W.Tukey cited in my http://www.ksi.mff.cuni.cz/~vojtas/MathPub/1993_GeneralizedGaloisTukey.pdf . We have to be careful the implication should not be true in a void sense (false implies * is true) - so some restrictions on $P_0, \phi^- , ...$ are necessary. In my Galois-Tukey relations can be arbitrary binary ones - so $\mathord\le\cap (P_0\times P)$ is OK. So what you ask is something between Tukey connections and Galois-Tukey (let us call it strong Tukey).
It seems, that if $Q_0, P_0$ are dominating in $Q, P$, then one can extend $\phi^-$ to whole Q. So, it is interesting when there is a strong Tukey between $\mathord\le\cap (P_0\times P)$ and $\mathord\le\cap (Q_0\times Q)$ and no Tukey connection between $P$ an $Q$.

A: As indicated in Peter Vojtas's answer, this notion is a special case of what he called generalized Galois-Tukey connections (in the paper he linked to) and what I later called morphisms (in my chapter of the Handbook of Set Theory). Specifically, what you describe is a morphism from $(P_0,P,\leq)$ to $(Q_0,Q,\leq)$. (In the terminology of generalized G-T connections, "from" and "to" would be interchanged.) In general, the domain and codomain of a morphism could be any triples of the form $(A_-,A_+,R)$ where $R\subseteq A_-\times A_+$, i.e., any two sets and a relation between them. What's special in your situation seems to be just that (1) $P_0\subseteq P$, (2) the $\leq$ relation that you actually use (between $P_0$ and $P$) is the restriction of a partial order on all of $P$, and (3,4) the same for $Q_0$ and $Q$.


text:
Q: Looping through folders How do I loop through folders inside an if statement. I want to tell the robot to search for filepath + row.item(0) + either one or double space + row.item(1).tostring? Some of the folders have double spaces and some have single space. Help is much appreciated.
Best regards

A: Why don't you do something like:
filepath + row.item(0).Trim() + " " + row.item(1).tostring.Trim()

Rename all the sub-folders under filepath/* and correct their names with a single space between name before applying above solution.
Another approach is, to use try-catch mechanism. If you are sure about these 2 conditions only - try with single space - if throws an error try with double space in the catch block.

A: to recursively get folders you can use the below method
GetDirectories(String, String, SearchOption)
If you use the following parameters you should be able to find your folders, the top method will return folders with one space the one below will return folders with two spaces.
Directory.GetDirectories(
    "C:\",
    filepath + row.item(0) + " " + row.item(1).tostring,
    SearchOption.AllDirectories)
Directory.GetDirectories(
    "C:\",
    filepath + row.item(0) + "  " + row.item(1).tostring,
    SearchOption.AllDirectories)
To combine this into a single line of code that can be used within an assign you can use the following.
Directory.GetDirectories("C:\",filepath + row.item(0) + " " + row.item(1).tostring,SearchOption.AllDirectories).AddRange(Directory.GetDirectories("C:\",filepath + row.item(0) + "  " + row.item(1).tostring,SearchOption.AllDirectories))
This will extract on list of directories with one space in then add the second list of directories to it with the double spaces in. This will give you a single list containing folders that match either of the search strings


text:
Q: Java! How to display the correct and incorrect answered questions after user finish answering the questions I have a Java program that asks user questions and totals their scores. I am trying to display the correct total of answered questions at the end of the program. However, I have no idea how to, can some please help me!
Here is an example of how my code looks like l! But this is not my actual code this is from another source!
Import java.util.Scanner;

public class App
{
    public static void main(String[] args) {

        // The array of questions.
        String questions[] = {
                "Plants derive most of their dry mass from the air.",
                "Aluminium is the most common metal in the Earth's crust.",
                "Vitamin C has be shown to prevent colds.",
                "We lose the most heat through our heads.",
                "Dogs are unable to digest chocolate.",
                "Apple pips contain cyanide.",
                "Cholesterol is a nat
                "When you're on a diet, you lose weight by oxidising fat to a gas and exhaling it.",
                "Human beings are unable to sense when the oxygen level of the air is low.",
                "Most of the Y chromosome is passed unchanged from father to son" };

        // The array of answers. The entries correspond to the questions.
        boolean answers[] = { true, true, false, false, false, true, false,
                              true, true, true };

        // Display the opening text.
        System.out.println("Answer each of the following questions with 't' (true) or 'f' (false)");

        // We'll use this to get user input.
        Scanner input = new Scanner(System.in);

        // Add up the user's score here as we go along.
        int score = 0;

        // The is the index into the questions array and the answers array.
        int questionNumber = 0;

        // Create a blank line.
        System.out.println();

        // The do-while loop will keep running while questionNumber is less
        // than the question array length.
        do {
            // Display the question
            System.out.println(questions[questionNumber]);

            // Display a little prompt to make it clearer that the user has to
            // enter something.
            System.out.print("> ");

            // Get the user's answer.
            String userAnswer = input.nextLine();

            // Check that the user has entered t or f.
            if (!userAnswer.equals("t") && !userAnswer.equals("f")) {
                System.out.println("Please enter t for true or f for false.\n");

                // Invalid input!
                // Skip the rest of this loop iteration and ask the same question again.
                continue;
            }

            // Check the answer.
            if (userAnswer.equals("t") && answers[questionNumber] == true) {
                // If the answer's t and the right answer is "true", the answer was correct.
                score++;
                System.out.println("correct\n");
            } else if (userAnswer.equals("f") && answers[questionNumber] == false) {
                // If the answer's f and the correct answer is "false", the answer was correct.
                System.out.println("correct\n");
                score++;
            }
            else {
                // Wrong answer!
                System.out.println("incorrect!\n");
            }

            // Now we can move to the next question when we go round the loop again.
            questionNumber++;

        } while (questionNumber < questions.length); // end of do-while.

        // This isn't really necessary, but closing the Scanner prevents a warning icon in Eclipse.
        input.close();

        // Tell the user their score.
        System.out.println("You scored: " + score);

        // Rank the score! Only one of the alternatives below will execute.
        // Java will check them in order from top to bottom.
        if(score < 5) {
            // Less than 5 -- not so good.
            System.out.println("Hmmm, maybe you're the artistic type. Try the test again!");
        }
        else if(score < 8) {
            // The score wasn't less than 5, but it IS less than 8.
            System.out.println("Not bad! But have another go.");
        }
        else if(score <= 9) {
            // The score wasn't less than 8, but it IS less than, or equal to, 9.
            System.out.println("Pretty good! But no perfect. Try again!");
        }
        else {
            // The score was more than 9 -- must be 10 because we've only got 10 questions.
            System.out.println("You're a certified science genius!");
        }

    }
}

A: Simply declare a boolean array containing user answers in your class:
public boolean[] userAnswers = new boolean[questions.length]; //remove the access modifier if you want to declare the array inside main instead of the class

Now in your do-while loop, after parsing the user input, do this:
userAnswers[questionNumber] = userAnswer.equals("t");

Outside of your do-while loop (after you close the Scanner), do the following to print all the questions and the user's answer:
for (int i = 0; i < questions.length; i++) {
    System.out.println("User answered \"" + userAnswers[i] + "\" on question " + (i + 1) + ": " + questions[i]);
}

A: You can use a list and add the question nummer when the user has answered the question correctly.
Before your do-while-loop you have to add
ArrayList<Integer> correctQuestions = new ArrayList<Integer>();

Then in your do-while-loop you have to add when the answer is correct
correctQuestions.add(questionNumber);

At the end of you program (outside the do-while-loop) you can make the output like this:
System.out.println("You answered the following questions correctly");
for (int k : correctQuestions) {
   System.out.println(questions[k]);
}


text:
Q: Kernel panic - not syncing: Watchdog detected hard LOCKUP Can someone help me why have i got this crash?
[2324956.184374] Kernel panic - not syncing: Watchdog detected hard LOCKUP on cpu 1
[2324956.184374] Pid: 0, comm: kworker/0:0 Tainted: P            3.1.10-gb20-default #1
[2324956.184374] Call Trace:
[2324956.184374]  [<ffffffff81003add>] dump_trace+0x98/0x223
[2324956.184374]  [<ffffffff813dc659>] dump_stack+0x69/0x6f
[2324956.184374]  [<ffffffff813def08>] panic+0xa4/0x1b4
[2324956.184374]  [<ffffffff81094b48>] watchdog_overflow_callback+0x79/0x9e
[2324956.184374]  [<ffffffff810b66b5>] __perf_event_overflow+0xf9/0x185
[2324956.184374]  [<ffffffff81010a2c>] intel_pmu_handle_irq+0x15d/0x1be
[2324956.184374]  [<ffffffff813f375b>] perf_event_nmi_handler+0x3e/0x87
[2324956.184374]  [<ffffffff813f4c0f>] notifier_call_chain+0x2e/0x5b
[2324956.184374]  [<ffffffff813f4c76>] __atomic_notifier_call_chain+0x3a/0x4d
[2324956.184374]  [<ffffffff813f4cc1>] notify_die+0x2d/0x32
[2324956.184374]  [<ffffffff813f2bbb>] default_do_nmi+0x29/0x1b5
[2324956.184374]  [<ffffffff813f2eb7>] do_nmi+0x47/0x6f
[2324956.184374]  [<ffffffff813f2a30>] nmi+0x20/0x30
[2324956.184374]  [<ffffffff8106b725>] arch_local_irq_save+0x1/0x17
[2324956.184374]  [<ffffffff813f1e9b>] _raw_spin_lock_irqsave+0xf/0x39
[2324956.184374]  [<ffffffff8105d9b7>] down_trylock+0xb/0x29
[2324956.184374]  [<ffffffff810409c2>] console_trylock+0xf/0x47
[2324956.184374]  [<ffffffff81040dc9>] console_unlock+0x100/0x129
[2324956.184374]  [<ffffffff8104120b>] vprintk+0x348/0x394
[2324956.184374]  [<ffffffff813df06b>] printk+0x53/0x58
[2324956.184374]  [<ffffffff81359902>] ip_handle_martian_source+0x6d/0xf6
[2324956.184374]  [<ffffffff8135b980>] ip_route_input_slow+0x45d/0x462
[2324956.184374]  [<ffffffff8135c02f>] ip_route_input_common+0x217/0x231
[2324956.184374]  [<ffffffff8137e995>] arp_process+0x181/0x4ac
[2324956.184374]  [<ffffffff81337bf5>] __netif_receive_skb+0x317/0x36b
[2324956.184374]  [<ffffffff81337b44>] __netif_receive_skb+0x266/0x36b
[2324956.184374]  [<ffffffff81339722>] netif_receive_skb+0x7e/0x84
[2324956.184374]  [<ffffffff8133979e>] napi_skb_finish+0x1c/0x31
[2324956.184374]  [<ffffffffa02e1dee>] igb_clean_rx_irq+0x30d/0x39e [igb]
[2324956.184374]  [<ffffffffa02e1ecd>] igb_poll+0x4e/0x74 [igb]
[2324956.184374]  [<ffffffff81339c88>] net_rx_action+0x65/0x178
[2324956.184374]  [<ffffffff81045c73>] __do_softirq+0xb2/0x19d
[2324956.184374]  [<ffffffff813f9aac>] call_softirq+0x1c/0x30
[2324956.184374]  [<ffffffff81003931>] do_softirq+0x3c/0x7b
[2324956.184374]  [<ffffffff81045f98>] irq_exit+0x3c/0xac
[2324956.184374]  [<ffffffff81003655>] do_IRQ+0x82/0x98
[2324956.184374]  [<ffffffff813f24ee>] common_interrupt+0x6e/0x6e
[2324956.184374]  [<ffffffff8123f91d>] intel_idle+0xdd/0x104
[2324956.184374]  [<ffffffff8130b76b>] cpuidle_idle_call+0xdf/0x181
[2324956.184374]  [<ffffffff81001201>] cpu_idle+0x56/0xa9


text:
Q: CentOS7 kswapd0 process eating 99% CPU
When I run top on centos7, I found kswapd0 eating 99% CPU, as shown in the screenshot above.
Below is some other information
top - 11:38:04 up 32 days, 16:14,  1 user,  load average: 0.06, 0.13, 0.19
Tasks: 142 total,   2 running, 140 sleeping,   0 stopped,   0 zombie
%Cpu(s): 12.0 us,  2.0 sy,  0.0 ni, 79.0 id,  6.7 wa,  0.0 hi,  0.0 si,  0.3 st
KiB Mem :  3618860 total,   199684 free,  1130200 used,  2288976 buff/cache
KiB Swap:        0 total,        0 free,        0 used.  2152124 avail Mem

  PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND
12493 mysql     20   0 1200596 402140   6868 S  5.3 11.1  46:54.22 mysqld
13460 apache    20   0 1089628  43932  22264 S  3.0  1.2   1:16.40 php-fpm
13462 apache    20   0 1088772  42704  21672 S  1.3  1.2   1:14.47 php-fpm
 9391 root      20   0  124508  11588   4852 S  0.7  0.3   8:38.31 AliYunDun
13474 apache    20   0 1073892  40976  19884 S  0.7  1.1   1:15.93 php-fpm
12609 apache    20   0 1088832  44976  24000 S  0.3  1.2   1:15.94 php-fpm
12615 apache    20   0 1077948  42776  21764 S  0.3  1.2   1:16.34 php-fpm
12616 apache    20   0 1077568  43116  22344 S  0.3  1.2   1:14.59 php-fpm
12619 apache    20   0 1085672  44144  22380 S  0.3  1.2   1:14.62 php-fpm
12663 nginx     20   0   66928   7604   2276 S  0.3  0.2   4:55.48 nginx
12664 nginx     20   0   68064   9124   2708 S  0.3  0.3   5:17.61 nginx
13451 apache    20   0 1077360  41092  20452 S  0.3  1.1   1:15.16 php-fpm
20987 root      20   0  143572   5788   4492 S  0.3  0.2   0:00.75 sshd
27671 root      20   0  157676   2208   1544 R  0.3  0.1   0:00.12 top
28370 apache    20   0 1071564  34900  15676 S  0.3  1.0   1:01.53 php-fpm
    1 root      20   0  191276   5412   1464 S  0.0  0.1   2:03.59 systemd
    2 root      20   0       0      0      0 S  0.0  0.0   0:00.06 kthreadd
    3 root      20   0       0      0      0 S  0.0  0.0   0:46.51 ksoftirqd/0
    5 root       0 -20       0      0      0 S  0.0  0.0   0:00.00 kworker/0:0H
    7 root      rt   0       0      0      0 S  0.0  0.0   0:00.00 migration/0
    8 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcu_bh
    9 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/0
   10 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/1
   11 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/2
   12 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/3
   13 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/4
   14 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/5
   15 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/6
   16 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/7
   17 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/8
   18 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/9
   19 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/10
   20 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/11
   21 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/12
   22 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/13
   23 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/14

I dont know why
[root@fl basic]#free -lh
              total        used        free      shared  buff/cache   available
Mem:           3.5G        1.1G        197M         87M        2.2G        2.1G
Low:           3.5G        3.3G        197M
High:            0B          0B          0B
Swap:            0B          0B          0B

A: Well, root don't eat your CPU, it do kswapd. There is known bug in linux kernel. We have same issues in CentOS 7.1 after upgrading to 7.2 it has gone. May be kernel update would be solution for you.

A: As stated by AlexanderT, it can be a kernel bug and so you should update your kernel.
If you can't do that, a possible workaround is to periodically drop the buffer/pagecache by issuing the following command: echo 3 > /proc/sys/vm/drop_caches

A: While in this case it looks like the kernel bug mentioned above, for other cases it may be something else.
It could be malware.  The process name has been changed to display kswapd0.  This is a common trick by malware, and kswapd0 is one I've specifically seen.
Some other clues this isn't just a benign kernel process:

*

*kernel processes doesn't have surrounding [brackets] around the name

*kernel processes are usually lower PIDs; kswapd are around 500 on a server with 64 cores (and more cores mean more kprocs like migration, watchdog, ksoftirqd, which run before kswapd)

*files in /proc/$PID/fd - a true kproc won't have any file descriptors.

*VIRT/RES/SHR will be 0 for kernel process, but a fake one will have non-zero values here.

*look for other suspicious processes.  Do you see things like uptime, ls -la, id, whoami, etc that normally return in a fraction of a second?  How are they all running the instant you ran ps? You might have malware.

You could still possibly have a genuine swap load.  If your system was low on free memory, or your swap had activity (if you have one), then it may be due to normal VM subsystem operation.


text:
Q: Mostrar OK en ves del valor 1 Necesito mostrar la palabra OK en vez del valor 1

   {data.measurements[data.measurements.length-1].value}
     {data.unity}

Ayuda Porfa!

A: Todo lo que necesitas es controlar mediante un ternario si se cumple cierta condición y renderizar una cosa u otra dependiendo del caso.

{data.measurements[data.measurements.length-1].value}
  {data.unity === 1 ? 'OK' : 'No Ok'}

Tambíen puedes crear una variable con esa condición y utilizarla en el render, eso a gustos:
const isUnityOk = data.unity === 1 ? 'OK' : 'No Ok';

Y utilizarla tal cual
  {isUnityOk}

A: La manera mas simple para que no sobre cargues de lógica tu código es usar el operador ternario que es una sintaxis acortada de un condicional, que puede ser simple o tan complejo como lo necesites.
Estructura de un operador ternario
(variable === 1) ? "Resultado si es cierto": "Resultado si es falso"

Entonces deberías crearla de este modo:

   { (data.unity === 1) ? "OK": "No OK" }

*

*Operador ternario


text:
Q: Vlc not installing on installing vlc i get this error message "Fail to fetch size mismatch" what could be the problem as we are not able to install vlc, gimp or any software even after installing synaptic package manager successfully. The software works fine only for 24 hours and then it gives the above message. Please help...urgently, thanks

A: This problem was solved here (bubblenet.be user) by executing in a terminal (press CTRL+ALT+T, also xTerm is fine):
sudo aptitude clean
sudo aptitude update

Please, since this is an uncommon and interesting problem, feel free to comment under here if you need more help and don't forget to press the UP arrow on the left if I'm of any help.
Have a nice day.

A: Open this link : http://www.chip.de/downloads/VLC-media-player-fuer-Linux_36673620.html Problem solved :) !!!

A: The Failed to fetch [package url] size mismatch error means that the downloaded package and the server package are different.
There is a chance your problem is due to a network restriction.

*

*Open a terminal (Ctrl + Alt + T)

*Run this command and enter your password: sudo apt-get install vlc

*Check the content of the partial downloaded package with this command: cat /var/cache/apt/archives/partial/vlc-*
If it has the form of an html page, it means that's the case.


text:
Q: Why is my script is opening then closing immediately when it shouldn't? (Python) I'm trying to make a warmer / colder game in python as a project. Currently, when I open the program it closes immediately despite there being several loops and inputs. I have spent a good 2 hours on it, and I can't figure it out. Any tips?
import random
Correct = random.randint(1, 100)
Oldval = 50
Newval = 50
while Newval != Correct:
    Newval = Newval + input("How much do you want to move?")
    if (Newval - Correct) > (Oldval - Correct):
        print("Colder!")
    else:
        print("Warmer!")
    Oldval = Newval
Win = input(You Win!)

A: You were trying to add a string and an integer. Also, your final input didn't have quotes around the You Win! string. Here's the code with the issues fixed:
import random
correct = random.randint(1, 100)
oldval = 50
newval = 50
while newval != correct:
    newval = newval + int(input("how much do you want to move?"))
    if (newval - correct) > (oldval - correct):
        print("Colder!")
    else:
        print("Warmer!")
    oldval = newval
win = input("You Win!")

A: You could use pylint tool to detect the error like missing quotes.

pylink test.py

E: 12, 0: invalid syntax (<string>, line 12) (syntax-error)

You could install pylint using pip install pylint


text:
Q: Query custom post type and group by taxonomy I struggle a bit with my piece of code - it's main goal is to show list of custom post type (called "career") childs grouped by custom taxonomy.
How it should work?
A user see default list of ALL available posts (from that career CPT). On top of that there are two dropdowns each field with terms from custom taxonomies. First custom taxonomy is called job-category and the second job-country. Once a user selects specific value from a dropdown and click 'filter' the list of shown posts changes. So all in all it is a simple filtering mechanism.
What works and what's not?
The filtering itself works ok. So if a user select any value from job-category list and filter the results it shows proper list in this way:
//CUSTOM TAXONOMY (job-category) TERM NAME
list of assigned posts

No other posts are suppose to be shown.
If a user selects value from BOTH dropdowns (so assign parameters from both taxonomies job-country and job-category) it also works in that way
//CUSTOM TAXONOMY (job-category) TERM NAME
list of assigned posts

The only thing that currently doesn't work is a condition when a user selects value from taxonomy job-country. I would like to be displayed in the same way as previously so
//CUSTOM TAXONOMY (job-category) TERM NAME
list of assigned posts

Now instead it shows just full list of posts meeting criteria for 'job-country'. Yet there is no grouping by taxonomy 'job-category'. This is my current code:
<?php

$args = array(
    'orderby' => 'date', // we will sort posts by date
    'order' => $_POST['date'], // ASC or DESC
    'post_type' => 'career',
    'posts_per_page' => -1,
'post_status' => 'publish'
);

if( isset( $_POST['categoryfilter'] ) && isset ($_POST['taxonomyfilter'])  ) {
  $args['tax_query'][] = array(
      array(
          'taxonomy' => 'job-category',
          'field' => 'name',
          'terms' => $_POST['categoryfilter']
      ),
      array(
          'taxonomy' => 'job-country',
          'field' => 'name',
          'terms' => $_POST['taxonomyfilter']
      ),
  );

} elseif( !isset( $_POST['categoryfilter'] ) && isset ($_POST['taxonomyfilter'])  ) {
  $args['tax_query'][] = array(
      'taxonomy' => 'job-country',
      'field' => 'name',
      'terms' => $_POST['taxonomyfilter']
  );

} elseif( isset( $_POST['categoryfilter'] ) && !isset ($_POST['taxonomyfilter'])  ) {
  $args['tax_query'][] = array(
      'taxonomy' => 'job-category',
      'field' => 'name',
      'terms' => $_POST['categoryfilter']
  );
}

$query = new WP_Query( $args );

if( $query->have_posts() ) :

if(isset($_POST['categoryfilter'])) {
  echo '
'. $_POST['categoryfilter'] .'
';
}
    while( $query->have_posts() ): $query->the_post();
?>

<?php echo $query->post->post_title ; ?>

<?php
    endwhile;
    wp_reset_postdata();
else :
    echo '
Sorry, no openings found :-(
';
endif;

die();


text:
Q: Eliminar archivos y carpetas temporales cuando se presente un error C# estoy creando un .zip, hago uso de carpetas temporales que guardan los archivos para que después de generar el zip eliminarlas y no llenar el Temp de carpetas por descarga que se haga.
Ahora necesito que cuando haya algún error al crear un PDF (que es lo que guarda mi zip) todos los archivos y carpetas que sí se lograron crear se eliminen para que el Temp no quede con carpetas y archivos que no se eliminaron porque no se pudo realizar la descarga.
¿De qué manera puedo realizar esa eliminación?
Dejo el código que uso para crear el zip y eliminar los temporales.
                                //Creación del .zip
                                ZipFile.CreateFromDirectory(rutaZip, pathZip);
                                FileInfo fileInfo = new FileInfo(pathZip);
                                string mimeName = MimeExtensionHelper.GetMimeType(zip);

                                //Apertura y lectura de fileInfo para recuperar en un byte[]
                                byte[] buffer;

                                FileStream fS = fileInfo.Open(FileMode.Open);
                                try
                                {
                                    int length = (int)fS.Length;
                                    buffer = new byte[length];
                                    int count;
                                    int sum = 0;

                                    while ((count = fS.Read(buffer, sum, length - sum)) > 0)
                                    sum += count;

                                }
                                finally
                                {
                                    fS.Close();
                                }

                                //Eliminación de archivos y carpetas temporales
                                if (Directory.Exists(path))
                                {
                                    Directory.Delete(path, true);
                                }
                                return File(buffer, mimeName, fileInfo.Name);


text:
Q: Scala - How to set default value instead None for Option[Int] I want to extend class Option[Int] it so that it returns 0 if None and value in Some if it's not None. How should I make the below code  work?
Some(10).default // returns 10
Option.empty[Int].default // returns 0

A: You can define an implicit class with the method you want, that wraps an Option[Int]:
implicit class OptionIntExtension(option: Option[Int]) {
  def default: Int = option.getOrElse(0)
}

When this class is imported into scope, the code from your question works.

A: You can do this a couple of ways.
With pattern matching:
val input: Option[Int] = Some(10)

input match {
  case Some(value) => 10
  case None => 0
}

Output:
res0: Int = 10

With getOrElse:
val input: Option[Int] = Some(10)
input.getOrElse(0)

Output:
res1: Int = 10

EDIT
To make this work like in your original question, pop it into an implicit class in scope (as Kolmar suggests):
implicit class DefaultExtension(input: Option[Int]) {
  def default: Int = input.getOrElse(0)
}

Some(10).default
res0: Int = 10

Option.empty[Int].default
res1: Int = 0

implicit class DefaultExtension(input: Option[Int]) {
  def default: Int = input match {
    case Some(value) => 10
    case None => 0
  }
}

Some(10).default
res0: Int = 10

Option.empty[Int].default
res1: Int = 0


text:
Q: Error: Cannot read property 'user' of null when calling passport.serializeUser so I have the next in my passport.js file:
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
var connection = require('./database');
const User = require('./models/user');

const verifyCallback = (username, password, done) => {

  User.findUser(username).then((user) => {
    if(!user)
      return done(null, false);

    const isValid = User.validPassword(password, user[0].password).then((isValid)=>{

      if(isValid)
        return done(null, user);
      else
        return done(null, false);

    })
  })
  .catch((err) =>{
    done(err);
  });
};

const strategy = new LocalStrategy(verifyCallback);

passport.use(strategy);

passport.serializeUser((user, done) => {
  console.log(user + "\n" + user.id);
  done(null. user.id);
});

passport.deserializeUser((userId, done) => {
  User.findById(userId)
    .then((user) =>{
        done(null, user)
    })
    .catch(err => done(err));
})

Everything works fine until the function passport.serializeUser which return the error Cannot read property 'user' of null
I don't know where is the user param coming from, I was following a tutorial but the guy didn't explained. How should I solve that error?
Here is the route:
var express = require('express');
var router = express.Router();
var passport = require('passport');
const controller = require('../controllers/LoginController');

router.get('/', controller.getLoginPage);
router.post('/', passport.authenticate('local', {failureRedirect: '/', successRedirect: '/register'}),controller.login);

module.exports = router;

A: As per you code you have written done(null. user.id);, it should be done(null, user.id);
You have used . instead of a ,


text:
Q: Does binary logging for MySQL slow down performance? The question is simple. Does turning on binary logs in MySQL slow down performance considerably, i.e. will it write large amount of data to disk thereby causing high I/O, will it hog memory, does it have any implications for the CPU ?
Thanks

A: Reference
Running a server with binary logging enabled makes performance slightly slower. However, the benefits of the binary log in enabling you to set up replication and for restore operations generally outweigh this minor performance decrement.

A: If the binary logs and the MySQL data write to the same disk mount, then yes it will slow things down.
If you create a separate disk mount just for logs, then it will not slow down as much.
In Facebook, there is a Database Engineer who splits up the MySQL files into separate disks. In light of this example, you could just setup a second disk, map log-bin to that disk. That way, no wasted spindles writing log data on a data volume.


text:
Q: Node JS and Python - POST image from Node JS to Python REST API I have a Node JS application. I want to send an image from the Node JS application to a REST API which is written in Python. The key and the inputs needed by the Python REST API are as follows
My problem is that I am able to POST a simple 'Hello World' string with the code I have written and get a response. However, when I try to send an image something goes wrong and I get no response.
var http = require('http');
var querystring = require('querystring');

// This is some dummy string data
var postData = querystring.stringify({
    msg: 'hello world'
});

var fs = require('fs')
    , path = require('path')
    , certFile = path.resolve(__dirname, 'ssl/client.crt')
    , keyFile = path.resolve(__dirname, 'ssl/client.key')
    , caFile = path.resolve(__dirname, 'ssl/ca.cert.pem')
    , request = require('request');

// I want to send an image from one server to another. What changes should I make to the options below for POSTing image data
var options = {
    hostname: '127.0.0.1',
    port: 8888,
    path : '/predict',
    //image: fs.createReadStream('car.jpg'),  //Should I give something like this??
    method: 'POST',
    headers: {
        'Content-Type': 'multipart/form-data',
        'Content-Length': postData.length
    }
};

var req = http.request(options, function (res) {
    console.log('STATUS:', res.statusCode);
    console.log('HEADERS:', JSON.stringify(res.headers));

    res.setEncoding('utf8');

    res.on('data', function (chunk) {
        console.log('BODY:', chunk);
    });

    res.on('end', function () {
        console.log('No more data in response.');
    });
});

req.on('error', function (e) {
    console.log('Problem with request:', e.message);
});

req.write(postData);
req.end();

Please let me know what changes I have to make to this code to post an image.I read about the use of multer package. However, the examples that I came across were using JS on both ends. Since for me, I have a Python REST API , I cannot use that. PLease help since I have been struggling with it for some time now.
Edit 1: Based on @Jana's suggestion, I added the multipart within the options and tried, where image is the key and the value is fs.createReadStream('car.jpg') . However, at the python end, it does not get the 'image' key because of which I get a False response. What am I missing?
 var options = {
    hostname: '127.0.0.1',
    port: 8888,
    path : '/predict',
    //image: fs.createReadStream('car.jpg'),  //Should I give something like this??
    multipart: [
        {
            'content-type': 'application/json',
             body: JSON.stringify({'image': fs.createReadStream('car.jpg')          })
        }

    ],
    method: 'POST',
    headers: {
        'Content-Type': 'multipart/form-data',
        //'Content-Length': postImageData.length
    }
};

A: Check this,
`request({
    method: 'POST',
    uri: 'http://127.0.0.1:8888/predict',
    multipart: [{
            'content-type': 'application/json',
            body: JSON.stringify({
                "key": "value"
            })
        },
        {
            body: fs.createReadStream('car.jpg')
        }
    ],
},
function(error, response, body) {
    if (error) {
        return console.error('upload failed:', error);
    }
    console.log('Upload successful!  Server responded with:', body);
})`

And also you can get the best examples from its own documentation Request - Simplified HTTP client


text:
Q: Remove 0xff from the end of a binary flash image using bash script I have a tool that generates a 32MB binary image to be written to a flash memory.
But only the first 2MB contains valuable data, the rest is just 0xff.
So I would like to remove the 0xff bytes from the end of the file using a nice bash / makefile script.
I could use head:
head -c 2M test.bin > out.bin

But I don't know the actual length, so I would like to find the first occurence of 0xff from the end of the file as input to head or similar.
I'm running my tool from a Makefile on cygwin, so it would be good if it could be executed using standard bash / makefile tools.

A: This sed one liner will operate only on the last line of the file and remove all trailing 0xFF bytes.
sed '$ s/\xff*$//' file > file.out

A: Counting the number of 0xFF bytes at the end of your file can be done with a combination of hexdump (or xxd, od...) to convert your binary file in a stream of ASCII hexadecimal values and a text processor like awk to do the counting. Example:
hexdump -v -e '/1 "%02X\n"' test.bin | \
  awk '/FF/ {n += 1} !/FF/ {n = 0} END {print n}'

Then, removing that number of bytes from the end of the file can be done using e.g. dd or head. Example:
head -c -$d test.bin > results/test.bin

All in all, your Makefile could resemble:
OUTDIR  := results
OLDBINS := $(wildcard *.bin)
NEWBINS := $(addprefix $(OUTDIR)/,$(OLDBINS))

.PHONY: all

all: $(NEWBINS)

$(OUTDIR)/%: % | $(OUTDIR)
    n=$$(hexdump -v -e '/1 "%02X\n"' $< | \
      awk '/FF/ {n += 1} !/FF/ {n = 0} END {print n}'); \
    head -c -$$n $< > $@

$(OUTDIR):
    mkdir -p $@

There are a few make subtleties like phony targets ( all), automatic variables ($<, $@), order-only prerequisites (| $(OUTDIR)), make expansion escaping in recipes (the $$ signs), make functions (wildcard, addprefix), a one-line recipe that uses line continuation (the \ at the end of lines)... But nothing very complicated.
EDIT: try to find a faster solution:
Another option may be more efficient (about 20 times faster on 32MB files in my super-simple tests) if the base64 utility is available and the size of your files is exactly 32MB:

*

*base64-encode without wrapping:
 base64 -w0

*Use sed to remove all trailing //// strings, followed by a last //8= at the end of the file (see the base64 RFC 4648) to understand why these strange trailing texts:
 sed -E 's#(////)*//8=$##'

*base64-decode:
 base64 -d

One-liner:
base64 -w0 test.bin | sed -E 's#(////)*//8=$##' | base64 -d > results/test.bin

Note that this may leave one or two 0xFF characters at the end on the file, depending on the size of the input file and on the number of trailing 0xFF characters. The new make recipe would be:
$(OUTDIR)/%: % | $(OUTDIR)
    base64 -w0 $< | sed -E 's#(////)*//8=$$##' | base64 -d > $@

A: head -c -1 test.bin > out.bin

The -1 strips the last byte.


text:
Q: Help with current draw in a circuit
Possible Duplicate:
Limiting current from a 5v power supply

I'm trying to build a DIY Xbox Kinect adapter to be able to plug the Kinect into my computer, but I'm getting some shaky information. From what I've seen, the official Kinect adapter (for using the Kinect with an non-slim Xbox 360) outputs 1.08A @ 12V. I've got a power supply that outputs 12V @ 3A and I need to know whether using this will damage the Kinect.
My understanding is that a circuit will only draw as much current as is required for it to operate. For example, I can connect an LED that requires 20mA @ 3.3V, in series with an 85 ohm resistor, to a wall-wort power supply that outputs 850mA @ 5V. Computer PSUs generally have a 12V rail with as high as 50A. I could plug a hard drive into one of those rails (as the only load on that rail) and nothing bad happens, and I guarantee that the HDD isn't drawing 50A.
At any rate, am I correct in assuming that using a power supply rated for a higher current won't damage the circuit, as the circuit will only pull as much as it needs?

A: You are correct. You can also think of it this way - you know a 50A power supply doesn't force 50A out all the time, b/c with nothing connected, you don't see a 50A arc ripping through the air between the terminals!

A: Jeff is right saying that it will give only what the load is asking; but pay attention:
Up to 50A, it will give all the current the load will ask!!
So if you connect a LED and nothing else, you will see it turning into a plasma blob unless there is some protection mechanism; the principle is that you want also some protection in the case that your load is doing something strange.
So, it will work but pay attention to what you connect to it!


text:
Q: Installing module in python Annoconda "python setup.py egg_info" failed with error code 1 I am trying to install skdata module in Annoconda 2.2 verison
using
conda install skdata

But its throwing error as follows,

Error: Package missing in current linux-32 channels:
    - skdata

Also its the same when I tried with
pip install skdata

Command "python setup.py egg_info" failed with error code 1 in
  /tmp/pip-build-ivxxkvsc/skdata/

I tried many solutions as
 python ez_setup.py
 pip install --upgrade setuptools
 sudo pip install --upgrade setuptools

None of these helping me to get rid of the error this error :Command "python setup.py egg_info" failed with error code 1
 python --version
Python 3.4.4 :: Anaconda 2.2.0 (32-bit)

Any help is much appreciated

A: I had a similar issue and everytime I tried to launch Anaconda Navigator, it errored out. I tried everything but nothing seemed to work. Finally, when I was on the verge of giving up, I added the PATH to the pyqt5 and pyside folder and that did it for me. Everything got sorted, my package got installed and even Spyder started working. Took me 4 long days, but I finally got Anaconda and Spyder to work. Maybe you'll have some luck too.

A: There's not right now any skdata packages in the default conda channels or even on .
Pretty sure your the core issue is that skdata assume you're using python2, and you're trying to install in a python3 environment.
Try this:
conda create -y -n skdata-env python=2 scikit-learn pip
source activate skdata-env
pip install skdata


text:
Q: What is a way to solve this with loops in c++? I've been coding all night so my head is in a state of shock. I'm trying to do the following, but I just don't get what our professor wants us to do. "Input an unsigned and call it number.. Then input number double values, then output the sum and product of the numbers. (If number is zero, then 0 doubles will be input; the sum of 0 numbers is 0, and the product of 0 numbers is 1)"
I could really appreciate if someone could help me with this. Thank you.
Edit:
This is what i have so far, The thing I'm currently confused with is on how to make the unsigned variable be the number of double inputs inside of the loop.
unsigned number, x;
double double_num, sum;
cout << "Input the number of value: \n";
cin >> number;
for (x = 0; x > number; x++) {
    cin >> double_num;
}
return 0;

A: What're you having difficulty with?
Here's a start:
// Input an unsigned and
unsigned int g;
cout << "Please Enter an unsigned int value, g" << endl;
cin >> g;

In your loop, you have:
for (x = 0; x > number; x++) {

Which means:

x is set to Zero.
  While x is bigger than some-number, keep going...

When do you think zero is bigger than a number such as 5??
How many times do you think that loop will run??

int main(void)
{
    unsigned g;
    double product(1);
    double sum(0);

    cout << "Input the number of value: \n";
    cin >> g;
    for (unsigned x = 0; x < g; x++) {
        double n;
        cout << "Input a number: " <<endl;
        cin >> num;
        product *= num;
        sum += num;
    }

    cout << "The product is" << product << "\n";
    cout << "The sum is" << sum << "\n" << endl;;
    return 0;
}

A: You need something like the following:
#include<iostream>
#include<cstdlib>

int main()
{
    unsigned int n;
    std::cin >> n;
    double g, p=1, s=0;
    while (n-->0 && std::cin >> g) p*=g,s+=g;
    return std::cin
        ? std::cout << s << std::endl << p << std::endl, EXIT_SUCCESS
        : (std::cerr << "Failed to read all inputs" << std::endl, EXIT_FAILURE);
}

You should be sure that you understand each statement and be prepared to justify your choices; if not, you probably haven't learnt anything and will be unlikely to pass your course.


text:
Q: How to replace variable with string in jquery flot graph I am using Flot line graph which is working alright:
data1 = [
    [1430369878000, 1690.25],
    [1430369879000, 1696.3],
    [1430369880000, 1659.65]

];

data2 = [
    [1430369878000, 1682.1],
    [1430369879000, 1680.65],
    [1430369880000, 1685.1]

];

However when I replace data1 and data2 with :
 dataset = [{
         label: "Team Red",
         data: [
             [1430369878000, 1690.25],
             [1430369879000, 1696.3],
             [1430369880000, 1659.65]
         ],
         color: "#FF0000",
         points: {
             fillColor: "#FF0000",
             show: true
         },
         lines: {
             show: true
         }
     }, {
         label: "Team Blue",
         data: [
             [1430369878000, 1682.1],
             [1430369879000, 1680.65],
             [1430369880000, 1685.1],
             color: "#0062E3",
             points: {
                 fillColor: "#0062E3",
                 show: true
             },
             lines: {
                 show: true
             }
         }
     ];

It just wont work, what am I doing wrong?

A: You're missing a closing square bracket for your second data value. Try this instead:
dataset = [
    {
        label: "Team Red",
        data: [
            [1430369878000, 1690.25],
            [1430369879000, 1696.3],
            [1430369880000, 1659.65]
        ],
        color: "#FF0000",
        points: {
            fillColor: "#FF0000",
            show: true
        },
        lines: {
            show: true
        }
    }, {
        label: "Team Blue",
        data: [
            [1430369878000, 1682.1],
            [1430369879000, 1680.65],
            [1430369880000, 1685.1]
        ],
        color: "#0062E3",
        points: {
            fillColor: "#0062E3",
            show: true
        },
        lines: {
            show: true
        }
    }
];


text:
Q: Can we create Fail over clustering using sql server 2012 standard edition on amazon EC2? We are planing to move on amazon's EC2 services.
So my question is that can we create fail over clustering on amazon EC2 using sql server 2012 standard edition ?

A: Amazon EC2 is just a virtual server that you can run Windows or Linux on. If you have the skills required to setup SQL Server fail over then you should be able to create this on EC2.
You might want to also look at Amazon RDS Multi-AZ deployments, which manage a backup database server for you, and fail over to the backup server automatically. For SQL Server, Amazon RDS supports SQL Server 2008 R2, 2012 and 2014 including Express, Web, Standard and Enterprise editions.


text:
Q: How do I pseduo live-stream video using DASH non chronologically? I want to stream a local mp4 file to the DASH.js html5 player, but I want don't want to play this mp4 file chronologically. My requirement is that I create a never ending video stream from a single mp4. I figure that this is best done server side within the creation of the MPD manifest file. I don't know how to achieve this though. I believe that this stream demonstrates the wrapping behaviour.
How do I generate a manifest similar to this stream, and how do I format my mp4 correctly to achieve this?
I have tried making a server that intentionally sends the wrong segments but this causes playback to fail. I have also attempted to create a live stream MPD manifest using MP4Box but this also causes playback to fail.
mp4box -dash 1000 -profile dashavc264:live -dynamic -out DASH.mpd -mpd-duration 0 -mpd-refresh 10 -time-shift 0 -min-buffer 5 vid.mp4#video vid.mp4#audio

This produces:
<?xml version="1.0"?>
<!-- MPD file Generated with GPAC version 0.6.2-DEV-rev636-g4bd31f8-ab-suite   at 2016-07-05T14:20:26.756Z-->
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" minBufferTime="PT0.005S" type="dynamic" publishTime="2016-07-05T14:20:26Z" availabilityStartTime="2016-07-05T14:20:26.756Z" timeShiftBufferDepth="PT0H0M0.000S" minimumUpdatePeriod="PT0H0M10.000S" maxSegmentDuration="PT0H0M1.001S" profiles="urn:mpeg:dash:profile:isoff-live:2011,http://dashif.org/guidelines/dash264">
 <ProgramInformation moreInformationURL="http://gpac.io">
  <Title>DASH.mpd generated by GPAC</Title>
 </ProgramInformation>

 <Period id="GENID_DEF" start="PT0H0M0.000S">
  <AdaptationSet segmentAlignment="true" maxWidth="1280" maxHeight="720" maxFrameRate="24000/1001" par="16:9" lang="und">
    <Representation id="1" mimeType="video/mp4" codecs="avc3.64001f" width="1280" height="720" frameRate="24000/1001" sar="1:1" startWithSAP="1" bandwidth="1428068">
    <SegmentTemplate timescale="24000" media="vid_dash_track1_$Number$.m4s" startNumber="1" duration="24000" initialization="vid_dash_track1_init.mp4"/>
   </Representation>
  </AdaptationSet>
  <AdaptationSet segmentAlignment="true" lang="eng">
   <Representation id="2" mimeType="audio/mp4" codecs="mp4a.40.2" audioSamplingRate="32000" startWithSAP="1" bandwidth="97557">
    <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="2"/>
    <SegmentTemplate timescale="32000" media="vid_dash_track2_$Number$.m4s" startNumber="1" duration="32000" initialization="vid_dash_track2_init.mp4"/>
   </Representation>
  </AdaptationSet>
 </Period>
</MPD>

The HTML5 player won't play any content, however, it will attempt to refetch the manifest in the correct manner. I'm not really sure what is going wrong, and what I need to do to replicate the stream above.

A: -time-shift needs to be set to a value higher than 0. E.g., set it to 60.
It means the available time of each segment after it is streamed.


text:
Q: Saving a Linq Query and Using When Resuming from Tombstoning I have a List of 500 objects that are queried against. When tombstoning, rather than save those 500 object to State, I'm wanting to save the query itself so that upon returning, I can just plug that into my class that shows the query of the 500 objects.
So if I have Dim pictures = (From s In p.AllPictures Where s.IsFavorite = True Order By s.Index Ascending).ToList, how can I save just the query itself to State so that upon returning from tombstoning I can assign that query to pictures?

A: You can't save a query per say, as the query is code and not data. You probably mean to assign the result of the query?
Simply save your pictures variable to the State rather than the p.AllPictures.


text:
Q: How to correctly use a series of independent if statements in python to get correct output? I am aware of the if-elif-else route but I felt this should work too.
please help me find my mistake. Made several attempts and finally no longer getting syntax or indentation errors but still getting wrong output.
My code:
cars = [ 'Audi' , 'bMw' , 'mercedes' , 'toyota' , 'soobie' ]

for car in cars:
    if car.lower() == 'bmw':
        print(car.upper())
        print("Your car's fast")

    if car.lower() == 'soobie':
        print("Subaru")
        print("You're probably a ricer")

    if car.lower() != 'bmw' and car.lower() in cars != 'soobie':
        print(car.title())
        print("Good choice!")

Intended output:

Audi
Good choice!
BMW
Your car's fast
Mercedes
Good choice!
Toyota
Good choice!
Subaru
You're probably a ricer

A: your wrong output is because of third if statement. It can be corrected as follows with elif.
cars = [ 'Audi' , 'bMw' , 'mercedes' , 'toyota' , 'soobie' ]

for car in cars:
    if car.lower() == 'bmw':
        print(car.upper())
        print("Your car's fast")

    elif car.lower() == 'soobie':
        print("Subaru")
        print("You're probably a ricer")

    elif car.lower() != 'bmw' and car.lower() != 'soobie':
        print(car.upper())
        print("Good choice!")


text:
Q: Delphi - does Intellisense pick up record helpers? I ended up using record helpers as a workaround to the fact that Delphi does not allow forward declarations of record types.
At least it compiles, but am rather unhappy with the fact that Intellisense does not pickup these helper methods:
Extents.TransformBy(Matrix);

TransformBy is a helper method. The code above compiles just fine, however TransformBy does not show up in the Intellisense List at all. I restart the IDE just in case, but still no luck. Am using Delphi XE 2.
I found the following statement regarding class helpers:

Really a class helper is a compiler trick, behind the scenes it is
  just functions operating on the class, but it doesn't polute the name
  space, and works with intellisense.

http://blogs.conceptfirst.com/blog/2006/05/08/class-helpers-good-or-bad/
So I still have some hope that this might eventually work.

A: In XE2, methods declared in record helpers do not show up in the list of available methods that appears when you type . and/or press CTRL+space. It seems, according to my experiments, that XE5 resolves the issue and XE5 Intellisense can see helper methods.
If only Embarcadero would allow forward declarations of records so that we would not need to resort to record helpers to make our types behave.


text:
Q: Difference between family = gaussian() and family = cox.ph(link='identity') in GAM and family = binomial(link="logit") I wonder how do u decide if family = gaussian() or family = cox.ph(link='identity') or family = binomial(link="logit") in GAM ( generalized additive model ) is suitable for the analysis? For my case, my dependent variable is in the form of percentage from 0 - 100%. Stage is a form of time variable. comparison_type is the two different activities performed by the same individual over a specific stage, which means time.
My end goal is to see if there is any significant difference in patterns between the two activities performed by the same individual over time.
library(gam)
library(mgcv)

b <- gam(ssim_exp ~ s(stage, k = 4, fx = TRUE, by = comparison_type) + comparison_type, data = df, family = cox.ph(link='identity'))
summary(b)

The distribution of my dependent variable looks like the below

Any input?

A: The choice of the conditional distribution of the response should be motivated by the features of the response variable you are modelling. The Gaussian distribution can be used for data that are continuous and over the whole real line (not integers and can be positive or negative), whereas the gamma, inverse Guassian, or Tweedie distributions are for positive (non-negative in the Tweedie case) continuous random variables. Distributions such as the Poisson or negative binomial are for non-negative, integer valued responses. Binomial is for counts from a total (number of heads out of m coin tosses, for example). The Cox PH family is for modelling survival data (time to event data), where you are interested in modelling the hazard of an event.
None of these distributions are suitable for the data you describe, which are bounded at some upper and lower value, but are continuous between the two bounds. If the data were recast to the interval 0-1, then you could look at the beta distribution (family = betar()) in {mgcv}, but you can't have true 0s and 1s (100%) in that family ({mgcv} will adjust the data so that the 0s are just slightly greater than 0, and the 1s slightly less than 1). If you have many such values, then zero-one-inflated beta models (which combine separate models for the 0s, 1s, and everything else) would be a starting point. But that distribution is not available in {mgcv}; you could look at {brms} for example as an option in that case.
I've taken you to have a continuous bounded value as the response, but there is some wiggle-room in your use of "form of"; if there is something specific you think we should know then edit your question to include it.


text:
Q: Javascript Classes - Accessing a function on the fly I have a javascript class:
MyClass = function(){
    this.m_SomeData = 5;
};

and I have created some functions for that class:
MyClass.prototype.MyClassFunction_1 = function(arg){
    // Some stuff that can return false
    return true;
};
MyClass.prototype.MyClassFunction_2 = function(arg){
    // Some stuff that can return false
    return true;
};
MyClass.prototype.MyClassFunction_3 = function(arg){
    // Some stuff that can return false
    return true;
};

Later on I have created an instance of that class. (They could be combined into a single function but there are design issues that make it nicer to separate them):
var myInstance = new MyClass();

Now the tricky bit. In an 'if' statement I am doing the following (as well as other stuff).
var funcUse;
var arg = 3; // Some value created at run time)
if((funcUse = val === 0 ? MyClassFunction_1
                        : (val === 1 ? MyClassFunction_2 : MyClassFunction_3)) !== "undefined" &&
    myInstance.funcUse(arg)){
}

The obvious problem is in the 'if' statement MyClassFunction_? are all undefined as they should be tied to an instance of the class, eg myInstance.MyClassFunction_?.
So how can this be done nicely in an if statement?

A: You can do this:
var funcUse =
    val === 0 ? 'MyClassFunction_1' :
    val === 1 ? 'MyClassFunction_2' :
    'MyClassFunction_3';

if (myInstance[funcUse] && myInstance[funcUse](arg)) {
    ...
}

Dot notation (obj.property) is just syntactic sugar for obj["property"], so you can simply make funcUse a string.

Alternatively, you can also do this:
var funcUse =
    val === 0 ? myInstance.MyClassFunction_1 :
    val === 1 ? myInstance.MyClassFunction_2 :
    myInstance.MyClassFunction_3;

if (funcUse && funcUse.call(myInstance, arg)) {
    ...
}

This extracts the function from the myInstance object, but then you have to be careful with calling funcUse to make sure myInstance is passed as this.

A: Don't worry about "classes"/inheritance, the problem you want to solve is really two more simple ones,

*

*Accessing a property of an Object dynamically

*Choosing the context/this of a function
You have a couple choices about which pattern to use

fn.call / fn.apply
var o = {foo: 'bar'};

function fizz() {return this;}

fizz.call(o); // returns `o`, Object {foo: 'bar'}

Bracket notation
var o = {foo: function () {return this}};

o['foo'](); // returns `o`

In your particular case I'd probably go with a switch..case or if..else pattern to decide on the property name, then invoke with bracket notation;
var method;
switch (val) {
    case 0: method = 'foo'; break;
    case 1: method = 'bar'; break;
}

if (method)
    o[method]();


text:
Q: Query with a list of embedded primary keys I'm trying to query for a list of objects using a list of embedded primary keys. Something like this:
User.java
public class User {
   @EmbeddedId
   protected UserPK userPK;

   //getter & setters...
}

UserPK.java
@Embeddable
public class UserPK {
    @Column(name = "id")
    private Long id;

    @Column(name = "group")
    private String group;

    //getter & setters...
}

UserDao.java
public List<Long> getUsersById(List<UserPK> ids) {
    TypedQuery<User> q = entityManager.createQuery(
        "SELECT u FROM User AS u WHERE u.userPK IN :ids", User.class);
    q.setParameter("ids", ids);
    return q.getResultList();
}

Basically, I'm querying for multiple users, lets say:
id=1 group="it"
id=2 group="eng"
How can I query Users with a list of composite primary keys?

A: What you did is totally fine, although there is a minor correction needed on the return type of getUsersById method, which should be List<User> instead of List<Long>.
You can query using a list of UserPKs objects and use that as a parameter to your IN operator. So the query below (like you did) will work fine:
public List<User> getUsersByIdCombo(List<UserPK> ids) {
    TypedQuery<User> q = entityManager.createQuery("SELECT u FROM User AS u WHERE u.userPK IN :ids", User.class);
    q.setParameter("ids", ids);
    return q.getResultList();
}

You can also query by traversing the embedded id class explicitly (userPK.id or userPK.group). Here are samples below:
public List<User> getUsersById(List<Long> ids) {
    TypedQuery<User> q = entityManager.createQuery("SELECT u FROM User AS u WHERE u.userPK.id IN :ids", User.class);
    q.setParameter("ids", ids);
    return q.getResultList();
}

public List<User> getUsersByGroup(List<String> groups) {
    TypedQuery<User> q = entityManager.createQuery("SELECT u FROM User AS u WHERE u.userPK.group IN :groups", User.class);
    q.setParameter("groups", groups);
    return q.getResultList();
}

public User getSingleUserByIdAndGroup(Long id, String group) {
    TypedQuery<User> q = entityManager.createQuery("SELECT u FROM User AS u WHERE u.userPK.id = :id AND u.userPK.group = :group", User.class);
    q.setParameter("id", id);
    q.setParameter("group", group);
    return q.getSingleResult();
}

Let's see how these queries behave by testing each method. Let's say we have this data on your USER table.

Example 1: Query users by list of UserPK objects
    List<UserPK> userPKs = new ArrayList<UserPK>();
    userPKs.add(new UserPK(1L, "it"));
    userPKs.add(new UserPK(4L, "eng"));
    List<User> userListQuery1 = userDAO.getUsersByIdCombo(userPKs);
    for (User user: userListQuery1) {
        System.out.println(user);
    }

Result:
ID: 4 | GROUP: eng
ID: 1 | GROUP: it

Example 2: Query users by List of ids
    List<Long> ids = new ArrayList<Long>();
    ids.add(2L);
    ids.add(5L);
    List<User> userListQuery2 = userDAO.getUsersById(ids);
    for (User user: userListQuery2) {
        System.out.println(user);
    }

Result:
ID: 5 | GROUP: eng
ID: 2 | GROUP: it

Example 3: Query users by list of groups
    List<String> groups = new ArrayList<String>();
    groups.add("it");
    groups.add("eng");
    List<User> userListQuery3 = userDAO.getUsersByGroup(groups);
    for (User user: userListQuery3) {
        System.out.println(user);
    }

Result:
ID: 4 | GROUP: eng
ID: 5 | GROUP: eng
ID: 1 | GROUP: it
ID: 2 | GROUP: it

Example 4: Query single user by id and by group
    User user = userDAO.getSingleUserByIdAndGroup(3L, "hr");
    System.out.println(user);

Result:
ID: 3 | GROUP: hr


text:
Q: Ubuntu 20.04 changing brightness I recently installed Ubuntu 20.04 on a new Dell Vostro and I'm facing a screen brightness issue. It seems that the brightness is adjusted based on the current window. If it's brighter, the rest of the screen (like the bottom bar) gets darker, and the other way around. Consequently, it is most apparent when selecting a text in terminal or in Intellij Idea (selecting text makes the background go darker).
See it in action here:
https://makeagif.com/gif/ubuntu-brightness-afO1vb
For some reason it's way less visible here than in real life, but you should get an idea about the issue. I tried a bunch of things, but none of them worked. Any ideas?

A: I have a Dell Inspiron 15 7501, and I experienced the same "issue" both on Ubuntu 20.04 and Pop!_Os 20.04.
I have BIOS version 1.4.1 and I found there the option "Eco Power" or something like that on Display settings. I disabled that and It worked for me.
Edit: Actually there is the possibility of upgrading the BIOS to newer version, 1.5.1. I am not sure which version you have, but I hope they did not change the name of that option above.


text:
Q: Why Netcoreapp3.1 not Compatible with net5.0 Class Library As per my understanding, net5.0 is compatible with both netcoreapp and older .net versions.
I am trying to create an Azure function that targets netcoreapp3.1 and use a library that was built targetting net5.0. However, I am getting the following error, which indicates there is incompatibility issues.

Error NU1202  Package XXX is not compatible with netcoreapp3.1 (.NETCoreApp,Version=v3.1).
Package XXX supports: net5.0 (.NETCoreApp,Version=v5.0)

I have quoted the above from VS 2019 but replaced package name with XXX for privacy. The two strings in bracket are verbatim and I am not clear why net5.0 is being listed as .NETCoreApp, Version 5.0.
Could someone explain what is going on and if there is anything I have misunderstood?

A:
As per my understanding, net5.0 is compatible with both netcoreapp and older .net versions.

Yes, but not the other way round. There are things in .NET 5.0 which aren't in .NET Core 3.1.
You can target a framework for an application and then use a library targeting an earlier framework, but not the other way round. So for example, it would be fine for your Azure function to target .NET 6.0 and use a library targeted at .NET 5.0.
Basically, to solve your problem you'll either need to use a different library (or an earlier version of the library which targeted .NET Core 3.1, or maybe .NET Standard) or update to a more recent runtime.


text:
Q: How to query a table from different databases without using alias of database? I am doing task of retrieving the data from both database tables,I included following query to achieve it.
Query in stored procedure:
--Some query here...
LEFT OUTER JOIN     aaa c
ON                  l.IDNo      = c.LogonIDNo
INNER JOIN          Data_00.dbo.yyy A
ON                  C.MacCusNo  = A.Cus_no
LEFT OUTER JOIN     abc T
ON                  A.xyz       = T.bbb

Tables:
aaa : table of database Data_01
yyy : table of database Data_00

Is there any way to retrieve the data from both the database tables without using 'Data_00.dbo.yyy' I want to use only yyy instead of it.

A: I'll assume you're using SQL Server.
Yes, you can create a synonym. Synonyms allow you to specify a shorthand name for accessing various database objects, whether they reside in the same database as the synonym rule or not.
USE Data_01;

CREATE SYNONYM yyy FOR Data_00.dbo.yyy;


text:
Q: Binary Calculator Assignment (Java) Here is the description of the requirements for the assignment:
For this lab, you will enter two numbers in base ten and translate them to binary. You will then add the numbers in binary and print out the result.
All numbers entered will be between 0 and 255, inclusive, and binary output is limited to 8 bits. This means that the sum of the two added numbers will also be limited to 8 bits. If the sum of the two numbers is more than 8 bits, please print the first 8 digits of the sum and the message "Error: overflow".
Your program should represent binary numbers using integer arrays, with the ones digit (2^0) stored at index 0, the twos digit (2^1) stored at index 1, all the way up to the 2^7 digit stored at index 7.
Your program should include the following methods:
int[] convertToBinary(int b)Translates the parameter to a binary value and returns it stored as an array of ints.
void printBin(int b[])Outputs the binary number stored in the array on one line. Please note, there should be exactly one space between each output 0 or 1.
int[] addBin(int a[], int b[])Adds the two binary numbers stored in the arrays, and returns the sum in a new array of ints.
When entering my code into CodeRunner (which tests the code and returns a grade back depending on the results of each test) I cannot seem to pass one of the tests. This is the message that I am getting:
*You had 43 out of 44 tests pass correctly.
Your score is 97%.
The tests that failed were:
Test: addBin() method
    Incorrect: Incorrect number returned*
Heres my code:
import java.util.Scanner;

class Main {
public static int [] convertToBinary(int a){
int [] bin = {0,0,0,0,0,0,0,0};
for(int i = bin.length-1; i >= 0; i--){
 bin[i] = a%2;
 a = a/2;
}
return bin;
 }

public static void printBin(int [] b){
int z;
    for(z=0; z < b.length; z++){
      System.out.print(b[z] + " ");
    }
    System.out.println();
}

public static int [] addBin(int [] c, int [] d){
int [] added = new int [8];
int remain = 0;
for(int x = added.length -1; x >= 0; x--)
{
 added[x] = (c[x] + d[x] + remain) % 2;
 remain = (c[x] + d[x] + remain)/2;
}
if (added[0] + c[0] + d[0] == 1){
added[0] = 1;
}
else if( (added[0] + c[0]+ d[0] == 2) || (added[0] + c[0]+ d[0] == 3) )
{

System.out.println("Error: overflow");
}
//System.out.println(added);
//don't need to print added, but it is the only way to check it
return added;
}

public static void main(String[] args){
Scanner scan = new Scanner (System.in);
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
int num1 = scan.nextInt();
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
int num2 = scan.nextInt();

int [] bin;
bin = convertToBinary(num1);
System.out.println("First binary number:");
printBin(bin);
int [] bin1 = bin;

bin = convertToBinary(num2);
System.out.println("Second binary number:");
printBin(bin);
int [] bin2 = bin;

System.out.println("Added:");
{
printBin(addBin(bin1,bin2));
}
 }}

If anyone could take a look at my code above and see if they could tell me what needs to be changed to fix the addbin() method so that it passes all of the tests, that'd be great! Any help is greatly appreciated even if you are not sure it would work! Thanks!

A: You are adding in the wrong direction.

ones digit (2^0) stored at index 0, the twos digit (2^1) stored at index 1, all the way up to the 2^7 digit stored at index 7

This means that:
int[] num1 = {1,0,1,0,0,0,0,0}; // 5
int[] num2 = {0,1,1,0,1,0,0,0}; // 22
int[] res = addBin(num1, num2); // 27 = {1,1,0,1,1,0,0,0}

You are adding from the end, rolling carryovers to the left:
  {  1,0,1,0,0,0,0,0}
+ {  0,1,1,0,1,0,0,0}
= {1,0,0,0,0,1,0,0,0} // Error: overflow


text:
Q: When stopping a service, what's the difference between "Services.msc" and "Task Manager"? When I tried to stop a service with "Task Manager > Services" on Windows 7, it failed saying "Access Denied". But when I tried with "Services.msc", it succeeded. I used the name user.
Why could "Services.msc" succeed when "Task Manager" fails? What's the difference between them?
Do they have different permissions or something like that?

A: You are most likely member of the Administrators group and your UAC settings are set to default.
In this case your user gets elevated and Servicesist started in the real administrator context of your user. Due to the mentioned settings you are not prompted to allow that.
You may set the UAC to the highest level and will be prompted then to allow this operations though.
In contrast, Task Manager always starts in the context of the current user without an upgrade.

A: Services.msc requires admin rights to modify(run, start, stop, etc.) any of the objects in its list, while task manager does not necessarily require admin rights to modify every one of the processes in its list. You can run task manager with admin rights to end certain processes that require system level privileges.


text:
Q: Pandas returning empty dataframe after merge I'm attempting to merge multiple sets of word data. Each csv file that is read in (there is 4 files) contains a column for each unique word in a book, and a column for how many times that word shows up. Whats supposed to happen is the word columns of all of these csv files are supposed to merge into one in this new matrix file I'm trying to create, but when I attempt to merge each csv file and its data, an empty data frame is returned.
The csv files are like:
Word Count
Thou   100
O      20
Hither 8

and I want them to merge like this:
Word  Book1  Book2 Book3
Thou   50     0      88
Hello  32     35     27
No     89     38      0
Yes    80     99       0

import os
from os import listdir
from os.path import isfile, join

import pandas as pd

dataPath = 'data/'
fileNames = [f for f in listdir(dataPath) if isfile(join(dataPath, f))]
columns = [os.path.splitext(x)[0] for x in fileNames]
columns.remove('rows')
columns.remove('cols')
columns.remove('matrix')
columns.insert(0, "Word")
wordData = []
matrix = pd.DataFrame(columns=columns)

for file in fileNames:
    if '.txt' in file:
        continue
    elif 'matrix' in file:
        continue
    else:
        myFile = open(f"./data/{file}", "r")
        readFile = myFile.read()
        dataVector = pd.read_csv(f"./data/{file}", sep=",")
        #print(dataVector)
        matrix.merge(dataVector, how="outer", on=["Word"])
        print(matrix)
        myFile.close()

pd.set_option("display.max_rows", None, "display.max_columns", None)
matrix = matrix.fillna(0)
matrix.to_csv(path_or_buf="./data/matrix.csv")

A: I think this may be the thing you needed.
Data:
import pandas as pd

book_list = []
book_list.append(pd.DataFrame({'Word': ['a', 'b'], 'Count': [1, 2]}))
book_list.append(pd.DataFrame({'Word': ['b', 'c'], 'Count': [3, 4]}))
book_list.append(pd.DataFrame({'Word': ['d', 'e', 'f'], 'Count': [5, 6, 7]}))
book_list.append(pd.DataFrame({'Word': ['c', 'e'], 'Count': [8, 9]}))

Code:
result = None
for idx_book, book in enumerate(book_list):
    if result is None:
        result = book
    else:
        result = result.merge(book, how="outer", on=["Word"], suffixes=(idx_book-1, idx_book))

Result:
    Word    Count0  Count1  Count2  Count3
0   a   1.0 NaN NaN NaN
1   b   2.0 3.0 NaN NaN
2   c   NaN 4.0 NaN 8.0
3   d   NaN NaN 5.0 NaN
4   e   NaN NaN 6.0 9.0
5   f   NaN NaN 7.0 NaN

A: Ended up solving it by using this lambda function:
matrix = reduce(lambda  left,right: pd.merge(left,right,on=['Word'],how='outer'), wordData).fillna(0)


text:
Q: Lifting Laplacian Eigenfunctions Suppose that $\mathbb{H}$ is the hyperbolic plane and $\Gamma$ is a discrete group of orientation-preserving isometries of $\mathbb{H}$ such that $M=\Gamma\setminus\mathbb{H}$ is a compact hyperbolic surface.
Given the Laplacian on $M$, by compactness, $L^2(M)$ has an orthonormal basis of Laplacian eigenfunctions $\{\psi_{\lambda_i}\}_{i\geq 0}$ with
\begin{align*}
 \Delta\psi_{\lambda_i} = \lambda_i\psi_{\lambda_i},
\end{align*}
and $0=\lambda_0<\lambda_1\leq\ldots\to\infty$. Given one of these eigenfunctions say $\psi_\lambda$, one can lift it to a function $\tilde{\psi}_\lambda$on $\mathbb{H}$ through the covering map.
From what I understand, $\tilde{\psi}_\lambda$ is an eigenfunction of the Laplacian on $\mathbb{H}$. However, I am confused since the spectrum of the Laplacian on $\mathbb{H}$ is $[\frac{1}{4},\infty)$ where as the spectrum of the Laplacian on $M$ is contained in $[0,\infty)$ (and certainly $0$ is an eigenfunction as constants on $M$ have eigenvalue zero). However, would this not imply that (for instance) I can lift $L^2$ eigenfunctions on $M$ with eigenvalue in $[0,\frac{1}{4})$ to eigenfunctions on $\mathbb{H}$ with the same eigenvalue, contradicting the spectrum of $\mathbb{H}$?
I think the solution to this is that $[\frac{1}{4},\infty)$ is the $L^2$ spectrum of the Laplacian on $\mathbb{H}$ and the lifts of these $L^2$ eigenfunctions on $M$ won't necessarily be $L^2$ eigenfunctions on $\mathbb{H}$ (just smooth functions satisfying the eigenvalue equation). Is this true?


text:
Q: Setting browser home page administratively We have a requirement to use a single browser homepage across our whole organisation.  This isn't a problem for our IE users, thanks to group policy, but we have several Firefox/Opera/Chrome users, and as far as I can tell, there isn't a way of administratively setting the homepages on those browsers, either through the registry or by adding/manipulating files on the user's PC.
Does anyone know any different?

A: Firefox I know has a group policy template you can get called FirefoxADM, not sure how up-to-date it is but there's an ADM to ADMX migrator around there somewhere if needed ^^
Obviously, if the end-users are free to install and/or run whatever application they want, this cannot be 100% enforced, eg. FirefoxADM won't work with portable installations and so on.

*

*Google Chrome - haven't really found anything but building on their Google Update templates might be a start.


text:
Q: reading azure pipeline environment variables in c# I have set environment variable in azure yaml pipeline like this
- task: PowerShell@2
  inputs:
targetType: 'inline'
script: |      $env:MY_VARIABLE = "$(my-value)"
$env:MY_VARIABLE >> test.txt
...

when I run the pipeline and go to published artifact in summary section of the pipeline, I can see that test.txt has correct value. Is there a way I can read  this MY_VARIABLE in c# code, which is going to be run with a specflow task in this yaml pipeline

A: You can't read Azure Pipelines variable directly in C#. However, each Azure Pipeline variable is mapped to an environment variable (except for secrets). You can read about this here.
So, all that you need is Environment.GetEnvironmentVariable.
And of course you need to run your code on pipeline, not compile create package and then run somewhere else.

A: Found that by using env: in task like below we can have compiled C# code ( in my case running on ms hosted agent)  read the variables directly.
- task: VSTest@2
  displayName: tests
  env:
    MY_VARIABLE = "$(my-value)"

and then in c# code we can do like this
 string  var= Environment.GetEnvironmentVariable("MY_VARIABLE", EnvironmentVariableTarget.Process);

Note that without using env: , it may not work


text:
Q: How to get system, user info with pure qml linux I am preparing pure qml plasmoid for my new panel appereance in KDE Plasma 4 and I have to use at most Qt 4.7 library and Qt.Quick 1.1 for that. Is it possible to pick up current user's fullname?
Is there any plasma API related to that like PlasmaCore or KSM etc. or any PlasmaCore datasource engine like the following:
#import org.kde.PlasmaCore 0.1 PlasmaCore
{
  Item{
      PlasmaCore.DataSource{
          engine  : "SystemInformation"
          connection : "get_user_fullname"
      }
  }
}

Or should I build a service like this? What are your suggestions, and thoughts?

A: I figured out ! I did create custom Data Engine that provides user's info over qdbus bridge you can learn basics of it from here : https://techbase.kde.org/Development/Tutorials/Plasma4/DataEngines @douyw basically misunderstood the question and i do not know who minused the question. Anyway , its an important issue for new generation of qml developing , making Data Engines is simply making API.

A: Anything can be exported into qml context via a cpp wrapper. The following sample code snippets are copied from official doc(Qt4.8).
1) Write a wrapper class:
In this example, it exports current datetime. You can export your stuff in a similar way.
class ApplicationData : public QObject
{
    Q_OBJECT
public:
    Q_INVOKABLE QDateTime getCurrentDateTime() const {
        return QDateTime::currentDateTime();
    }
};

2) Export the wrapper class via qml context:
int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    QDeclarativeView view;

    ApplicationData data;
    view.rootContext()->setContextProperty("applicationData", &data);

    view.setSource(QUrl::fromLocalFile("MyItem.qml"));
    view.show();

    return app.exec();
}

3) Use it in qml file(MyItem.qml):
import QtQuick 1.0

Text { text: applicationData.getCurrentDateTime() }

That's it!


text:
Q: Array Loop Assuming Nil Data? I've created an auto-populating array in a counted loop for each month using timestamps, e.g 2016-06-11 00:00:00 - the database layout that the loop is fetching from is:
TimeRecord          | Views
2016-06-11 00:00:00 | 22
2016-08-11 00:00:00 | 44

Now, the above example skips the 07 (July) month, there is NO DATA for this month, and so when the loop goes through this month, it should return either null or 0, but it returns the previously known number (which is 22 in this case).
For 2016-09, there is no specified data, so the array will give "44".
The code for the loop and fetching from the database to generate the array is like so:
$startMonth = date("y-m-d");
$endMonth = date("y-m-d");

while ($Month <= 12){

$ViewsThisMonth = mysqli_fetch_object(mysqli_query($db, "SELECT    SUM(Views) AS NumberFinalViews, EXTRACT(YEAR_MONTH FROM TimeRecord) AS YearMonth FROM BlogViews WHERE TimeRecord > '$startMonth' AND TimeRecord < '$endMonth' GROUP BY YearMonth"));

if (is_null($ViewsThisMonth->NumberFinalViews)){
$ViewsThisMonth->NumberFinalViews = 0;
}

$ArrayTimeStamp[] = $ViewsThisMonth->NumberFinalViews;
$Month = $Month + 1;
$startMonth = date("y-m-d",strtotime("-$Month month"));
}

An example returned JSON Encoded Array is:
[0,"29392","333","4000","4000","99","99","99","99","99","99","99"]

A screenshot of the database values that caused the above array can be found here. As you can see, 4000 repeats itself twice as there is no record for the 5th month, causing it to use the 4th month's data. 99 is also repeated, as there are no values for the 6th-12th month, therefore it uses the 6th month's value instead of returning a 0.
If there is no TimeRecord for that month when the loop goes through, I want it to return 0, not assume that the view number is the same as the previous month.

A: The problem is that you perform the same query multiple times, albeit with a changing date. The query is designed to give a result for several months, yet you only use one of the result rows. As there is no order by clause, it could be that you get the rows in an unexpected order. Also the way you change the start date in the loop is strange: it moves backwards in time.
It would be better to execute the query only once, and then store the results into a prepared array that is keyed by month-year.
Note that you can perform the null check in the SQL query itself with COALESCE.
The code becomes something like this:
$startYearMonth = date('Ym', strtotime("2015-01-01")); // set this date as you wish
$endYearMonth = date('Ym', strtotime("now"));

// Prepare result array: one entry per month, with all values set to 0
for ($yearMonth = $startYearMonth; $yearMonth <= $endYearMonth;
                                   $yearMonth += ($yearMonth % 100 == 12 ? 89 : 1)) {
    $months[$yearMonth] = 0;
}

// improved query
$result = mysqli_query($db, "
    SELECT   COALESCE(SUM(Views), 0) AS NumberFinalViews,
             EXTRACT(YEAR_MONTH FROM TimeRecord) AS YearMonth
    FROM     BlogViews
    WHERE    EXTRACT(YEAR_MONTH FROM TimeRecord)
                   BETWEEN '$startYearMonth' AND '$endYearMonth'
    GROUP BY YearMonth");

// Featch and store each result in their proper year-month slot
while ($ViewsThisMonth = mysqli_fetch_object($result)) {
    $months[$ViewsThisMonth->YearMonth] = $ViewsThisMonth->NumberFinalViews;
}

// output the result
print_r($months);


text:
Q: Kendo grid columns not displaying field off of a JSON object I have a kendo grid, defined as such:
$("#auditGrid").kendoGrid({
height: 650,
width: 650,
sortable: true,
filterable: true,
resizable: true,
columns: [
     { field: "ChangeTypeDescription", title: "Change Type" },
     { field: "LevelDescription", title: "Level" },
     { field: "Site.ShortName", title: "Site", width: "100px", },
     { field: "TimeStampLocal", title: "Date", type: "date", format: "{0: yyyy-MM-dd HH:mm:ss}" }
]
});

However, the column labelled "Site" does not display anything, even when I know there should be something there. Setting the field as "Site" instead of "Site.ShortName" shows a value of [object Object], but whenever I try to display ShortName off of Site, it shows an empty column. All other columns display properly.
Does anyone have any insight as to why this is happening?
The datasource schema, in case you need to see it:
schema: {
    model: {
        fields: {
            ChangeTypeDescription: { type: "string" },
            LevelDescription: { type: "string" },
            Site: { type: "string" },
            TimeStampLocal: { type: "date" }
        }
    }
},

A: You needs to use the template functionality for achieving it, just change the column description of the field Site as follows
{ field: 'Site', title: 'Site', template: '#= Site.ShortName# '}


text:
Q: Mathematica table error messages For the following (some package-related statements omitted):
CartesianMap[ func_, {x0_,x1_,dx_}, {y0_,y1_,dy_} ] =
  Module[ { x, y, tx, ty, llpx, llpy},
    tx = Table[{Re[func[x + I y]], Im[func[x + I y]]},
                  {x, x0, x1, dx}, {y, y0, y1, dy}];
    ty = Table[{Re[func[x + I y]], Im[func[x + I y]]},
                  {y, y0, y1, dy}, {x, x0, x1, dx}];
    llpx = ListLinePlot[tx];
    llpy = ListLinePlot[ty];
    Show[ llpx, llpy, Axes -> True, AspectRatio -> Automatic,
                 ImageSize -> Large]
  ]

CartesianMap[ Cos, { 0.2, Pi - 0.2, (Pi - 0.4)/19}, {-2, 2, 4/16}]

When I execute:
In[99]:= << CartesianMap1.m

I get the following errors:
During evaluation of In[99]:= Table::iterb: Iterator {x$31836,x0,x1,dx} does not have appropriate bounds. >>

During evaluation of In[99]:= Table::iterb: Iterator {y$31836,y0,y1,dy} does not have appropriate bounds. >>

During evaluation of In[99]:= ListLinePlot::lpn: Table[{Re[func[x$31836+I y$31836]],Im[func[x$31836+I y$31836]]},{x$31836,x0,x1,dx},{y$31836,y0,y1,dy}] is not a list of numbers or pairs of numbers. >>

During evaluation of In[99]:= ListLinePlot::lpn: Table[{Re[func[x$31836+I y$31836]],Im[func[x$31836+I y$31836]]},{y$31836,y0,y1,dy},{x$31836,x0,x1,dx}] is not a list of numbers or pairs of numbers. >>

During evaluation of In[99]:= Show::gcomb: Could not combine the graphics objects in Show[ListLinePlot[Table[{Re[func[x$31836+Times[<<2>>]]],Im[func[x$31836+Times[<<2>>]]]},{x$31836,x0,x1,dx},{y$31836,y0,y1,dy}]],ListLinePlot[Table[{Re[func[x$31836+Times[<<2>>]]],Im[func[x$31836+Times[<<2>>]]]},{y$31836,y0,y1,dy},{x$31836,x0,x1,dx}]],Axes->True,AspectRatio->Automatic,ImageSize->Large]. >>

**************************************************************
End error messages.

*

*The generated graphics are good.

*The problem is that at compile time the iterators for table are arguments, so not defined.  The check should be at run time, not compile time. Poor decision by Wolfram.

*Prefixing all statements with Quiet[...] is ugly.

*Is there a clean solution to the messages?

A: Functions should be defined with SetDelayed (:=), i.e.
CartesianMap[func_, {x0_, x1_, dx_}, {y0_, y1_, dy_}] :=
  Module[{x, y, tx, ty, llpx, llpy},
  tx = ...


text:
Q: Android SSLProtocolException and unexpected end of stream on Connection on OkHttp There is very low probability to produce "HTTP FAILED: javax.net.ssl.SSLProtocolException: Read error: ssl=0xdfa6e140: Failure in SSL library, usually a protocol error
error:100000d7:SSL routines:OPENSSL_internal:SSL_HANDSHAKE_FAILURE (external/boringssl/src/ssl/ssl_lib.c:710 0xe57a3144:0x00000000)" and "unexpected end of stream on Connection{xmart.xiaopeng.com:443, proxy=DIRECT hostAddress=xmart.xiaopeng.com/118.31.212.217:443 cipherSuite=TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 protocol=http/1.1}".

A: Our company's certificate is saved at the android assets folder and we will validate it with server's.
So I think as you said, our company just want to work with our company's certificate rather than other additional certificates.
So How can I avoid this similar exception? These SSLProtocolExceptions will happen at very low probability.(not 100% happen, the happen probability maybe 1%)
I search this SSLProtocolException with "error:100000d7" in Google and Baidu. there are very few people encounter these similar exceptions(because the error code is error:100000d7, this error code is very few in the google search).


text:
Q: Apscheduler run job every weekday on specific time range I have a current apscheduler that runs the job mon-fri and an interval of ~4 mins all day long. Is it possible to run the job for a specific time range? Lets say from 9:00 am to 5:00 pm in this case?
My expression looks like this:
scheduler.add_job(feed_data, 'cron', day_of_week='mon-fri', minute='*/3', jitter=30)

Is it possible to add start/end datetime to this expression?

A: You can just add hour='9-17' to accomplish that.


text:
Q: Book/article recommendations for an introduction to hypergroups and subsequent research I'm a grad student and I'm choosing an area to follow on my doctorate (in?) and I've been thinking about extension of topological group theory results to topological hypergroups, but for that I need to be introduced to the subject.
What is an awesome book which could serve as an introduction to the theory of hypergroups in general? As corollaries: is there such a book? Is the subject too new?
Bonus question: What are the directions this area is following/heading towards? Specific examples as papers would be more than welcome.

A: See references in http://planetmath.org/hypergroup
Besides see
B.Davvaz, W.Dudek, T.Vougiouklis, A generalization of $n$-ary algebraic systems.
Communications in Algebra, v.37(2009), pp.1248–1263,
and other papers of W.Dudek.

A: This paper seems to have the most citations among those I saw:
Hypergroups and hypergroup algebras:http://link.springer.com/article/10.1007/BF01088201
But this book has even more (and some of it is on Google books):
Generalized wavelets and hypergroups:http://www.amazon.com/Generalized-Wavelets-Hypergroups-Khalifa-Trimeche/dp/9056990802
I would recommend trying them out before buying (check out previews!) The level may be wrong.

A: The first thing to realize is that the term "hypergroup" is used for several different mathematical objects. Besides the generalisation of a group that you mention which allows the multiplication to be multivalued, there is also the notion of a hypergroup that are topological spaces with a convolution product for measures on this space which satisfies several axioms which are automatically satisfied for the convolution on a locally compact topological group. This direction comes from harmonic analysis, the reference given by Rushton concern this notion of hypergroup. See also the book by Bloom and Heyer http://books.google.fr/books?id=EUVGq4ciuMsC&dq=bloom+heyer&source=gbs_navlinks_s.
For hypergroups in your sense (hyperstructures) see also the Wikipedia article http://en.wikipedia.org/wiki/Hypergroup and its references.