text:
Q: How to pause a ListIterator Im using Firebase database to store my users scores games , at the end of the game users can see the final results of every members of the party
My users data and their scores are stored at 2 different places
here how looks my structure in Firebase.
Posts
-KLpcURDV68BcbAvlPFy
    user_id: "KLpcURDV68BcbAvlPFy"
    score: "A"

-asdasdasddsad
   user_id: "asdasdasddsad"
    score: "B"

Users
-KLpcURDV68BcbAvlPFy
    id: "KLpcURDV68BcbAvlPFy"
    name: "Jordan"

-asdasdasddsad
   id: "asdasdasddsad"
    name: "Tyler"

So I load first Id  from  Child (Posts )  inside an Arraylist and after I user the ListIterator to load data for every id  in the Child(Users ) .
My question is simple . How can I pause a ListIterator
I have an Firebase onDataChanged Load inside a My ListIterator  , it return null because my list finish faster than my Firebase load , How can I make my List wait for my Firebase database to load necessary data and then resume itself ?
My code
  for (ListIterator<String> it = list.listIterator(); it.hasNext(); i++) {

            String UserUid= it.next();

            LoadataValue(UserUid, new OnObjectExistListener<String>() {
                @Override
                public void onDataChanged(Data  userData) {

 ListIterator must resume here

                }

        });

   ListIterator must pause Here
    }

A: You cannot pause a list iterator they way you want it to. Let me explain a little bit.
Firebase gets the data over the internet in a separate background thread and it should take some time to trigger that onDataChanged method whereas your list iterator might be running in the main thread. Hence, you will always have to wait for the background thread to be completed and return some data to your main thread to be able to show them. You can achieve the behavior in many different ways.
It looks like you are trying to get all the user details from the firebase. I assume, the simplified structure of your firebase database looks like the following.
users:
    user1:
       userDetails:
            name: Everyone
    user2:
       userDetails:
            name: Needs
    user3:
       userDetails:
            name: some
    user4:
       userDetails:
            name: help

You can try getting all the values at once from the users node, and store them locally (maybe inside a List<User>). Then once the list of users are downloaded correctly in your onDataChange function, trigger your list iterator in a separate method so that it can go over that locally stored list and provide you the results that you want.
Here's a pseudo implementation.
// Get a reference to your users
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("your-firebase-url/users");

// Attach a listener to read the data from your firebase database
ref.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    List<User> users = dataSnapshot.getValue(User[].class);
    callAFunctionThatRunsThroughThisListOfUsers(users);
  }
});


