text:
Q: Spaghettification - Singularity is just energy? So... as matter falls into a black hole the tidal forces tend toward infinity as you get closer to the singularity.
These tidal forces overcome the bonds between atoms, then the bonds between nucleons etc. etc.
Has there been any research to indicate whether or not it is possible that these tidal forces get so strong that they break the fundamental building blocks of matter (be that string or otherwise). Then you would have a signularity that is purely composed of energy, which gets over the whole compressing mass into such a small volume thing.
I thought about this the other night and I couldn't immediately think of any fundamental reason to dismiss it. However, it seems slightly too obvious for it to have never been looked into.

A: Thinking about the singularity as a lot of mass in a tiny volume is a popular science simplification. When you do the math of the Schwarzschild metric right, you can find that while the singularity corresponds to $r=0$ in the usual coordinate system, the actual geometry makes it more like a surface than a point. This is also a spacelike surface, something more akin to a certain time rather than a place. As it is approached tidal forces go to infinity, but regardless of whether particles are disrupted or not, the remnants end up at the singularity.
Models of the quark-gluon plasma give some evidence of how it heats up as the singularity is approached. There have been proposals that strings unwind to form "fuzzballs" but these are still black holes with singularities (and remain rather speculative).
In the end, the singularity is not composed of matter or energy. The singularity is not even a proper place, but a limiting state reached by infalling stuff. It is not made of anything.

A: If fundamental entities (strings, point-like particles, or whatever structure) could be torn apart then they aren't fundamental anymore. So if particles get torn apart inside a black hole then that means there are more fundamental structures.
These structures will just stay what they are inside the black hole. As these structures have a mass, they have energy. So there is only mass (or energy) inside the black hole. Maybe all mass is converted into photons (due to a mutual annihilation of elementary particles), which seems to me the closest to viewing the content of the black hole as pure energy (when you consider photons as pure energy)


text:
Q: Fix duplicate information in R I'd like to know why I'm getting my output with duplicate values. Notice that I have twice values for Wednesday, Thursday and Friday. How can I fix this?
Executable code below:
library(dplyr)
library(tidyverse)

df1<-structure(list(Id = c(1, 1, 1, 1, 1, 1), date1 = c("2021-06-28",
"2021-06-28", "2021-06-28", "2021-06-28", "2021-06-28", "2021-06-28"),
date2 = c("2021-06-18","2021-06-19", "2021-06-20", "2021-06-25", "2021-06-26", "2021-06-27"),
Week = c("Wednesday","Thursday", "Friday", "Wednesday","Thursday", "Friday"),
DT = c(1, NA_character_, NA_character_,1, NA_character_, NA_character_), Category = c("AB","CD", "EF", "AB", "CD", "EF"),
Time = c(2, 4, 2, 4, 3, 4)), row.names = c(NA, -6L), class = c("tbl_df","tbl", "data.frame"))

f2 <- function(df1,idd,ds,codagr,dt) {

  nms <- c('Time|time')

  mtime <- df1 %>% mutate(DT = replace_na(DT, "")) %>%
    filter(Id==idd,Week == ds, Category == codagr,DT == dt) %>%
    group_by(Id,Week,Category,DT) %>%
    summarise(across(matches(nms), mean, .names = 'Time',na.rm = TRUE), .groups = 'keep') %>%
    mutate(Time = format(round(Time, digits = 2), nsmall = 2))

  return(mtime)
}

df1 %>% mutate(DT = replace_na(DT, "")) %>%
  rowwise %>%
  mutate(f2(df1,Id,Week,Category, DT))%>%
 select(-c(date1, date2))%>%data.frame()

  Id      Week DT Category Time
1  1 Wednesday  1       AB 3.00
2  1  Thursday          CD 3.50
3  1    Friday          EF 3.00
4  1 Wednesday  1       AB 3.00
5  1  Thursday          CD 3.50
6  1    Friday          EF 3.00

A: A dirty fix, but distinct_all() will remove duplicates
Ouput:
# A tibble: 3 x 5
# Rowwise:
     Id Week      DT    Category Time
  <dbl> <chr>     <chr> <chr>    <chr>
1     1 Wednesday "1"   AB       3.00
2     1 Thursday  ""    CD       3.50
3     1 Friday    ""    EF       3.00

A: To be honest, I don't even understand, why your code actually works, since I don't understand what
mutate(f2(df1, Id, Week, Category, DT))

does. In my understanding, this is an usual way of using mutate. I acutally only know mutate(new_var = do_stuff()) and mutate(across(...)).
However: If we take a look at
df1 %>%
  mutate(DT = replace_na(DT, "")) %>%
  rowwise() %>%
  mutate(f2(df1,Id,Week,Category, DT))

we get
# A tibble: 6 x 7
# Rowwise:
     Id date1      date2      Week      DT    Category Time
  <dbl> <chr>      <chr>      <chr>     <chr> <chr>    <chr>
1     1 2021-06-28 2021-06-18 Wednesday "1"   AB       3.00
2     1 2021-06-28 2021-06-19 Thursday  ""    CD       3.50
3     1 2021-06-28 2021-06-20 Friday    ""    EF       3.00
4     1 2021-06-28 2021-06-25 Wednesday "1"   AB       3.00
5     1 2021-06-28 2021-06-26 Thursday  ""    CD       3.50
6     1 2021-06-28 2021-06-27 Friday    ""    EF       3.00

As we can see, the Time column has changed, but the at the moment, there are no duplicated data. Compare row 1 to row 4 you see that there is a difference in column date2.
The next step select(-c(date1, date2)) just removes those columns, so now there is no difference between row 1 and row 4 (for example) anymore:
# A tibble: 6 x 5
# Rowwise:
     Id Week      DT    Category Time
  <dbl> <chr>     <chr> <chr>    <chr>
1     1 Wednesday "1"   AB       3.00
2     1 Thursday  ""    CD       3.50
3     1 Friday    ""    EF       3.00
4     1 Wednesday "1"   AB       3.00
5     1 Thursday  ""    CD       3.50
6     1 Friday    ""    EF       3.00

So for now and the sake of completeness, you current code can be simplified to
df1 %>%
  mutate(DT = replace_na(DT, ""),
         across(c(date1, date2), as.Date)) %>%
  group_by(Id, Week, Category, DT) %>%
  summarise(across(matches("(t|T)ime"), mean, .names = 'Time', na.rm = TRUE),
            .groups = "drop") %>%
  mutate(Time = format(round(Time, digits = 2), nsmall = 2))

Perhaps this gives you a clue for the problem you are working on.
One more thing: If you want/need to apply custom functions on your dataset or parts of your dataset, the purrr package with its map_*, imap_* and/or map2_* functions might be an option.

redpajama_set_name: RedPajamaStackExchange


text:
Q: The hierarchy of the type MainActivity is inconsistent I created a new Android project via eclipse, with a MainActivity.
I added ActionBarSherlock to the project (Properties > Android and clicked Add).
Then, when I replace "extends Activity" with "extends SherlockFragmentActivity" I get a compile error "The hierarchy of the type MainActivity is inconsistent".
I also tried to create a project without an Activity, then created a class "MainActivity" that inherits from SherlockFragmentActivity, and there are no compile time errors, but with a run-time error "ClassNotfoundException: com.NadavLitvak.nadavfragmentdemo.MainActivity"

A: Sometimes, when Eclipse gets retarded, it doesnt add the SDK jar in your project (the Android x.y folder missing in project) so then you need to add it Properties > Android > Project Build Target (usually nothing there is ticked)

A: Your project should also reference the android-support-v4.jar (which is included in ABS's libs folder.)  So, Properties->Java Build Path->Add JARs... and select that jar from ActionBarSherlock->libs


text:
Q: Average of product of matrix elements in the special orthogonal group Given two lists $i$ and $j$ of $2n$ positive integers less than $N$, Collins and Sniady have computed, in Integration with respect to the Haar measure on unitary, orthogonal and symplectic group (see also On some properties of orthogonal Weingarten functions by Collins and Matsumoto), the integral over the orthogonal group,
$$ \int_{O(N)} \prod_{k=1}^{2n}u_{i_kj_k}du=\sum_{\sigma,\tau}\Delta_\sigma(i)\Delta_\tau(j) {\rm Wg}_N(\sigma^{-1}\tau),\qquad (1)$$ where the sum is over matchings, $\Delta_\sigma(i)=1$ if and only if the sequence $i$ satisfies the matching $\sigma$ and ${\rm Wg}_N$ is called the Weingarten function.
This implies for instance that $\int_{O(N)} u_{11}u_{22}du=0$ because the list $(1,2)$ does not match.
On the other hand, we know that a matrix from $SO(2)$ is of the form $u=\begin{pmatrix}\cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \\
  \end{pmatrix}$ so clearly we have $\int_{SO(2)} u_{11}u_{22}du=1/2$. This shows that the $SO(N)$ result can be quite different from the $O(N)$ one.
Is there a general theory of integrals like (1) over $SO(N)$?

A: That's a good question. This is not quite an answer  but a bit long for a comment.
A quick remark is that for $N$ odd a Haar-random element of $O(N)$ can be obtained as $\epsilon U$ where $\epsilon=\pm1$ with equal probability, and $U$ is a Haar-random element of $SO(N)$. So if your monomial has an even number of factors the integrals over $O(N)$ and $SO(N)$ coincide and thus Weingarten calculus is applicable. This is of course because for $N$ odd $-I$ has determinant $-1$ and is in the center of $O(N)$. I don't know if there is a similar trick for $N$ even.
I said it is a good question because, when looking at the vast probability/representation theory literature, I didn't see much as far an analogue of Weingarten calculus for special groups. Even the work of Chatterjee (and Basu and Ganguly,...) on $SO(N)$ lattice gauge theories does not seem to use Weingarten calculus. So for $SO(N)$, my answer to the question is: I don't know. However, for $SU(N)$ there is a combinatorial calculus. It is explained in my two answers to
How to constructively/combinatorially prove Schur-Weyl duality?
This technique was worked out explicitly by Creutz but it has its roots in the work of Clebsch and Hilbert in invariant theory. See for example, the averaging operator $[\cdot]$ used by Hilbert on p. 523 of "Ueber die Theorie der algebraischen Formen" is basically the same as Creutz's formula for $SU(2)$. Also note that if a combinatorial Weingarten-like calculus for $SO(N)$ is perhaps missing, there is at least an Euler angle parametrization due to Hurwitz (see this review by Diaconis and Forrester).


text:
Q: How to encrypt and decrypt a file with 3DES (Triple DES) in Java This is what I have, but I can not decipher the file.
I do not find a logic that allows me to decipher.
I do not know if it is encrypting correctly, because I can not decipher it.
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.security.GeneralSecurityException;
 import java.security.MessageDigest;
 import javax.crypto.Cipher;
 import javax.crypto.SecretKey;
 import javax.crypto.SecretKeyFactory;
 import javax.crypto.spec.DESedeKeySpec;
 import javax.crypto.spec.IvParameterSpec;

 public class TestEncryptor {

     public static void main(String... args) {
         try {
             String KEY_STRING = "asdasdasd";
             byte[] key = getEnKey(KEY_STRING);
             String pFilePath = "D:\\fileTest.png";
             String pFilePathEncryp = "D:\\fileTestEncryp.png";
             byte[] archivoDecrypt = encryptFile(pFilePath, key);

             try (FileOutputStream fos = new FileOutputStream(pFilePathEncryp)) {
                 fos.write(archivoDecrypt);
             }
         } catch (Exception e) {
             e.printStackTrace();
         }

     }

     public static byte[] encryptFile(String pFilePath, byte[] pKey) throws GeneralSecurityException, IOException {
         File file = new File(pFilePath);
         long length = file.length();
         InputStream is = new FileInputStream(file);

         // You cannot create an array using a long type.
         // It needs to be an int type.
         // Before converting to an int type, check
         // to ensure that file is not larger than Integer.MAX_VALUE.
         if (length > Integer.MAX_VALUE) {
             // File is too large
         }

         // Create the byte array to hold the data
         byte[] bytes = new byte[(int) length];

         // Read in the bytes
         int offset = 0;
         int numRead = 0;
         while (offset < bytes.length
                 && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
             offset += numRead;
         }

         // Close the input stream and return bytes
         is.close();

         // Ensure all the bytes have been read in
         if (offset < bytes.length) {

             throw new IOException("Could not completely read file " + file.getName());
         }

         SecretKeyFactory lDESedeKeyFactory = SecretKeyFactory.getInstance("DESede");
         SecretKey kA = lDESedeKeyFactory.generateSecret(new DESedeKeySpec(pKey));

         IvParameterSpec lIVSpec = new IvParameterSpec(new byte[8]);
         Cipher desedeCBCCipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");

         desedeCBCCipher.init(Cipher.ENCRYPT_MODE, kA, lIVSpec);
 //        desedeCBCCipher.init(Cipher.DECRYPT_MODE, kA, lIVSpec);
         byte[] encrypted = desedeCBCCipher.doFinal(bytes);

         return encrypted;
     }

     private static byte[] getEnKey(String spKey) {
         byte[] desKey = null;
         try {
             byte[] desKey1 = md5(spKey);
             desKey = new byte[24];
             int i = 0;
             while (i < desKey1.length && i < 24) {
                 desKey[i] = desKey1[i];
                 i++;
             }
             if (i < 24) {
                 desKey[i] = 0;
                 i++;
             }
         } catch (Exception e) {
             e.printStackTrace();
         }

         return desKey;
     }

     private static byte[] md5(String strSrc) {
         byte[] returnByte = null;
         try {
             MessageDigest md5 = MessageDigest.getInstance("MD5");
             returnByte = md5.digest(strSrc.getBytes("GBK"));
         } catch (Exception e) {
             e.printStackTrace();
         }
         return returnByte;
     }
 }

A: This is the solution, if someone else needs it.
    try {
        File inputFileNAme = new File(origen);
        FileInputStream fileInputStream = new FileInputStream(inputFileNAme);
        FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath);
        SecretKey secretKey = getKey(keyString);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        ObjectInputStream objectInputStream = new ObjectInputStream(new CipherInputStream(fileInputStream, cipher));
        System.out.println(objectInputStream.available());
        fileOutputStream.write((byte[]) objectInputStream.readObject());
        fileOutputStream.flush();
        fileOutputStream.close();
        fileInputStream.close();
        objectInputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }


text:
Q: Configuring MongoDB connector in MuleStudio when authentication is disabled - "failed to connect" error I'm writing some flows in MuleStudio that save to and query a MongoDB database. The flows work fine when pointed at a database that has one user with dbAdmin and userAdmin roles and is configured with that user's credentials. However, when I point it to a different database with no users added, I get the error below. I kept the username and password in the MongoDB connector config in Mule, as dummy text as is suggested in the documentation, then took them out, but to no avail. I'm using 3.3.1 CE runtime.
Error message with dummy credentials:
ERROR 2013-10-10 14:48:08,176 [[sso-mds].connector.http.mule.default.receiver.02] org.mule.retry.notifiers.ConnectNotifier: Failed to connect/reconnect: Work Descriptor. Root Exception was: Could not create a validated object, cause: Couldn't connect with the given credentials. Type: class java.util.NoSuchElementException
ERROR 2013-10-10 14:48:08,181 [[sso-mds].connector.http.mule.default.receiver.02] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message               : Failed to invoke findObjectsUsingQueryMap. Message payload is of type: LinkedHashMap
Code                  : MULE_ERROR--2
--------------------------------------------------------------------------------
Exception stack is:
1. Could not create a validated object, cause: Couldn't connect with the given credentials (java.util.NoSuchElementException)
  org.apache.commons.pool.impl.GenericKeyedObjectPool:1219 (null)
2. Failed to invoke findObjectsUsingQueryMap. Message payload is of type: LinkedHashMap (org.mule.api.MessagingException)
  org.mule.module.mongo.processors.FindObjectsUsingQueryMapMessageProcessor:177 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/MessagingException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
java.util.NoSuchElementException: Could not create a validated object, cause: Couldn't connect with the given credentials
    at org.apache.commons.pool.impl.GenericKeyedObjectPool.borrowObject(GenericKeyedObjectPool.java:1219)
    at org.mule.module.mongo.connectivity.MongoCloudConnectorConnectionManager.acquireConnection(MongoCloudConnectorConnectionManager.java:437)
    at org.mule.module.mongo.connectivity.MongoCloudConnectorConnectionManager.acquireConnection(MongoCloudConnectorConnectionManager.java:27)
    + 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)

Error message with no credentials:
ERROR 2013-10-10 14:19:48,572 [[sso-mds].connector.http.mule.default.receiver.02] org.mule.retry.notifiers.ConnectNotifier: Failed to connect/reconnect: Work Descriptor. Root Exception was: null. Type: class java.lang.NullPointerException
ERROR 2013-10-10 14:19:48,574 [[sso-mds].connector.http.mule.default.receiver.02] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message               : Failed to invoke findObjectsUsingQueryMap. Message payload is of type: LinkedHashMap
Code                  : MULE_ERROR--2
--------------------------------------------------------------------------------
Exception stack is:
1. null (java.lang.NullPointerException)
  org.mule.module.mongo.connectivity.MongoCloudConnectorConnectionKey:86 (null)
2. Failed to invoke findObjectsUsingQueryMap. Message payload is of type: LinkedHashMap (org.mule.api.MessagingException)
  org.mule.module.mongo.processors.FindObjectsUsingQueryMapMessageProcessor:177 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/MessagingException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
java.lang.NullPointerException
    at org.mule.module.mongo.connectivity.MongoCloudConnectorConnectionKey.hashCode(MongoCloudConnectorConnectionKey.java:86)
    at java.util.HashMap.hash(Unknown Source)
    at java.util.HashMap.getEntry(Unknown Source)
    + 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)

Mule config:
<mongo:config name="Mongo_DB"  doc:name="Mongo DB" database="${mongo.db}" host="${mongo.host}" port="${mongo.port}" password="${db.password}" username="${db.username}>
    <mongo:connection-pooling-profile initialisationPolicy="INITIALISE_ONE" exhaustedAction="WHEN_EXHAUSTED_GROW"/>
</mongo:config>
<flow name="user_gets_simple" doc:name="user_gets_simple">
    <composite-source doc:name="Composite Source">
        <http:inbound-endpoint exchange-pattern="request-response" host="${my.host}" port="${my.ID}" path="user/getAll" doc:name="HTTP /user/getAll"/>
        <http:inbound-endpoint exchange-pattern="request-response" host="${my.host}" port="${my.ID}" path="user/getByUsername" doc:name="HTTP /user/getByUsername"/>
        <http:inbound-endpoint exchange-pattern="request-response" host="${my.host}" port="${my.ID}" path="user/getById" doc:name="HTTP /user/getById"/>
        <http:inbound-endpoint exchange-pattern="request-response" host="${my.host}" port="${my.ID}" path="user/getByEmail" doc:name="HTTP /user/getByEmail"/>
    </composite-source>
    <flow-ref name="get_from_MongoDB" doc:name="Get from MongoDB subflow"/>
</flow>

<flow name="user_save_flow" doc:name="user_save_flow">
    <http:inbound-endpoint exchange-pattern="request-response" host="${my.host}" port="${my.ID}" path="user/save" doc:name="HTTP /user/save" />
    <byte-array-to-string-transformer doc:name="Byte Array to String"/>
    <json:json-to-object-transformer doc:name="JSON to Object" returnClass="java.util.Map"/>
    <mongo:insert-object-from-map config-ref="Mongo_DB" collection="${mongo.collection}" doc:name="Insert in Mongo DB"  >
        <mongo:element-attributes>
            <mongo:element-attribute key="firstName">#[payload.firstName]</mongo:element-attribute>
            <mongo:element-attribute key="lastName">#[payload.lastName]</mongo:element-attribute>
            <mongo:element-attribute key="location">#[payload.location]</mongo:element-attribute>
        </mongo:element-attributes>
    </mongo:insert-object-from-map>
    <set-payload value="Saved successfully" doc:name="Set Payload"/>
</flow>

<sub-flow name="get_from_MongoDB" doc:name="get_from_MongoDB">
    <byte-array-to-string-transformer doc:name="Byte Array to String"/>
    <json:json-to-object-transformer returnClass="java.util.Map" doc:name="JSON to Object"/>
    <mongo:find-objects-using-query-map config-ref="Mongo_DB" collection="${mongo.collection}" doc:name="Find objects in Mongo DB" limit="5">
        <mongo:query-attributes ref="#[payload]"/>
    </mongo:find-objects-using-query-map>
    <mongo:mongo-collection-to-json doc:name="Mongo collection to JSON"/>
</sub-flow>

Any suggestions on how I can connect to this database without adding a user?

A: Not sure how putting any dummy value would work as the connector will pass that as the username and pwd. But I tried this trick and it works. ${db.user} and in mule-app.properties just have an empty entry db.user= and that works fine.

A: Hi that is an issue as the Mule ESB doesnt work without authentication...
The user and the password fields are not "@optional".
for creating users in mongo and running mongo in authentication mode
http://www.mkyong.com/mongodb/mongodb-authentication-example/
and then you can put it the credentials in Mule ESB and you are good to go
....

A: Just add mongo-java-driver: 2.13.3 dependency. Check the maven dependency for the conflicts.


text:
Q: Change variable text
Possible Duplicate:
In C++, how do you clear a stringstream variable?

