text:
Q: Escaping input for insertion into XQuery string Say I have the following code:
let $search := "placeholder"
...
...functx:get-matches-and-non-matches($t,$search)...

This code is stored like this in a file, gets loaded into a string (by PHP), placeholder gets replaced with user input, and then the code gets executed.
Obviously, " needs to be escaped somehow.
Is there any other stuff that needs to be escaped or removed before any user input is safe?
So far, I discovered that I need to replace " with " for stuff to work, and in the process also discovered that \ actually needs to be \\ here (or \\, which makes it "\\\\" in php) and that escaping { and } might be a good idea, because they make the regex parser throw up otherwise.

A: Don't dynamically construct queries if you don't have to, you'll  have to put lots of effort into escaping to prevent code injections (and still might overlook a parameter somewhere). Consider using externally bound variables instead, which can be compared to prepared statements in SQL.
As you seem to use BaseX and PHP, this is an example for the BaseX PHP binding:
// create query instance
$input = 'declare variable $name external; for $i in 1 to 10 return element { $name } { $i }';
$query = $session->query($input);
// bind variable
$query->bind("name", "number");
// print results
print $query->execute()."\n";

If you're using another interface to BaseX, registering external variables should be possible with all of them. Other XQuery implementations should also provide similar mechanics to bind variables, external variables are officially XQuery standard.


text:
Q: Initializing elements of a map conditionally in Clojure I'm looking for the best way to conditionally avoid adding an element to a map when it is being initialized/defined. In this case, I want to avoid adding an element to a map if the value for the key is nil.
(defn create-record [data]
  (let [res {
    :username (data :username)
    :first-name (get-in data [:user-info :name :first])
    :last-name (get-in data [:user-info :name :last])
    :gender (get-in data [:user-info :sex])
   }])
)

I don't want to add gender to the map if the results of the get-in are nil (the sex field in the data does not exist). Is there a way to do this when I create the map? I could remove all keys whose value is nil after I create the map but, in some cases, I want some keys to have nil values and others to not be in the map at all if they would have nil values.

A: (cond-> {:username   (data :username)
         :first-name (get-in data [:user-info :name :first])
         :last-name  (get-in data [:user-info :name :last])}
    (get-in data [:user-info :sex]) (assoc :gender (get-in data [:user-info :sex])))

A: I would use a combination of merge and when-let for these optional parameters.
The core idea is to merge in either a single element map or nil for each of the optional parameters.  Merging in nil will do nothing, so you won't see the nil in the map.
(defn create-record [data]
  (let [res (merge {:username (data :username)
                    :first-name (get-in data [:user-info :name :first])
                    :last-name (get-in data [:user-info :name :last])}
                   (when-let [gender (get-in data [:user-info :sex])]
                     {:gender gender}))]
    res))

Depending on how frequently you need to do this, I would recommend writing a short macro or function around the when-let to keep the code more concise.

A: (defn create-record [data]
   (merge {:username   (data :username)
           :first-name (get-in data [:user-info :name :first])
           :last-name  (get-in data [:user-info :name :last])}
           (when
             (get-in data [:user-info :sex])
             {:gender (get-in data [:user-info :sex])})))

Just add when for each element you want to check if it is not nil and then it will return a map to be merged or nil that will not affect the return map value.
You can merge several maps together so there is no limit of maps to merge and you can return a separate map for each element that is not nil.