text:
Q: Ionic cordova resources --splash Error
× Generating platform resources - failed! Error: encountered bad
  status code (400) for https://res.ionic.io/api/v1/transform body:
  {"Error":"source image 1280x1920 too small for
  Default-Landscape@2x~ipad.png, requires at least 2048x1536 source
  file"}
      at Response.res.on (C:\Users\newuser\AppData\Roaming\npm\node_modules\ionic\node_modules\@ionic\cli-utils\lib\cordova\resources.js:148:32)
      at emitNone (events.js:106:13)
      at Response.emit (events.js:208:7)
      at emitNone (events.js:111:20)
      at IncomingMessage.emit (events.js:208:7)
      at endReadableNT (_stream_readable.js:1064:12)
      at _combinedTickCallback (internal/process/next_tick.js:138:11)
      at process._tickCallback (internal/process/next_tick.js:180:9)

A: Your image (1280x1920) is too small for Default-Landscape@2x~ipad.png
It requires at least 2048x1536px.
Try upload a bigger image
See Ionic Cordova Resources

redpajama_set_name: RedPajamaStackExchange


text:
Q: ZeroMQ library linking: undefined reference to symbol, error adding symbols: DSO missing from command line When compiling a simple c++ file that uses ZeroMQ, I get:
/usr/bin/ld: /tmp/ccbHbSAY.o: undefined reference to symbol '_ZNSt8ios_base4InitD1Ev@@GLIBCXX_3.4'
//usr/lib/x86_64-linux-gnu/libstdc++.so.6: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

which I think is trying to tell me that I'm calling a symbol that does not exist in the shared library that I'm linking. Here's my compiling command:
gcc -Wall -I/usr/local/include zeromq_worker.cpp /usr/local/lib/libzmq.so.5.0.2

I tried with libzqm.so and libzmq.so.5, which are also in /usr/local/lib, but the same error occurs
Also, _ZNSt8ios_base4InitD1Ev@@GLIBCXX_3.4 is the compiled name for some structure. Which is it? I think it can help understanding where the error comes from.

A: Use g++ not gcc if it's a C++ file.
Also it's not usual to explicitly specify a library that way: normally you should give a link directive like -lzmq preceded if necessary by a library search path directive of the form -L /usr/local/lib.
So try
g++ -Wall -I /usr/local/include zeromq_worker.cpp -L /usr/local/lib -lzmq


text:
Q: Real-time streaming cep system with delayed reaction I need help for an archetecture issue.
I develope a cep system based on kafka technology with java.
CEP should have followed characteristics:

*

*distributed (cluster)

*scalable

*fault-tolerance

CEP should make followed actions:

*

*create events from different sources, which is actually are multi-partitioned kafka-topics (ETL-part)

*analyze sequences of that events and if they are matched for a special patterns (scenario) put reaction-record to some store (analyze-part)

*every X period query this store to do some communication with a client if it's the time (schedule-part)

During X period if a cancel-event appears, so I remove a reaction record from store.
I created that system using KafkaStreams library. But the archetecture as a result is not so good.
KafkaStreams use RocksDB in backend to store states. There are many problems with managing stores in cluster mode and having a consistent data. Also I cant to make sql-queries to them to resque from iterating every record in store to check if the time for reaction is heppen.
I'm not an architect and I only one who is busy in this task. I was adviced to look at KafkaStreams and Flink for create cep programm. But in fact are these technologies really fit?
There are no question for an ETL-part.
But how can I built an analyze-part and (it's more interesting) query-part? What tools can I use?
I'm grateful for any help and advices
[UPD]
About queries and stores:

*

*We need to check if the time to send a communication is heppen. If it's true so communicate with a person: push-message, email or any other chanel.

select
...where event_time + wait_time < now

*After that we need update that record in store to next message of this scenario (and make this algorithm until the person go to last message of scenario or does the cancel action)

Sequence of scenario A:
ev A -> ev B -> ev C -> ev D -----> start scenario -----> ev E or msg c was sent -----> cancel scenario
Messages for scenario A:

*

*msg a (send after wait_time: 10 minutes)

*msg b (send after wait_time: 1 day)

*msg c (send after wait_time: 7 days) - last

update
... where user_id = xxx and scenario_id = A

*If action was made in 2nd point, so we also need to update userStore (there are some information about users, including special counters; they are help to not spam the client and no sending messagies to him at night)

update
... where user_id = xxx
I wrote an engine for CEP with some rules, which I save in special store - scenarioStore.
Thus, there are a several stores:

*

*initialStore (keep last event in scenario sequencies with message parameters, waiting the time to be sent) - ev D

*scenarioStore (sequences of events by scenarios) - CEP rules

*messageStore (texts and other properties of messages) - msg rules

*userStore (information about users)

A: You can definitely do complex event processing CEP with Kafka Streams. There are even open-source libraries for that kafkastreams-cep.
Kafka Streams framework supports interactive-queries where you can query your state stores to retrieve required data. You can add a REST layer to make it queryable from REST API. Please, see a code example WordCountInteractiveQueriesExample.


text:
Q: Configure Send Blackout Window for Mobile Messages I want to configure a Send Blackout Window to prevent Mobile Messages to be sent at night. I use Journey Builder to send these Mobile Messages.
While SF recommend to configure the Send Blackout Window directly in Mobile Connect, I don't know exactly where I must set up this functionnality. In addition to that, what happens after the blackout window? Are mobile messages still sent out?
Thanks a lot for your insigths!

A: Configure the Send Blackout under Administration in MobileConnect:
In Administration,

*

*click Set Blackout Window.
Change the status to Enabled.
Set the beginning and end of the send blackout.
Save the  send blackout.
What happens after the blackout window?

If your send starts at 9 PM and takes two hours, and your send
  blackout starts at 10 PM, the send continues until 11 PM, into the
  send blackout time period.

Are mobile messages still sent out? --> YES
Important notes:
Note 1:

Set the Send Blackout in MobileConnect and not in Journey Builder.

Note 2:

In Journey Builder, a send blackout window completely prevents
  messages from sending. Messages don't queue for sending at later time.

References:

*

*Send Blackouts

*Set a Send Blackout


text:
Q: Proper use of "whom" Have I used "whom" correctly in the following sentence?
Rarely a day goes by here that I don't witness this core value manifesting itself in a myriad of thoughtful, sincere, acts of kindness toward our residents, many of whom have enriched our lives beyond measure.

A: You use whom as an object and who as a subject.
At first glance, it may appear that in the sentence "many of whom have enriched...", whom is acting as a subject, but it isn't.
In this sentence, whom is acting as the object of the preposition of in the phrase "many of whom", and "many of whom" is the subject.
So, whom is the proper form here.


text:
Q: A function with only a partial derivative not Hölder-continuous I'm looking for a function of two variables, say $u(t,x)$, such that for some $\alpha\in ]0,1]$

*
1. $x\mapsto u(t,x)$ is $C^{2,\alpha}$;

*
2. $t\mapsto u(t,x)$ is $C^{1,\alpha}$;

*
3. $t\mapsto \partial_x u(t,x)$ is not $C^{0,\alpha}$.

All the statements must be true in a neighbourhood of  $0$. I don't even now if a such a function can exists..
Thanks.

A: Let $\varphi:\mathbb R\to\mathbb R$ be a $C^\infty$-smooth compactly supported function such that $\varphi(0)=0$ and $\varphi'(0)\ne 0$. Define
$$
u(x,t) = \begin{cases} \varphi(x/t),\quad & t>0 \\ 0,\quad & t\le 0\end{cases}
$$

*

*For every fixed $t$ the function $x\mapsto u(x,t)$ is $C^\infty$ smooth.

*For every fixed $x$ the function $t\mapsto u(x,t)$ is $C^\infty$ smooth. (Indeed: if $x=0$, then it's zero identically. If $x\ne 0$, then $\varphi(x/t)=0$ when $t$ is sufficiently small, so transition at $t=0$ happens without a problem.)

Then take a look at the derivative
$$
\partial_x u(x,t) = \begin{cases} t^{-1}\varphi'(x/t),\quad & t>0 \\ 0,\quad & t\le 0\end{cases}
$$
and observe that

*For $x=0$, the function $t\mapsto \partial_x u(x,t)$ has a serious problem at $t=0$.

If the above example seems too extreme ($u$ is not even jointly continuous), you can use a milder one:
$$
u(x,t) = \begin{cases} t\,\varphi(x/t),\quad & t>0 \\ 0,\quad & t\le 0\end{cases}
$$

A: I have a curiosity about this examples! In some sense we assume that 1., 2. and 3. are not uniform in all variables. If we request a uniform condition, that is we say $x\to u(t,x)$ is $C^{0,\alpha}$ uniformly in $t$, if there exist a constant $C>0$ s.t.
$$\sup_{\substack{{x,y\in\mathbb{R},{x\not=y}}\\t\in\mathbb{R}}}\frac{|u(x,t)-u(y,t)|}{|x-y|^\alpha}\le C.$$
In this case what can we say about the regularity of $t\to\partial_x u(t,x)$?
For instance in the second example, considering a positive sequence of point $x_n$ s.t. $x_n\to0^+$. If we compute the derivative in $t$ on the point $x_n$ we have
$$\partial_t u(t,x_n)=\varphi(x_n/t)+\varphi'(x_n/t),$$
and this is not uniformly continuous in $x_n$:

*

*if we take $t=x_n$ we have convergence to $\varphi(1)+\varphi'(1)$ (in general different to zero),

*if we take $t=x_n^2$ we have convergence to zero.

Any hints, remarks and corrections are welcome!


text:
Q: Is it possible to run a plugin system on AppHarbor? I've written a plugin system for my web application where at application start assemblies are read and cataloged.  Is this possible if I have a "plugins" folder that I push to, and how would I reference that folder if it is not located in my webapp folder structure?
Edit
I found this this SO question regarding the use of exe files for external processes and it seems that files included in the build are a possibility.  Is this a matter of creating a folder in hte application path that IIS can access?

A: If you ensure that the relevant assemblies are copied to build output, then this should work fine. You can probably accomplish this by including the relevant assemblies in a plugins-directory that's part of the Visual Studio project with the dll's marked as "Content" (as you would for javascript and other content that you want deployed). You can experiment with the AppHarbor build process to get this working by following the suggestions in the FAQ.


text:
Q: Upgrading to firebase-messaging 19.0.0 and up breaks kotlinx's synthetic When I upgrade to firebase-messaging 19.0.0 and up it seems to cause conflict with kotlinx synthetic. The existing imports for synthetics are unused when I try with version 19. I didn't migrate to androidx yet.
Anybody has seen this issue ?


text:
Q: Negative Binomial Regression Dispersion Parameter I have seen conflicting definitions in the literature as to whether the variance of the response under a negative negative binomial regression model is specified as $\mu + \kappa \mu^2$ or as $\mu + \dfrac{\mu^2}{\kappa}$, where $\mu$ is the mean. Which one does R take it to be? Because when I fit the model I get a "theta", as R calls it, of 1.5. It seems more rational that it should be the latter, but I would like to make sure. Thanks in advance!

A: The model specification for the negative binomial GLM as encoded in glm.nb in the MASS library is:
$$\text{Var}(Y) = \mu + {\mu^2 \over \theta}$$
(from p. 206 of Venables and Ripley, MASS).  Note that this is different from the (less common) specification in the question.
Other libraries, however, may use the alternative formulation:
$$\text{Var}(Y) = \mu + k\mu^2$$
In your case, since the data structure returned contains a parameter explicitly labelled "theta", I assume you are using glm.nb, in which case the first formulation is the correct one.


text:
Q: How to create a stacked area chart in R over time (24 hours)? I'm trying to create a stacked area chart in R Studio to represent my productivity in different areas of my life over a normal 24 hour day.
Here's a snipped of my dataset:
Time   Coursework    Leisure Intern    PD
 1 00:00           0       0      0     0
 2 01:00           0       0      0     0
 3 02:00           0       0      0     0
 4 03:00           0       0      0     0
 5 04:00           0       0      0     0
 6 05:00           1       0      0     0
 7 06:00           1       0      0     2
 8 07:00           6       1      0     6
 9 08:00          17       1      0     1
10 09:00          18       0      0     1

The part I'm struggling most with is how to format my CSV file and group all this data together.  I'm totally lost in how to frame this data in the context of a 24-hour day. Can anyone please help me get started with this?

A: You can try this tidyverse approach. You have to format your data to long. In order to display the time you can hack it with factor(). Here the code:
library(tidyverse)
#Code
df %>% pivot_longer(-Time) %>%
  ggplot(aes(x=factor(Time),y=value,color=name,group=name))+
  geom_line()+
  xlab('Time')

Output:

Some data used:
#Data
df <- structure(list(Time = c("00:00", "01:00", "02:00", "03:00", "04:00",
"05:00", "06:00", "07:00", "08:00", "09:00"), Coursework = c(0L,
0L, 0L, 0L, 0L, 1L, 1L, 6L, 17L, 18L), Leisure = c(0L, 0L, 0L,
0L, 0L, 0L, 0L, 1L, 1L, 0L), Intern = c(0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L), PD = c(0L, 0L, 0L, 0L, 0L, 0L, 2L, 6L, 1L, 1L
)), class = "data.frame", row.names = c("1", "2", "3", "4", "5",
"6", "7", "8", "9", "10"))

A: Just changing @Duck 's to area and using tidyverse to simplify data definition:
library(tidyverse)
library(ggplot2)

df <- tribble(
~rn,  ~RecordTime, ~Coursework,    ~Leisure, ~Intern,    ~PD,
  1,  "00:00",           0,       0,           0,      0,
  2,  "01:00",           0,       0,           0,      0,
  3,  "02:00",           0,       0,           0,      0,
  4,  "03:00",           0,       0,           0,      0,
  5,  "04:00",           0,       0,           0,      0,
  6,  "05:00",           1,       0,           0,      0,
  7,  "06:00",           1,       0,           0,      2,
  8,  "07:00",           6,       1,           0,      6,
  9,  "08:00",          17,       1,           0,      1,
 10,  "09:00",          18,       0,           0,      1,
)

#x <-
  df %>%
  pivot_longer(-c(RecordTime)) %>%
  filter(name != "rn") %>%
  ggplot(aes(x=RecordTime,y=value,group=name, color=name, fill = name))+
  geom_area()

Results:

A: This might work:
ggplot('data', aes('x', 'y')) + geom_smooth(aes(fill = 'variables'), color = 'choose line color') see how the code will work
You'll have to arrange the data in a way where your variables (coursework, intern, etc) are in one column.


text:
Q: Facebook web hooks for page I have an account on FB and I then created a page on FB as admin of the page.
I then setup Facebook web hook Page subscriptions. Here are the details:
Web hook details
I checked every single item including "feed" which are important in this case.
Now I signed in to FB using another user/account and posted a post on the Facebook page. However my webhook endpoint is not getting hit. I can confirm that it is not getting hit.
Is there anything else that I have to do to enable web hook page subcriptions? I read the documentation and everything seems very tangled.
Please let me know.

A: It looks like the solution to this problem is to add the accounts you want to access the webhooks as testers, developers, or admins on your app configuration page.  Go to https://developers.facebook.com/apps/{YOUR_APP_ID}/roles/ and click Add Administrators, Add Developers, or Add Testers .

A: Once you've set up the Webhook
Until your app is approved by Facebook only testers, developers, or admins can see it and use it. link
As soon as you're happy with how your app behaves, you should follow Facebook's App Review guide to submit your app for approval.
Then only you can use it for public use.


text:
Q: C++11 concurrency; condition_variable; fizz, buzz, fizzbuzz; STUCK I am unable to find any bug, the program doesn't show any output; however if I introduce a cout with some print in number() just after while I see some output, are signals getting missed?
I have launched 4 threads, all are using unique_lock on a common mutex and a condition variable. The same logic works if I use semaphores but when I converted them to c++11 condition_variable I am seeing no output on the screen. The threads are hung and are waiting for signals. But the thread[3] should run because the condition for which it is on wait if true; curr=1.
#include<iostream>
#include<thread>
#include<mutex>
using namespace std;

class FizzBuzz {
private:
    int n;
    int curr;
    std::mutex mtx;
    std::condition_variable cv;

public:
    FizzBuzz(int n) {
        this->n = n;
        curr = 1;
    }

    // printFizz() outputs "fizz".
      void fizz(function<void()> printFizz) {
        while(curr <= n) {
            std::unique_lock<std::mutex> lck(mtx);
            cv.wait(lck, [&]{return (curr <= n && curr % 3 == 0 && curr % 5 != 0);});
            printFizz();
            curr++;
            lck.unlock();
            cv.notify_all();
        }
    }

    // printBuzz() outputs "buzz".
      void buzz(function<void()> printBuzz) {
        while(curr <= n) {
            std::unique_lock<std::mutex> lck(mtx);
            cv.wait(lck, [&]{return (curr <= n && curr % 3 != 0 && curr % 5 == 0);});
            printBuzz();
            curr++;
            lck.unlock();
            cv.notify_all();
        }
    }

    // printFizzBuzz() outputs "fizzbuzz".
      void fizzbuzz(function<void()> printFizzBuzz) {
        while(curr <= n) {
            std::unique_lock<std::mutex> lck(mtx);
            cv.wait(lck, [&]{return (curr <= n && curr % 3 == 0 && curr % 5 == 0);});
            printFizzBuzz();
            curr++;
            lck.unlock();
            cv.notify_all();
        }
    }

    // printNumber(x) outputs "x", where x is an integer.
      void number(function<void(int)> printNumber) {
        while(curr <= n) {
            std::unique_lock<std::mutex> lck(mtx);
            cv.wait(lck, [&]{return (curr <= n && curr % 3 != 0 && curr % 5 != 0);});
            printNumber(curr);
            curr++;
            lck.unlock();
            cv.notify_all();
        }
    }
};
void printFizz (void) {
  cout << "Fizz";
};
void printBuzz (void) {
  cout << "Buzz";
};
void printFizzBuzz (void) {
  cout << "FizzBuzz";
};
void printNumber (int n) {
  cout << n;
};

int main(int argc, char* argv[]) {
  int num;

  sscanf(argv[1], "%d", &num);

  std::function<void(void)> f_fizz     = printFizz;
  std::function<void(void)> f_buzz     = printBuzz;
  std::function<void(void)> f_fizzbuzz = printFizzBuzz;
  std::function<void(int)>  f_num      = printNumber;
  FizzBuzz *objPtr = new FizzBuzz(num);

  std::thread threads[4];

  threads[0] = std::thread(&FizzBuzz::fizz, objPtr ,f_fizz);
  threads[1] = std::thread(&FizzBuzz::buzz,objPtr, f_buzz);
  threads[2] = std::thread(&FizzBuzz::fizzbuzz,objPtr, f_fizzbuzz);
  threads[3] = std::thread(&FizzBuzz::number,objPtr, f_num);

  for (auto& th: threads) th.join();
  return 0;
}

A: The notify_all reaches other threads, but the condition curr <=n && ...is not satisfied. Therefore, the other threads continue to wait and hang the program.
For example, the following code would terminate properly, because setting the terminated flag will wake all threads and have them break the loop.
#include<iostream>
#include<thread>
#include<mutex>
#include <functional>
#include <condition_variable>
using namespace std;

class FizzBuzz {
private:
    int n;
    int curr;
    std::mutex mtx;
    std::condition_variable cv;
    bool terminated;

public:
    FizzBuzz(int n) {
        this->n = n;
        curr = 1;
        terminated = false;
    }

    // printFizz() outputs "fizz".
      void fizz(function<void()> printFizz) {
        while(curr <= n) {
            std::unique_lock<std::mutex> lck(mtx);
            cv.wait(lck, [&]{return (terminated || (curr % 3 == 0 && curr % 5 != 0));});
            if (terminated)
                break;
            printFizz();
            curr++;
            lck.unlock();
            cv.notify_all();
        }
        cout << "fizz exiting" << endl;
        terminated = true;
    }

    // printBuzz() outputs "buzz".
      void buzz(function<void()> printBuzz) {
        while(curr <= n) {
            std::unique_lock<std::mutex> lck(mtx);
            cv.wait(lck, [&]{return (terminated || (curr % 3 != 0 && curr % 5 == 0));});
            if (terminated)
                break;
            printBuzz();
            curr++;
            lck.unlock();
            cv.notify_all();
        }
        cout << "buzz exiting" << endl;
        terminated = true;
    }

    // printFizzBuzz() outputs "fizzbuzz".
      void fizzbuzz(function<void()> printFizzBuzz) {
        while(curr <= n) {
            std::unique_lock<std::mutex> lck(mtx);
            cv.wait(lck, [&]{return (terminated || (curr % 3 == 0 && curr % 5 == 0));});
            if (terminated)
                break;
            printFizzBuzz();
            curr++;
            lck.unlock();
            cv.notify_all();
        }
        cout << "fizzbuzz exiting" << endl;
        terminated = true;
    }

    // printNumber(x) outputs "x", where x is an integer.
      void number(function<void(int)> printNumber) {
        while(curr <= n) {
            std::unique_lock<std::mutex> lck(mtx);
            cv.wait(lck, [&]{return (terminated || (curr % 3 != 0 && curr % 5 != 0));});
            if (terminated)
                break;
            printNumber(curr);
            curr++;
            lck.unlock();
            cv.notify_all();
        }
        cout << "number exiting" << endl;
        terminated = true;
    }
};
void printFizz (void) {
  cout << "Fizz" << endl;
};
void printBuzz (void) {
  cout << "Buzz" << endl;
};
void printFizzBuzz (void) {
  cout << "FizzBuzz" << endl;
};
void printNumber (int n) {
  cout << n << endl;
};

int main(int argc, char* argv[]) {
  int num;

  sscanf(argv[1], "%d", &num);

  std::function<void(void)> f_fizz     = printFizz;
  std::function<void(void)> f_buzz     = printBuzz;
  std::function<void(void)> f_fizzbuzz = printFizzBuzz;
  std::function<void(int)>  f_num      = printNumber;
  FizzBuzz *objPtr = new FizzBuzz(num);

  std::thread threads[4];

  threads[0] = std::thread(&FizzBuzz::fizz, objPtr ,f_fizz);
  threads[1] = std::thread(&FizzBuzz::buzz,objPtr, f_buzz);
  threads[2] = std::thread(&FizzBuzz::fizzbuzz,objPtr, f_fizzbuzz);
  threads[3] = std::thread(&FizzBuzz::number,objPtr, f_num);

  for (auto& th: threads) {
      th.join();
  }
  return 0;
}


text:
Q: How to display the avatar of all the user but it should have a limit of 6 or 4 then there will be a display all button to display the rest? I'm creating a component in react that will display the avatar of the user but the catch is there will be limit on how many avatar will show. The solution that I'm thinking is using .slice(0,4).map then I'm gonna make a condition statement that if the length of the list is greater than 4 the button show all will appear. If the user click the button that rest of the user will pop up. The problem is how can display the rest of the user inside the pop up container?

          {filterInfo &&
            filterInfo
              .slice(1, 10)
              .map((data) => (
                <img
                  className={`mr-2 rounded-full border-1px ${
                    active === data.creator[0]._id
                      ? 'border-primary p-0.5 opacity-100'
                      : ''
                  } cursor-pointer transition duration-75 ease-in opacity-70`}
                  key={data._id}
                  id={data.creator[0]._id}
                  src={data.creator[0].accountProfileUploaded}
                  alt={`${data.creator[0].firstName} ${data.creator[0].lastName}`}
                  title={`${data.creator[0].firstName} ${data.creator[0].lastName}`}
                  style={{ width: '40px', height: '40px' }}
                  onClick={handleOnFilterByProfile}
                />
              ))}

          {filterInfo && filterInfo.length >= 2 ? (

              <ChevronDoubleDownIcon
                className='h-4 w-4 absolute mt-3.5 ml-3 opacity-60 cursor-pointer hover:text-primary'
                aria-hidden='true'
              />

          ) : null}

Thanks!


text:
Q: Use enum like a getter? I have a util class that keeps track of important system variables:
public static final String REQUEST_ADDRESS = "http.request.address";
public static final String REQUEST_PORT = "http.request.port";

public static final String get(String property) {
    return System.getProperty(property);
}

And I can retrieve these values like so:
String port = SystemPropertyHelper.get(SystemPropertyHelper.REQUEST_PORT);

Is it possible, in Java, to get these like an enum?
REQUEST_PORT {
    return System.getProperty("http.request.port");
}

String port = SystemPropertyHelper.REQUEST_PORT;

A: I'd solve it that way.
public static final String REQUEST_PORT = System.getProperty("http.request.port");

A:         enum SystemPropertyHelper {
            REQUEST_PORT("http.request.port"), ...;

            private String key;

            Config(String key) {
                this.key = key;
            }

            public String get() {
             return System.getProperty(key);
            }
        }

and use it like SystemPropertyHelper.REQUEST_PORT.get();

A: Sure, you could create an enum like this, which would give you access to the property name, and the value:
public enum SystemPropertyEnum {
    REQUEST_PORT("http.request.port"),
    REQUEST_ADDRESS("http.request.address");

    private String propertyName;
    private String value;

    SystemPropertyEnum(final String propertyName) {
        this.propertyName = propertyName;
        this.value = System.getProperty(propertyName);
    }

    public String getPropertyName() {
        return propertyName;
    }

    public String getValue() {
        return value;
    }
}

However, you could avoid the need to call a getter by just using public static final String variables for your properties, as @halloei suggests.

A: Also you can do something like this:
public enum Properties {
    REQUEST_PORT("http.request.port"),
    REQUEST_USE_SSL("http.request.ssl");
    // Add others...

    private final String value;

    Properties(String value) {
        this.value = System.getProperty(value);
    }

    public String getValue() {
        return this.value;
    }
}

This can be use like:
String port = Properties.REQUEST_PORT.getValue();


text:
Q: wordpress 4.7.3 reload same page i'm trying to fix a strange issue of my website.
I use latest wordpress version with woocommerce and wootheme.
I really don't know when it started that problem.
The problem is very simple, when i am in backend often i can't change page, i can click everywhere but reloads the same page.
For example if i am in Posts>Example1 and i want to go to Pages i click on it, i see "?post_type=page" but reloads Example1! is very frustrating because to change page i need to wait many secs or mins.. like a cache problem but i disabled all plugin cache!
If i hold 30 secs and i click the page loads correctly.
Sometimes that same problem appears in website, not only in backend.
For example I tried to add a product to cart, after adding I put it back and the problem recurred, the page is reloaded and the product was always there, I had to clear the cache manually (Ctrl + F5) and then worked.


text:
Q: multithread vector I am working on a project in C++ that uses self created maps to store data - maps in this sense would be more like a "geographical" map, so an image. There are different threads reading from and writing to it. The data of a map is stored in an std vector of vectors of integers. Its size does not change, only the content of certain pixels through getter and setter functions.
My problem is the following:
Sometimes everything works just fine, but more often I get corrupted images, in the sense that the value of a pixel changes sign or become completely different from what they should be. Could this be an issue of the threaded read/write access to the pixels, if so what should I use instead of the standard vectors?
I have tried using mutex to ensure that only one thread reads or writes to the vector, however these read/write operations happen so often, that the application becomes too slow if I lock the vector at every operation.

A: You will need some kind of locking. To prevent that from hurting your performance too badly, you should try to make the scope of the locks as small as possible. For instance, you could lock individual row-vectors, so that writes on different rows would not interfere with each other. What kind of solution is most appropriate for you depends on your access-patterns and platform.

A: When you do multithreading, try to isolate the scope of the threads as much as possible.
Consider and example. Imagine you have a wall and you want to get it painted with black and white stripes.
And to speed up the job, you decide to hire two employees.
Now, you could allocate this job in two ways.
1. Assign painting the black stripes to one worker and the white to another worker.
2. Divide the wall into two partitions and assign the left partition to one worker and the right portion to the second worker
Now which one is likely to yield better performance?
In, general case 2nd one is better since the worker's working area is well seperated and one need not wait for the other to do his job.
Of course 1st approach is not wrong, but, it is possible that one worker is painting at some place and the second guy might also reach the same place and will have to wait for the first one to finish.
Now imagine what would happen if you had 10 workers each is painting only one particular color.
Multithreaded programming is similar. If you can partition your problem data in a better way, you can make the threads to work effectively.

A: *

*Use lightweight locks. That is on windows use "CriticalSection". Or write your own user space locks e.g. like in in TinyThread (http://tinythreadpp.bitsnbites.eu/). These are written in ASM and should have almost zero overhead to actually lock and unlock.

*Once you're sure the locks themselves are fast, if things still run slowly it is because you have lock contention. E.g. multiple threads all needing to lock the same resource. In your usage case consider something like a 'read/write' mutex. This is a class that would have a read mutex, and a write mutex. The "readLock" method on the mutex only locks for a few cycles to increment a reference count on the mutex. "readUnlock" does decrements the reference count. "writeLock" locks the read mutex, and sets a flag that keeps readers from locking the read mutex. And then locks the write mutex and does the write operation. So you guarantee that only one write operation can happen at a time, and that no reads can happen during write. But simultaneous reads are allowed.


text:
Q: Can't open popup using JQuery and magnific popup.js I've loaded magnific popup.js library to display a popup for a form.
HTML:
    Open form

<form id="test-form" class="mfp-hide white-popup-block">

Form

    <fieldset style="border:0;">

Lightbox has an option to automatically focus on the first input. It's strongly recommended to use inline popup type for lightboxes with form instead of ajax (to keep entered data if the user accidentally refreshed the page).

                Name
                <input id="name" name="name" type="text" placeholder="Name" required="">

                Email
                <input id="email" name="email" type="email" placeholder="example@domain.com" required="">

                Phone
                <input id="phone" name="phone" type="tel" placeholder="Eg. +447500000000" required="">

                Textarea

                <textarea id="textarea">Try to resize me to see how popup CSS-based resizing works.</textarea>

    </fieldset>
</form>

JS:
$(document).ready(function () {
    $('.popup-with-form').magnificPopup({
        type: 'inline',
        preloader: false,
        focus: '#name',

        // When elemened is focused, some mobile browsers in some cases zoom in
        // It looks not nice, so we disable it:
        callbacks: {
            beforeOpen: function () {
                if ($(window).width() < 700) {
                    this.st.focus = false;
                } else {
                    this.st.focus = '#name';
                }
            }
        }
    });
});

This isn't displaying the form in a popup as expected. You may see the example with dependencies  here

A: Magnific popup doesn't apply any styles to the popup.  You have to do it yourself: http://dimsemenov.com/plugins/magnific-popup/documentation.html#inline_type.  If you want to make it look like their example add:
.white-popup-block {
  position: relative;
  background: #FFF;
  padding: 20px;
  width: auto;
  max-width: 500px;
  margin: 20px auto;
}

http://jsfiddle.net/yWpC4/3/


text:
Q: creating a list / array from a text file or csv file using bash I'm trying to wrote a small shell script to parse a simple CSV file (just one column) and assign the value in each value to a variable that needs to be an array / list.
Sample file:
Title_ID
123
456
789
000

Need the script to parse the file and output the results to a variable called title such that
echo ${title[1]} returns 456
Here is my current script
while read line; do
temp_title[$i]="$line"
i=$((i++))
done < ./title_master_list.csv

I keep getting the following error zsh: temp_title: assignment to invalid subscript rang
Any idea what I'm doing wrong?

A: From man zshparam:

The elements are numbered beginning with 1, unless the KSH_ARRAYS option is set in which case they are numbered from zero.

So, the problem you're having is because you're trying to use indexing starting at 0, not 1. Use:
#!/usr/bin/zsh
typeset -a temp_title
i=1
while IFS= read -r line; do
    temp_title[i++]="$line" # Note the postincrement in the index expression
done < ./title_master_list.csv
echo "${temp_title[1]}"

But there's better ways to do it, without using a loop, using zsh parameter expansion flags:
temp_title=("${(@f)"$(<./title_master_list.csv)"}")

This splits the file up at newlines into an array.
It can also be done with a single read:
IFS=$'\n' read -r -d '' -A temp_title < ./title_master_list.csv

For completeness's sake, other loop based approaches:
Setting the option to use 0-based arrays:
#!/usr/bin/zsh
setopt KSH_ARRAYS
typeset -a temp_title
i=0
while IFS= read -r line; do
    temp_title[i++]="$line"
done < ./title_master_list.csv
echo "${temp_title[0]}"

Don't use indexes, use +=() to append to the array:
#!/usr/bin/zsh
typeset -a temp_title
while IFS= read -r line; do
    temp_title+=("$line")
done < ./title_master_list.csv
echo "${temp_title[1]}"

When using bash instead of zsh, use the mapfile builtin to read a file into an array:
mapfile -t temp_title < ./title_master_list.csv

Really old versions might have to use:
IFS=$'\n' read -r -d '' -a temp_title < ./title_master_list.csv

(Similar to the zsh version, but uses a lowercase -a)


text:
Q: Dreamweaver CS5.5 BSOD (Blue Screen of Death) help? I just finished downloading and installing the trial version of the Adobe Dreamweaver CS5.5 but for some reason, whenever I try to run it, I get a BSOD or Blue Screen of Death. I'm pretty sure I meet and exceed the requirements for Windows as defined HERE.
I would so much want to try it to see if it's worth buying but as I said, it keeps giving me the BSOD. Has anyone ever encountered this before? Is there a "fix" to this problem? What should I do?
Additional Note:
I'm using Windows XP Service Pack 2.

A: It certainly looks like it went corrupt on the install.  Try uninstalling the trial and then run the CS Clean tool to get the registry entries and other junk removed too:
http://www.adobe.com/support/contact/cscleanertool.html


text:
Q: PHPStorm exclude Tests from coverage percentage I am wondering if it is possible to configure PHPStorm to exclude the Test folder from the percentages, since my module has 100% coverage but the Test folder is bringing the overall value down to 50%.

This could be unrelated, but I also have an issue where the coverage window never displays the actual coverage data, neither in the separate tab nor viewing the file itself.

Chances are I have mis-configured something, or it is something to do with my project setup (composer based Magento project with symlinking) but I'm banging my head against the wall a bit. Any suggestions welcome.
Update to include phpunit.xml:
<?xml version="1.0"?>
<!-- initial phpunit configuration file, that you can modify for your project needs -->
<phpunit cacheTokens="true"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         stopOnError="false"
         stopOnFailure="false"
         stopOnIncomplete="false"
         stopOnSkipped="false"
         strict="false"
         stderr="true"
         verbose="false"
         bootstrap="app/code/community/EcomDev/PHPUnit/bootstrap.php">
    <listeners>
        <listener file="app/code/community/EcomDev/PHPUnit/Test/Listener.php" class="EcomDev_PHPUnit_Test_Listener"/>
    </listeners>
    <testsuite name="Magento Test Suite">
        <file>app/code/community/EcomDev/PHPUnit/Test/Suite.php</file>
    </testsuite>
    <filter>
        <blacklist>
            <!-- Exclude Magento Core files from code coverage -->
            <directory suffix=".php">app/code/core</directory>
            <!-- Exclude EcomDev_PHPUnit classes from code coverage -->
            <directory suffix=".php">app/code/community/EcomDev/PHPUnit</directory>
            <directory suffix=".php">lib/EcomDev/Utils</directory>
            <directory suffix=".php">lib/EcomDev/PHPUnit</directory>
            <directory suffix=".php">lib/Spyc</directory>
            <directory suffix=".php">lib/vfsStream</directory>
            <!-- Exclude Mage.php file from code coverage -->
            <file>app/Mage.php</file>
            <!-- Exclude template files -->
            <directory suffix=".phtml">app/design</directory>
            <!-- Exclude Varien & Zend libraries -->
            <directory suffix=".php">lib/Varien</directory>
            <directory suffix=".php">lib/Zend</directory>
            <directory suffix=".php">lib/Magento</directory>
        </blacklist>
    </filter>
    <logging>
        <log type="coverage-html" target="var/phpunit/coverage" charset="UTF-8" yui="true" highlight="false" lowUpperBound="35" highLowerBound="70"/>
        <log type="coverage-clover" target="var/phpunit/coverage.xml"/>
        <log type="junit" target="var/phpunit/junit.xml" logIncompleteSkipped="false"/>
    </logging>
</phpunit>

The reason I thought it might be PHPStorm is the fact that the HTML version of the coverage works perfectly, correctly excluding the Test folder.

A: This has nothing to do with PhpStorm. You simply need to configure a whitelist for your project.


text:
Q: Why does scala allow private case class fields? In scala, it is legal to write case class Foo(private val bar: Any, private val baz: Any).
This works like one might hope, Foo(1, 2) == Foo(1, 2) and a copy method is generated as well. In my testing, marking the entire constructor as private marks the copy method as private, which is great.
However, either way, you can still do this:
Foo(1, 2) match { case Foo(bar, baz) => bar } // 1
So by pattern matching you can extract the value. That seems to render the private in private val bar: Any more of a suggestion. I saw someone say that "If you want encapsulation, a case class is not the right abstraction", which is a valid point I reckon I agree with. But that raises the question, why is this syntax even allowed if it is arguably misleading?

A: It's because case classes were not primary intended to be used with private constructors or fields in the first place. Their main purpose is to model immutable data. As you saw there are workarounds to get the fields so using a private constructor or private fields on a case class is usually a sign of a code smell.
Still, the syntax is allowed, because the code is syntactically and semantically correct - as far as the compiler is concerned. But from the programmer's point of view is at the limit of "does it makes sense to be used it like that?" Probably not.
Marking the constructor of a case class as private does not have the effect you want, and it does not make the copy method private, at least not in Scala 2.13.
LATER EDIT: In Scala 3, marking the constructor as private, does make the apply and copy methods private. This change was also developed for Scala 2 and can be found here - but it was delayed for the 2.14 future release. The reason it can't go into Scala 2.13 is because it's a breaking change.
case class Foo private (bar: Int, baz: Int)

The only thing I can't do is this:
val foo1 = new Foo(1, 2)   // no constructor accessible from here

But I can do this:
  val foo2 = Foo(1, 2)       // ok
  val foo3 = Foo.apply(1, 2) // ok
  val foo4 = foo2.copy(4)    // ok - Foo(4,2)

A case class as it's name implies means the object is precisely intended to be pattern matched  or "caseable" - that means you can use it like this:
case Foo(x, y) =>       // do something with x and y

Or this:
val foo2 = Foo(1, 2)
val Foo(x, y) = foo2    // equivalent to the previous

Otherwise why would you mark it as a case class instead of a class ?
Sure, one could argue a case class is more convenient because it comes with a lot of methods (rest assured, all that comes with an overhead at runtime as a trade-off for all those created methods) but if privacy is what you are after, they don't bring anything to the table on that.
A case class creates a companion object with an unapply method inside which when given an instance of your case class, it will deconstruct/destructure it into its initialized fields. This is also called an extractor method.
The companion object and it's class can access each other's members - that includes private constructor and fields. That is how it was designed. Now apply and unapply are public methods defined on the companion object which means - you can still create new objects using apply, and if your fields are private - you can still access them from unapply.
Still, you can overwrite them both in the companion object if you really want your case class to be private. Most of the times though, it won't make sense to do so, unless you have some really specific requirements:
  case class Foo2 private (private val bar: Int, private val baz: Int)

  object Foo2 {
    private def apply(bar: Int, baz: Int) = new Foo2(bar, baz)
    private def unapply(f: Foo2): Option[(Int, Int)] = Some(f.bar, f.baz)
  }

  val foo11          = new Foo2(1, 2)   // won't compile
  val foo22          = Foo2(1, 2)       // won't compile
  val foo33          = Foo2.apply(1, 2) // won't compile
  val Foo2(bar, baz) = foo22            // won't compile

  println(Foo2(1, 2) == Foo2(1, 2))     // won't compile

  val sum = foo22 match {
    case Foo2(x, y) => x + y            // won't compile
  }

Still, you can see the contents of Foo2 by printing it, because case classes also overwrite toString and you can't make that private, so you'll have to overwrite it to print something else. I will leave that to you to try out.
 print(foo11)  // Foo2(1,2)

As you see, a case class brings multiple access points to it's constructor and fields. This example was just for understanding the concept. It is not an example of a good design. Usually in OOP, you need an instance of some class, to perform operations on it. So a class that you cannot instantiate at all is no more useful than a Scala object. If you find yourself blocking all ways to create an instance of some class or case class, that's a sign you probably need an object instead since object is already a singleton in Scala.

A: Adding to the previous answer: you can make the copy method inaccessible by adding a private method named copy:
case class Foo3(private val x: Int) {
  private def copy: Foo3 = this
}

Foo3(1).copy(x = 2) // won't compile ("method ... cannot be accessed")


text:
Q: php domdocument loadhtml turns $ into (url encoding)%24 unexpectedly for this php script,
$dom = new DOMDocument();
    $dom->substituteEntities =FALSE;
    $dom->loadHTML('$a');
    // print_r ($dom->getElementsByTagName("a")->item(0)->getAttribute("href"));

//the above statement show $a? correctly
    echo $dom->saveHTML();

but it returned $a to the browser when a saveHTML method was called.
The $ in the href attribute was turned into %24 whereas the $ in the content of the a tag remains unchanged.
I expect the output is $a
Is there any way to do this aside from the replace method?
By the way,
  echo $dom->saveXML();

I get what I want with saveXML();
but together with an unexpected


text:
Q: Download PDF in ASP Error on Some Machines I am using this code to generate pdf's to download on an ASP page and the pdf does download properly on some pages but not on all.  Several users are experiencing an error message as seen in the attached image.  Please let me know if you have suggestions on how to fix this problem.  It is sporadic so its been hard to nail down a cause.
Public Sub Download(filename As String)
    Response.Clear()
    Response.BufferOutput = False
    Response.ContentType = "application/pdf"
    Response.AddHeader("content-disposition", "attachment; filename=" + Path.GetFileName(filename))
    Response.WriteFile(filename)
    Response.Close()

End Sub

A: Try Response.Flush(), followed by Response.End().


text:
Q: how to get a bound or perplexity value of the new unseen document on trained model? I would like to find outliers in my dataset by using LDA. In order to specify outliers, For this case, I am planning to use a bound or perplexity value of the new unseen document on trained model?
After that, I will sort the values in ascending order to check whether it is the outlier or not?
My issue is that I could not get a bound/perplex value of individual doc, the model throws me "TypeError: 'int' object is not subscriptable" error.
I would appreciate if you help me to solve my case?
Just in case, I am attaching my code :
tokenized_corpora = dictionary.doc2bow(_acc[2])
total_number_of_words_tokenized_corpora = len(tokenized_corpora)
bound_corpora = ldaModel.bound(tokenized_corpora)
per_word_perplex_corpora = np.exp2(-bound_corpora /
total_number_of_words_tokenized_corpora)

Thanks in advance.

A: According to my research, in order to get log perplexity of single document, the following command can be used :
ldaModel.log_perplexity([bow])


text:
Q: Tested MCP1700-3300E dropout voltage doesn't match datasheet I have several MCP1700-3300E LDO regulators that I plan to use. The datasheet claims that this LDO has:

Low Dropout (LDO) Voltage-  178 mV Typical @ 250 mA for VOUT=2.8V

And the dropout plot for 2.8V:

Actually, I am using 3.3V variant, not the 2.8V one, but unfortunately the datasheet doesn't provide dropout plot for 3.3V variant. Nevertheless, dropout should be similar, right?
So, I rigged up a simple schematic. My PSU feeding 3.7V to the MCP, and a 22 ohm resistor between the output of the MCP and the ground to give it a load. Running, my PSU says the current is 128 mA, around half of the maximum this LDO can handle. But measuring the voltage between the output and the ground of the MCP gives 2.97V, which is a 0.73V drop - far more than the datasheet suggests. This is a schematic of the exact setup I have for testing:

So, what am I missing here? According to the datasheet, I should be getting ~ 0.1V dropout, so the output should still be 3.3V. But the actual dropout is way more than that. I tried several different MCP's, thinking this one might be defected, but all of them show the same behavior. Can anyone help?

A: The first thing I would check is how it works if you use the recommended decoupling:

This from the datasheet link you posted.
Without the decoupling, the LDO may oscillate and not give the correct DC voltages.
Also note they use ceramic capacitors - it may not work if the ESR does not meet the requirements - see sections 5.1 and 5.2 in the datasheet.
Most voltage regulators are critical about the decoupling - LDOs with low drop out are particularly demanding - always read the datasheet.

A: Dropout does not refer to the output, the output should be within the stated tolerance of the regulator, at the voltage it is meant to supply. Dropout means the amount over that voltage that you have to supply at the input, in order to reliably deliver the output voltage promised. For example, a 7805 regulator has a minimum input voltage of 7 volts to deliver 5 volts at the output. So the dropout is 2 volts. A low dropout regulator can operate reliably with just a little more than the output voltage specified. So your 1700 will be happy with about .2 volts more than the 3.0 or 3.3 or whatever you plan to deliver. These regulators can be more efficient, they don't have to waste as much energy as heat, because they aren't (depending on what you give them) having to drop so much voltage from input to output. And they may also be more convenient or give you more margin in your circuits, stepping down from a moderate voltage to a lower one, you aren't required to have such a high voltage input. For example, I use a 7805 to get 5 volts from a 9 volt wall adapter, but I use the 1700 to go from 5 V to 3.3 V elsewhere in the system. As an aside, related to other comments, you DO want to follow the manufacturer's recommendations on input and output capacitors, this is necessary for the regulators to be stable and respond adequately to changes in load.
If you're seeing too low a voltage at the output, you are probably current limiting or thermally limiting, and the regulator is not able to keep the voltage up at that current load. Since you measured the current, my guess is that the regulator is not able to transfer the heat out effectively, and is limiting because it is getting too hot.
Or perhaps you mistakenly bought the 3 volt variant.


text:
Q: Middle value using python 3 UPDATED
a = int(input("Give a value: "))
b = int(input("Give a value: "))
c = int(input("Give a value: "))
def middle(a, b ,c) :
    m = min(a,b,c)
    M = max(a,b,c)
    return a+b+c-m-M

This is where im at. It takes my numbers into the data. How would I get it to display the middle one?! Sorry I'm so terrible at this. Way in over my head on this intro course. @CommuSoft @Zorg @paxdiablo and everyone else

A: Like others mentioned, you're missing a colon, but for simplicity sake:
def middle(a, b, c):
    return sorted([a, b, c])[1]

A: You should put a colon (:) on the first line (def) as well.
This works for the online python environment:
def input(a, b, c) :
    if a <= b <= c or c <= b <= a :
      return b
    elif b <= a <= c or c <= a <= b :
      return a
    else:
      return c

Furthermore it is more advisable to make use of min and max I guess. Min and max are sometimes directly supported by a CPU and there are implementations that avoid branching (if-then-else's):
def input(a, b, c) :
    m = min(a,b,c)
    M = max(a,b,c)
    return a+b+c-m-M

or:
def input(a, b, c) :
    return min(max(a,b),max(b,c),max(a,c))

The last one is also numerically stable.
In most cases if-then-else clauses should be avoided. They reduce the amount of pipelining although in interpreted languages this might not increase performance.

Based on the comments, I guess you want to write an interactive program. This can be done like:
def middle(a, b, c) : #defining a method
    return min(max(a,b),max(b,c),max(a,c))

a = int(input("Give a value: "))
b = int(input("Give b value: "))
c = int(input("Give c value: "))
print("The requested value is ")
print(middle(a,b,c)) #calling a method

Defining a method will never result in Python using that method. The a, b and c in the def block are not the a, b and c in the rest of your program. These are "other variables that happen to have the same name". In order to call a method. You write the methods name and between brackets the parameters with which you wish to call your method.

A: Post your full syntax error (or any other full traceback) whenever you're having trouble.
And your def line needs a colon.

A: You could do:
def middle(a,b,c):
    s={a,b,c}
    s-={min(s),max(s)}
    return s.pop()

What this does:
Create a set of the unduplicated values:
>>> a,b,c=1,2,3
>>> s={a,b,c}
>>> s
{1, 2, 3}

Remove the max and the min, leaving the middle:
>>> s-={min(s), max(s)}
>>> s
{2}

Pop the only remaining value:
>>> s.pop()
2


text:
Q: Column not found: 1054 Unknown column 'is_processed' in 'field list' I wrote a migration to add a column to orders table and the migration ran successfully and created the column in that table.
Here is the migration:
class UpdateOrdersTableAddProcessedColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->boolean('is_processed')
                ->after('incot')
                ->default(1);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->dropColumn('is_processed');
        });
    }
}

And here is my model:
class Order extends Model
{
    protected $connection = 'multi_tenant';

    protected $table = 'orders';

    protected $fillable = ['is_processed'];
}

So the problem here is when I try to insert some data to the orders table, it gives me the following error:

Doctrine\DBAL\Driver\PDOException(code: 42S22): SQLSTATE[42S22]:
Column not found: 1054 Unknown column 'is_processed' in 'field list'
at
/home/vagrant/code/phirater-l51/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:79,
PDOException(code: 42S22): SQLSTATE[42S22]: Column not found: 1054
Unknown column 'is_processed' in 'field list' at
/home/vagrant/code/phirater-l51/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:77)