I have a problem with a string i want to use to display in my loop.
I set it up like this in my loop:
//while {
 std::stringstream s;
 s << "Hello";

  font_surface = TTF_RenderText_Solid(font,s.str().c_str(),font_color);
  apply_surface(x,y,font_surface,screen);

  s << "GoodBye";
  if(font_surface = TTF_RenderText_Solid(font,s.str().c_str(),font_color);
  apply_surface(bx,by,font_surface,screen);

//end loop }

The problem i have is the output first shows Hello then in the other location it has HelloGoodBye, i need to clear the content before i add Goodbye so i only see that in the second location on screen.
So how would i clear the information of Hello before I change it to Goodbye ?

A: If you must use a stringstream, call
s.str("");

to clear it


text:
Q: Where is the Execute Permissions function in IIS7 In IIS6 or below where on a folder you want to block any files that would normally be handled by a script processor such as asp.dll, you would open the properties dialog for that folder in IIS manager then on the directory tab under application settings you would change the combo-box next to "Execute Permission" and set it to "none".
How is this done on II7?

A: In IIS 7 this is included in the Handler Mappings section. On your site click the Handler Mappings Icon, then click the Edit Handler Permissions option in the actions menu.

A: 1.Open IIS Manager and navigate to the level you want to manage. For information about opening IIS Manager, see Open IIS Manager (IIS 7). For information about navigating to locations in the UI, see Navigation in IIS Manager (IIS 7).
2.In Features View, on the server, site, or applicationHome page, double-click Handler Mappings.
3.In the Actions pane, click Edit Feature Permissions.
4.In the Edit Feature Permissions dialog box, do the following:
Select Read to enable handlers that require read access or clear Read to disable handlers that require read access to a virtual directory.
Select Scripts to enable handlers that require script rights or clear Scripts to disable handlers that require script rights in a virtual directory.
Select Execute to enable handlers that require execute rights or clear Execute to disable handlers that require execute rights in a virtual directory. The Execute option is enabled only when Scripts is selected.


text:
Q: FitNesse Error while executing Sikuli code I am trying to execute sikuli code through FitNesse.
the following error is displayed.
Could not detect death of command line test runner.
java.lang.IllegalThreadStateException: process has not exited
        at java.lang.ProcessImpl.exitValue(Native Method)
        at fitnesse.testsystems.CommandRunner.join(CommandRunner.java:86)
        at fitnesse.testsystems.slim.SlimTestSystem.bye(SlimTestSystem.java:117)

Same code is working through eclipseIde but while running Test from FitNesse
Thanks in Advance

A: Adding more information on the observed issue:
I have integrated Sikuli code for upload a file  and following is the Sikuli code for upload:
public void uploadSikiuliCode(String image){

                       String target ="C:/Users/TestQA/Desktop/TextBox.png";
                            Screen s = new Screen();
                            try{
                                            s.click(target,0);
                                            s.type(image, 0);
                                            waitForPageLoad(3);
                                            s.click("C:/Users/TestQA/Desktop/Open.png",0);
                            }
                            catch(Exception e){
                                            e.printStackTrace();
                                            }

}
I have executed and able to upload file using Eclipse IDE
I have integrated the same to FitNesse and executed it was working fine till it enters into the Sikuli (upload) method
After entering into the method while executing the
Screen s = New Screen ()
The following error is displayed
Could not detect death of command line test runner.java.lang.IllegalThreadStateException: process has not exited
    at java.lang.ProcessImpl.exitValue(Native Method)
    at fitnesse.testsystems.CommandRunner.join(CommandRunner.java:86)
    at fitnesse.testsystems.slim.SlimTestSystem.bye(SlimTestSystem.java:117)


text:
Q: Conditional expectation of integral of Ornstein-Uhlenbeck process Given that $X(t)$ is an Ornstein-Uhlenbeck process with $X(0) = x_0$, which is a Markov process, but not a Martingale, how could I go forward if I would like to calculate
$E[\int_0^T X(s)ds | \mathcal{F}_t]$?
I have been twisting my brain for hours, but can't seem to find any reasonable approach.

A: I will try to reply to your question with some assumptions as you were not precise in your description.
Let $(\Omega,\mathcal{F},\lbrace{\mathcal{F_t}\rbrace}_{t\in\mathbb{R}_+},P)$ be a filtered probability space where we defined a $\lbrace{\mathcal{F_t}\rbrace}-$brownian motion $\lbrace{W_t\rbrace}_{t\in\mathbb{R}_+}$ starting from 0. We suppose that the process $X$ satisfies the following SDE:
\begin{equation}
dX_t = \theta(\mu-X_t)dt + \sigma dW_t
\end{equation}
where $\sigma >0, \theta >0, \mu \in \mathbb{R}$ and $X_0 \in L^2$ and independant to  $W$. We can show that it exists a unique strong solution to this SDE and is given by:
\begin{equation*}
\forall t\in \mathbb{R}_+, \quad  X_t = e^{-\theta t}X_0 + \mu(1+e^{-\theta t}) +\sigma\int_0^te^{-\theta(t-s)}dW_t
\end{equation*}
The problem was to compute: for $T>t$, $E\left[\int_0^TX_sds|\mathcal{F_t}\right]$
\begin{align*}
 E\left[\int_0^TX_sds|\mathcal{F_t}\right] &= E\left[\int_0^T\left(e^{-\theta s}X_0 + \mu(1+e^{-\theta s}) +\sigma\int_0^se^{-\theta(s-u)}dW_u\right)ds|\mathcal{F}_t\right] \\
 &=\int_0^T\left(e^{-\theta s}X_0 + \mu(1+e^{-\theta s})\right)ds + \sigma E\left[\int_0^T\int_0^se^{-\theta(s-u)}dW_uds|\mathcal{F}_t\right] \quad \\
 &= \int_0^T\left(e^{-\theta s}X_0 + \mu(1+e^{-\theta s})\right)ds + \sigma E\left[\int_0^T\int_u^Te^{-\theta(s-u)}dsdW_u|\mathcal{F}_t\right] \text{Fubini stochastic} \\
 &= \int_0^T\left(e^{-\theta s}X_0 + \mu(1+e^{-\theta s})\right)ds + \sigma E\left[\int_0^T\phi(u)dW_u|\mathcal{F}_t\right] \text{where} \ \phi(u) := \int_u^Te^{-\theta(s-u)}ds \\
 &= \int_0^T\left(e^{-\theta s}X_0 + \mu(1+e^{-\theta s})\right)ds + \sigma \int_0^t\phi(u)dW_u \quad \text{a.s.}
\end{align*}
The last equality holds because the function $\phi$ is $L^2(\mathbb{R}_+, dt)$. Thus the stochastic integral is a Wiener integral (which is a martingale).


text:
Q: Center responsive absolutely positioned element with fixed margins I have an absolutely positioned CSS banner that has a responsive width and height based on viewport size. The element is centered on desktop and tablet devices, but not on mobile (when the banner's width starts to shrink).
I can't use the classic margin: 0 auto; trick because the margins have to be set to a fixed value for the banner to work.
The code is below:
HTML:

A Simple CSS Banner

CSS:
@import url(https://fonts.googleapis.com/css?family=Rye);

body
{ background: #eee; }

.banner {
  position: absolute;
  left: 50%;
  display: block;
  margin: 100px -200px;
  width: 400px;
  max-width: calc(100% - 150px);
  height: 60px;
  border: 1px solid #8a1;
  font: normal 30px/60px 'Rye';
  text-align: center;
  color: #451;
  background: #9b2;
  border-radius: 4px;
  box-shadow: 0 0 30px rgba(0,0,0,.15) inset,
    0 6px 10px rgba(0,0,0,.15);
}

.banner::before,
.banner::after {
  content: '';
  position: absolute;
  z-index: -1;
  left: -70px;
  top: 24px;
  display: block;
  width: 40px;
  height: 0px;
  border: 30px solid #9b2;
  border-right: 20px solid #791;
  border-bottom-color: #94b81e;
  border-left-color: transparent;
  transform: rotate(-5deg);
}

.banner::after {
  left: auto;
  right: -70px;
  border-left: 20px solid #791;
  border-right: 30px solid transparent;
  transform: rotate(5deg);
}

@media (max-width: 475px) {

  .banner {
    height: 90px;
    line-height: 45px;
  }

  .banner::before,
  .banner::after {
    border-width: 45px;
    border-right-width: 30px;
  }

  .banner::after {
    border-left-width: 30px;
    border-right-width: 45px;
  }

}

Link to working codepen: https://codepen.io/Adam0410/pen/QZOKdV
Thanks for the help!

A: Check if this helps you.

@import url(https://fonts.googleapis.com/css?family=Rye);

body {
  background: #eee;
}

.banner {
  position: absolute;
  left: 50%;
  transform: translate(-50%);
  display: block;
  margin: 100px 0;
  width: 400px;
  max-width: calc(100% - 150px);
  min-height: 60px;
}
.banner span {
  display: block;
  position: relative;
  z-index: 1;
  border: 1px solid #8a1;
  font: normal 30px/60px "Rye";
  text-align: center;
  color: #451;
  background: #9b2;
  border-radius: 4px;
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.15) inset, 0 6px 10px rgba(0, 0, 0, 0.15);
}
.banner::before,
.banner::after {
  content: "";
  position: absolute;
  z-index: -1;
  left: -70px;
  bottom: -24px;
  display: block;
  width: 40px;
  height: 0px;
  border: 30px solid #9b2;
  border-right: 20px solid #791;
  border-bottom-color: #94b81e;
  border-left-color: transparent;
  transform: rotate(-5deg);
}

.banner::after {
  left: auto;
  right: -70px;
  border-left: 20px solid #791;
  border-right: 30px solid transparent;
  transform: rotate(5deg);
}

@media (max-width: 475px) {
  .banner {
    min-height: 90px;
    line-height: 45px;
  }

  .banner::before,
  .banner::after {
    border-width: 45px;
    border-right-width: 30px;
  }

  .banner::after {
    border-left-width: 30px;
    border-right-width: 45px;
  }
}

A Simple CSS Banner

A: This way you keep the top and bottom margin:
left: 0; right: 0;
margin: 100px auto;

A: You can simply use Media queries and adapt Width and margin.
something like:
media (max-width: 475px) {
  .banner{
    width: 200px;
    margin:100px -100px;
  }
}

A: If you want to center an absolute or fixed element you should :
  position: absolute;
  left: 0%;
  right:0%;
  margin: 0 auto;


text:
Q: mongoDB best practice: microservices with independent data stores A common pattern for microservices is that each should reference an independent data store.  To that end, I am planning on allocating a single mongoDB instance, but provisioning a separate database for each microservice (all databases, that is, co-located within the same mongoDB instance).
This partitions the data store by microservice, but also introduces potential contention issues (over network bandwidth, connection limits to mongoDB, etc).
Is there a best practice with respect to mongoDB deployment / configuration in this context?


text:
Q: How do I change to specific sheet via variable name during runtime in OpenPyXl? So what I want to do is to make a translation program. I want to read the file name of the text-file to translate and then look for a sheet with the same name in my workbook. Example:
TranslateMe.txt -> Look for sheet name with TranslateMe.txt
Problem is, I can't seem to change the string value of sheet using a real string.
sheet = wb.get_sheet_by_name(wb.sheetnames[0])
It gives me an error: 'str' object has no attribute 'cell' when I try changing it. I will send my code
I tried changing the value to a string, but it didn't work during runtime...
import openpyxl
import glob
import os
import fileinput
import codecs

currentDir = os.path.dirname(os.path.realpath(__file__)) # Sets path to this place

txtFile = "" # The txt-file that is about to be translated.
# I use this string value to try to change sheet value
wb = openpyxl.load_workbook('Translate.xlsx')

sheet = wb.get_sheet_by_name(wb.sheetnames[0])

# Define amount of rows and columns in current Sheet
rows = sheet.max_row
columns = sheet.max_column

# Languages: 1 = placeholders, 2 = English, 3 = Greek, 4 = Swedish
language = 2

def FindFilesForTranslation():

    filesToTranslateNames = []
    global txtFile
    global sheet

    for file in glob.glob("*.txt"):
        print(file)
        filesToTranslateNames.append(file)
        print(filesToTranslateNames)
        for i in range(len(filesToTranslateNames)):
            print(i)
            txtFile = filesToTranslateNames[i]

            if sheet != filesToTranslateNames[0]: # Underlying problem
                sheet = filesToTranslateNames[i]

            print("TxtFile Name: ", txtFile, "Sheet: ", sheet)
            TranslateFiles()

def TranslateFiles():
    for row in range(1, rows+1):
        for col in range(1, columns+1):

            # Make sure that col does not exceed the value of language
            if col >= language:
                col = language

            wordToReplace = sheet.cell(row=row, column=col).value # THIS IS WHERE THE ERROR LIES!
            replacerWord = sheet.cell(row=row, column=language).value # same #error over here

So whenever I reach the wordToReplace = sheet.cell   code lines, I get the runtime error: 'str' object has no attribute 'cell'
It's important to find the specific name of the file I'm translating, as the sheets won't be in a specific order and cannot be found with a logical for-loop. So how do I change the value of that variable sheet during runtime using the txtFile string???
Sorry for a weird and semi-incoherent post. This is my very first post here on Stackoverflow. Thanks for any help!
EDIT: I just found out that I am changing the string value of sheet during runtime. However, for some reason, " 'str' object has no attribute 'cell' " runtime error

A: I solved my own question, and in case you made a silly mistake like I did, here was the answer:
sheet = filesToTranslateNames[i]

should be
sheet.active = filesToTranslateNames[i]

Thanks for the posted answers, ya'll!


text:
Q: Spark and categorical string variables I'm trying to understand how spark.ml handles string categorical independent variables.  I know that in Spark I have to convert strings to doubles using StringIndexer.
Eg., "a"/"b"/"c" => 0.0/1.0/2.0.
But what I really would like to avoid is then having to use OneHotEncoder on that column of doubles. This seems to make the pipeline unnecessarily messy. Especially since Spark knows that the data is categorical. Hopefully the sample code below makes my question clearer.
import org.apache.spark.ml.feature.StringIndexer
import org.apache.spark.ml.feature.VectorAssembler
import org.apache.spark.ml.classification.LogisticRegression

val df = sqlContext.createDataFrame(Seq(
Tuple2(0.0,"a"), Tuple2(1.0, "b"), Tuple2(1.0, "c"), Tuple2(0.0, "c")
)).toDF("y", "x")

// index the string column "x"
val indexer = new StringIndexer().setInputCol("x").setOutputCol("xIdx").fit(df)
val indexed = indexer.transform(df)

// build a data frame of label, vectors
val assembler = (new VectorAssembler()).setInputCols(List("xIdx").toArray).setOutputCol("features")
val assembled = assembler.transform(indexed)

// build a logistic regression model and fit it
val logreg = (new LogisticRegression()).setFeaturesCol("features").setLabelCol("y")
val model = logreg.fit(assembled)

The logistic regression sees this as a model with only one independent variable.
model.coefficients
res1: org.apache.spark.mllib.linalg.Vector = [0.7667490491775728]

But the independent variable is categorical with three categories = ["a", "b", "c"]. I know I never did a one of k encoding but the metadata of the data frame knows that the feature vector is nominal.
import org.apache.spark.ml.attribute.AttributeGroup
AttributeGroup.fromStructField(assembled.schema("features"))
res2: org.apache.spark.ml.attribute.AttributeGroup = {"ml_attr":{"attrs":
{"nominal":[{"vals":["c","a","b"],"idx":0,"name":"xIdx"}]},
"num_attrs":1}}

How do I pass this information to LogisticRegression? Is this not the whole point of keeping dataframe metadata? There does not seem to be a CategoricalFeaturesInfo in SparkML. Do I really need to do a 1 of k encoding for each categorical feature?

A: Maybe I am missing something, but this really looks like the job for RFormula (https://spark.apache.org/docs/latest/ml-features.html#rformula).
As the name suggests, it takes an "R-style" formula that describes how the feature vector is composed from the input data columns.
For each categorical input columns (that is, StringType as type) it adds a StringIndexer + OneHotEncoder to the final pipeline implementing the formula under the hoods.
The output is a feature vector (of doubles) that can be used with any algorithm in the org.apache.spark.ml package, as the one you are targeting.


text:
Q: RecyclerView clicks twice after adding new items I have a RecyclerView display some data depending on what the user searches for.When the user clicks on one of the items it launches a new intent with more information regarding the item that he clicked.In the first search it works fine but when i clear the recyclerview and add new items then the five first items launch the intent twice while the rest of the 5 launch it once(what is supposed to happen)
MatchListCustomAdapter.cs
  private void MMainView_Click(object sender, EventArgs e)
        {
            int position = mRecyclerView.GetChildLayoutPosition((View)sender);

            mainAct.launchActivity(mgame[position].Id);
        }

MainActivity.cs
 private void function1()
        {
            //Clears the list at the beginning and each time a new user is queried so it doesn't add more than 10 games.
            game.Clear();
            mAdapter.NotifyDataSetChanged();
            System.Diagnostics.Debug.WriteLine("This is from the recentgamesdoworkcompleted");
            for (int i = 0; i < 10; i++)
            {
                //This sets the color of the listview depending if it's a victory or defeat.
                if (mclass.win[i])
                {
                    winorlose = Color.ParseColor("#42A5F5");
                }
                else
                {
                    winorlose = Color.ParseColor("#D32F2F");

                }
                game.Add(new Models.MatchHistoryListView()
                {
                    Name = "" + mclass.summonerId[0, i],
                    ChampionId = mclass.championId[0, i],
                    Id = mclass.recentGamesId[i],
                    Score = mclass.summonerScoreText[i],
                    championPortraito = new Uri("http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/" + mclass.championName[0, i] + ".png"),
                    Item0 = new Uri("http://ddragon.leagueoflegends.com/cdn/6.24.1/img/item/" + mclass.summonerItems[i, 0] + ".png"),
                    Item1 = new Uri("http://ddragon.leagueoflegends.com/cdn/6.24.1/img/item/" + mclass.summonerItems[i, 1] + ".png"),
                    Item2 = new Uri("http://ddragon.leagueoflegends.com/cdn/6.24.1/img/item/" + mclass.summonerItems[i, 2] + ".png"),
                    Item3 = new Uri("http://ddragon.leagueoflegends.com/cdn/6.24.1/img/item/" + mclass.summonerItems[i, 3] + ".png"),
                    Item4 = new Uri("http://ddragon.leagueoflegends.com/cdn/6.24.1/img/item/" + mclass.summonerItems[i, 4] + ".png"),
                    Item5 = new Uri("http://ddragon.leagueoflegends.com/cdn/6.24.1/img/item/" + mclass.summonerItems[i, 5] + ".png"),
                    Item6 = new Uri("http://ddragon.leagueoflegends.com/cdn/6.24.1/img/item/" + mclass.summonerItems[i, 6] + ".png"),
                    listViewColor = winorlose

                });

            }
        }

A: Fixed it by setting the adapter again it's time the RecyclerView data is updated.


text:
Q: Probability of not picking a row in a random draw where the number of rows are N There are $N$ rows :$R_1, R_2,R_3,..., R_N$. What is the probability of not picking a row in a random draw?
My try and understanding :
Let $X$ be a random variable which is defined as follows:
$$X = \text{ Number of rows picked in a random draw.}$$
So, the values of random variable which it can take are :
$$X = 0, 1,2,3,4,...N$$
Hence the required probability is :
$$
\begin{aligned}
\text{ Probability of not picking a row in a random draw } & = 1-\text{Probability of picking a row in a random draw } \\
 & = 1 - P(X = 1) \\
 & = 1 - \frac{N}{2^N}
\end{aligned}
$$
The size of sample space is $|S| = 2^N$ and the favourable outcomes are $N$ for $X =1$
Could someone explain whats wrong in it, because I read a blog on the medium* where it is mentioned the required probability is $\frac{N-1}{N}$. Follow the mentioned link or see the below screen shot:

Note: Please try to open the website in incognito mode to get rid from sign in etc and the probability thing is mentioned at the end of the blog.

A: $X$ is not explicitly mentioned in the article, so I think in this context, $X$ refers to the row number that is picked and not the number of rows picked in a random draw. If this is indeed the case, then I think the statement

probability of not picking a row in a random draw is

should be re-worded to

probability of not picking a row in a random draw of size $N = 1$

which would make it clearer. Since
\begin{align}
\sum_{i = 0}^{N} p(X = i) &= 1 \\
\left[\sum_{i \neq x} p(X = i)\right] + p(X = x) &= 1 \\
\sum_{i \neq x} p(X = i) &= 1 - p(X = x) \\
&= p(X \neq x)
\end{align}
and so
$$
p(X \neq x) = \sum_{i \neq x} p(X = i)
$$
Since there are $N$ rows to pick from, and assuming that each row is equally likely to be picked, then
$$
\sum_{i \neq x} p(X = i) = \frac{N-1}{N}
$$


text:
Q: What is a good starting point to read about Wolverine and the X-Men? Can someone direct me to which comic or series of comics to start reading so I can understand Logan's story line better?
Is there an order I should be reading the comics in?  Is the X-Men story over?
EDIT for ADDT'L info:
I would like to read some storyline, the best, for Wolverine. I would like to start (maybe read the prequel first if there is).
My 2nd question was, if the X-Men story has ended or is there still comics being published upto date.

A: To get an overview of Wolverine, there are a number of storylines that can be read to give a nice overview of the character. Wolverine is a character that has been around since 1974, so he has a lot of history, both with and without the X-Men. I'd recommend:

*

*Incredible Hulk #180-181 (1974): Wolverine's debut appearance from 1974. It's his first appearance, so it's as good a place as any to start.

*Giant-Size X-Men #1, X-Men #94-100 (1975-1976): Wolverine joins the X-Men as part of their second generation (alongside Colossus, Storm, Nightcrawler, etc.). This collection covers his first adventures with the team.

*X-Men #109, 120-121 (1978-1979): Wolverine's origin is briefly explored for the first time, mostly covering his history with the Canadian superteam Alpha Flight.

*Wolverine #1-4, Uncanny X-Men #172-173 (1982): This is the first solo Wolverine story, covering his time in Japan and courtship of Mariko Yashida. The issues of Uncanny X-Men cover his attempted wedding with Mariko. All are pretty integral to his character, and this is widely considered to be the definitive Wolverine story.

*Uncanny X-Men #205, Marvel Comics Presents #72-84 (1986, 1991): Barry Windsor-Smith told some definitive Wolverine stories, including the epic Weapon X storyline that showed how Wolverine got his adamantium skeleton. This is also considered essential.

*Wolverine: Origin #1-6 (2001-2002): After nearly 30 years of existence, Marvel finally got around to telling Wolverine's definitive origin with this mini-series. This goes all the way back to Canada in the mid-1800s and starts with Wolverine as a child.

*X-Men: Schism (2011): If you want to jump into the current adventures of Wolverine and/or the X-Men, then this storyline is essential since it sets up the current status quo.

*Wolverine & The X-Men #1-7 (2011-2012): Wolverine currently runs a school for mutants in Westchester, alongside the X-Men, and this is where that storyline starts.
As for your second question, yes, Wolverine and X-Men comics are still being published today. Comic books as a medium tend to latch on to what is popular and publish them until they are not popular anymore...or even well past it. That's why characters like Superman, Batman, Spider-Man, the X-Men and Wolverine have been continuously published for the past 40-70 years. Just this month alone, March 2012, Marvel is publishing 16 comics starring either Wolverine or the X-Men

*

*Avengers vs. X-Men

*Ultimate Comics X-Men

*Astonishing X-Men

*Uncanny X-Men

*Wolverine and the X-Men: Alpha & Omega

*Wolverine and the X-Men

*Wolverine

*Uncanny X-Force

*X-Men

*X-Men Legacy

*Daken: Dark Wolverine

*X-23

*New Mutants

*X-Factor

*X-Club

*Generation Hope

So there's a lot to choose from, and if you go into a local comic book shop, you'll see Wolverine on the covers of a bunch of comics. I'd recommend starting with any of the ones I've linked to.

A: If you don't care about sticking to the main Marvel continuity, you could pick up the Ultimate X-Men line.
It started as a reboot/reimagining of the Marvel Universe in the early 2000s, so you only have ~9 years of history instead of 50-60.
Of course, it rapidly got it's own convoluted continuity.  Ultimate X-Men ended a few years ago with the Ultimatum story arc, and the story picked up (along with the rest of the Ultimate lines) in Marvel Ultimate Comics: X-Men.
It's a VERY different world than the current modern continuity, though.

A: You should pick up the essential x-men trades (they are only about 15 buck and in black and white) and start with the chris claremont years. You'll get a good sense of where wolverine and the x-men came from and what the foundations are of the current iterrations.

A: Picking up the trade reprints of Uncanny X-men is the most lucrative route and the best place to start reading, too. The entire Ultimate line at Marvel is overblown tripe, imo, and changes things that shouldn't have been; the movies, for the most part, are pulled from that line, sadly...The Avengers written as SHIELD agents and Nick Fury being black are just the tip of the iceberg; they changed everything about the X-men in that line.
The Claremont/Byrne run at the beginning of Uncanny X-men holds some of the best X-tales ever written, to this day.


text:
Q: Randomly select a row from each group using pandas I have a pandas dataframe df which appears as following:
Month   Day mnthShape
1      1    1.016754224
1      1    1.099451003
1      1    0.963911929
1      2    1.016754224
1      1    1.099451003
1      2    0.963911929
1      3    1.016754224
1      3    1.099451003
1      3    1.783775568

I want to get the following from df:
Month   Day mnthShape
1       1   1.016754224
1       2   1.016754224
1       3   1.099451003

where the mnthShape values are selected at random from the index. i.e. if the query is df.loc[(1, 1)] it should look for all values for (1, 1) and select randomly from it a value to be displayed above.

A: One way is to Series.sample() a random row from each group:
pd.np.random.seed(1)

res = df.groupby(['Month', 'Day'])['mnthShape'].apply(lambda x: x.sample()).reset_index(level=[0, 1])

res
   Month  Day  mnthShape
0      1    1   1.099451
1      1    2   1.016754
2      1    3   1.016754

A: Use groupby with apply to select a row at random per group.
np.random.seed(0)
df.groupby(['Month', 'Day'])['mnthShape'].apply(np.random.choice).reset_index()

   Month  Day  mnthShape
0      1    1   1.016754
1      1    2   0.963912
2      1    3   1.099451

If you want to know what index the sampled rows come from, use pd.Series.sample with n=1:
np.random.seed(0)
(df.groupby(['Month', 'Day'])['mnthShape']
   .apply(pd.Series.sample, n=1)
   .reset_index(level=[0, 1]))

   Month  Day  mnthShape
2      1    1   0.963912
3      1    2   1.016754
6      1    3   1.016754


text: Q: Some pistons won't extend in complex creations The piston extender fully extends with a circuit. The same piston extender/circuit jams in large or complex creations even though there's no redstone interference. Do i need a more powerful computer?


text:
Q: enzyme mount returns unrendered component without erros I have the following component wrapped in react-i18next and a mobx-react provider:
import React from "react";
import s from "styled-components";
import { observer, inject } from "mobx-react";
import { translate } from "react-i18next";

@inject("uiStore", "fieldsStore")
@observer
export class HeaderCell extends React.Component {
  render() {
    const { t } = this.props;

    return (
      <InputSyle>
        <div className="rootCell" />
      </InputSyle>
    );
  }
}

const InputSyle = s.tr`
  background-color: red;
`;

export default translate()(HeaderCell);

I am trying to write a simplet test to assert that the .rootCell div gets rendered:
import React from "react";

import { Provider } from "mobx-react";

import Enzyme from "enzyme";
import { mount } from "enzyme";
import Adapter from "enzyme-adapter-react-15";

import HeaderCell from "./HeaderCell";

import { I18nextProvider } from "react-i18next";
import i18n from "../../../../utils/i18n";

const stores = {
  uiStore: {},
  fieldsStore: {}
};

Enzyme.configure({ adapter: new Adapter() });

describe("HeaderCell.js", () => {
  it("renders a single .rootCell div", () => {
    const wrapper = mount(
      <I18nextProvider i18n={i18n}>
        <Provider {...stores}>
          <HeaderCell />
        </Provider>
      </I18nextProvider>
    );
    expect(wrapper.find(".rootCell")).toHaveLength(1);
  });
});

But instead of the test passing I get the following console output:

FAIL
  src/components/Sidebar/ParcelsGrid/HeaderCell/HeaderCell.test.js   ●
  HeaderCell.js › renders a single .rootCell div
expect(received).toHaveLength(length)

Expected value to have length:
  1
Received:
  {"length": 0, Symbol(enzyme.__unrendered__): null, Symbol(enzyme.__renderer__): {"batchedUpdates": [Function

batchedUpdates], "getNode": [Function getNode], "render": [Function
  render], "simulateEvent": [Function simulateEvent], "unmount":
  [Function unmount]}, Symbol(enzyme.root): {"length": 1,
  Symbol(enzyme.unrendered): , Symbol(enzyme.renderer):
  [Object], Symbol(enzyme.root): [Circular],
  Symbol(enzyme.node): [Object], Symbol(enzyme.nodes): [Array],
  Symbol(enzyme.options): [Object]}, Symbol(enzyme.node):
  undefined, Symbol(enzyme.nodes): Array [],
  Symbol(enzyme.options): {"adapter": [Object]}}
      received.length:
        0
  at Object.it (src/components/Sidebar/ParcelsGrid/HeaderCell/HeaderCell.test.js:30:39)
      at new Promise (<anonymous>)
  at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
      at <anonymous>
  at process._tickCallback (internal/process/next_tick.js:188:7)

From the message I am assuming that my component is not getting rendered, but I have no idea why.
I am using "custom-react-scripts": "^0.2.0", "enzyme": "^3.2.0",
    "enzyme-adapter-react-15": "^1.0.5", "react-i18next": "^6.0.6".
I would say that the test code is correct, but not really sure? All the wrappers also seem to be working OK as there are no console errors.


text:
Q: Accepting a Language Vs Rejecting a language I have a question on complexity theory.  I have the following definition in my notes:

If algorithm A is such that A(s) halts with output 1 for all s in language L, then A accepts L.

My question is, can we still say that A accepts L if A(s) halt with output 1 and s is not in L?  That is, does an algorithm that just returns 1 accept every language?
Thanks


text:
Q: Using jQuery to recall a function window onblur+ onfocus hI got a problem to use jQuery to recall afunction if window is on focus.
And when window is not on focus (onblur) so pause that function until window is on focus again.
Here is my code:
function functiondosomething (user_id) {

var myInterval;
var time_delay = 1000;

    $(window).focus(function () {

 setTimeout(function() { functiondosomething (user_id); }, time_delay);

    }).blur(function () {
        clearTimeout(myInterval); // Clearing interval on window blur

    });

 setTimeout(function() { functiondosomething (user_id); }, time_delay);// ## problem here

}

My problem is :

*

*When I remove that line (which I marked problem here above.) the
function will not work at first time until I click out of window to
make it onblur and come back on focus again, so it starting to work.

*If I let that line (which I marked problem here above.) be there,
the function could not pause, even I click out of window to make it
be onblur.

*When I click onfocus it start working and stop. I have to click out
of window and focus the window again again and again. Something like it need to be activate by clicking out of window and clicking back to window again.
What should I do ?

A: I see a few problems here:

*

*You're not setting myInterval so when you call clearTimeout(myInterval) it's not clearing anything.

*You're using the same function to set up your listeners and call setTimeout recursively. This means your handlers are being set every time you recur, and the recursion means it will run whether the handlers run or not.

I think you need to separate things a bit:
function functiondosomething(user_id) {
  // Do stuff...
}

function setupHandlers(user_id) {
  var myInterval;
  var time_delay = 1000;

  function doSomethingWrapper() {
    functiondosomething(user_id);
    myInterval = setTimeout(doSomethingWrapper, time_delay);
  }

  $(window).focus(function () {
    doSomethingWrapper();
  }).blur(function () {
    clearTimeout(myInterval); // Clearing interval on window blur
  });
  doSomethingWrapper();
};


text:
Q: Python complete ordering of a nested dict I have some sort of trie composed of OrderedDicts (but in the wrong order) which looks like this:
    test = {
        'ab':{
            '1':{},
            '2':{
                '002':{},
                '001':{}}},
        'aa':{
            '02':{
                'ac':{},
                '01':{},
                'ca':{},
                'ab':{}},
            '01':{
                'b':{},
                'z':{
                    '0':{},
                    '1':{}}}}
    }

How can I get a complete ordering of this dict in all subsequent levels?
If I use collections.OrderedDict(sorted(test.iteritems())) I get it sorted only for the first level.
I feel that I need to create a function that it will somehow call itself recursively until the deepest level, but after I spent many hours trying different ways to solve the problem, I am still stuck here.
Eventually it has to look like this:
    test = {
        'aa':{
            '01':{
                'b':{},
                'z':{
                    '0':{},
                    '1':{}}},
            '02':{
                '01':{},
                'ab':{},
                'ac':{},
                'ca':{}}},

        'ab':{
            '1':{},
            '2':{
                '001':{},
                '002':{}}}
    }

A: With recursion, remember there are two cases: the branch, and the leaf. Be sure to account for both.
def make_ordered(d):
    if isinstance(d, dict):
        return OrderedDict(sorted((key, make_ordered(value)) for key, value in d.iteritems()))
    else:
        return d

A: If you can afford an extra dependency I would recommend blist package. It provides many sorted containers including sorteddict. Then your dictionary would just always stay sorted.
Check the sorteddict class docs for exact usage. The package itself is production quality and BSD licence, so not a problem to use in any proprietary code.

A: from collections import OrderedDict as OD
def order(X):
    retval = OD()

    # The standard iterator of a dict is its keys.
    for k in sorted(X):
        # Incase it something we can't handle.
        if isinstance(X[k], dict):
            # I want my children dicts in order.
            retval[k] = order(X[k])
        else:
            retval[k] = X[k]

    return retval


text:
Q: Proving that $\{\cos n\mid n\in\mathbb N\}$ is dense in $[-1,1]$ I am trying to prove that $\cos n$, $n\in \mathbb{N}$,  is dense in $[-1,1]$ and would like to know if my answer is rigorous and correct enough.

Given any $x,y \in [-1,1]$ with $y>x$, there are $a,b \in [0,\pi)$ with $a>b$ such that $\cos a = x$ and $\cos b = y$, since the cosine function is decreasing on $[0,\pi)$.
  Using the fact that $\{m+n\pi\mid m,n\in\mathbb{Z}\}$ is dense on $\mathbb{R}$, there exists $m+2n\pi$ $\in(b,a)$. Hence there is a $\cos(m+2n\pi)=\cos (m)\in (y,x) $ with $m\in \mathbb{N}$.

Is it correct?

A: Arguments don't just exist in vacuums waiting to be determined "correct" or otherwise. In this case, comment by HCP16 is appropriate: If you are willing to assume that $\{m + n\pi\}_{m,n \in \mathbb{Z}}$ is dense in $\mathbb{R}$, then a proof like this ought to work easily.
Taking what you've written at face value, one question that comes to my mind is: How do you go from $m + n \pi$ being dense to $m + 2n\pi \in (b,a)$?

A: As others have said, how good your argument is depends greatly on what you are assuming has already been shown, but there are a couple of genuine minor gaps. If you are willing to assume that the cosine function is continuous and is decreasing on $[0,\pi]$, you can appeal to the intermediate value theorem to justify the existence of your $a$ and $b$, but you do need to use the closed interval $[0,\pi]$, not $[0,\pi)$: otherwise you can't handle the possibility that $x=-1$.
If you are willing to assume that $\{m+n\alpha:m,n\in\Bbb Z\}$ is dense in $\Bbb R$ when $\alpha$ is irrational, then certainly $\{m+n\pi:m,n\in\Bbb Z\}$ is dense in $\Bbb R$, but that does not obviously justify your conclusion that there are $m,n\in\Bbb Z$ such that $m+2n\pi\in(b,a)$. However, $2\pi$ is also irrational, so $\{m+2n\pi:m,n\in\Bbb Z\}$ is also dense in $\Bbb R$, and we can indeed conclude that there are $m,n\in\Bbb R$ such that $m+2n\pi\in(b,a)$. (And I now see that you corrected that oversight in the comments, though not yet in the question itself.)
However, the fact that $\{m+n\alpha:m,n\in\Bbb Z\}$ is dense in $\Bbb R$ when $\alpha$ is irrational is really the heart of the argument and its most difficult part1: the rest is comparatively trivial, assuming that the intermediate value theorem and basic facts about the cosine function are already available (and I do think that a reasonable assumption). I would therefore expect a proof of the desired result to include (or, in a textbook, directly refer to) a proof of this fact.
That can actually be quite short: in this answer I used the pigeonhole principle to give a short, easy proof that $\{n\alpha\bmod 1:n\in\Bbb Z\}$ is dense in $[0,1)$ if $\alpha$ is irrational, where $x\bmod 1=x-\lfloor x\rfloor$ is the fractional part of $x$, and from this it follows immediately that $\{m+n\alpha:m,n\in\Bbb Z\}$ is dense in $\Bbb R$. In this answer I point out that the same argument works if we replace $\Bbb Z$ by $\Bbb Z^+$ and show how to extend the argument to show that in fact $\{m+n\alpha:m,n\in\Bbb Z^+\}$ is dense in $\Bbb R$.
1 The proof that $\pi$ is irrational is actually harder, but in most contexts that fact qualifies as known even if no proof has been exhibited.


text:
Q: .emacs .txt file visual-line-mode simultaneously with muse-mode I indicate my muse-mode files (usually named with .txt suffix) as being muse-mode by starting them with a "#title". To do this, I have

    ;; muse-mode on *.txt files, if a #title or sect. header is on top 4 lines
    (add-hook 'text-mode-hook
              (lambda ()
                (unless (or (eq major-mode 'muse-mode)
                (not (stringp buffer-file-truename)))
                  (when (equal (file-name-extension buffer-file-truename) "txt")
                    (save-excursion
                      (goto-line 5)
                      (if (re-search-backward "\* [A-Z][a-z]+.*\\|#title " 1 t)
                          (muse-mode)))))))

If I also have

    (add-to-list 'auto-mode-alist '("\\.txt$" . visual-line-mode))

in the .emacs (following the code above), then muse-mode no longer works. Though if I invoke visual-line-mode with Meta-x from within emacs on a muse file, it doesn't mess things up.
Ideally, I would like to have visual-line-mode working on all .txt files, but without messing up muse. Or else, I would like to start all .txt files in visual-line-mode except when they are muse files.

A: The variable 'auto-mode-alist chooses the major mode.
visual-line-mode is a minor mode, and by adding it to the 'auto-mode-alist you're making it act like a major mode, which replaces the text-mode you were starting with.
Instead, add turn-on-visual-line-mode-in-txt to the text-mode-hook like so:
(add-hook `text-mode-hook 'turn-on-visual-line-mode)

(defun turn-on-visual-line-mode-in-txt ()
  (when (and (buffer-file-name)
             (string-match ".txt$" (buffer-file-name)))
    (turn-on-visual-line-mode)))

For more information on the differences, read the manual for major and minor modes.

A: I think @treyJackson identified the problem, but here are some extra comments:
BTW, your use of a text-mode-hook to switch to muse-mode will misbehave in various circumstances (because you first switch to text-mode, then halfway through you activate muse-mode, after which the end of the text-mode activation (usually, not much left to do, but there could be more functions on the text-mode-hook to run) will still be performed).  A more robust approach might be to do:
(add-to-list 'auto-mode-alist '("\\.txt\\'" . text-or-muse-mode))

(defun text-or-muse-mode ()
  (if (save-excursion
        (goto-line 5)
        (re-search-backward "\\* [A-Z][a-z]+.*\\|#title " 1 t))
      (muse-mode)
    (text-mode)))

Of course, you could also use a -*- muse -*- on the first line, or rely on magic-mode-alist instead.


text:
Q: Reading a specific header from HttpClient response (POST) I'm using HttpClient PostAsync to a server that will provide an authentication token in the response header.  The header name is "Authorization".  How can I get this value?

A: System.Collections.Generic.List<string> authHeaders = (System.Collections.Generic.List<string>)response.Headers.GetValues("Authorization");
authHeaders[0];


text:
Q: How tailed area decided for hypothesis testing? I have a doubt in basic hypothesis testing. Suppose I have a testing setup as below. I have assumed null hypothesis that my sampling distribution has $\mu = 60$, and I get a sample set with sample mean at $\overline{x} = 62.75$

Now to evaluate my hypothesis, if discrete distribution, I would simply look up at $p(\overline{X} = 62.75)$ and if that is less than $\alpha$ we reject null or otherwise.
Since it is continuous,  $p(\overline{X} = 62.75)$ is 0. But why instead of doing a continuity correction around 62.75, we take all probabilities above 62.75? What is the justification for that?
I am not able to justify why we leave the whole blue area. I understand my alternate hypothesis is $\mu > 60$, but not $\mu > 62.75$ or something like that. So its confusing.
Kindly clarify.


text:
Q: How to get aurelia-cli and Syncfusion non aurelia-syncfusion-bridge to work? Windows 7 x64
aurelia-cli 0.23.0
syncfusion 14.4.20
jquery 3.1.1
I saw the other question regarding this but it doesn't seem to follow the bootstrap example. I believe Syncfusion should also be setup using the bootstrap example as a template but I cannot seem to get it to work.
My test project is just a new aurelia-cli project with default settings.
I am using the ejDatePicker control as an example.
aurelia.json I added
    {
        "name": "jsrender",
        "path": "../node_modules/jsrender",
        "main": "jsrender",
        "deps": ["jquery"],
        "exports": "$"
      },
      {
            "name": "syncfusion",
            "path": "../node_modules/syncfusion-javascript",
            "main": "/Scripts/ej/web/ej.web.all.min",
            "deps": ["jquery", "jsrender"],
            "exports": "$",
            "resources": [
              "Content/ej/web/ej.widgets.core.min.css",
              "Content/ej/web/bootstrap-theme/ej.theme.min.css"
            ]
          }

app.html
<template>
  <require from="syncfusion/Content/ej/web/ej.widgets.core.min.css"></require>
  <require from="syncfusion/Content/ej/web/bootstrap-theme/ej.theme.min.css"></require>
  <!--Container for ejDatePicker widget-->
  <input id="startDate" type="text" />
</template>

app.js
export class App {
  constructor(){
    $("#startDate").ejDatePicker();
  }
}

main.js
import 'jquery';
import 'jsrender'
import 'syncfusion'
......

I am not getting any errors but the control is not displaying.  However if I remove the suncfusion config from aurelia.json then $("#startDate").ejDatePicker(); complains that ejDatePicker is not valid so to me that means that the config in aurelia.json is pulling in the correct javascript file.

A: I had the $("#startDate").ejDatePicker(); in the constructor instead of attached().  It is working after I made that change.


text:
Q: Implement autocomplete (typeahead with inputText) with BootsFaces I develop a web application in Java EE, in this one there is an inputText allowing to search for a student according to his name.
However, I am faced with a problem that I cannot find the solution to.
I use an inputText with a typeahead (Bootsfaces), if I send it a List Etudiant (My List Object) it works however when I send it a List String no suggestion appears:/
In my controller (Java), I return a List containing the name and surname of each student and I would like to be able to make appear the suggestion of this list.
There is my xHtml code :
<b:inputText style="width:200px" value="" placeholder="Rechercher étudiant" typeahead="true" typeahead-values="#{etudiantController.getEtudiants()}"/>

There is my Controller (etudiantController) code :
public List<String> getEtudiants() {
    etudiants = gestionEtudiant.selectAll();
    List<String> listeNomPrenom = new ArrayList<String>();

    for(Etudiant e : etudiants) {
        listeNomPrenom.add(e.getNom() + " " + e.getPrenom());
    }

    return listeNomPrenom;
   }

I hope not to disturb with my post, thanks in advance ;)

A: So there are several things to address here...
First of all, you need a backing bean value in order for the component to have a proper reference value. Not setting value might work for the auto completion depending on how the component is implemented, but you won't have access to what the user actually entered later in your controller. With some components it might make the component function in an undesirable way. So you need to connect it to a bean property.
Secondly, typeahead-values is expecting either a straight up string, or a bean property. Only in very special circumstances will you ever need to call the getter of a bean property - so you should reference the property.
Thirdly, instead of returning a new list of students, try to take advantage of Java's built in toString() functionality in your typeahead-values. Then you don't have to create a completely new list, but instead can rely on Java doing the conversion for you.
So a complete solution mimicing what you are trying to do and translated to English would look like this;
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"
      xmlns:b="http://bootsfaces.net/ui">
    <h:head>
        <title>Autocomplete test</title>
    </h:head>
    <h:body>
        <h:form>
            <b:inputText value="#{studentBean.studentEntry}" placeholder="Search student"
                         typeahead="true" typeahead-values="#{studentBean.students}"/>
        </h:form>
    </h:body>
</html>

@Data
@Named
@ViewScoped
public class StudentBean implements Serializable {
    private List<Student> students;
    private String studentEntry;

    @PostConstruct
    public void init() {
        students = new ArrayList<>();
        students.add(new Student("Carl", "Sagan"));
        students.add(new Student("Enrico", "Fermi"));
        students.add(new Student("Jay", "Miner"));
    }

    @Data
    @AllArgsConstructor
    public class Student {
        private String firstName;
        private String lastName;

        @Override
        public String toString() {
            return String.format("%s %s", lastName, firstName);
        }
    }
}

Note that this example uses Lombok - so the @Data annotation creates the needed setters and getters for the properties.
Also notice how toString() actually flips the name and puts the surname first
just like you do in your code.


text:
Q: How Do i make the ping command an embed (discord bot)     if (message.content === '-ping') {
      message.channel.send(`Latency is : ${Date.now() - message.createdTimestamp}ms.
API Latency is : ${Math.round(client.ws.ping)}ms`);
}
  });

i dont know how to make my code an embed ,how do i make this an embed?

A: To make a basic embed, you can do:
if (message.content === '-ping') {
    const pingEmbed = new Discord.MessageEmbed()
        .setTitle("Ping")
        .setDescription(`:ping_pong: Pong!\nLatency is : ${Date.now() message.createdTimestamp}ms.
API Latency is : ${Math.round(client.ws.ping)}ms`)
        .setColor("#03a1fc")
    message.channel.send(pingEmbed);
}

Just make sure at the top of the file you add const Discord = require('discord.js');, but if you're looking at message content for a command, chances are that's already at the top of your page. Also I'd recommend reading the docs on embeds, there are all sorts of cool methods to add images, fields, etc.


text:
Q: Windows 10 Home :can't reach 'localhost:8000' using Docker I'm beginning to use Docker and following the tutorial (https://docs.docker.com/get-started/part2/) and I am stuck at this point:
docker run --publish 8000:8080 --detach --name bb bulletinboard:1.0

When I try to reach localhost:8080 it says "impossible to reach the site".
When I run docker-machine ip and visiting http://192.168.99.100:8080 with a web client, it does not work.

A: Please access with port 8000 like localhost:8000 because you mapping docker port from 8080 to 8000 to access from outsaide docker container

A: Change Port from 8080 to 8000 like this http://192.168.99.100:8000 because you connect machine port 8000 to docker port 8080.
I hope it may help you.

A: When you use docker commands, always remember..
outside_world -> docker_world
In your 8000:8080 means. You open your container to outside world on port 8000 , inside docker its 8080
Or simply mapping docker port 8080 to 8000 outside.
In this configuration, you should use localhost:8000
docker-machine ip this is completely different network, thats why you can not access it. Its container network.


text:
Q: is it possible to get files from a root directory and sub directories with glob? I'm working on a script that when ran uses glob() to get all the files from a directory that is passed through an arg, and then check their modification time. Is it possible to have glob() go through the files in the dir, and the files in the sub dirs?

A: Is glob() a requirement? For a recursive implementation I prefer using RecursiveDirectoryIterator(). This does the same job in a much more readable way.
$realpath = realpath('/path/to/file');

$fileObjects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($realpath));

foreach($fileObjects as $key => $object){
    echo $object->getFilename();
}


text:
Q: How are things embedded inside of a browser? Adobe embedded flash and Oracle embedded Java. How does one go about embedding external programs inside a browser. I'm on Linux BTW.

A: You write something called a browser plug-in, which is done via the NPAPI, and then you get users to install it (or you get system makers to pre-install it).


text:
Q: Difficulty in acquiring inspect element code through scrapy I have written a small code to scrape the inspect element code to apply css or xpath selectors from this website https://www.marinetraffic.com/en/ais/home/centerx:-12.0/centery:25.0/zoom:4. Now, I am unable to get that code, I am getting page source code instead. As, I am novice in Python, not able to figure out what to do.
I am attaching my code here.
import scrapy
class MarineSpider(scrapy.Spider):
    name = "marine"
    start_urls = ['http://quotes.toscrape.com/page/1/']
    def start_requests(self):
        headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:48.0) Gecko/20100101 Firefox/48.0'}
        for url in self.start_urls:
            yield scrapy.Request(url = url, headers=headers)
    def parse(self, response):
        file_name = 'innercode.html'
        with open(file_name, 'wb') as f:
            f.write(response.body)


text:
Q: Unable to change mac address using ioctl Recently i'm interested in how to access and set network interfaces in linux using a low level aproach. So i found, searching on the net the ioctl callback and i learnt how to use it. I started writing down something but today i'm having problem to change the mac address of a interface.
The code that i'm using is:
int change_mac(int handler){
  srand(times(NULL));

  get_hwaddr(handler,&req);
  for(int i=0;i<6;i++){
    req.ifr_hwaddr.sa_data[i]=(char)rand();
  }
  char err=ioctl(sock,SIOCSIFHWADDR,&req);
  if(err<0){
    printf("Problem to change the mac address with a random one\n %i",err);
    exit(0);
  }
}

int get_hwaddr(int handler,struct ifreq* req_a){
  if(handler>=current){
    return -1;
  }
  strncpy(req_a->ifr_name,interfaces[handler],strlen(interfaces[handler]));

  if(ioctl(sock,SIOCGIFHWADDR,req_a)<0){
    return -2;
  }
}

To better understand my code the "interfaces" variable is a char** where i store the name of interfaces when i initializate a new interface, and in that  function after store the name in that variable, i'm returning a int as handler.
Before changing the mac address, from the code i put the interface down.
Now when i call ioctl to change the mac address with the SIOCSIFHWADDR ioctl return -1.
Can anyone help me? Sorry for the english

A: Have a look at netdevice(7) man page:

SIOCGIFHWADDR, SIOCSIFHWADDR
Get  or set the hardware address of a device using ifr_hwaddr.
The hardware  address  is  specified  in  a  struct  sockaddr.
sa_family  contains  the  ARPHRD_* device type, sa_data the L2
hardware address starting from byte 0.  Setting  the  hardware
address is a privileged operation.

So, you need few things to change the MAC:

*

*ifr_name (must be nul terminated string)

*sa_family contains the ARPHRD_* device type (filled in get_hwaddr()?)

*sa_data the L2 hardware address starting from byte 0 (done)

*setting the  hardware address is a privileged operation (sudo)

Since you confirmed in comments you run it with sudo on a host, please make sure your interface name is correct and nul terminated, i.e. change line:
strncpy(req_a->ifr_name,interfaces[handler],strlen(interfaces[handler]));

to line:
strncpy(req_a->ifr_name,interfaces[handler],strlen(interfaces[handler]) + 1);

Here is an example of the code to change a MAC:
https://gist.github.com/mad4j/8864135


text:
Q: minimum/maximum of the linear function $f(x,y)=ax+by$ Suppose that the function $f(x,y)=ax+by$, $(a,b)\neq(0,0)$ defined on a closed and bounded set $\mathcal{D}$. Since $(\vec{\nabla}f)(x,y)=(a,b)\neq(0,0)$, the extremum points are on the boundary of $\mathcal{D}$.
My question regards the case $\mathcal{D}$ is a polygon: A basic result in Linear Programming asserts that $f$ get it extremum points on the vertices if $\mathcal{D}$ is $\mathbf{convex}$ (as I read in https://en.wikipedia.org/wiki/Linear_programming). Is that result true also for non-convex polygon?
My attempt: Every polygon can be divided to convex polygons (e.g., if $ABCD$ is a non-convex quadrilateral with vertices $A(0,0)$, $B(3,0)$, $C(1,1)$, $D(0,3)$, then $ABCD$ can be divided into two convex triangles, namely $ABC$ and $ACD$). By applying the basic result for each of these convex polygons, it follows that the extremum. Is this argument correct?
Thanks!

A: You are using the fact that every polygon (not to mention higher polytopes) can be divided into convex polygons. Interestingly, it would be a not as trivial as you think exercise to formally prove this fact (or the essential step: "Every non-convex polygon has an interior diagonal").
But we can simply prove the claim about the maximum occuring in a vertex in a different way, namely by induction on the dimension:
You already know that there is a point $p\in\partial \mathcal D$ with $f(p)=\max_{x\in\mathcal D}f(x)$.
But for a polytope, $\partial D$ consists of several lower-dimensional polytopes. So if $\mathcal F$ is the "face" of $\mathcal D$ containing $p$, we know by induction hypothesis that there is a vertex $q$ of $\mathcal F$ with $f(q)=\max_{x\in\mathcal F}f(x)=\max_{x\in\mathcal D}f(x)$. But of course $q$ is also a vertex of $\mathcal D$!


text:
Q: Read data from multiple pipes I want to do a model of fully connected mesh topology. I have parent and children which communicate each other using pipes. So each process have to read data from several pipes. And I don't know how to do that.
Each process has "local id" as increment (0 - parent, 1,2,3 etc).
I created 2d array of pipes. A first array - destinations, second arrays - sources:
struct pipes_t
{
   int rdwr[2];
};

struct dataIO_t
{
    int processes; // number of processes
    int8_t lid; // prosecc local id (0,1,2 etc)
    struct pipes_t pipes[MAX_LOCAL_ID+1][MAX_LOCAL_ID+1];
};

Function for sending multicast message:
int send(struct dataIO_t* data) {
    for(int i = 0; i < data->processes; i++)
        if(write(data->pipes[i][data->lid].rdwr[1], "Hello world\n", 12) != 1)
            return 1;
    return 0;
}

How to read data from many pipes from any process without threads?
I tried to use function dup2 for connection all pipes in one but it was bad idea:
int receive(struct dataIO_t* data) {
    int fd[2];
    pipe(fd);

    const int BSIZE = 100;
    ssize_t nbytes;
    char buf[BSIZE];

    for(int i = 0; i < data->processes; i++)
        if(i != data->lid)
            if (dup2(data->pipes[data->lid][i].rdwr[0], fd[0]) == -1)
                return 1;

    nbytes = read(fd[0], buf, BSIZE);
    printf("Msg (%d): %s\n", data->lid, buf);

    return 0;
}

Prohibitions: in this exercise I can't use poll, select and same functions.

A: You say you want to read from multiple file descriptors without using poll, select, etc.
As you may have discovered, you cannot simply read from one of several pipes and hope it works, because if there is no data, you will block.
To solve this, you can set all of the file descriptors you want to read as non-blocking, which means a read from them will return immediately if no data is available.
In pseudo-code:
for each fd in fds
    mode = fcntl(fd, F_GETFL);
    fcntl(fd, F_SETFL, mode | O_NONBLOCK)

forever
    for each fd in fds
        if read(fd)
            process data
    sleep a little to avoid 100% CPU usage


text:
Q: Is it a best practice in Java to declare variables before give them as parameters Assuming this code :
public static Dataset<Row> getData(SparkSession sparkSession,
                                             StructType schema, String delimiter, String pathToData) {

    final Dataset<Row> dataset = sparkSession
            .read()
            .option("delimiter", "\\t")
            .csv(pathToData);

    StructType nSchema= newSchema(schema, schema.size(), dataset.columns().length);
 ...
}

Is it a best practice to declare variables and make them final before giving them to newSchema method, like this ?
public static Dataset<Row> getData(SparkSession sparkSession,
                                             StructType schema, String delimiter, String pathToData) {

    final Dataset<Row> dataset = sparkSession
            .read()
            .option("delimiter", "\\t")
            .csv(pathToData);

    final int dataSize = dataset.columns().length;
    final int schemaSize = schema.size();

    StructType nSchema = newSchema(schema, schemaSize, dataSize);
 ...
}

Thank you

A: It's a matter of taste.
Introducing local variables allows you to name concepts. Have simpler statements. Simplify inner loops. Potentially remove common code without introducing new functions.
On the other hand. Naming is hard. The code will be shorter if you bung it all on one line. It may be easier to factor out code if it is not dependent on too many local variables.
final for locals is probably over the top, unless the code is already a mess.

A: It depends, let's say you have a call like func(list.get(0).getName.toString())
It would be much more readable to just assign that to a variable and plug it in. Some people might not like the extra lines of code but to me it is worth assigning to a variable.


text:
Q: Access multiple elements with ID from within a node, but also with specific class I need to retrieve all elements who's ID ends with "_inputError" from within a specific element! AND also , I need to retrieve only the inputError that has class 'b-block' set.. How would I do this using javascript/jquery ?
I know I can get my form node with: var formNode = $("#frm1");
I know I can get ALL elements with ID ending, but this will get them all, which isn't quite what I need: var inputErrors = $("[id$=_inputError]");.
How do I mix'em all together as to retrieve only the input errors with 'd-block' class from within a specified form node ?
Cheers!
UPDATE: This seems to work for me:
var inputErrors = $("[id$=_inputError].d-block");
console.warn(inputErrors[0]);

It'll retrieve all inputError with class .d-block. However, I've yet to find how to do this check ONLY from a selected form element id, instead of the hole page. (I can have multiple forms on a single page!)

A: To help others if it can, here's the final solution and why I needed this:
Essentially, I get a response back from an ajax post like so:
{
  type: 2,
  formid: 'frmProfile',
  fields: {
    username: "Invalid username!",
    email: "Invalid email!"
  }
}

I loop my response.fields to show the individual errors under each failed inputs.
I then needed to find a way set focus on the first failed input! Because my fields are NOT 0-indexed based, I could not simply set the focus on the first field in the array! They are 'randomly' looped through!
Therefor, I decided to get all input errors that we're showing (id=*_inputError and with class d-block). The first one in the returned array is in fact the first input error! So, I use its ID to determine the corresponding input name and set focus to it:
var inputErrors = $("#" + response.formid + " [id$=_inputError].d-block");
var firstInputError = inputErrors[0].id.replace(/_inputError$/, ''); // get just the name of the failed input! Its name/id should be the same as <name>_inputError!

document.getElementById(firstInputError).focus();

This seems to do the trick for me ;) Hopefully, this can serve ideas to others.
Thanks for your help folks!
P


text:
Q: Too many instances of httpd and mysqld I have a VPS with 4 GB of ram and 8 cores and about 200K Visits per day. I have DirectAdmin Installed and I always see a huge number of PIDs for httpd and mysqld in DirectAdmin Service Monitor.
e.g. about 40 number of PIDs for mysqld and it increases in a while.
I have CSF installed and configured httpd.conf/my.cnf
sometimes this load prevents the server from responding and it freezes.
Administrators installed 32bit Centos and defined only 512 MB for SWAP
Swap:       524280          4     524276

any ideas to fix this ?
Thanks

A: If you want to add swap space, I'd suggest reading CentOS.org's documentation on the subject.
You may also find this guide from Techotopia helpful.
CentOS recommends your swap being at 6GB for your particular build.
For swap file size, refer to this documentation from CentOS.org.

Swap should equal 2x physical RAM for up to 2 GB of physical RAM, and
  then an additional 1x physical RAM for any amount above 2 GB, but
  never less than 32 MB.
So, if:
M = Amount of RAM in GB, and S = Amount of swap in GB, then

If M < 2
    S = M *2
Else

S = M + 2


text:
Q: Execute logic when RxJS 5 refCount() connects to or unsubscribes from source According to the RxJS 5 manual's section on Multicasting

...we can use ConnectableObservable's refCount() method (reference counting), which returns an Observable that keeps track of how many subscribers it has. When the number of subscribers increases from 0 to 1, it will call connect() for us, which starts the shared execution. Only when the number of subscribers decreases from 1 to 0 will it be fully unsubscribed, stopping further execution.

I'd like to understand whether it's possible to hook into each of these events and execute some logic, ideally before the source observable's connect() or unsubscribe() occurs, but even after the fact would be acceptable.
If there's no way to do this when using the refCount() operator, it'd be much appreciated if you could provide an example how one could achieve this with a custom operator.
I thought maybe I could somehow use the completeFn from do(nextFn,errFn,completeFn) to hook into this, but doesn't seem to work as shown by the below snippet.

var source = Rx.Observable.interval(500)
  .do(
    (x) => console.log('SOURCE emitted ' + x),
    (err) => console.log('SOURCE erred ' + err),
    () => console.log('SOURCE completed ')
  );
var subject = new Rx.Subject();
var refCounted = source.multicast(subject).refCount();
var subscription1, subscription2, subscriptionConnect;

// This calls `connect()`, because
// it is the first subscriber to `refCounted`
console.log('observerA subscribed');
subscription1 = refCounted.subscribe({
  next: (v) => console.log('observerA: ' + v)
});

setTimeout(() => {
  console.log('observerB subscribed');
  subscription2 = refCounted.subscribe({
    next: (v) => console.log('observerB: ' + v)
  });
}, 600);

setTimeout(() => {
  console.log('observerA unsubscribed');
  subscription1.unsubscribe();
}, 1200);

// This is when the shared Observable execution will stop, because
// `refCounted` would have no more subscribers after this
setTimeout(() => {
  console.log('observerB unsubscribed');
  subscription2.unsubscribe();
}, 2000);
<script src="https://unpkg.com/@reactivex/rxjs@5.0.3/dist/global/Rx.js"></script>

A: You can use a combination of .do(null,null, onComplete) before your actual stream and .finally() after completion/unsubscribe to have events before subscription and after completion/unsubscribe:

const source = Rx.Observable.empty()
  .do(null,null, () => console.log('subscribed'))
  .concat(Rx.Observable.interval(500))
  .finally(() => console.log('unsubscribed'))
  .publish().refCount();

const sub1 = source
  .take(5)
   .subscribe(
     val => console.log('sub1 ' + val),
     null,
     () => console.log('sub1 completed')
   );
const sub2 = source
  .take(3)
  .subscribe(
    val => console.log('sub2 ' + val),
    null,
    () => console.log('sub2 completed')
  );

// simulate late subscription setting refCount() from 0 to 1 again
setTimeout(() => {
  source
    .take(1)
    .subscribe(
      val => console.log('late sub3 val: ' + val),
      null,
      () => console.log('sub3 completed')
    );

}, 4000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.2/Rx.js"></script>


text:
Q: Include two inputs in same LI element in Formtastic Using formtastic, I have a quantity field and unit field that asks for the quantity of the item and the unit it's measured in.
My problem, is that I would like the unit box to display along side the quantity box. However, because formtastic pust each input in it's own LI element, I can't get them to appear next to each other.
Any ideas?

A: Use an html wrapper for your quantity and unit fields:
<%= form.input :quantity,   :wrapper_html => { :class => 'fl' } %>
<%= form.input :unit,       :wrapper_html => { :class => 'fl' } %>

And in your css (probably formtastic-changes.css), a css float property to float the li. I've added a bit of right margin to give the unit label some room to breathe:
form.formtastic fieldset ol li.fl {float: left; margin-right: 2em;}

You may have to have specific classes or ids for the wrapper_html and fiddle with the css to get your layout and spacing working the way you'd like.


text:
Q: How to prevent Rate limit attack? I'm using AspNetCoreRateLimit in .net6, when X-Real-IP change in request then rate limit reset.
  "IpRateLimitOptions": {
    "EnableEndpointRateLimiting": false,
    "DisableRateLimitHeaders": true,
    "StackBlockedRequests": false,
    "RealIpHeader": "X-Real-IP",
    "ClientIdHeader": "X-ClientId",
    "EndpointWhitelist": [ "get:/js/*", "get:/lib/*", "get:/fonts/*", "get:/favicon.ico" ],
    "HttpStatusCode": 429,
    "QuotaExceededMessage": "API calls quota exceeded",
    "GeneralRules": [
      {
        "Endpoint": "*",
        "Period": "1s",
        "Limit": 5
      },
      {
        "Endpoint": "*",
        "Period": "15m",
        "Limit": 100
      },
      {
        "Endpoint": "*",
        "Period": "12h",
        "Limit": 1000
      },
      {
        "Endpoint": "*",
        "Period": "7d",
        "Limit": 10000
      }
    ]
  },


text:
Q: Don't skip lists have the same limitation as arrays? Would I be right in saying, Skip Lists like arrays can be very efficient if one knows the 'n' (number of elements to  be stored) beforehand?
Maxlevel of a skip list is (log n + 1), and since I need to know  the maxlevel before creating the skip list it means I should  have an idea of what could  be the number of elements that are gonna be stored.

A: You don't need to know the max level of a skiplist before you create it, as long as you are prepared to dynamically resize the head, whose size is precisely maxlevel. Since maxlevel is approximately log N, resizing the head happens rarely and when it does happen, it involves very little work. If you really wanted to avoid even that, you could initially create the head with a capacity sufficient for the entire available storage, although that would be a waste of space if most of your skiplists were a few hundred elements.
This all works because the search procedure for a skiplist never moves up a level; only down. So inserting a new node with a higher level than any existing node does not require modifying any existing node except the head, which must be modified to point to the new node at its highest level. (Otherwise, the new level will be useless.)
As a curious implementation detail, it's not necessary to store the size of a node; the fact that a node is pointed to at level i is sufficient to demonstrate that the node has at least i levels, so there is never any need to compare i with the size of the node. Only the size of the head needs to be known.

A: maxlevel can be dynamically increased.
use maxlevel=2^(n-1) for the first (2^n-1) nodes. when the 2^n node come, it is assigned with level=2^n, and the next 2^n...2^(n+1) nodes use maxlevel=2^n.


text:
Q: I cannot compile an OpenGL application due to library issues I am having alot of trouble compiling any simple OpenGL application in c++. I have been looking around and have mostly seen that the problem is linking, but i haven't been able to find a solution that works for me. I have added MinGW to the Path and also moved the freeglut and glut libraries and headers over. I have used a simple openGL tutorial example and its supposed to draw a white line in a black box. Here is my code:
#include <gl/freeglut.h>

using namespace std;

void Draw(){
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0,1.0,1.0);
    glBegin(GL_LINES);
        glVertex3f(.25, .25, 0.0);
        glVertex3f(.75, .75, 0.0);
    glEnd();
    glFlush();
    }
void Initialize(){
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}
int main(int iArgc, char** cppArgv){
    glutInit(&iArgc, cppArgv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(250, 250);
    glutInitWindowPosition(200, 200);
    glutCreateWindow("XoaX.net");
    Initialize();
    glutDisplayFunc(Draw);
    glutMainLoop();
    return 0;
}

Here is my build log:
-------------- Build: Debug in OpenGL (compiler: GNU GCC Compiler)---------------

mingw32-g++.exe  -o bin\Debug\OpenGL.exe obj\Debug\main.o
obj\Debug\main.o: In function `glutInit_ATEXIT_HACK':
c:/mingw/include/gl/freeglut_std.h:614: undefined reference to `_imp____glutInitWithExit@12'
obj\Debug\main.o: In function `glutCreateWindow_ATEXIT_HACK':
c:/mingw/include/gl/freeglut_std.h:616: undefined reference to `_imp____glutCreateWindowWithExit@8'
obj\Debug\main.o: In function `glutCreateMenu_ATEXIT_HACK':
c:/mingw/include/gl/freeglut_std.h:618: undefined reference to `_imp____glutCreateMenuWithExit@8'
obj\Debug\main.o: In function `Z4Drawv':
C:/Users/Jack/Programs/OpenGL/main.cpp:8: undefined reference to `glClear@4'
C:/Users/Jack/Programs/OpenGL/main.cpp:9: undefined reference to `glColor3f@12'
C:/Users/Jack/Programs/OpenGL/main.cpp:10: undefined reference to `glBegin@4'
C:/Users/Jack/Programs/OpenGL/main.cpp:11: undefined reference to `glVertex3f@12'
C:/Users/Jack/Programs/OpenGL/main.cpp:12: undefined reference to `glVertex3f@12'
C:/Users/Jack/Programs/OpenGL/main.cpp:13: undefined reference to `glEnd@0'
C:/Users/Jack/Programs/OpenGL/main.cpp:14: undefined reference to `glFlush@0'
obj\Debug\main.o: In function `Z10Initializev':
C:/Users/Jack/Programs/OpenGL/main.cpp:17: undefined reference to `glClearColor@16'
C:/Users/Jack/Programs/OpenGL/main.cpp:18: undefined reference to `glMatrixMode@4'
C:/Users/Jack/Programs/OpenGL/main.cpp:19: undefined reference to `glLoadIdentity@0'
C:/Users/Jack/Programs/OpenGL/main.cpp:20: undefined reference to `glOrtho@48'
obj\Debug\main.o: In function `main':
C:/Users/Jack/Programs/OpenGL/main.cpp:24: undefined reference to `_imp__glutInitDisplayMode@4'
C:/Users/Jack/Programs/OpenGL/main.cpp:25: undefined reference to `_imp__glutInitWindowSize@8'
C:/Users/Jack/Programs/OpenGL/main.cpp:26: undefined reference to `_imp__glutInitWindowPosition@8'
C:/Users/Jack/Programs/OpenGL/main.cpp:29: undefined reference to `_imp__glutDisplayFunc@4'
C:/Users/Jack/Programs/OpenGL/main.cpp:30: undefined reference to `_imp__glutMainLoop@0'
collect2.exe: error: ld returned 1 exit status
Process terminated with status 1 (0 minute(s), 0 second(s))
19 error(s), 0 warning(s) (0 minute(s), 0 second(s))

I am using code blocks on a windows 7 system.
This is my new error
Building to ensure sources are up-to-date
Selecting target:
Debug
Adding source dir: C:\Users\Jack\Programs\OpenGL\
Adding source dir: C:\Users\Jack\Programs\OpenGL\
Adding file: C:\Users\Jack\Programs\OpenGL\bin\Debug\OpenGL.exe
Changing directory to: C:/Users/Jack/Programs/OpenGL/.
Set variable: PATH=.;C:\MinGW\bin;C:\MinGW;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;c:\Program Files (x86)\Intel\iCLS Client;c:\Program Files\Intel\iCLS Client;C:\Program Files\Broadcom\Broadcom 802.11 Network Adapter\Driver;\;C:\Windows\System32;C:\Windows;C:\Windows\System32\wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Program Files\WIDCOMM\Bluetooth Software;C:\Program Files\WIDCOMM\Bluetooth Software\syswow64;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Microsoft SQL Server\110\Tools\Binn;c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn;c:\Program Files\Microsoft SQL Server\100\Tools\Binn;c:\Program Files\Microsoft SQL Server\100\DTS\Binn;C:\Program Files (x86)\CMake 2.8\bin
Starting debugger: C:\MinGW\bin\gdb.exe -nx -fullname  -quiet  -args C:/Users/Jack/Programs/OpenGL/bin/Debug/OpenGL.exe
failed

A: Headers are just tables of contents for the compiler. You also need to add the actual libraries to the project build linker options, so that a working executable can be created. You need to add -lopengl32 -lglut to the compiler options.