A: Building a map and dissocing the keys which you want to impose conditions upon based on a predicate (here -- nil?) might be the simplest approach (NB. this function only tests keys explicitly mentioned as arguments; those not mentioned are never removed, whether the values attached to them satisfy the predicate or not):
(defn dissoc-when
  "Dissoc those keys from m which are mentioned among ks and whose
   values in m satisfy pred."
  [pred m & ks]
  (apply dissoc m (filter #(pred (m %)) ks)))

At the REPL:
user> (dissoc-when nil? {:foo nil :bar true :quux nil} :foo :bar)
{:quux nil, :bar true}

Though generally speaking, if you expect to work with a lot of maps representing real world entities of some particular type, you might want to go with records -- and then you can just skip all nils at the stage where you extract values from your input map, because records, when viewed as maps, always seem to include the keys corresponding to their fields. E.g.
(defrecord Person [username first-name last-name])

Then you can factor out the logic for "schema conversions" between maps:
(defn translate-map
  "Transforms the data map in accordance with the spec in table.
   Skips nil-valued entries."
  [data table]
  (->> table
       (keep (fn [[to from]]
               (when-let [from-val (get-in data from)]
                 [to from-val])))
       (into {})))

Now your create-record function becomes a composition of translate-map and map->Person:
(defn create-person [data]
  (map->Person
   (translate-map data {:username [:username]
                        :first-name [:user-info :name :first]
                        :last-name [:user-info :name :last]
                        :gender [:user-info :sex]})))

If you do prefer working with regular maps, you could use something like the following instead for equivalent output:
(defn create-person [data]
  (merge (zipmap [:username :first-name :last-name] (repeat nil))
         (translate-map data {:username [:username]
                              :first-name [:user-info :name :first]
                              :last-name [:user-info :name :last]
                              :gender [:user-info :sex]})))

At the REPL (record version in Clojure 1.3):
user> (create-person {:username "jsmith"
                      :user-info {:name {:first "John" :last "Smith"}}})
#user.Person{:username "jsmith", :first-name "John", :last-name "Smith"}
user> (create-person {:username "jsmith"
                      :user-info {:name {:first "John" :last "Smith"}
                                  :sex :male}})
#user.Person{:username "jsmith", :first-name "John", :last-name "Smith", :gender :male}

A: You could do something like
(let [not-nils #{:gender}]
  (defn create-record [data]
    (into {} (for [[k v] {:username (data :username)
                          :first-name (get-in data [:user-info :name :first])
                          :last-name (get-in data [:user-info :name :last])
                          :gender (get-in data [:user-info :sex])}
                   :when (not (and (nil? v) (not-nils k)))]
               [k v]))))

A: (defn create-record [data]
  (let [gender (get-in data [:user-info :sex])]
    (->> {:username (data :username)
          :first-name (get-in data [:user-info :name :first])
          :last-name (get-in data [:user-info :name :last])}
         (#(if gender (assoc % :gender gender) %)))))

A: Here is an attempt:
(defn exclude-nils-for [m kw-set]
    (apply hash-map (apply concat (remove (fn [[k v]] (and (kw-set k) (nil? v))) m))))

Test:
user> (exclude-nils-for {:gender "m" :name "Thomas" :age "24"} #{})
{:age "21", :gender "m", :name "Thomas"}
user> (exclude-nils-for {:gender "m" :name "Thomas" :age "24"} #{:name})
{:age "21", :gender "m", :name "Thomas"}
user> (exclude-nils-for {:gender "m" :name nil :age "24"} #{:name})
{:age "21", :gender "m"}
user> (exclude-nils-for {:gender "m" :name nil :age nil} #{:age})
{:gender "m", :name nil}

A: You can define your fields and which ones are optional:
(def fields
[[:username   [:username]]
 [:first-name [:user-info :name :first]]
 [:sex        [:user-info :sex]          true]])

and then write a function to use that info:
(defn create-record [data keys]
  (->>
    (for [[n k ignore-nil?] keys
            :let [v (get-in data k)]
            :when (or (not ignore-nil?) v)]
      [n v])
    (into {})))

and it will work like this:
; If :sex is missing don't create a field
user=> (create-record {:username "dr" :user-info { :name {:first "Dave"} }} fields)
{:username "dr", :first-name "Dave"}

user=> (create-record {:username "dr" :user-info { :name {:first "Dave"} :sex :m }} fields)
{:username "dr", :first-name "Dave", :sex :m}

; If :first is missing, create a nil field
user=> (create-record {:username "dr" :user-info { :name {} :sex :m }} fields)
{:username "dr", :first-name nil, :sex :m}

Modify as needed :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Understanding the Application of HMM to a Dataset I have been working on a dataset that has $1000$ rows and $10$ columns with $1$ response and $9$ predictor variables. The response variable is binary and the predictors are integers.
I am thinking to apply hidden Markov model to predict response variable $y$ for given predictors $x_i$, $i=1,...,9$. I have read many documents and forum discussions about how to apply hidden Markov models for prediction purposes. However, I could not clarify/resolve my questions/concerns.
Let me tell you what I know about how to apply HMM into my problem, for sure; since $y$ is binary, I have $2$ hidden states; "$0$" and "$1$".
What I am not sure is as follows:

*

*How should we handle observations? That is; (1) history of $y$ itself could be observations, just like a time series model, (2) one of the predictors could be observations (not sure how to select the one), or (3) all $9$ predictors could be observations. However, when I read the functions of HMM in $R$, observations always defined as sequence of observations, then how to apply the third option? Can sequence of observations be a matrix? Are all these options always available (even might not be options)? How to know which one to choose?

*If I choose to apply the first option given above, then are observable states (observations) as the same as the hidden states?

*If I choose to apply the third option given above, how to create emission probabilities for each predictor/observation?

*I will be using $R$ to solve the problem. Which function would be more suitable for my problem. Because, I have tried the third option with depmixS4 package, but I got "NA/NaN/Inf in foreign function call (arg 10)" error.

Thank you.


text:
Q: Having an issue while doing Socket programming in C
In this problem, client is sending server, two strings. And server is getting the values correctly, but the only problem is that after the loop breaks, n[0] and n[1] contains the same values, maybe the last value is overwritten on both indices. If I print n[0] and n[1] inside the loop right after storing values, it shows correct output.

const char * n[2];
    int i = 0;
    while(i<2)
    {
        valread = read( new_socket , buffer, 1024);
        n[i] = buffer;
        printf(n[i]);
        printf("\n");
        i++;
    }

    printf("After loop: \n\n");
    printf(n[0]);
    printf(n[1]);

Sample output:

Hello
there
After loop:
therethere

A: You are overwriting the buffer in the second iteration, consider using:
char buffer[2][1024];
while (i < 2)
{
    ssize_t size = read(new_socket, buffer[i], 1024);

    buffer[i][size] = '\0';
    printf("%s\n", buffer[i]);
    i++;
}
printf("After loop: \n\n");
printf("%s\n", buffer[0]);
printf("%s\n", buffer[1]);

or using dynamic memory:
char *buffer[2];
while (i < 2)
{
    buffer[i] = malloc(1024);

    ssize_t size = read(new_socket, buffer[i], 1024);

    buffer[i][size] = '\0';
    printf("%s\n", buffer[i]);
    i++;
}
printf("After loop: \n\n");
printf("%s\n", buffer[0]);
printf("%s\n", buffer[1]);

Notice that read can fail, always check the return:
ssize_t size = read(new_socket, buffer[i], 1024);

if (size == 0)
{
    // handle EOF
}
else if (size == -1)
{
    // handle error
    perror("read");
    ...
}


text:
Q: Run threads socket parallel in java I have a program in java with two threads. One thread is a socket server and the other thread is a socket client.
This program communicates with other programs, sending and receiving messages on different ports.
I'm able to send and receive a message, but when I receive a message as the server, then I cannot send a message as the client (it seems to be stuck in server mode).
example:
port1 is the client and I am able to send a message to the server and receive back the response message on this port.
port2 is the server and I am able to receive a message and send back the response from this port.
So far, the two seem to work fine.
However, when the server accepts the connection, I am not able to send a message from the client thread, I can only accept messages from the server thread.
Two threads must be running at the same time because I don't know when the server thread may receive a message.
I have tried to suspend and resume the two threads in a while true loop with sleep in between, but it's not working. The problem is that when the server thread starts and accepts a connection, I cannot handle the client thread and send messages.
The two threads must run in parallel.
This is my code:
    class subcl extends Thread{
    int port1,port2;
    String name;
    public subcl(int port1,int port2,String name) {
        this.port1=port1;
        this.port2=port2;
        this.name=name;
    }
    @Override
    public void run() {
         try  {
            Socket echoSocket = new Socket("localhost", port1);
            System.out.println("Client started.");
            PrintWriter serverOut = new PrintWriter(echoSocket.getOutputStream(), true);
            Scanner serverIn = new Scanner(echoSocket.getInputStream());

            Scanner keyboard = new Scanner(System.in);

            while (true/*keyboard.hasNextLine()*/)  {
             System.out.println("subscribe ");
             String msg=keyboard.nextLine();
             serverOut.println(name+"~"+msg+"~"+port2);
             String response = serverIn.nextLine();
             System.out.println("Response: " + response);

                     }

          /*  serverIn.close();
            serverOut.close();
            echoSocket.close();*/
        }
        catch (UnknownHostException e)  {
            System.err.println("Unknown host: " + e);
            System.exit(1);
        }
        catch (IOException e)  {
            System.err.println("Could not communicate with server: " + e);
            System.exit(1);
           }
           }//end run
           }//end class

     class subser extends Thread {

      int port;

      public subser (int port) {
        this.port = port;
        }

      @Override

       public void run() {

        try  {
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("Server started");

            Socket clientSocket = serverSocket.accept();
            System.out.println("Accepted connection");
            Scanner clientIn = new Scanner(clientSocket.getInputStream());

            PrintWriter clientOut = new PrintWriter(clientSocket.getOutputStream(), true);

            //String message;
            do  {
                String message = clientIn.nextLine();
                System.out.println("Received: " + message);
                clientOut.println(message);

               }  while (true);

            /*clientOut.close();
            clientIn.close();
            clientSocket.close();
            serverSocket.close();*/
        }
        catch (IOException e)  {
            System.err.println(e);
            System.exit(1);
        }
       }//end run
      }//end class

     public class Sub1 {

     public static Thread threadcl;

     public static Thread threadser;

    public static void main(String[] args) {

        int port1=7777;// server port
        int port2=7779;//sub port
        String name="s1";

         threadcl= new subcl(port1,port2,name);
           threadcl.start();

         threadser=new subser(port2);
        threadser.start();

      }//end main
      }


text:
Q: Typescript evaluating node modules? I have a mostly js project in which only the tests are written in typescript.  However these tests (jest) show errors from node modules e.g.
 console.error
      Warning: Failed prop type: Invalid prop `in` of type `function` supplied to `ForwardRef(Fade)`, expected `boolean`.

How can I tell typescript to ignore all files except my test files?
Thanks

A: Question similar to How to force tsc to ignore node_modules folder?
You can try --skipLibCheck. But it's better to solve the type problem, usually it spots some problems (like duplicated versions)

A common case where you might think to use skipLibCheck is when there are two copies of a library's types in your node_modules. In these cases, you should consider using a feature like yarn's resolutions to ensure there is only one copy of that dependency in your tree or investigate how to ensure there is only one copy by understanding the dependency resolution to fix the issue without additional tooling.


text:
Q: Ranking criteria for the same frequency words in Tokenizer() and working of Tokenizer().texts_to_matrix() in Keras For the text list,
sent = ["I am whatever you say I am and if I wasn't, why would you say I am" ,
        'but but but, anyways, it is still me because I am me']

tokenizer_obj = Tokenizer(num_words=15)

tokenizer_obj.fit_on_texts(sent)

You get the  answer from tokenizer_obj.texts_to_sequences(sent)
as
>>> [[1, 2, 7, 4, 5, 1, 2, 8, 9, 1, 10, 11, 12, 4, 5, 1, 2],
     [3, 3, 3, 13, 14, 6, 1, 2, 6]]

and from tokenizer_obj.word_index, a dict of words based on frequency as
{'i': 1,
 'am': 2,
 'but': 3,
 'you': 4,
 'say': 5,
 'me': 6,
 'whatever': 7,
 'and': 8,
 'if': 9,
 "wasn't": 10,
 'why': 11,
 'would': 12,
 'anyways': 13,
 'it': 14,
 'is': 15,
 'still': 16,
 'because': 17}

I get that the raking is based on the most frequent words but what if there is a tie and there is in my case for the words in the dict where is frequency is 1 for all the words. What is the criteria for that because I don't see any pattern in that.
Plus  the code, tokenizer_obj.texts_to_matrix(sent) returns a matrix in binary as
>>> array([[0., 1., 1., 0., 1., 1., 0., 1., 1., 1., 1., 1., 1., 0., 0.],
           [0., 1., 1., 1., 0., 0., 1., 0., 0., 0., 0., 0., 0., 1., 1.]])

What does that stands for?

A: Let's take a simpler example.
sent = ["I am whatever you say say"]

If there's a tie in the frequency the next in line would be the "order" the words appeared. The words appeared first gets the lower id. You can verify this with the following example.
tokenizer_obj = Tokenizer(num_words=6)
tokenizer_obj.fit_on_texts(sent)
print(tokenizer_obj.word_index)

Which gives,
>>> {'say': 1, 'i': 2, 'am': 3, 'whatever': 4, 'you': 5}

Here you can see that the word "say" (most frequent) gets the lowest ID and the rest is followed by the order they appear in the corpus.
What does texts_to_matrix do?
It's simply a binary vector (num_words) elements long. Value at each index indicates whether that word (with the ID indicated by the index) is present in the data or not. E.g. If we take the word "I" (which has ID 2), the element at index 2 is set to 1.
print(tokenizer_obj.texts_to_matrix(sent))

>>> [[0. 1. 1. 1. 1. 1.]]

You might note the leading 0. 0 is a reversed ID in the keras Tokenizer, used to indicate padding. So that will become 1 only if you have padding in your sentence.


text:
Q: Rails-6: Mass import HABTM produces thousands inserts After hours of googling for best practice, I came up here.
I have a new Foo object, and want to mass-assign thousands of bars to it, which I've pre-loaded:
@foo = Foo.create
@bars = Bar.find_all_by_some_attribute(:a)

What's the fastest way to do this? I've tried:
@foo.bars = @bars
@foo.bars << @bars

This results in thousands of insert queries being created.
Is there a Rails 6 (Insert_all) way to solve my issue or do I have to solve it with the "m2m_fast_insert" gem or hardcoded SQL?

A: If you have a Join table setup, like:
class Item < ActiveRecord::Base
  has_and_belongs_to_many :orders
end

class Order < ActiveRecord::Base
  has_and_belongs_to_many :items
end

class ItemsOrders < ActiveRecord::Base
  belongs_to :item
  belongs_to :order
end

I believe you could insert many ItemOrders in this case (or whatever your join model is) with insert_all, which is new in Rails 6. If not your best bet is some amount of custom SQL. I did find another answer on SO that seemed to have a good starting point for the SQL: What is the fastest way to create mass HABTM associations in Rails?


text:
Q: Proof of the cube root trick I'm wondering about the cube root trick:
To find a cube root of a large number, you only have to memorize the cube roots of numbers 1 to 10.
Take the last digit of your number, it'll be the last digit of the result.
then ignore the last 3 digits, look at what remains, and find which of the first 10 cubes is the closest to it without going over.
No put the result together.
Example: $\sqrt[3]{39304} = 34$ because last digit of 39304 is 4 and $3^3 =  27$ is closest cube to 39.
How can you proof that this trick works?

A: If you only look at the last digit (modulo $10$), you have the pattern:
$$0^3\equiv_{10}0$$
$$1^3\equiv_{10}1$$
$$2^3\equiv_{10}8$$
$$3^3\equiv_{10}7$$
$$4^3\equiv_{10}4$$
$$5^3\equiv_{10}5$$
$$6^3\equiv_{10}6$$
$$7^3\equiv_{10}3$$
$$8^3\equiv_{10}2$$
$$9^3\equiv_{10}1$$
For instance, $\sqrt[3]{140608}=52$, since $5^3<140<6^3$, and the last digit $8$ corresponds to the $2$ (see pattern). The reason why you don't have to think about the three last digits is because $$(a\cdot 10+b)^3=a^3\cdot 1000+3a^2b\cdot 100+3ab^2\cdot 10+b^3$$ So the first three digits is greater than $a^3$ (which means that this method would become hard to use for large numbers). This only works when you know that the number you're given is a perfect cube.


text:
Q: Creating local branch and rebasing it to master I am sure there is already lots of discussions of this but we had a long discussion of this at work and there was no clear answer which is the right way to do this. We came up with two different techniques and maybe there is even more ways you can handle this situation.
First way:
git clone master
git checkout -b dev_branch
[do some changes, commit]
[master branch changed]
git checkout master
git pull
git checkout dev_branch
git rebase master
git push master

Second way:
git clone master
git checkout -b dev_branch
[do some changes, commit]
[master branch changed]
git checkout master
git pull
git rebase --onto master master dev_branch
git push master

Is there something wrong to push from local development branch to the actual master in this case?

A: Why not skip then unnecessary checkout of master?
git clone
git checkout -b dev_branch
[do some changes, commit]
git fetch origin
git rebase origin/master
git push origin HEAD:master


text:
Q: Virtualized SQL Server Memory Oddity I've not seen this before, though perhaps it is common.  I am looking at a virtualized (VMWare 5.5) SQL Server (2008R2 on Windows 2008 R2). What I am seeing is that in Task Manager*, sqlserver.exe is using about 163 MB of RAM, if I use procexp, the same service shows just under 500 MB of RAM used.
The VM has 32GB of RAM and Task Manager shows 31.7 GB of that RAM being used.  The VMWare Perfmon counter does not seem to be indicating any ballooning (perhaps I read something the wrong way).
Thoughts/guidance appreciated.  I am trying to right size a new SQL VM.  At this point I have not yet obtained access to vSphere or the vCenter database.
* Using Task Manager because I was looking at overall memory utilization, not just SQL Server. I was warned by a performance touchy admin to keep my treading very very light.

A:
What I am seeing is that in Task Manager, sqlserver.exe is using about 163 Mb of RAM, if I use procexp, the same service shows just under 500 MB of RAM used.

You should never look at task manager to check SQL Server memory utilization. It would never show you correct result. You should use a DMV sys.dm_os_process_memory, if you are using SQL Server 2008 and above, to check SQL Server memory utilization.
select
(physical_memory_in_use_kb/1024) as PhyMemory_usedby_Sqlserver_MB,
(locked_page_allocations_kb/1024 ) as Locked_pages_used_Sqlserver_MB,
(virtual_address_space_committed_kb/1024 ) as Total_MemoryUsed_in_MB,
process_physical_memory_low,
process_virtual_memory_low
from sys. dm_os_process_memory

Note:
PhyMemory_usedby_Sqlserver_MB is the committed memory and is backed by physical RAM.
Total_MemoryUsed_in_MB is the total memory used by SQL Server (RAM and page file)
You are making a mistake, which probably many 'newbies' make when referring to memory used by SQL Server. It would never show you correct memory utilization in task manager if Locked pages in memory privilege(LPIM) is there for the account running SQL Server service.  This is because the task manager only shows Process Private Bytes, the memory allocated via Virtual_alloc function which is pageable. Now if the SQL Server service account has LPIM, most part of the memory allocation would be done by AWE API. The memory allocated via AWE API is NOT pageable and thus does not shows up in task manager, which, in the end shows you different (incorrect) values.
Further reading:
Fun with Locked Pages, AWE, Task Manager, and the Working Set… (CSS SQL Server Engineers)

A: The tool I needed to figure it out was RAMMAP, which showed the AWE pool as the memory hog.  Yes, someone enabled AWE on a 64-bit OS with 64-bit SQL.


text:
Q: How to put list values into two separate columns This is the code I am working with currently.
data = {'ID': ['O1', 'O2', 'O3', 'O4'],'DATE': ['2010-09-09','2010-10-15','2011-02-09','2011-08-12'], 'RESULT': [1160, 6112, 21175, 10830]}
df = pd.DataFrame(data) #putting into a dataframe
grouped=df.groupby('ID')['RESULT','DATE'].apply(list) #groupby method and putting into list

Running this code gives me the following table.
ID
O1    [1160,  2010-09-09]
O2    [6112,  2010-10-15]
O3    [21175, 2011-02-09]
O4    [10830, 2011-08-12]

I want the [RESULT, DATE] to be separated so the format becomes as below.
ID    VL      DATES
O1    1160    2010-09-09
O2    6112    2010-10-15
O3    21175   2011-02-09
O4    10830   2011-08-12

There are more than 100 rows so I am looking for a suitable way to put them in the table shown above.

A: You can just call tolist on the result and pass that to pd.DataFrame (here I'm using pipe to make it a nice one-liner):
>>> df.groupby('ID')[['RESULT','DATE']].apply(list).pipe(lambda x: pd.DataFrame(x.tolist(), index=x.index, columns=['VL', 'DATE']))
        VL  DATE
ID
O1  RESULT  DATE
O2  RESULT  DATE
O3  RESULT  DATE
O4  RESULT  DATE


text:
Q: Certificate expired, renewed. Got now this error: server did not recognize the value of http Header SOAP Action I have an secured webservice with a certificate. These webservice was always working, but after the certificate was expired and renewed, it doesnt work anymore. I have a test webservice tool to check if the webservice is working or not. When I test it, one of the webmethods is working and the other gives me an error.
When I enter the webservice url in the browser on the local server where the webservice is running, it is accessable. I can see all the webmethods in this webservice.
1 webmethod "HelloWorld" is working.
1 other webmethod "copyIntoItems" is not working. The webmethod "copyIntoItems" webmethod copies a file to a SharePoint portal. It was always working and nothing changed (only the certificate renewed). This webmethod returns the following error:
server did not recognize the value of http Header SOAP Action.
I have checked where the old certificate was located. It was located on the local computer in the folder personal. I have removed the old one and imported the new one. Thats it.
Can someone tell me why I got this problem?
image soap test tool


text:
Q: Receive data from Arduino serial port then place it on text box the data came from rfid tag Good day, my project is vb.net using rfid which is MFRC522, my reader is arduino, I connected and receive data from serial successfully, but my problem is in every time I tap the id the pin of id will stack on the text box,and continuously add, I want that in every time that I tap the id the pin change or update,
This is my code
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    receivedData = ReceiveSerialData()
    studtag.Text &= receivedData
    time.Text = Now
    timein.Text = TimeOfDay.ToString("h:mm:ss tt")
End Sub

Function ReceiveSerialData() As String
    Dim Incoming As String
    Try
        Incoming = SerialPort1.ReadExisting()
        If Incoming Is Nothing Then
            Return "nothing" & vbCrLf
        Else
            Return Incoming
        End If
    Catch ex As TimeoutException
        Return "Error: Serial Port read timed out."
    End Try
End Function

advance Thank you..
all replies are really much appreciated. I'm using VB.net 2010


text:
Q: How to share variables between namespaces in C++? I come from a C# background so I kindly ask the answers could compare to C#.
I have a namespace with functions and variables to parse input for my program. The namespace is defined in a header and a source file. I also have defined a struct which have one property for each input param in my program to facilitate communication across classes. Like the minimum working example below:
mytypes.h
#ifndef _MYTYPES_H_
#define _MYTYPES_H_
namespace MyTypes
{
    enum class Par1Opt
    {
        opt1,opt2
    };
    struct InputParam_t
    {
        Par1Opt par1;
        int test;
    };
}
#endif // _MYTYPES_H_

myinput.h
#ifndef _MYINPUT_H_
#define _MYINPUT_H_
#include <unordered_map>
#include <string>
#include "mytypes.h"
namespace MyInput
{
    static const std::string par1 = "par1";
    static int testVar;
    static MyTypes::InputParam_t inputParam;
    static std::unordered_map<MyTypes::Par1Opt, std::string> Par1OptToStr;
    void InitVariables(void);
}
#endif // _MYINPUT_H_

myinput.cpp
#include <unordered_map>
#include <string>
#include "mytypes.h"
#include "myinput.h"
namespace MyInput
{
    void InitVariables(void) // set some default values
    {
        inputParam.par1 = MyTypes::Par1Opt::opt1; // default value
        inputParam.test = 10;
        Par1OptToStr = std::unordered_map<MyTypes::Par1Opt, std::string>({
            { MyTypes::Par1Opt::opt1, "opt1" },
            { MyTypes::Par1Opt::opt2, "opt2" }
        });
        testVar = 20;
    }
}

main.cpp
#include <iostream>
#include "myinput.h"
int main(int argCount, char* args[])
{
    MyInput::InitVariables(); // expect to set MyInput:: variables here
    std::cout << MyInput::par1 << " = "
        << MyInput::Par1OptToStr[MyInput::inputParam.par1]
        << std::endl; // par1 =
    std::cout << "inputParam.test = " << MyInput::inputParam.test
        << std::endl; // inputParam.test = 0
    std::cout << "testVar = " << MyInput::testVar
        << std::endl; // testVar = 0
    std::cin.get(); // pause
    // none of the values set for the MyInput:: variables inside InitVariables() method
    // are available in main
}

The questions are:

*

*Why are the values set inside InitVariable() not available in main()? Since the variables are static, I would expect (with mainly C# background) that the values would be available anywhere I use #include "myinput.h". How can I solve it?

*If I remove static keyword from variable declarations in myinput.h, then I get the Multiply defined symbols error. Why?
Thanks in advance!

A: When you declare a global variable in .h file with static specifier, you create a separate variable in each translation unit in which the .h file is included, so the variables referenced in myinput.cpp are not the same as variables referenced from main.cpp despite they have the same names.
When you create it with no specifier, you violate One Definition Rule.
What you should do is to declare variables with extern specifier in .h file and define them in one of .cpp files:
myinput.h
namespace MyInput
{
    extern const std::string par1;
    extern int testVar;
}

myinput.cpp
namespace MyInput
{
    const std::string par1 = "par1";
    int testVar;
}

A: In C# every module automatically sees any symbol from any other module or source file it references, provided the symbol is accessible, public or internal.
In C++, however, that is not the case. Even if the variable you want to access is public and global, you still need an external declaration to be able to use it. For example:
file1.cpp
int global = 0;

file2.cpp
int main()
{
    global = 1; //error: undefined symbol `global`.

    extern int global; //a declaration, not a definition
    global = 2; //ok!
}

Now, writing an extern declaration inside a function, as I just did is considered bad practice. It is better to write them globally.
extern int global;

int main()
{
    global = 3; //ok;
}

Then, writing the extern declaration this way is also considered bad practice, because you have to copy it in every module that needs to use the variable. It is better to write that in a file and #include it:
file1.h
extern int global;

file2.cpp
#include "file1.h"
int main()
{
    global = 4; //ok;
}

Then, it is also good practice to #include this .h file in the definition of the variable, so that the compiler can check that the definition and the declaration are consistent:
file1.cpp
#include "file1.h"
int global = 0; //ok: definition and initialization

float global; //error: type mismatch

If the declaration in the h file were not marked as external it would actually be a definition, and you could end up with multiple definitions of the same symbol, and a compiler or linker error.
Remember that #include does not do any magic under the hood, it is just a textual inclusion of the referred file. The magic is actually in the linker, but that's another story...


text:
Q: jQuery iterate over sortable tree structure I'm creating a dynamic navigation tree structure using jQuery UI sortables and nested sortable.
When the items are relocated, I'm trying to iterate over each branch and add a button at the bottom if it doesn't have one.
I'm having some problems with creating a recursive function to iterate over each branch. If I use .children('.ui-menu-item-branch'), it doesn't seem to find the sub-branches. If I use .find('> .ui-menu-item-branch'), it finds all sub-branches.
How should I amend the code to iterate over each branch only once?

function addButton (el, index) {
 var tpl = '
<button class="ui-button button-add-item" type="button">Add menu item</button>
';

 var branches = $(el).children('.ui-menu-item-branch');
 console.log ('branches: ' + index);
 console.log (branches);

 $.each(branches, function(i, el) {
  console.log ('element: ' + index);
  console.log (el);
  index++;
  addButton (el, index);
 });
}

$(document).ready(function() {
 $('.sortable').nestedSortable({
  handle: '.ui-menu-handle',
  placeholder: 'ui-menu-placeholder',
  items: 'li:not(.add-menu-item)',
  toleranceElement: '> div',
  branchClass: 'ui-menu-item-branch',
  leafClass: 'ui-menu-item-leaf',
  collapsedClass: 'ui-menu-item-collapsed',
  expandedClass: 'ui-menu-item-expanded',
  errorClass: 'ui-menu-item-invalid',
  isTree: true,
  distance:0,
  maxLevels: 3,
  isAllowed: function (placeholder, placeholderParent, currentItem) {
   if (placeholder.prev().hasClass('add-menu-item')) {
    return false;
   }
   if (placeholderParent && placeholderParent.hasClass('add-menu-item')) {
    return false;
   }
   return true;
  },
  relocate: function (event, currentItem) {
   var target = $(event.target);
   addButton (target, 0);
  }
 });

  $('.sortable').on('click', '.button-add-item', function (e) {
  var el = $(this);
  var tpl = '

Sub Content 2

';
  $(tpl).insertBefore(el);
 });
});
body {
margin: 0;
}
.ui-stack {
 display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    margin-top: -1.6rem;
    margin-left: -1.6rem;
}
.ui-stack>* {
 -webkit-box-flex: 0;
 -webkit-flex: 0 0 auto;
 -ms-flex: 0 0 auto;
 flex: 0 0 auto;
 margin-top: 1.6rem;
 margin-left: 1.6rem;
}
.ui-stack-wrap {
 -webkit-flex-wrap: wrap;
 -ms-flex-wrap: wrap;
 flex-wrap: wrap;
}
.ui-stack-center {
    -webkit-box-pack: center;
    -webkit-justify-content: center;
    -ms-flex-pack: center;
    justify-content: center;
}
.ui-stack-align-center {
  -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
}
.ui-stack-vertical {
 -webkit-box-orient: vertical;
 -webkit-box-direction: normal;
 -webkit-flex-direction: column;
 -ms-flex-direction: column;
 flex-direction: column;
}
.ui-stack-item {
    min-width: 0;
    max-width: 100%;
}
.ui-stack-item-fill {
    -webkit-box-flex: 1;
    -webkit-flex: 1 1 auto;
    -ms-flex: 1 1 auto;
    flex: 1 1 auto;
}
.ui-card-section.ui-navigation {
 padding: 0;
 margin-top: 20px;
}

.ui-navigation ol {
 margin: 0;
 padding: 0;
 list-style: none;
}
.ui-navigation li {
 padding: 0;
}

.ui-navigation ol ol {
 padding-left: 30px;
}

.ui-navigation ol ol .sortable-menu-item, .ui-navigation ol ol .button-add-item {
 border-left: 1px solid #dfe3e8;
}
.sortable-menu-item {
 padding: 10px;
 background: white;
 border-top: 1px solid #dfe3e8;
 -webkit-box-shadow: 0 1px 0 0 #dfe3e8;
 box-shadow: 0 1px 0 0 #dfe3e8;
 margin-top: 0;
 margin-left: 0;
 line-height: 30px;
 -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.ui-menu-handle {
 width: 20px;
 height: 20px;
 background-color: #5c6ac4;
 border-radius: 50%;
 cursor: pointer;
 margin: 0;
}
.ui-menu-placeholder {
 position: relative;
 background-color: #5c6ac4;
 height: 2px;
 width: 100%;
 margin-top: -1px;
 margin-bottom: -1px;
}
.ui-menu-placeholder:before {
 position: absolute;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    border: 2px solid #5c6ac4;
    top: -4px;
    left: -9px;
    content: "";
}
.ui-menu-placeholder.ui-menu-item-invalid, .ui-menu-placeholder.ui-menu-item-invalid:before {
 background-color: #ddd;
 border-color: #bbb;
}

.ui-menu-item-title {
 margin: 0;
 padding: 0 0.8rem;
}
.button-add-item {
 width: 100%;
 background: #f4f5fa;
    color: #5c6ac4;
    text-align: left;
    -webkit-transition: none;
    transition: none;
    border: 0;
    border-top: 1px solid #dfe3e8;
    border-color: #dfe3e8;
    border-radius: 0;
    line-height: 34px;
 padding: 10px 15px;
}
.button-add-item:hover {
 border-color: #5c6ac4;
    background: #5c6ac4;
 color: white;
}

Content 1

Content 2

Sub Content 1

Sub Content 2

        <button class="ui-button button-add-item" type="button">Add menu item to Content 2</button>

Content 3

    <button class="ui-button button-add-item" type="button">Add menu item</button>

A: As I understand you want something like the below snippet.
I used this selector: var $branches = $el.parents('li.ui-menu-item-branch').not(':has( > ol li.add-menu-item)');
Instead of recursion, jQuery does that for us.

function addButton($el) {
  var tpl = '
<button class="ui-button button-add-item" type="button">Add menu item</button>
';

  var $branches = $el.parents('li.ui-menu-item-branch').not(':has( > ol li.add-menu-item)');
  $branches.each(function(i, el) {
    $(el).find('> ol').append(tpl);
  });
}

$(document).ready(function() {
  $('.sortable').nestedSortable({
    handle: '.ui-menu-handle',
    placeholder: 'ui-menu-placeholder',
    items: 'li:not(.add-menu-item)',
    toleranceElement: '> div',
    branchClass: 'ui-menu-item-branch',
    leafClass: 'ui-menu-item-leaf',
    collapsedClass: 'ui-menu-item-collapsed',
    expandedClass: 'ui-menu-item-expanded',
    errorClass: 'ui-menu-item-invalid',
    isTree: true,
    distance: 0,
    maxLevels: 3,
    isAllowed: function(placeholder, placeholderParent, currentItem) {
      if (placeholder.prev().hasClass('add-menu-item')) {
        return false;
      }
      if (placeholderParent && placeholderParent.hasClass('add-menu-item')) {
        return false;
      }
      return true;
    },
    relocate: function(event, currentItem) {
      var target = $(event.target);
      console.log('relocate', currentItem);
      addButton(currentItem.item);
    }
  });

  $('.sortable').on('click', '.button-add-item', function(e) {
    var el = $(this);
    var tpl = '

Sub Content 2

';
    $(tpl).insertBefore(el);
  });
});
body {
  margin: 0;
}

.ui-stack {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  margin-top: -1.6rem;
  margin-left: -1.6rem;
}

.ui-stack>* {
  -webkit-box-flex: 0;
  -webkit-flex: 0 0 auto;
  -ms-flex: 0 0 auto;
  flex: 0 0 auto;
  margin-top: 1.6rem;
  margin-left: 1.6rem;
}

.ui-stack-wrap {
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}

.ui-stack-center {
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
}

.ui-stack-align-center {
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
}

.ui-stack-vertical {
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  -ms-flex-direction: column;
  flex-direction: column;
}

.ui-stack-item {
  min-width: 0;
  max-width: 100%;
}

.ui-stack-item-fill {
  -webkit-box-flex: 1;
  -webkit-flex: 1 1 auto;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
}

.ui-card-section.ui-navigation {
  padding: 0;
  margin-top: 20px;
}

.ui-navigation ol {
  margin: 0;
  padding: 0;
  list-style: none;
}

.ui-navigation li {
  padding: 0;
}

.ui-navigation ol ol {
  padding-left: 30px;
}

.ui-navigation ol ol .sortable-menu-item,
.ui-navigation ol ol .button-add-item {
  border-left: 1px solid #dfe3e8;
}

.sortable-menu-item {
  padding: 10px;
  background: white;
  border-top: 1px solid #dfe3e8;
  -webkit-box-shadow: 0 1px 0 0 #dfe3e8;
  box-shadow: 0 1px 0 0 #dfe3e8;
  margin-top: 0;
  margin-left: 0;
  line-height: 30px;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.ui-menu-handle {
  width: 20px;
  height: 20px;
  background-color: #5c6ac4;
  border-radius: 50%;
  cursor: pointer;
  margin: 0;
}

.ui-menu-placeholder {
  position: relative;
  background-color: #5c6ac4;
  height: 2px;
  width: 100%;
  margin-top: -1px;
  margin-bottom: -1px;
}

.ui-menu-placeholder:before {
  position: absolute;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  border: 2px solid #5c6ac4;
  top: -4px;
  left: -9px;
  content: "";
}

.ui-menu-placeholder.ui-menu-item-invalid,
.ui-menu-placeholder.ui-menu-item-invalid:before {
  background-color: #ddd;
  border-color: #bbb;
}

.ui-menu-item-title {
  margin: 0;
  padding: 0 0.8rem;
}

.button-add-item {
  width: 100%;
  background: #f4f5fa;
  color: #5c6ac4;
  text-align: left;
  -webkit-transition: none;
  transition: none;
  border: 0;
  border-top: 1px solid #dfe3e8;
  border-color: #dfe3e8;
  border-radius: 0;
  line-height: 34px;
  padding: 10px 15px;
}

.button-add-item:hover {
  border-color: #5c6ac4;
  background: #5c6ac4;
  color: white;
}

Content 1

Content 2

Sub Content 1

Sub Content 2

                <button class="ui-button button-add-item" type="button">Add menu item to Content 2</button>

Content 3

            <button class="ui-button button-add-item" type="button">Add menu item</button>


text:
Q: Booting "Linux from Scratch" doesn't bring up # prompt I have been following A Minimal Linux System from Scratch in order to build a Linux with a small footprint (10MB or less).
I'm fairly certain that there were no errors up until the last point, where I'm actually testing the image, using the command qemu-system-i386 -L . -hda minux.img
Instead of actually booting to the # prompt as the tutorial showed, I'm greeted by the Grub Rescue Prompt. In order to attempt booting, I used kernel /boot/kernel_name then boot, which ultimately fails with:

My grub.conf is below, identical to the one in the tutorial:
default 0
timeout 30
title Minux
root (hd0,0)
kernel /boot/vmlinux-2.6.21-1 root=/dev/hda1 rw

So far the only difference I've managed to find was in fdisk, where my starting sector is 2048, since it's the minimum I can set using fdisk and as a consequence the offset is bigger. Another difference is that I'm using x86_64-pc grub and some of my busybox libs are named differently, but this should not interfere with boot.
How could I fix the procedure to make my linux work? Or is there a better way to make a linux distribution under 10MB?

A: let me try answer the second question about make a small system . since we are building on x86 i guess what is intended is to make a system to boot of a flash drive , rather than burn into embedded chips for which is a very different story .
consider drop disk images and use a cpio initramfs . then boot like this .
qemu-system-i386 -kernel vmlinuz -initrd root.cpio.gz
i love this because we have more flexibilites and don't have to be confused with disk locations .
i also suggest grub4dos the bootloader . despite "dos" in the name , it can be installed from linux and boot linux kernels . the installation is as simple as write an mbr and copy one 213k file to any partition . and grub4dos recognises many filesystems .

besides , in your configuration it seems you didn't set up grub right , for there is a rescue console showed . even though you should type kernel /boot/kernel_name with a "root=" before boot .
and on my machine the qemu guest kernel recognises the disk image as "/dev/sda" instead of "/dev/hda" .


text:
Q: Trying to write parsed JSON to file using Python Requests, but only saving 1 of 678 objects I'm retrieving data from the USGS, parsing it, pulling out the values I want, recomposing it into a smaller JSON object and writing that to a new file. Or, that's what I'm trying to do. I've gotten almost all of it working. When I run the script the resulting file only contains the data from the final object in the series. I'm very inexperienced with this stuff, so I apologize if this is obvious. I'm working in 'append' mode, so I was under the impression each object would be appended to the end of the file, but it seems like they are being overwritten. Insight is greatly appreciated.
Here is the script:
#libs
import requests
import json
import os

try:
    os.remove('newdata.json')
except OSError:
    pass

# daily values request url, generated from USGS web services
url = "http://waterservices.usgs.gov/nwis/dv/?format=json&indent=on&huc=17&startDT=2015-01-01&endDT=2015-06-04&parameterCd=00060&siteType=OC,OC-CO,ES,LK,ST,ST-CA,ST-DCH,ST-TS&siteStatus=active"

# create request
r = requests.get(url)

# parse
data = json.loads(r.text)

#jump forward a few layers in the tree
timeSeries = data['value']['timeSeries']

# counter for dealing with trailing commas
counter = 0

#extract relevant data for each streamgage site and write to file
with open('newdata.json', 'a+') as f:
    for site in timeSeries:
        json_data = '{'
        counter+=1
        json_data = json_data + '"sitecode": "{}"'.format(site['sourceInfo']['siteCode'][0]['value']) + ',' + \
        '"properties": { "usgs_name":  ' + '"' + site['sourceInfo']['siteName'] + '",' + \
        '"HUC": "{}"'.format(site['sourceInfo']['siteProperty'][1]['value']) + ',' + \
        '"lat": "{}"'.format(site['sourceInfo']['geoLocation']['geogLocation']['latitude']) + ',' + \
        '"long": "{}"'.format(site['sourceInfo']['geoLocation']['geogLocation']['longitude']) + \
        '}, "timeSeries": ['
        for chunk in site['values']:
            counter2 = 0
            for daily in chunk['value']:
                counter2+=1
                json_data = json_data + '{"streamflow": ' + '"' + daily['value'] + '",' + \
                '"dateTime": ' + '"' + daily['dateTime'] + '"'
                if counter2 < len(chunk['value']):
                    json_data = json_data + '},'
                else:
                    json_data = json_data +'}]'
        if counter < len(timeSeries):
            json_data = json_data + '},'
        else:
            json_data = json_data + '}'
    f.write(json_data)

Here is a gist with the resulting file.
And here is a gist with the raw json response.
If, while you're here, you see anything else I'm doing that's obviously stupid, please let me know. Thank you for your help.


text:
Q: $A' \cap (A' \cup B') \cap T= A' \cap T$ Let $A'$ denotes the complement of A with respect to $ \mathbb{R}$ and $A,B,T$ are subsets of $\mathbb{R}$. I am trying to prove $A' \cap (A' \cup B') \cap T= A' \cap T$, but I got some problems along the way.
$A' \cap (A' \cup B') \cap T= (A' \cap A') \cup (A' \cap B') \cap T= A' \cup (A \cup B) \cap T =(A' \cup A)\cup B \cap T= \mathbb{R} \cup B \cap T = B \cap T$ Something wrong?

A: Well, given arbitrary sets $X,Y$ we always have $X\cap(X\cup Y) = X$ since the intersection of a set with a union of that same set and anything else is just the first set itself (I hope that's not too wordy). Try drawing all possibilites with sets to see this. So $A'\cap (A' \cup B') = A'$ and that gives you your answer.
Your fault is that in the second equality does not hold: for arbitrary sets $X,Y$ in general $(X \cap X) \cup (X\cap Y) \neq X \cup (X'\cup Y')$. Again, drawing all possibilites really helps to make this clear. Here I'm generalizing slightly from what you have, so for you $X$ is $A'$ and $Y$ is $B'$. Recall $A'' = A$.

A: Let $x \in A' \cap (A' \cup B) \cap T$.  Then $x \in A'$ and $x \in T$, so $x \in A' \cap T$.  This proves that $A' \cap (A' \cup B) \cap T \subset A' \cap T$.  The reverse inclusion is similar.

A: Dilip's comments point out the flaw re: DeMorgan's Laws.
To avoid that mess altogether, a both-directions-subset proof works concisely. On the one hand, it is clear that $A' \cap (A' \cup B') \cap T \subset A' \cap T$, since the LHS intersects all of the RHS's elements with another set.
On the other hand, expanding the LHS yields $A' \cap ((A' \cap T) \cup(B' \cap T)) = (A' \cap T)\cup(A' \cap B' \cap T)$ . Certainly, $A' \cap T \subset (A' \cap T)\cup(A' \cap B' \cap T)$ .

A: $A' \cap (A' \cup B') \cap T= ((A' \cap A') \cup (A' \cap B')) \cap T= (A' \cup (A' \cap B')) \cap T$.  But, $A' \cap B' \subset A'$ and so $A' \cup (A' \cap B') = A'$ giving
$(A' \cup (A' \cap B')) \cap T = A' \cap T$ without dragging DeMorgan's Laws into it.


text:
Q: Issue in Installing components through Bower from GitHub When I tried to create an application with help of JHipster there some issues in fetching the components through git hub with bower.
Currently tried in another way to pull the components directly with help Bower but couldn't
I tried in two ways (i) with git & (ii) with https, both the ways it is getting failed.
Attached the screenshot below for your reference.
Kindly let me know in case of more information.

A: Would you be behind a proxy ? It seems you can't reach github.com on the git port (9418). If that 's the case configure your git to use https:// instead of git://


text:
Q: There has to be a better way to check for certain known numbers I have project going that contains a lot more numbers than shows in my code below but would like to know a better way of checking to see if certain numbers are in any of the lines of text in a richtextbox. I only list 3 numbers here but there are many more. The code does work but surely there is a better way.
For i As Integer = RichTextBox1.Lines.Length - 1 To 0 Step -1
        ' Get the line
        Dim line As String = RichTextBox1.Lines(i)

        ' Search and find numbers 1, 2, 3 etc.
        Dim index As Integer = line.IndexOf("1")
        Dim index2 As Integer = line.IndexOf("2")
        Dim index3 As Integer = line.IndexOf("3")

        ' If found the match 1
        If index <> -1 Then
          ' Do code
        End If

        ' If found the match 2
        If index2 <> -1 Then
          ' Do code
        End If

        ' If found the match 3
        If index3 <> -1 Then
          ' Do code
        End If

    Next


text:
Q: How to count group by rows in rails? When I use User.count(:all, :group => "name"), I get multiple rows, but it's not what I want. What I want is the count of the rows. How can I get it?

A: Try using User.find(:all, :group => "name").count
Good luck!

A: Currently (18.03.2014 - Rails 4.0.3) this is correct syntax:
Model.group("field_name").count

It returns hash with counts as values
e.g.
SurveyReport.find(30).reports.group("status").count

#=> {
  "pdf_generated" => 56
}

A: *

*User.count will give you the total number of users and translates to the following SQL: SELECT count(*) AS count_all FROM "users"

*User.count(:all, :group => 'name') will give you the list of unique names, along with their counts, and translates to this SQL: SELECT count(*) AS count_all, name AS name FROM "users"  GROUP BY name
I suspect you want option 1 above, but I'm not clear on what exactly you want/need.

A: Probably you want to count the distinct name of the user?
User.count(:name, :distinct => true)

would return 3 if you have user with name John, John, Jane, Joey (for example) in the database.
 ________
| name   |
|--------|
| John   |
| John   |
| Jane   |
| Joey   |
|________|

A: I found an odd way that seems to work. To count the rows returned from the grouping counts.
User Table Example
________
| name   |
|--------|
| Bob    |
| Bob    |
| Joe    |
| Susan  |
|________|

Counts in the Groups

User.group(:name).count

# SELECT COUNT(*) AS count_all
# FROM "users"
# GROUP BY "users"."name"

=> {
  "Bob" => 2,
  "Joe" => 1,
  "Susan" => 1
}

Row Count from the Counts in the Groups
User.group(:name).count.count

=> 5

Something Hacky
Here's something interesting I ran into, but it's quite hacky as it will add the count to every row, and doesn't play too well in active record land. I don't remember if I was able to get this into an Arel / ActiveRecord query.
SELECT COUNT(*) OVER() AS count, COUNT(*) AS count_all
FROM "users"
GROUP BY "users"."name"

[
  { count: 3, count_all: 2, name: "Bob" },
  { count: 3, count_all: 1, name: "Joe" },
  { count: 3, count_all: 1, name: "Susan" }
]


text:
Q: Ruby - share logger instance among module/classes Working on a little Ruby script that goes out to the web and crawls various services. I've got a module with several classes inside:
module Crawler
  class Runner
  class Options
  class Engine
end

I want to share one logger among all those of those classes. Normally I'd just put this in a constant in the module and reference it like so:
Crawler::LOGGER.info("Hello, world")

The problem is that I can't create my logger instance until I know where the output is going. You start the crawler via command line and at that point you can tell it you want to run in development (log output goes to STDOUT) or production (log output goes to a file, crawler.log):
crawler --environment=production

I have a class Options that parses the options passed in through the command line. Only at that point do I know how to instantiate the logger with the correct output location.
So, my question is: how/where to I put my logger object so that all my classes have access to it?
I could pass my logger instance to each new() call for every class instance I create, but I know there has to be a better, Rubyish way to do it. I'm imagining some weird class variable on the module that shared with class << self or some other magic. :)
A little more detail: Runner starts everything by passing the command line options to the Options class and gets back an object with a couple of instance variables:
module Crawler
  class Runner
    def initialize(argv)
      @options = Options.new(argv)
      # feels like logger initialization should go here
      # @options.log_output => STDOUT or string (log file name)
      # @options.log_level => Logger::DEBUG or Logger::INFO
      @engine = Engine.new()
    end
    def run
      @engine.go
    end
  end
end

runner = Runner.new(ARGV)
runner.run

I need the code in Engine to be able to access the logger object (along with a couple more classes that are initialized inside Engine). Help!
All of this could be avoided if you could just dynamically change the output location of an already-instantiated Logger (similar to how you change the log level). I'd instantiate it to STDOUT and then change over to a file if I'm in production.  I did see a suggestion somewhere about changing Ruby's $stdout global variable, which would redirect output somewhere other than STDOUT, but this seems pretty hacky.
Thanks!

A: Inspired by this thread I created the easy_logging gem.
It combines all the features discussed such as:

*

*Adds logging functionality anywhere with one, short,
self-descriptive command

*Logger works in both class and instance methods

*Logger is specific to class and contains class name

Installation:
gem install 'easy_logging

Usage:
require 'easy_logging'

class YourClass
  include EasyLogging

  def do_something
    # ...
    logger.info 'something happened'
  end
end

class YourOtherClass
  include EasyLogging

  def self.do_something
    # ...
    logger.info 'something happened'
  end
end

YourClass.new.do_something
YourOtherClass.do_something

Output
I, [2017-06-03T21:59:25.160686 #5900]  INFO -- YourClass: something happened
I, [2017-06-03T21:59:25.160686 #5900]  INFO -- YourOtherClass: something happened

More details on GitHub.

A: With the design you've laid out, it looks like the easiest solution is to give Crawler a module method that returns a module ivar.
module Crawler
  def self.logger
    @logger
  end
  def self.logger=(logger)
    @logger = logger
  end
end

Or you could use "class <<self magic" if you wanted:
module Crawler
  class <<self
    attr_accessor :logger
  end
end

It does the exact same thing.

A: The may be some weird Ruby magic that could let you avoid it, but there's a fairly simple solution that doesn't need weird.  Just put the logger into the module and access it directly, with a mechanism to set it.  If you want to be cool about it, define a "lazy logger" that keeps a flag to say if it has a logger yet, and either silently drops messages until the logger is set, throws an exception of something is logged before the logger is set, or adds the log message to a list so it can be logged once the logger is defined.

A: A little chunk of code to demonstrate how this works. I'm simply creating a new basic Object so that I can observe that the object_id remains the same throughout the calls:
module M

  class << self
    attr_accessor :logger
  end

  @logger = nil

  class C
    def initialize
      puts "C.initialize, before setting M.logger: #{M.logger.object_id}"
      M.logger = Object.new
      puts "C.initialize, after setting M.logger: #{M.logger.object_id}"
      @base = D.new
    end
  end

  class D
    def initialize
      puts "D.initialize M.logger: #{M.logger.object_id}"
    end
  end
end

puts "M.logger (before C.new): #{M.logger.object_id}"
engine = M::C.new
puts "M.logger (after C.new): #{M.logger.object_id}"

The output of this code looks like (an object_id of 4 means nil):
M.logger (before C.new): 4
C.initialize, before setting M.logger: 4
C.initialize, after setting M.logger: 59360
D.initialize M.logger: 59360
M.logger (after C.new): 59360

Thanks for the help guys!

A: As Zenagray points out, logging from class methods was left out of Jacob's answer.  A small addition solves that:
require 'logger'

module Logging
  class << self
    def logger
      @logger ||= Logger.new($stdout)
    end

    def logger=(logger)
      @logger = logger
    end
  end

  # Addition
  def self.included(base)
    class << base
      def logger
        Logging.logger
      end
    end
  end

  def logger
    Logging.logger
  end
end

The intended use is via "include":
class Dog
  include Logging

  def self.bark
    logger.debug "chirp"
    puts "#{logger.__id__}"
  end

  def bark
    logger.debug "grrr"
    puts "#{logger.__id__}"
  end
end

class Cat
  include Logging

  def self.bark
    logger.debug "chirp"
    puts "#{logger.__id__}"
  end

  def bark
    logger.debug "grrr"
    puts "#{logger.__id__}"
  end
end

Dog.new.bark
Dog.bark
Cat.new.bark
Cat.bark

Produces:
D, [2014-05-06T22:27:33.991454 #2735] DEBUG -- : grrr
70319381806200
D, [2014-05-06T22:27:33.991531 #2735] DEBUG -- : chirp
70319381806200
D, [2014-05-06T22:27:33.991562 #2735] DEBUG -- : grrr
70319381806200
D, [2014-05-06T22:27:33.991588 #2735] DEBUG -- : chirp
70319381806200

Note the id of the logger is the same in all four cases.  If you want a different instance for each class, then don't use Logging.logger, rather use self.class.logger:
require 'logger'

module Logging
  def self.included(base)
    class << base
      def logger
        @logger ||= Logger.new($stdout)
      end

      def logger=(logger)
        @logger = logger
      end
    end
  end

  def logger
    self.class.logger
  end
end

The same program now produces:
D, [2014-05-06T22:36:07.709645 #2822] DEBUG -- : grrr
70350390296120
D, [2014-05-06T22:36:07.709723 #2822] DEBUG -- : chirp
70350390296120
D, [2014-05-06T22:36:07.709763 #2822] DEBUG -- : grrr
70350390295100
D, [2014-05-06T22:36:07.709791 #2822] DEBUG -- : chirp
70350390295100

Note that the first two id's are the same but are different from the 2nd two ids showing that we have two instances -- one for each class.

A: I like to have a logger method available in my classes, but I don't like sprinkling @logger = Logging.logger in all my initializers. Usually, I do this:
module Logging
  # This is the magical bit that gets mixed into your classes
  def logger
    Logging.logger
  end

  # Global, memoized, lazy initialized instance of a logger
  def self.logger
    @logger ||= Logger.new(STDOUT)
  end
end

Then, in your classes:
class Widget
  # Mix in the ability to log stuff ...
  include Logging

  # ... and proceed to log with impunity:
  def discombobulate(whizbang)
    logger.warn "About to combobulate the whizbang"
    # commence discombobulation
  end
end

Because the Logging#logger method can access the instance that the module is mixed into, it is trivial to extend your logging module to record the classname with log messages:
module Logging
  def logger
    @logger ||= Logging.logger_for(self.class.name)
  end

  # Use a hash class-ivar to cache a unique Logger per class:
  @loggers = {}

  class << self
    def logger_for(classname)
      @loggers[classname] ||= configure_logger_for(classname)
    end

    def configure_logger_for(classname)
      logger = Logger.new(STDOUT)
      logger.progname = classname
      logger
    end
  end
end

Your Widget now logs messages with its classname, and didn't need to change one bit :)

A: How about wrapping the logger in a singleton then you could access it using MyLogger.instance

A: Based on your comment

All of this could be avoided if you could just dynamically change the output location of an already-instantiated Logger (similar to how you change the log level).

If you are not restricted to the default logger you may use another log-gem.
As an example with log4r:
require 'log4r'

module Crawler
  LOGGER = Log4r::Logger.new('mylog')
  class Runner
    def initialize
        LOGGER.info('Created instance for %s' % self.class)
    end
  end
end

ARGV << 'test'  #testcode

#...
case ARGV.first
  when 'test'
    Crawler::LOGGER.outputters = Log4r::StdoutOutputter.new('stdout')
  when 'prod'
    Crawler::LOGGER.outputters = Log4r::FileOutputter.new('file', :filename => 'test.log') #append to existing log
end
#...
Crawler::Runner.new

In prod mode the logging data are stored in a file (attached to existing file, but there are options to create new log files or implement rolling log files).
The result:
 INFO main: Created instance for Crawler::Runner

If you use the inheritance mechanism of log4r (a), you may define a logger for each class (or in my following example for each instance) and share the outputter.
The example:
require 'log4r'

module Crawler
  LOGGER = Log4r::Logger.new('mylog')
  class Runner
    def initialize(id)
      @log = Log4r::Logger.new('%s::%s %s' % [LOGGER.fullname,self.class,id])
      @log.info('Created instance for %s with id %s' % [self.class, id])
    end
  end
end

ARGV << 'test'  #testcode

#...
case ARGV.first
  when 'test'
    Crawler::LOGGER.outputters = Log4r::StdoutOutputter.new('stdout')
  when 'prod'
    Crawler::LOGGER.outputters = Log4r::FileOutputter.new('file', :filename => 'test.log') #append to existing log
end
#...
Crawler::Runner.new(1)
Crawler::Runner.new(2)

The result:
 INFO Runner 1: Created instance for Crawler::Runner with id 1
 INFO Runner 2: Created instance for Crawler::Runner with id 2

(a) A logger name like A::B has the name B and is a child of the logger with the name A. As far as I know this is no object inheritance.
One advantage of this approach: If you want to use a single logger for each class, you need only to change the name of the logger.

A: Although an old question, I thought it worthwhile to document a different approach.
Building on Jacob's answer, I would suggest a module that you can add in as and when needed.
My version is this:
# saved into lib/my_log.rb

require 'logger'

module MyLog

  def self.logger
    if @logger.nil?
      @logger = Logger.new( STDERR)
      @logger.datetime_format = "%H:%M:%S "
    end
    @logger
  end

  def self.logger=( logger)
    @logger = logger
  end

  levels = %w(debug info warn error fatal)
  levels.each do |level|
    define_method( "#{level.to_sym}") do |msg|
      self.logger.send( level, msg)
    end
  end
end

include MyLog

I have this saved into a library of handy modules, and I would use it like this:
#! /usr/bin/env ruby
#

require_relative '../lib/my_log.rb'

MyLog.debug "hi"
# => D, [19:19:32 #31112] DEBUG -- : hi

MyLog.warn "ho"
# => W, [19:20:14 #31112]  WARN -- : ho

MyLog.logger.level = Logger::INFO

MyLog.logger = Logger.new( 'logfile.log')

MyLog.debug 'huh'
# => no output, sent to logfile.log instead

I find this a lot easier and more versatile than other options I've looked at so far, so I hope it helps you with yours.


text:
Q: orderedtests not working with vstest.console.exe when .runsettings file is specified - MS Test I have the following:

*

*.orderedtest file which has a list of tests in an order

*.runsettings file where I have specified some test parameters

I am trying to execute the tests through command line, using the following command:
vstest.console.exe MyOrderedTests.orderedtest /Settings:MyTestParameters.runsettings /TestCaseFilter:"TestCategory=Production" /Logger:trx
I am getting the below warning and none of the tests are executed.
Warning: No test is available in MyOrderedTests.orderedtest. Make sure that installed test discoverers & executors, platform & framework version settings are appropriate and try again.
I really appreciate the help!
I even tried to run tests through the VS IDE. To elaborate more:
1. I have two tests
2. I have a Class Initialize which access the TestRunParameters from a .runsettings file.
3. I print the TestRunParameter in the tests.
4. I execute the tests individually and even all at once, they execute just fine.
Now I introduce the test ordering using .orderedtest file
1. I execute the tests using this orderedtest file and I get the NullReferenceException in the Class Initialize (where it tries to access the TestRunParameters from .runsettings file)
Class Initialization method TestTestProject.UnitTest1.ClassInit threw exception. System.NullReferenceException: System.NullReferenceException: Object reference not set to an instance of an object..
Below is my simple sample test code:
public static string url;
    [TestMethod]
    public void TestMethod1()
    {
        Console.WriteLine("Test Method 1");
        Console.WriteLine(url);
    }

    [TestMethod]
    public void TestMethod2()
    {
        Console.WriteLine("Test Method 2");
        Console.WriteLine(url);
    }

    [ClassInitialize]
    public static void ClassInit(TestContext context)
    {
        url = context.Properties["webAppUrl"].ToString();
    }

I get the NullReferenceException in the ClassInit().


text:
Q: What is the minimum historical data/sample data required for a time series forecasting analysis? Are there any statistical power analysis/sample size deteminations methods for time series data analysis/forecasting?
For example if I have time series of 30 data points, how can I with confidence use a particular statistical methods like exponential smoothing or arima for predict the future ?
I have seen in some textbooks that have a cursary mention on historical data points required for ARIMA would be 50 or 60. But I have not encountered a formal approach on how much history is required for a a particular time series forecasting method.
I did a thorough search on major time series textbooks and the internet, I'm unable to find any literature on this topic. Any guidance would be helpful.

A: No, there is no power test.  The 60 data points suggested by Box-Jenkins and the 36 by Makradakis are arbitrary and are more from the mind set of a "best fit" modeling approach.
I am of the belief that any time series can be modeled.  The signal to noise ratio determines how well you can identify a pattern that would be more complicated than a mean model with some outliers, for example.

A: I have been teaching Ops management in NTU singapore. This is a standard question my students ask me. To be honest there is no definite answer to the number of historical data points. It depends on what you are forecasting. Assuming stable past data with out trends,even 10 data points can return a reasonable forecast compared to 30 or 60 data points. The smoothing factor is the key. with the right alpha Value you can reduce the number of data points. here is an example below. if you choose alpha value closer to 0.1, the forecasts are very different. I would conclude that for short term forecasting with reasonably stable past, 10 to to 20 points is good, but we must select the right Alpha value with lowest MSE .


text:
Q: Set Handling Time and Inventory update I was wondering if there is any way to set the Handling Time with Inventory update.
We are having the issue, when changing the quantity, the RestockDate & Handling Times fields are reset to being empty for that item. After reading through documentation, I understand this is the way MWS works.
We use the _POST_INVENTORY_AVAILABILITY_DATA_ feedtype when updating inventory.
Is there any way or report to retrieve those 2 fields or  to to add Handling time with Inventory update service of feedtype _POST_INVENTORY_AVAILABILITY_DATA_.

A: In Amazon's XML terminology, the handling time is called FulfillmentLatency:

FulfillmentLatency - The number of days between the order date and the ship date (a whole number between 1 and 30).

The following XML snippet shows where that information fits in.
<Inventory>
<SKU>MyProductCode</SKU>
<Quantity>100</Quantity>
<FulfillmentLatency>3</FulfillmentLatency>
</Inventory>

Assuming you already have the rest of the feed up and running and are not getting any errors, the addition of FulfillmentLatency in your XML feed should take care of your problem.
This and further info on the Amazon MWS API XML formats can be found in the Selling on Amazon
Guide to XML


text:
Q: Xamarin: list view cell height at start Using a listView, I am experimenting (only on iOS) that dynamic cells are showed bad a start. The cell are a mix of Image and text and at first execution, text an image are mixed.
Then, after scroll they resized well.
My code is:
<ListView x:Name="MyListView"  HasUnevenRows="true" IsVisible="false">
                    <ListView.ItemTemplate>
                        <DataTemplate>

                             <ViewCell>
                                <StackLayout Spacing="6" Margin="16">

                                    <Image   Aspect="AspectFill">
                                        <Image.Source>
                                          <UriImageSource Uri="{Binding Imagen}"/>
                                        </Image.Source>
                                    </Image>

                                    <Label  Style="{StaticResource Noticia}" Font="11" Text="{Binding Fecha, StringFormat='{0:dd/MM/yyyy}'}"/>
                                    <Label  Style="{StaticResource Titular}" Text="{Binding Titular}" />
                                 </StackLayout>
                            </ViewCell>

                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>

how solve that?

A: Looking at your code you are asking your image to fill a stacklayout of undefined height. Would say the solution here is to define height manually. Easy when your images are all like 100 height.
But if you want to have a dynamic image height then please let me welcome you to the world of a limited xamarin listview and propose several solutions.

*

*Respond to image loaded event (you might have one for sure - Success, if you are using ffimageloading plugin) obtain the recieved image original width/height and calculate your needed heightrequest proportionally upon your current listview width.
            double ratio = item.ImageHeight / item.ImageWidth;
            item.ImageDynamicHeight = ratio * basewidth;  //basewidth can be YourListView.Width, remember to check if it's not -1

*More fun to come: your server api must include image original height/width info in passed data, you will set heightrequest according to this info and then your image will perfectly land inside when downloaded. Using this solution for news feed lists, server passing me news images height along with news texts.

*If you do not have many memory consuming rows you can let yourself use a custom control, consisting of a stacklayout with a bindable Source property, your cells becoming children of this stacklayout, what visually will behave more like it should and more smooth that a standard xamarin.forms listview. Using this solution for menu lists, short products lists and such.


text:
Q: How to open external URL in default browser and all internal links in WebView Android? I am using WebView in my page and using local file assets to displaying in WebView but in main HTML page external website (not local) and I want to open just that link in default Browser on the users device

This is my code in 'onCreate' method
WebView v;

v=(WebView) rootView.findViewById(R.id.webView1);
v.getSettings().setJavaScriptEnabled(true);
WebViewClient vc= new WebViewClient();
v.setWebViewClient(vc);
v.loadUrl("file:///android_asset/home.html");

When I run the application the internal link is working good but the external link "www.apple.com" en in the web view
I searched the same question and found this solution but still external link opens in WebView
WebView webView = (WebView) rootView.findViewById(R.id.webView1);
webView.setWebViewClient(new MyWebViewClient());
String url = "file:///android_asset/home.html";
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);

and class
class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(url.contains("http")){ // Could be cleverer and use a regex
            return super.shouldOverrideUrlLoading(view, url); // Leave webview and use browser
        } else {
            view.loadUrl(url); // Stay within this webview and load url
            return true;
        }
    }
}

A: Change
  if (url.contains("http")) { // Could be cleverer and use a regex
    return super.shouldOverrideUrlLoading(view, url); // Leave webview and use browser
  } else {
    view.loadUrl(url); // Stay within this webview and load url
    return true;
  }

to
 if (url.contains("http")) { // Could be cleverer and use a regex
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    mContext.startActivity(intent);
    return true;
 }
 return false;

Note : replace mContext with your activity context.


text: Q: How to calculate mean and variance of non central chi distribution of the problem? If $Y = \sqrt{\sum_{i=1}^N X_i^2} $, where $X_i \sim \mathcal{N}(\mu,\sigma^2)$, i.e. all $X_i$ are i.i.d gaussian random variables of same mean and variance, then what is the resultant PDF of $Y$? How to calculate the mean and variance of the resultant pdf?


text:
Q: How to mock executeNamedQuery(query, params) for Junit Testing @Repository
public class DAOImpl extends GenericDaoImpl implements SomeDAO {
@Autowired
EntityManager em;

@Override
public List<PropertyURL> getProperties(String env) throws Exception{
    List<String> inParam = new ArrayList<>();
    inParam.add(env);
    Map<String, Object> params = new HashMap<>();
    params.put(ProEnum.ENV.getProperty(), inParam);
    List<PropertyURL> URL = null;
    String query = "PropertyURL.getProperty";
    URL = executeNamedQuery(query, params);
    return URL;
}

How can i mock  executeNamedQuery(query, params) call and return some thing  Ex:Mockito.when(entityManagerMock.merge(Mockito.any())).thenReturn(someObject);


text:
Q: How to replace a set of x axis labels with another one I am plotting roughly 300 variables, R automatically sets x-axis labels and has them as numbers, I don't want this. But if I use the xaxt = 'n' feature and then 'axis', it won't work because for axis I'll need to define x labels for 300 variables to....
Is there any way to fix this?
To give a better example of my issue, my code looks something like this:
plot(data, xaxt = 'n')
x = c("Time 1", "Time 2", "Time 3", "Time 4", "Time 5", "Time 6")
axis(side = 1, at = 1:6, labels = x[1:6])

But this is not working, I think it has to do with the fact that I have 300 data points, not 6, but I just want it to equally space out these 6

A: at should contain 6 numbers between 1 and 300 at which you want the labels to be placed, not just 1 through 6, because this will squash them all at the beginning/left side.
dat=rnorm(300)
plot(dat, xaxt="n")
x=c("Time 1", "Time 2", "Time 3", "Time 4", "Time 5", "Time 6")
axis(1, at=floor(seq(1,300,length=6)), labels=x)


text:
Q: How to anchor visual element in xamarin I am making a landing page for this application I am developing. I have done a pre-render for the background and am currently working out how to place elements above it so that it appears seamless. Currently, I have placed the first element, an entry box, approximately where I want it to be. My issue now is that I need It to remain there regardless of the screen size it may be displayed on. My intuition tells me this can be done with AnchorX and AnchorY.
Here is my code:
    <ContentPage.Content>
        <AbsoluteLayout>
            <Image AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0,0,1,1" Source="{local:ImageResource Untitled.Images.predrawVers2.png}" Aspect="AspectFill"></Image >
            <Grid AbsoluteLayout.LayoutBounds="0,0,1,1" AbsoluteLayout.LayoutFlags="All" BackgroundColor="Transparent">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                    <RowDefinition Height="24" />
                    <RowDefinition Height="50" />
                    <RowDefinition Height="*" />
                    <RowDefinition Height="*" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="317" />
                    <ColumnDefinition Width="420" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>

                <Entry Placeholder="System name" PlaceholderColor="Aqua" Grid.Column="4" Grid.Row="2" VerticalOptions="Fill" HorizontalOptions="Fill"></Entry>
            </Grid>
        </AbsoluteLayout>
    </ContentPage.Content>


text:
Q: Please explain about the red dots in the below picture
I saw the picture some where and wondering if the red dots are buried vias or test points

A: The red dots definitely have the same shape and size as the showing pads for TP4003 and TP4003. The ones that are red are covered with the solder mask and thus the reason that they appear in the red color!!
It is likely that the original PC board artwork designer placed test points on every net of the board and then later modified the solder mask to cover those not needed on finished assemblies. There are several pairs of covered test point pads in the lower right corner of the picture that even have silk screen indicators as test points that support this guess.
Some bare board manufacturing facilities may make use of all these test points to electrically check a raw, in process, board for shorts before committing it to later stages of fabrication. In the early manufacturing stages these pads would not yet be covered with the solder mask. This can lower overall fallout at the finished board test station, especially for cases where there are a lot of layers involved in the board stackup. Such in process testing may also apply for testing buried via layers as well.


text:
Q: Name ' outcome' is not defined - Python 3 I have a rock, paper, scissors, game that I am running and when I reach the part where I will display the result in a new window, a NameError occurs saying name 'outcome' is not defined.
def game():

ai_choice = {'0':'Rock', '1':'Paper', '2': 'Scissors'}
def rock():
    ai = ai_choice[str(random.randint(0,2))]
    if ai == "Rock":
       output = "Tie"
    elif ai == "Scissors":
        output = "User Win"
    else:
        output = "User Lose"
    outcome.config(text = output)
    output_window()
def paper():
    ai = ai_choice[str(random.randint(0,2))]
    if ai == "Rock":
       output = "User Lose"
    elif ai == "Scissors":
        output = "Tie"
    else:
        output = "User Win"
    outcome.config(text = output)
    output_window()
def scissors():
    ai = ai_choice[str(random.randint(0,2))]
    if ai == "Paper":
       output = "Tie"
    elif ai == "Scissors":
        output = "User Lose"
    else:
        output = "User Win"
    outcome.config(text = output)
    output_window()

def output_window():
    global outcome
    show_output = Tk()
    show_output.title("Result")
    show_output.geometry("200x200")
    outcome = Label(show_output, text ='')
    outcome.pack()

A: From the look of it, "output" is a local variable. This would mean that the other methods don't have access to it. I would recommend making output a global variable and using the global keyword whenever you need to set it. This should fix the problem.


text:
Q: Alternatives to MySQL I would like to store data persistently for my application, but I don't really need a full blown relational database. I really could get by with a basic "cache"-like persistent storage where the structure is just a (key, value) pair.
In lieu of a database what are my best, scalable options?

A: if you want a 'persistent cache', and already use memcached, check memcachedb. it's a persistent hashtable using the memcached protocol, no need for a new client (but a new daemon)

A: I ask a similar question recently.  Here are some choices:

*

*The Berkley DB is groovy.  (also see the Berkley DB Wikipedia entry)

*If you are on Windows, then you can use the built in Extensible Storage Engine. This used to be called "Jet Blue".

*Microsoft SQL Compact Edition is also free (But not built into the OS.

A: If you need scalability, then a RDBMS is your best bet. At the most basic level, you can serialize data structures into files - however, then you'd need to account for file locking issues which would limit concurrency.
SQLite is an SQL file-based database engine, which can run without a persistent database daemon (in PHP for example, it runs as an extension), however it too has concurrency issues (read the answers to this question which could help you decide if SQLite is right for you).
Unless you have a really good reason not to use a real DRBMS, I'd suggest you stick with MySQL or other "full-blown" engines.

A: There's always SQLite, a database that's stored in a file. SQLite already has built-in concurrency, so you don't have to worry about things like file locking, and it's really fast for reads.
If, however, you are doing lots of database changes, it's best to do them all at once inside a transaction. This will only write the changes to the file once, as opposed to every time an change query is issued. This dramatically increases the speed of doing multiple changes.
When a change query is issued, whether it's inside a tranasction or not, the whole database is locked until that query finishes. This means that extremely large transactions could adversely affect the performance of other processes because they must wait for the transaction to finish before they can access the database. In practice, I haven't found this to be that noticeable, but it's always good practice to try to minimize the number of database modifying queries you issue.

A: If you want something really scalable, I wouldn't opt for a flat or XML file. As your data grows, it could kill your performance.
If you will have a lot of data at some stage, I would still opt for a database - I would take a look at something like SQLIte with a very simple schema to suit your needs.

A: I'm really not sure you should but have you considered just storing info in an XML doc if it really is that light? And if it's not have you considered SQLite?

A: If your writing a java program that wants an imbedded database look at hsqldb since it is written in java and works much better then sqlite if being called from java programs.

A: If you are writing Java, then there are Java database implementations (Jared mentions hsqldb, there are others) that you can directly include.
SQLite is fine for static inclusion, however you can also include MySQL within your application if you're using a compatible language such as C.
I think you would appreciate having SQL available as well. XML files just don't cut it any longer, maybe a couple of years ago when writing PDA software, but even the iPhone and Android includes SQLite now.

A: hsqldb in in-memory mode will give you much better performance than flat file based databases. It's pretty easy to use too. And if the table gets too big, there is an option to cache it on disk too. Check out this performance comparison:

(source: hsqldb.org)

A: For Key=Value pairs, you can use INI file format with simple load and save procedures to load it and save it to in-memory hash table.
That can later scale up to anythig, just by changing load and save procedures to work with db.

A: You could try CounchDB, it is a very flexible document-oriented database that doesn't force you to define a schema up-front. It was written in Erlang and thanks to this it is considered very scalable solution. It can be easily queried through a REST interface.


text:
Q: Scroll to element not working? Javascript / jQuery This is for our website and we do not know why when you click 'apply'. It doesn't take you to that part of the page.
It should be able to scroll to that point on the page and have the title of that section at the top.
Please could you help us, thank you!

Apply

You can see here that I want it to scroll down to the div called #apply when you click this anchor tag.
$(document).ready(function(){
  function scrollTo(place) {
    $('html, body').animate({ scrollTop: $(place).offset().top }, 'slow');
  }
});


text:
Q: How to reset a react redux form split in different parts (Wizard form)? I cannot manage to reset my react redux form that is split in 3 different forms/pages. It's a wizard form and I have been trying many ways to reset it unsuccessfully.
I've been using these 2 resources:
How to build a wizard form:
https://redux-form.com/8.3.0/examples/wizard/
How to reset a form:
https://redux-form.com/6.0.0-alpha.4/docs/faq/howtoclear.md/
However, it seems clear to me now that it kinda impossible to do so.
I have 3 pages like so:
WizardForm.jsx
<div className="wizard__form-wrapper">
  {page === 1
  && (
    <WizardFormOne
      onSubmit={this.nextPage}
      initialValues={initialValues}
    />
  )}
  {page === 2
  && (
    <WizardFormTwo
      previousPage={this.previousPage}
      onSubmit={this.nextPage}
    />
  )}
  {page === 3
  && (
    <WizardFormThree
      previousPage={this.previousPage}
      onSubmit={values => onSubmit(values)}
    />
  )}
</div>

and on each form I'm exporting my form like so:
WizardFormOne.jsx
export default reduxForm({
  form: 'wizard', //                 <------ same form name
  destroyOnUnmount: false, //        <------ preserve form data
  forceUnregisterOnUnmount: true, // <------ unregister fields on unmount
  validate,
})(WizardFormOne);

The form works great but I cannot reset it. I've been trying all 4 options described in the link above. FOr example, in my WizardForm.jsx I do:
componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch(reset('wizard'));
  }

But nothing happens, and my form is not cleared.
Any help is much appreciated. Thank you.

A: For what its worth I found a solution to this issue:
You can pass a prop such as resetForm to the child component that contains the form, in m case it's WizardFormOne.jsx and do something like this:
constructor(props) {
    super(props);
    if (props.resetForm && props.isPristine) {
      props.destroy();
    }
  }

I'm sure you can put it in componentDidMount I'll have to keep working on it. That did it in my case.


text:
Q: Android taking picture with camera and save to sqlite causes java.lang.IllegalStateException: Can't compress a recycled bitmap Android app trying to save an image to the sqlite database using content resolver after taking a photo with the camera.
However no matter what I do I still get variations of "Can't compress a recycled bitmap"
I have looked at numerous posts on stackoverflow but none of them address my issue. I can't seem to find the code where my bitmap is recycled causing the error:
Caused by: java.lang.IllegalStateException: Can't compress a recycled bitmap
    at android.graphics.Bitmap.checkRecycled(Bitmap.java:394)
    at android.graphics.Bitmap.compress(Bitmap.java:1077)
    at com.wernerraubenheimer.ujcp.fragments.UserInputFragment.getBytes(UserInputFragment.java:269)
    at com.wernerraubenheimer.ujcp.fragments.UserInputFragment.saveImage(UserInputFragment.java:248)
    at com.wernerraubenheimer.ujcp.fragments.UserInputFragment.onActivityResult(UserInputFragment.java:241)

My code:
private void takePhotoFromCamera() {
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, CAMERA);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == getActivity().RESULT_CANCELED) {
        return;
    }
    if (requestCode == GALLERY) {
        if (data != null) {
            Uri contentURI = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), contentURI);
                saveImage(bitmap);
                CircleTransform circleTransform = new CircleTransform();
                avatarView.setImageBitmap(circleTransform.transform(bitmap));

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "Failed!", Toast.LENGTH_LONG).show();
            }
        }
    } else if (requestCode == CAMERA) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        CircleTransform circleTransform = new CircleTransform();
        avatarView.setImageBitmap(circleTransform.transform(thumbnail));
        saveImage(thumbnail);
    }
}

public void saveImage(Bitmap myBitmap) {

    ContentValues userValues = new ContentValues();
    userValues.put(ProgrammeCourseContract.LearnersEntry.COLUMN_AVATAR, getBytes(myBitmap));

    if(!HAS_AVATAR) {
        userValues.put(ProgrammeCourseContract.LearnersEntry._ID, 1); // Only one user for now, future may include more
        getActivity().getContentResolver().insert(
                ProgrammeCourseContract.LearnersEntry.CONTENT_URI,
                userValues);

    } else { //there is already an avatar image, save the new one
        getActivity().getContentResolver().update(
                ProgrammeCourseContract.LearnersEntry.CONTENT_URI,
                userValues,
                ProgrammeCourseContract.LearnersEntry._ID + " = ?",
                new String[]{"1"});
    }
    onAvatarUpdateListener.onAvatarUpdate();
}

// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    return stream.toByteArray();
}

// convert from byte array to bitmap
public static Bitmap getImage(byte[] image) {
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}

A: As per Mike M, moved saveImage(thumbnail) to before CircleTransform:
else if (requestCode == CAMERA) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            saveImage(thumbnail);
            CircleTransform circleTransform = new CircleTransform();
            avatarView.setImageBitmap(circleTransform.transform(thumbnail));
        }


text:
Q: creat stacked barplot from a raster file I have two raster files (raster1 and raster2). Each raster file has probability value (0-1). What I want to do is to create a stacked barplot for each raster (my probability classes should be: 0.1-0.2,0.2-0.4,0.4-0.6,0.6-0.8,0.8-1.0) and plot them next to each other.
Thank you for your help.

A: g1=hist(getValues(raster1), breaks=c(0.1,0.2,0.4,0.6,0.8,1),plot=F)
g2=hist(getValues(raster2), breaks=c(0.1,0.2,0.4,0.6,0.8,1),plot=F)
barplot(rbind(g1,g2))


text:
Q: Angular- When I click on a component, all instances of that component are reinitalized There is a page of project cards. Each card has a favorite button. If the project is not in favorites, it will become a favorite when the button is clicked. There is an icon in the project-card that changes according to whether the project is a favorite or not.
The problem is when I click the favorite button, all project-card components are reinitalized and favorite icon doesn't change. The following code will help more.
project-carousel.component.html
<app-project-card *ngFor="let project of projects" [project]="project" [isFavorite]="isFavorite(project.id)"></app-project-card>

project-card.component.html

project-card.component.ts
export class ProjectCardComponent implements OnInit {

  @Input() project: Proje;
  @Input() isFavorite: boolean;

  constructor(private favoriteService: FavoriteService) {
  }

  ngOnInit(): void {
  }

  favorite(): void {
    if (this.isFavorite) {
      this.favoriteService.deleteFavorite(this.project.id);
    } else {
      this.favoriteService.addFavorite(this.project.id);
    }
    this.isFavorite = !this.isFavorite;
  }
}

So what I want to do is; When I click on the favorite button, I want to add that project to favorites and change the favorite icon.
I am waiting for your suggestions for a solution or a different approach.

A: Try using trackBy with your ngfor. this will probably solve this kind of issues you are facing.
check angular doc for implementation https://angular.io/api/common/NgForOf
or try below code,
<app-project-card *ngFor="let project of projects; trackBy:trackByProjectId" [project]="project" [isFavorite]="isFavorite(project.id)" ></app-project-card>

in component.ts
trackByProjectId(index: number, project: any): string {
    return project.id;  // need to return unique key from your project , you can adjust this one

  }