Here is how I am inserting the data:
$newOrder = new Order();
$newOrder->is_processed = 0;
$newOrder->save();

I have already tried clearing the cache, config cache, rolling back the migration and migrating again but it doesn't work. What is going wrong here.
My Laravel version is 5.5 with PHP7.1.


text:
Q: React: remove localstorage item on page load this my function to remove item from localstorage
const removeItem = () => localStorage.removeItem("key")

how to run function when page load, try this but its not working

Successful payment landing page

A: useEffect(() => {
    removeItem();
}, [])

A: Try this:

//paste this function anywhere above render()
removeItem() {
  localStorage.removeItem("key");
}


text:
Q: Create table html as the image https://jsfiddle.net/tn7rd9sq/
I need create the table of this image:

        text
        text

       text
       text

         1
          2

       other text
       2
       2

I do not know how to do the part when there are 3  together

A:

td {
  width: 20px;
  height: 20px;
}

td.wider {
  width:  60px;
}

tr.taller {
  height: 40px;
}


text:
Q: Accessing JSON fields in html of LWC I am calling an external system from an @wire method and it returns a json string.  When I parse the json into an object I am able to use dot notation to access fields from the json object in JS but when I set it to an @track variable I am unable to use dot notation in the HTML to access the fields from the json object.
JS:
import { LightningElement, track, wire } from 'lwc';
import getProfile from '@salesforce/apex/SFG_ECC_GP_ProfileController.getProfile';
export default class GpCaseScreenProfile extends LightningElement {
    @track profile;
@wire(getProfile)
        handleJson({ error, data} ){
            if (data) {
                this.profile = JSON.parse(data);
                console.log(this.profile.Name.First); // THIS WORKS
            } else if (error) {

                this.error = error;
                this.profile = undefined;
                console.log('ERROR is:', error + 'profile is:', this.profile );
            }
        }
    }

HTML:
<template>
    {profile.Name.First}
</template>

The above html throws an error saying Name is undefined
if I just do
<template>
    {profile}
</template>

it renders as
[Object Object]

Any thoughts on how to inform the HTML that profile is a custom json object?
I also tried using square bracket notation profile['Name']['First'] but that wouldn't compile.

A: That is because HTML will load before your external call finishes and Profile will be undefined before getting response and so I would suggest to use conditional rendering in HTML itself so that you can fetch the values directly instead of increasing Javascript code for implementing multiple getters.
HTML:
<template>
    <template if:true={profile}>
        {profile.Name.First}
        {profile.Name.Last}
        {profile.Email}
        {profile.Phone}
    </template>
</template>

As you see, there is no need of implementing 4 getters in JS

A: Change your template to use a getter that checks for null down the object tree
in JS
get name(){
let returnValue = '';

if(this.profile && this.profile.Name && this.profile.Name.First){
  returnValue = this.profile.Name.First;
}
return returnValue;
}

in html
<template>
    {name}
</template>

What's happening is you are looking for the name on profile before the browser has had a chance to make the call to the service so there is no name to get yet.
Reference: https://wipdeveloper.com/lwc-getting-data-with-the-wire-service/


text:
Q: Object detection : is deep learning the only way to go? It seems that deep learning based approaches are currently more superior to the more "traditional" methods in the domain of object detection. Methods like YOLO, for example, seem to be doing something magical that can't be replicated by the other methods. However, these deep neural networks are trained on hundreds of classes and require a huge amount of computational power. So I have been wondering if we limit the object detection algorithm to a single class of objects (cats or a bicycle for example) can methods based on feature detectors(SIFT, SURF...) and machine learning algorithms (SVM, ANN...) perform similarly to deep learning algorithms?

A: Object detection is completely dominated by deep learning. Essentially it is now down to one-stage detectors (e.g., YOLO) when you want speed and two-stage detectors (e.g., faster-RCNN) when you want accuracy.
Check out any recent survey on object detection, like this one or this one.

However, these deep neural networks are trained on hundreds of classes and require a huge amount of computational power.

This is often true, but not strictly so. Many networks focus exclusively on humans (detecting pedestrians, or estimating human pose) for example. And modern hardware is quite capable of running high speed detectors like YOLO9000 in at least near real-time, even on cell phones (especially network weight quantizations).

If we limit the object detection algorithm to a single class of objects (cats or a bicycle for example) can methods based on feature detectors(SIFT, SURF...) and machine learning algorithms (SVM, ANN...) perform similarly to deep learning algorithms?

It's possible, sure. One case where you might do well is when there is very little training data available. Another is for objects that you can describe very well at multiple scales with a hand-crafted feature. However, I suspect that even with a relatively small amount of labeled training data, a deep CNN can do better, especially if it is via transfer learning or using low-shot/few-shot learning techniques.
Anecdotally, however, I know of a recent commercial/industrial object detection task in a production setting that was only designed to target a very small number of categories for a single class of objects (i.e., "fine-grained recognition and detection"). Their starting point was RetinaNet, I believe.
As to your comment

Do you think then, that a combination of CNN and images descriptors can be worth pursuing

I am not sure that it is worth it to look into image descriptors (i.e., hand-crafted feature extraction), since CNNs already do this very well.
What you should look into are ways to combine classical techniques with deep learning methods. Much useful knowledge from traditional computer vision has been forgotten and is waiting for rediscovery, I suspect. For example, take the recent "attention" work from CVPR by Ramachandran et al, which obtains state-of-the-art performance with fewer FLOPs and no convolutions at all, by taking advantage of so-called self-attention. Yet, this approach is simply a form of learned non-local means and/or parameterized bilateral filtering - both old computer vision techniques. In other words, while feature extraction may be done very well by deep models, there is still plenty of room for the use of classical methods in other areas I think.

A: Deep learning outperforms classical machine learning methods in terms of quality of solutions, it's also less complicated to implement universal solutions. Since DL was born you don't need to focus on features, because you expect that model will recognize the most useful of them from the data by itself (this is the strongest point). You should only provide the exact capability of the model to catch all needed features and don't allow to catch noises or overfit. It's much simpler. You can try preparing models with features descriptors and then use SVM, however SVM computation complexity is high, memory consumption is extremely high and it's hard to processing data in parallel. On the other hand computation of DNN are matrix-based and is relatively simple, finally can be easily done in parallel. Because of that SVM can't handle a large amount of data, it's much faster to do it on GPU-based DNN. The amount of training data is key to the quality of a solution. Many papers confirm that the classical approach performs worse than DL.
Finally, you can prepare DNN for less class and much simpler tasks.


text:
Q: Is it OK to tag the same document using different Content-Types based on Accept headers? Let's say I've designed a media type which is a strict subset of another media type.  For example, my media type is application/vnd.example.foo+xml (hereafter abbreviated foo+xml).  This media type is a strict subset of the application/xhtml+xml (hereafter abbreviated xhtml) media type.  Basically my media type definition adds additional processing instructions (or replaces them completely) to certain constructs within the xhtml media type.  For the sake of example, it could say that in any foo+xml documents, the xpath //ul[@class='foo']/li[a] shall be shown in a specific way by clients, and the rest of the document shall be ignored, a processing model which is quite different from that of the original xhtml media type.
Armed with this information, the server can now start creating representations of that type, and my clients can pass Accept headers and happily consume this type of document, both of them honoring the processing instructions laid out in my type definition.  However, it's a custom media type which I can't assume anyone will know how to process.
An option that I have is this:

*

*When a client prefers the foo+xml media type, I serve the document with a Content-Type set to that media type.

*When a client prefers the xhtml media type, I serve the same document with an xhtml Content-Type header

This means that generic clients that don't know what foo+xml but likely understand what xhtml is can still process my document, follow links to other resources, present it to users in a generic fashion and so on.  Likewise, a client that knows the semantics of foo+xml can actually get a confirmation that this document is actually just that, instead of having to guess or introspect the document to see if it at all looks like something it can process (e.g. via HTML profiling, microformats, etc.).

*

*What are the pros and cons of doing this

*Is there prior art that echoes this technique?

A: Although I have never seen any authoritative discussion on this particular issue I would say it seems perfectly valid.  It is similar to the idea of requesting text/plain for an HTML document to effectively do a view source operation.
From the client's perspective, it has no idea that the bytes are identical to another representation, so I cannot see how there could be pros or cons for the client.
I guess the tricky issue comes with caching.  Are you going use the same URI to return both representations, or are you going to redirect from the generic URI to ones specific to the representation?  Will there be one or two copies of the bytes in the cache?  Do you need to set the Vary header to vary on Content-type?  Can you live with two copies in the cache?  Do you need to do updates on one or both of these representations?  If so, will the cache invalidate both copies if they exist?


text:
Q: what's the enzyme equivalent of a TextNode and how do I select it in my unit test? I'm writing tests with jest and enzyme for a React component which looks like this:
function Message(props) {
  return (

      {props.message}

  );
}
Message.propTypes = { message: PropTypes.string.isRequired };

I'd like to write a test that says "props.message is rendered exactly once by this component", and I'd like to do it without calling wrapper.find('span') (it's an acceptance test, not a unit test, so the fact that the message is wrapped in a  is an implementation detail and therefore immaterial).
I'm currently using .findWhere to return a NodeList, and then expect the length of the list to be 1:
it(`renders props.message`, function() {
    const msg = 'hello';
    const wrapper = shallow(
      <Message message={msg} />
    );
  });

  function nodeTextEqualsMessage(node) {
    // return nodes with no element name ( = text nodes)
    // and where node text = message
    return !node.name() && node.text() === msg;
  }

  const nodeList = wrapper.findWhere(nodeTextEqualsMessage);

  expect(nodeList.exists()).toBe(true);
  expect(nodeList.length).toBe(1);
});

the test passes, which is great.  But if I "accidentally" update my component:
function Message(props) {
  return (

      {props.message}
      {props.message}

  );
}

the same test still passes, which is not so great.  The snapshot of nodeList looks like this:
exports[`the component renders props.message 1`] = `"hello"`;

why is enzyme collapsing multiple findWhere results into a single node?  Can I stop it from doing that?  Is there an alternative enzyme method I should use instead?
thanks!


text:
Q: Python: How to convert the integers in a string that's combined with integers and special characters to floats without changing the structure? If I have a string like: '2 5 3 $ # 2 ^ 1 4 !'
how can I format it to:  '2.0 5.0 3.0 $ # 2.0 ^ 1.0 4.0 !'?
What would be the most optimal way to do it?

A: Split the string, check each part to see if it's numeric - if so, make it into a float
in_string = '2 5 3 $ # 2 ^ 1 4 !'
out_string = ' '.join(str(float(x)) if x.isnumeric() else x for x in in_string.split())
print(out_string)

Output:
2.0 5.0 3.0 $ # 2.0 ^ 1.0 4.0 !

A: One way could be using re.sub and back-referencing the matches:
import re
s = '2 5 3 $ # 2 ^ 1 4 !'

re.sub(r'(\d)', r'\1.0', s)
# '2.0 5.0 3.0 $ # 2.0 ^ 1.0 4.0 !'


text:
Q: How to Invoke two or more ant targets from eclipse? I use ant plugin for eclipse.
from comman line I can write
ant clean all

What analog can I use with plugin?
UPDATE

what I can click after?

A: You can create one of the target and specify depends property of the targets you want to execute.
Refer to below sample code
<project name="some name" default="executeMultipleTargets">
<target name="executeMultipleTargets" depends="myTarget1,target2,target3,clean" >
<echo>Build Successfull....</echo>
</target>
</project>

A: Ant is considered an external tool. So you do not have a run configuration but an external tool configuration for ant runs. There even exists a sub-point "Ant Builds" in that window.
It is very strange that you do not have the option run as ant build when right-clicking an ant build file. I can only assume, you do not have the appropriate plugin (although that is installed by default).
But maybe you are satisfid by just creating an external tool configuration for running ant.

A: You can specify multiple targets in Ant GUI: open your build.xml file and in outline view right click desired target. Then select "Run as -> Ant build..." and check all desired targets.

A: You can go on eclipse-> external tools configurations, select in Targets tab your preferable ant targets and be executed in order.


text:
Q: How to add dynamic commentary in less? How to make the review itself was written?
.className {
    some style...

    // .className .children (how to write this comments?)
   .children {
       some style...
   }
}

A: If you want that comment will be visible after LESS compilation as a simple CSS comment, simply replace // (LESS single row comment) with /*...*/ (CSS comment). Probably you have to move it down into the relative rule, to be sure that is placed near it. So:
.className {
    some style...

   .children {
       /* .className .children (how to write this comments?) */
       some style...
   }
}

Please note that this is the default behaviour if final code will not minified (minification strips all comments, LESS and CSS ones).
Final code:
.className {
  some style...
}

.className .children {
  /* .className .children (how to write this comments?) */
  some style...
}


text:
Q: Can we call procedure or function from anonymous block in oracle? Can i call a pl/sql object by procedure or function from within an anonymous block?
This is a very frequent interview question.
Thanks

A: Yes:
SQL> set serveroutput on
SQL> --
SQL> select banner from v$version;

BANNER
--------------------------------------------------------------------------------
Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production

SQL> show user;
USER is "C##TEST"
SQL> --
SQL> CREATE OR REPLACE PROCEDURE myproc
  2  IS
  3  BEGIN
  4   dbms_output.put_line('myproc: OK');
  5  END;
  6  /

Procedure created.

SQL> --
SQL> show errors
No errors.
SQL> --
SQL> CREATE OR REPLACE FUNCTION myfunc RETURN VARCHAR2
  2  IS
  3  BEGIN
  4   return 'myfunc: OK';
  5  END;
  6  /

Function created.

SQL> --
SQL> show errors
No errors.
SQL> --
SQL> begin
  2   myproc;
  3  end;
  4  /
myproc: OK

PL/SQL procedure successfully completed.

SQL> --
SQL> declare
  2   myvar VARCHAR2(50);
  3  begin
  4   select myfunc into myvar from dual;
  5   dbms_output.put_line(myvar);
  6  end;
  7  /
myfunc: OK

PL/SQL procedure successfully completed.


text:
Q: No Connection Adapters Using ThreadPool I'm running ThreadPool through a list of urls currently in a csv. When the code runs it kicks back the error posted below:
InvalidSchema: No connection adapters were found for '['http://axiomglobal.sharepoint.com/sites/MarkandElena-Strategic']'

It looks like python is looking at the brackets as part of the url, but the list itself appears to omit them:
[['http://axiomglobal.sharepoint.com/sites/123456'], ['http://axiomglobal.sharepoint.com/sites/SharePointo365globaltestsite'], ['http:3456789']

Is there something in the code below that is causing it to search for the sites in the list with the brackets included?
I've tried using a single url against the ThreadLoop portion of the code, rather than the entire list and it generates the correct result.
def get_site_status(site):
    try:
        response = requests.get(site)
    except requests.exceptions.ConnectionError:
        print('Connection Refused')
        return 1
    if response.status_code == 401:
        print('web site exists, permission needed')
    elif response.status_code == 404:
        print('web site does not exist')
    elif response.status_code == 400:
        print('web site does not exist')
    elif response.status_code == 403:
        print('web site forbidden')
    elif response.status_code == 423:
        print('web site locked')
    elif response.status_code == 200:
        print('web site exists and is available')
    else:
        print('other')
    return 0
pool = ThreadPool(processes=1)

results = pool.map_async(get_site_status, Row_list)

print('Results: {}'.format(results.get()))

I expect the code to populate a  list of each row with it's result from the ThreadPool part of the code (approx. 1500 rows of urls).

A: gevent is way faster with requests. You are not trapping the errors correctly or handing it an SSL cert incase of an upgrade.
from gevent import monkey, spawn, joinall
monkey.patch_all()
import requests, certifi
from time import time
t0 = time()
Row_list = ['http://axiomglobal.sharepoint.com/sites/123456', 'http://axiomglobal.sharepoint.com/sites/SharePointo365globaltestsite', 'http:3456789', 'https://www.yahoo.com']
def get_site_status(site):
    try:
        response = requests.get(site, verify=certifi.where())
        status = response.status_code
    except:
        print('Connection Refused')
        return False
    if status == 401:
        print('web site exists, permission needed')
    elif status == 404:
        print('web site does not exist')
    elif status == 400:
        print('web site does not exist')
    elif status == 403:
        print('web site forbidden')
    elif status == 423:
        print('web site locked')
    elif status == 200:
        print('web site exists and is available')
    else:
        print('other')
    return True
threads = []
for row in Row_list:
    threads.append(spawn(get_site_status, row))
joinall(threads)

for thread in threads:
    print thread.value

print time() - t0

A: Realized the issue, I was using a list within a list earlier on in the code which caused the loop to look for '[url]' rather than 'url'


text:
Q: How to redirect to a url after drag and drop upload finishes I'm using drag & drop to upload images to replace a users avatar.  It's working fine, but I'm having difficulty in working out where to put code for redirect once the upload has finished.
Here is my code:
<script>
Dropzone.options.myDropzone = {
addRemoveLinks: true,
init: function() {
thisDropzone = this;
//listen to removedfile event
thisDropzone.on('removedfile', function(file){
$.get('avatar_handler.php?userid=id<?php echo $id2use; ?   >&action=remove&page=avatar&name='+file.name);
});
}
}
</script>

And my handler script:
switch( $action ) {
case 'upload':
if ( !empty($_FILES) ) {
storeFile($_FILES);
}
break;
case 'remove':
$filename = $_GET['name'];
removeFile( $filename );
break;
case 'show':
showFiles();
break;
}
function showFiles()
{
$result = array();
$files = scandir(DES);
if ( false!==$files ) {
foreach ( $files as $file ) {
//ignore current and parent folder indicator
if ( '.'!=$file && '..'!=$file) {
$obj['name'] = $file;
$obj['size'] = filesize(DES.$file);
$result[] = $obj;
}
}
}
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($result);
}
function storeFile( $file )
{
$tempFile = $file['file']['tmp_name'];

//move file to server
$targetPath = dirname( __FILE__ ) . DS. DES ;
$targetFile = $targetPath. time().$file['file']['name'];
** THIS IS WHERE I WANT TO DO A REDIRECT - after files is saved **
}
function removeFile( $fileName ) {
$targetPath = dirname( __FILE__ ) . DS. DES ;
$targetFile = $targetPath. $fileName;
//remove only when file exists
if ( file_exists($targetFile) ) {
unlink($targetFile);
}
}

Whenever I try adding to the handler.  The script errors
//show stored files
$.get('avatar_handler.php?userid=id<?php echo $id2use; ?>&action=show&page=avatar',   function(data) {
$.each(data, function(key,value){
var mockFile = { name: value.name, size: value.size };
thisDropzone.options.addedfile.call(thisDropzone, mockFile);
thisDropzone.options.thumbnail.call(thisDropzone, mockFile,
"usermedia/id<?php echo getuserid(); ?>/avatar/"+value.name);
});
},success: function(msg) {
window.location = 'http://mymusicwall.co.uk';
});

The above is what I tried. Stephen

A: You would put a redirect into the success function of your $.get call:
$.get(
    url: 'avatar_handler.php',
    data: {
        userid: 'id<?php echo $id2use;?>',
        action: 'remove',
        page: 'avatar',
        name: file.name
    },
    success: function(msg) {
        window.location = 'http://yourredirectlocation.com';
    }
);

Docs: http://api.jquery.com/jquery.get/

A: use:
document.location = '<redirect_location_url>';

in the success of your drag function


text:
Q: Difference in memory layout of pointer to base and pointer to derived object If I have the following classes:
class A
{
public:
  A(int val) : m_valA(val) {}

private:
   int m_valA;
};

class B : public A
{
public:
  B(int val) : A(0), m_valB(val) {}

private:
  int m_valB;
};

    B* pb = new B;

if I have a function which takes a A*, eg:
void func(A* pVal) {}

and pb is passed to this function, then in terms of low level memory layout, what is the difference between pval (in the function) and the pb pointer?
Doesn't a pointer point to the beginning of the object?  In which case how will the two pointers be different?

A:
Doesn't a pointer point to the beginning of the object? In which case how will the two pointers be different?

If you pass a pointer to a B object to func(A* pVal), then inside the func() implementation the pVal pointer will point to the A sub-object part of the B object.  It's unspecified whether they will be at the same location (though for a simple inheritance situation as in your example, it almost certainly will be).
If the A sub-object is actually at a different offset (which might need to be the case if multiple inheritance is involved, for example), then the compiler will make the appropriate adjustment automatically when it compiles the call.  The compiler can do this because at the call site it knows it's dealing with a B* and needs to convert it to an A* to pass to func().  That's a safe and normal conversion since B publicly inherits from A.

A: void func(A* pVal) {}

pb is upcasted to pVal. It points to the base class sub-object. However, if it is a polymorphic class, it calls the overridden derived class methods if virtual.
pb can access both the sub-objects members depending upon access level. However, pVal access only the base class sub-object members. However run-time polymorphism is possible if the base class is polymorphic.


text:
Q: How fast is git over subversion with remote operations? I've seen a ton of statistics about how git is faster than svn, but most of those statistics are only comparing git's local operations to SVN's equivalent remote operation. Dos anyone have links to hard data comparing git's speed with remote operations to SVN's speed with remote operations?

A: As mentioned in the comments, the remote operations involved with Git are quite different than with Subversion:

*

*git will initially get all the history of a repo, and then can work autonomously.

*Subversion will only get the most recent history, and request more information to the server when needed.

But do not forget that Git has been built around one major feature: being able to apply dozen of patches (and/or merges) fast.
That is the one operation which should be measured between the two tools, and one where Git has a sizable advantage, the comparison and merge of different versions of a file being a pure local operation, as illustrated in this Git Subversion comparison page (disclaimer: written in the Git wiki)

Git is extremely fast. Since all operations (except for push and fetch) are local there is no network latency involved to:

That means compare only remote operations will greatly restrict the features being compared...

A: Take a look at references (original sources) mentioned on http://git.wiki.kernel.org/index.php/GitBenchmarks.
Some of them did include comparison of speed with Subversion, if I remember it correctly.


text:
Q: If a continuous function is positive on the rationals, is it positive almost everywhere? I made up this question, but unable to solve it:

Let $f : \mathbb R \to \mathbb R$ be a continuous function such that $f(x) > 0$ for all $x \in \mathbb Q$. Is it necessary that $f(x) > 0$ almost everywhere?

This is my attempt.

*

*It is easy to show that $f(x) \geq 0$ everywhere, so the real question is whether $f$ can be zero at an "almost all" irrational points.

*The function can become $0$ at isolated points, e.g., $f(x) = (x - \sqrt{2})^2$. In particular, the qualification "almost" is necessary for the question to be nontrivial.

*Every rational point has an open neighborhood where $f$ is positive. Hence at least know that the set $\{ x \,:\, f(x) > 0 \}$ is not a measure-zero set.

*I first mistakenly assumed that Thomae's function provides a counter-example to this. Indeed, it is positive at all rationals and zero at all irrationals, but the function is continuous at only the irrationals, not everywhere.
Then I tried to prove that the question has an affirmative answer, but do not have much progress there. Please suggest some hints!

A: Here's a hint: If you can think of closed set $C \subset \mathbb{R}$ of positive measure containing no rationals, then the function sending $x$ to its distance from $C$ is an example.
(I changed this because I just realized you were looking for a hint)

A: Here's another approach to the question, in hint form:
(1) Construct a function $f(x)$ that is continuous, nonnegative, positive at $x=0$, bounded above by 1, and supported on an interval of length at most 1.
(2) Deduce that if $a,b>0$ and $c$ are real numbers, then $a f(b(x-c))$ is continuous, nonnegative, positive at $x=c$, bounded above by $a$, and supported on an interval of length at most $1/b$.
(3) Let $q_1,q_2,q_3,\dots$ be an enumeration of the rationals. Show that the function $$\sum_{j=1}^\infty 2^{-j} f\big( 2^j(x-q_j) \big)$$ is continuous, nonnegative, positive at every rational number, but equal to zero on a set of infinite measure.


text:
Q: Liu 1.1.5, extension of scalars I tried to do the exercise 1.1.5 on Liu's Algebraic Geometry and Arithmetic Curves. Namely,
Let $\rho:A\to B$ be a ring homomorphism, $M$ an $A$-module, and $N$ a $B$-module. How can I show that there exists a canonical isomorphism of $A$-modules
$$\operatorname{Hom}_A(M,\rho_*N)\simeq \operatorname{Hom}_B(\rho^*M,N)?$$
Here $\rho_*$ is the module induced by natural way by $a\cdot y=\rho(a)y$ and $\rho^*M$ is the extension of scalars $M\otimes_AN$.
Do I have to use the universal property of tensor products?


text:
Q: Erro ao salvar conteudo de TRichEdit Delphi no PostgresSQL Tenho que gravar textos formatados na base de dados PostgreSQL, quando eu carrego o RichEdit mostra o texto normal, mas quando salvo e vou olhar na base de dados os caracteres etão assim:

屻瑲ㅦ慜獮屩湡楳灣ㅧ㔲尲敤晦笰晜湯瑴汢屻て晜睳獩屳灦煲尲捦慨獲瑥‰慃楬牢㭩筽晜就湦汩晜档牡敳ぴ䌠䑉潆瑮䘫㬳筽晜尲湦汩晜档牡敳ぴ䌠䑉潆瑮䘫㬵筽晜尳湦汩晜档牡敳ぴ䌠䑉潆瑮䘫㬴筽晜尴湦汩晜档牡敳ぴ䌠䑉潆瑮䘫㬷筽晜尵湦汩晜档牡敳ぴ䌠䑉潆瑮䘫㬸筽晜尶湦汩晜档牡敳ぴ䌠䑉潆瑮䘫㬶筽晜尷湦汩晜档牡敳ぴ吠桡浯㭡絽਍屻潣潬瑲汢㬠牜摥㔲尵牧敥㉮㔵扜畬㉥㔵尻敲㡤尹牧敥㡮尹汢敵㤸尻敲㕤尴牧敥㥮尵汢敵㐱㬶牜摥尰牧敥の扜畬づ尻敲㕤就牧敥㕮就汢敵ㄵ尻敲つ杜敲湥尰汢敵㔲㬵ൽ尊楶睥楫摮尴捵就慰摲煜屪慬杮〱㘴晜尰獦㠱传䰠䍔

Na base de dados eu uso UTF-8 e no cliente LATIN1, tudo funciona normal menos o RichEdit
Estou sem parametro pra resolver esse problema
Segue parte do código para melhor entendimento de como os dados entram na base, a parte em questão é no if (fdm.Salvar)...
  if (zqrOrcItens.RecordCount = 0) then
  begin
    TFuncoes.pMensagem('Não existem itens na lista para editar');
    Exit;
  end;
  fdm.Salvar := False;
  fdm.RichStream := TStringStream.Create(zqrOrcItensTexto.AsAnsiString);
  //zqrOrcItensTexto.SaveToStream(fdm.RichStream);

  f_richedit := Tf_richedit.Create(nil);
  fdm.RichStream.Position := 0;
  f_richedit.RichEdit.Lines.LoadFromStream(fdm.RichStream);
  TFuncoes.pJustRichEdit(f_richedit.RichEdit, False);
  f_richedit.ShowModal;

  if (fdm.Salvar) then
  begin
    zqrOrcItens.Edit;
    fdm.RichStream.Position := 0;
    zqrOrcItensTexto.AsString := fdm.RichStream.DataString;
    zqrOrcItenstexto_puro.AsString := fdm.TextoPuro;
    zqrOrcItens.Post;
    fdm.zConecta.Commit;
  end;
  FreeAndNil(fdm.RichStream);

RichStream é uma variável TStringStream que esta dentro de um datamodule para ser vista em vários pontos da aplicação.
A ideia é criar uma variável do tipo TStringStream para receber o conteúdo do RichEdit e converter em caractere aceitável pelo PostgreSQL
Importante: Essa rotina foi feita a muito tempo com versões antigas do Delphi, PostgreSQL e Zeos e na época foi a única forma que consegue inserir conteúdo de RichEdit na base e visualizar de maneira compreensível.


text:
Q: Changing a string pointer in C Apparently I'm a member of a large club that just doesn't understand C-style pointers correctly. Here's my program:
void changethestring (const char * thestring)
{
    thestring = "string two";
}

int _tmain(int argc, _TCHAR* argv[])
{
    const char * teststring = "string one";
    changethestring(teststring);
    printf("The string is: %s.\n", teststring);
    return 0;
}

My intent is that changethestring() should cause the pointer to point to "string two". My logic is that I'm giving the function a pointer. The function should be able to change the pointer to point to a different area in memory. And that change should persist outside the function.
Yet that's not what happens. In the printf() statement, the string is still "string one".
Can anyone explain why this is, what's happening under the covers, and how I can write a function changethestring() to change the string to which the pointer points?

A: You should give pointer to a pointer instead of just pointer. The reason for this is that in C, all arguments are sent by value. So in order to change the value of a variable which is a pointer, you need to send a pointer to this variable, therefore, pointer to a pointer.
UPDATE: You can define string literal outside of the changethestring function, but it's not needed, because string literals are stored in a global string table for the whole lifetime of the program. So both this:
const char* STRING_TWO_LITERAL = "string two";

void changethestring (const char ** thestring)
{
    *thestring = STRING_TWO_LITERAL;
}

int _tmain(int argc, _TCHAR* argv[])
{
    const char * teststring = "string one";
    changethestring(&teststring);
    printf("The string is: %s.\n", teststring);
    return 0;
}

and this:
void changethestring (const char ** thestring)
{
    *thestring = "string two";
}

int _tmain(int argc, _TCHAR* argv[])
{
    const char * teststring = "string one";
    changethestring(&teststring);
    printf("The string is: %s.\n", teststring);
    return 0;
}

should work.

A: By passing the pointer by value, it will get back to its initial value when you exit your function.
You should pass it by reference as Ashalynd suggest or you can also return a new value for this pointer:
const char * changethestring (const char * thestring)
{
     thestring = "string two";
     return thestring;
}

int main(void)
{
    teststring = changethestring(teststring);
}


text:
Q: Invalid client in aqueduct's db_and_auth/wildfire example I am new to Aqueduct and I am facing a invalid client error whenever I try to make a request to the /auth/token or /auth/code route.
I have already added the OAuth2.0 client and verified the secret is correct.
My request to /auth/token looks like this:
Future main() async {
  var http2 = new http.Client();
  var clientID = "com.wildfire.mobile";
  var clientSecret = "myspecialsecret ";
  var body = "username=usr&password=pwd&grant_type=password";
  var clientCredentials = new Base64Encoder().convert(
      "$clientID:$clientSecret".codeUnits);
  var response = await
  http.post(
      "http://localhost:8081/auth/token",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": "Basic $clientCredentials"
      },
      body: body);

And when I try logging in in /auth/code with a username in the _user database the server throws a 400:invalid_client

A: It was indeed a misconfiguration issue. After deleting all my databases, I added a database.yaml file, which I thought was the same as the config.yaml but apparently is not.
The database.yaml looks like this:
 username: adan
 password: pass
 host: localhost
 port: 5432
 databaseName: wildfire_db

while the config.yaml looks like this:
database:
 username: adan
 password: pass
 host: localhost
 port: 5432
 databaseName: wildfire_db

I also ran the aqueduct auth and aqueduct db commands without the --connect flag, i.e. using the config files.


text:
Q: Give two inputs to torch::jit::script::Module forward method I am trying to build and train a network in python using pytorch . My forward method takes two inputs as follows :
def forward(self, x1, x2):

I trained this model in python and saved using torch.jit.script .
Then I load this model in c++ using the torch::jit::load.
How do I now pass the inputs to the model in c++ ?
If I try passing two separate tensors to the forward method like the following
    std::vector<torch::jit::IValue> inputs1{tensor1};
    std::vector<torch::jit::IValue> inputs2{tensor2};
    at::Tensor output = module.forward(inputs1,inputs2).toTensor();

then I receive an error saying that the method forward expects 1 argument, 2 provided.
I can't also concatenate the two tensors since the shapes are different in all axis.

A: The problem is by concatenating the two tensors and giving the concatenated tensor as input to the model. Then in the forward method, we can create two separate tensors using the concatenated tensor and use them separately for the  output computation.
For concatenation to work, I appended the tensors with 0's so that they are of the same size in all axis except the one in which concatenation is to be done.


text:
Q: Data Binding in Xamarin.Forms I want all the records created in ASP.NET Web Application to be shown in my Mobile App Xamarin.Forms. What's happening to my program is that I was able to create records in my Web Application but I wasn't able to make it bind it in my Xamarin.Forms Mobile app. I have created a MainViewModel that will get the records from the Web Application which I have binded in my MainPage.
What can I do to show all the records I have created?
These are my codes. Any help will be highly appreciated. Thank you so much.
MainPageMain.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:XamarinDemoApp"
         x:Class="XamarinDemoApp.MainPageMain"
         xmlns:ViewModels="clr-namespace:XamarinDemoApp.ViewModels;assembly=XamarinDemoApp"
         BackgroundColor="Teal"
         Title=" Title Bar">

 <ContentPage.BindingContext>
  <ViewModels:MainViewModel/>
   </ContentPage.BindingContext>

  <StackLayout Orientation="Vertical">

    <ListView ItemsSource="{Binding EmployeesList}"
          HasUnevenRows="True">
     <ListView.ItemTemplate>
      <DataTemplate>
      <ViewCell>
        <StackLayout Orientation="Horizontal">
          <Label Text="{Binding Name}"
                  FontSize="24"/>
          <Label Text="{Binding Department}"
                  FontSize="24"/>

        </StackLayout>

      </ViewCell>

     </DataTemplate>

     </ListView.ItemTemplate>

  </ListView>

   <Label Text="This is the Main Page"/>

   </StackLayout>
 </ContentPage>

MainViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using XamarinDemoApp.Models;
using XamarinDemoApp.Services;

namespace XamarinDemoApp.ViewModels
    {
public class MainViewModel : INotifyPropertyChanged
{

    private List<Employee> _employeesList;

    public List<Employee> EmployeesList
    {
        get {return _employeesList;}
        set
        {
            _employeesList = value;
            OnPropertyChanged();
        }
    }

    public MainViewModel()
    {

        InitializeDataAsync();
    }

    private async Task InitializeDataAsync()
    {
        var employeesServices = new EmployeesServices();

        EmployeesList = await employeesServices.GetEmployeesAsync();
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
           PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    }
}

A: In your code you are using List<Employee> as a source to your listview.
Refer this link. It says :

If you want the ListView to automatically update as items are added, removed and changed in the underlying list, you'll need to use an ObservableCollection. ObservableCollection is defined in System.Collections.ObjectModel and is just like List, except that it can notify ListView of any changes

Update your code to use ObservableCollection.
ObservableCollection<Employee> employees= new ObservableCollection<Employee>();

// Convert/Add your list in observable collection
foreach (Employee e in EmployeesList )
{
    employees.Add(new Employee { Name=e.Name,Department=e.Department } )
}

After that you can set this as a source to your ListView.
UPDATE
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using XamarinDemoApp.Models;
using XamarinDemoApp.Services;

namespace XamarinDemoApp.ViewModels
    {
public class MainViewModel : INotifyPropertyChanged
{

    private ObservableCollection<Employee> _employeesList;

    public ObservableCollection<Employee> EmployeesList
    {
        get {return _employeesList;}
        set
        {
            _employeesList = value;
            OnPropertyChanged();
        }
    }

    public MainViewModel()
    {

        InitializeDataAsync();
    }

    private async Task InitializeDataAsync()
    {
        var employeesServices = new EmployeesServices();

        var EmployeesListNew = await employeesServices.GetEmployeesAsync();

        foreach (Employee e in EmployeesListNew )
        {
            EmployeesList.Add(new Employee { Name=e.Name,Department=e.Department } )
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
           PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    }
}


text:
Q: SSRS BIDS 2008 R2 pie chart data labels overlapping
As seen in image, the data labels are overlapping and making the data difficult to read. Anybody know how to sort this?

*

*Have now updated the question as I have changed the PieLabelStyle to Outside and in the picture you can see in the design view above it acknowledges this however when I preview the chart it remains on the inside! (See image 3 link below)

image3

A: Technet has a nice piece on this:
The secret is in the Properties pane under the Custom Attributes section:

A: A good solution is to sort the pie chart between small and big pieces. I posted a script that helps with this issue:
http://williameduardo.com/development/ssrs/pie-chart-series-label-overlapping-in-ssrs/