wso2am 2.6.0: SSL exception when invoking API which uses custom class mediator

Question: Installed wso2am 2.6.0.

Created and published API - Myapi. Myapi is visible in API store and it can be invoked from there (receives correct response).
Created my own custom class demo mediator (nothing fancy, just outputs some information) and uploaded it to <API-M_HOME>/repository/components/lib.
Created sequence xml with my own custom class and manually uploaded it for Myapi (in API publisher 'Enabled message Mediation', for 'In Flow').
Restarted server and it looks like registered my custom class mediator successfully.

But now then i try to invoke this API through API store it throws such exception:
[2019-03-23 21:04:00,858] ERROR - SourceHandler I/O error: Received fatal alert: certificate_unknown
javax.net.ssl.SSLException: Received fatal alert: certificate_unknown
        at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
        at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1666)
        at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1634)
        at sun.security.ssl.SSLEngineImpl.recvAlert(SSLEngineImpl.java:1800)
        at sun.security.ssl.SSLEngineImpl.readRecord(SSLEngineImpl.java:1083)
        at sun.security.ssl.SSLEngineImpl.readNetRecord(SSLEngineImpl.java:907)
        at sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:781)
        at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:624)
        at org.apache.http.nio.reactor.ssl.SSLIOSession.doUnwrap(SSLIOSession.java:245)
        at org.apache.http.nio.reactor.ssl.SSLIOSession.doHandshake(SSLIOSession.java:280)
        at org.apache.http.nio.reactor.ssl.SSLIOSession.isAppInputReady(SSLIOSession.java:410)
        at org.apache.http.impl.nio.reactor.AbstractIODispatch.inputReady(AbstractIODispatch.java:119)
        at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:159)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:338)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:316)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:277)
        at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:105)
        at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:586)
        at java.lang.Thread.run(Thread.java:748)
[2019-03-23 21:04:00,874]  INFO - LogMediator IN_MESSAGE = json_validator
[2019-03-23 21:04:00,879]  INFO - LogMediator STATUS = Executing default 'fault' sequence, ERROR_CODE = 0, ERROR_MESSAGE = Error occured in the mediation of the class mediator

Same issue happens when i selected another i.e. json_validator mediator (which is not my custom, so issue is not just in my custom mediator), but i.e. with debug_in_flow mediator everything works.
It seems that this issue appears when mediator uses some class mediator and then it throws this SSL exception.
Any ideas where certificate should be added? As I understand inner service tries to invoke custom java class without certificate and fails.
Comment: Invoking Java class has nothing to do with any certificate. The exception indeed indicates, that something is trying to call a https endpoint and the ssl handshake fails. It is not clear if it's from your custom mediation or the service target endpoint. `Received fatal alert: certificate_unknown`   this may indicate the endpoint requires a client certificate for mutual ssl. Do you have it configured?
Comment: @gusto, custom mediator is very simple, it outputs just a string to log. And target endpoint is http (without mediator everything is working).
Comment: With the given information, this behavior is very strange. I feel something is missing in the description. You said your API worked before attaching the sequence. I have 2 questions. (1) If you set in sequence `None`, does that work again? (2) If you remove your jar from lib and set `json_validator` does that work?
Comment: @Bee, thanks for suggestion, your thoughts gave me an idea to reinstall wso2am server from scratch (as there were some configuration made before) and now it throws this exception all the time, but it doesn't affect mediation flow - custom mediator is being invoked anyway (I've updated it a little bit and now it logs information). Also I think that this exception is because wso2am runs on my vagrant ubuntu box and I try to access wso2am from my host computer, not from localhost.
Comment: What is your deployment like? A single node one? and do you have a loadbalancer in the front?
Comment: It's default ubuntu/trusty64 vagrant box installed with apt-get (https://wso2.com/api-management/install/apt/), I guess one node, no loadbalancer.
Answer: Exception is throwing, but it doesn't affect custom mediator flow.


Cross join in R with filtering/matching

Question: I want to do a cross join in R. If we have no conditions, then the data.table package will do it. But what would be the equivalent of this SQL query in R?
Select table1.value as value1, table2.value as value2
from table1 cross join table2 where table1.id = table2.id

consider this example
table1:
id  value
1   1
1   2
2   1
3   1
3   3
3   4

table2:
id  value
1   5
1   4
2   1
3   4
3   3

in this case my desired output is:
value1 value2
1      5
1      4
2      5
2      4
1      1
1      4
1      3
3      4
3      3
4      4
4      3

please note that neither the id column is unique nor the result set has unique rows.
Answer: Columns value.x and value.y are what you need
   table1 <- data.frame(id= c(1,1,2,3,3,3), value=c(1,2,1,1,3,4))
   table2 <- data.frame(id=c(1,1,2,3,3), value=c(5,4,1,4,3))
   merge(table1,table2,by="id",all.y=TRUE)

   id    value.x  value.y
1   1       1       5
2   1       1       4
3   1       2       5
4   1       2       4
5   2       1       1
6   3       1       4
7   3       1       3
8   3       3       4
9   3       3       3
10  3       4       4
11  3       4       3

Answer: You can't cross join on an index by definition, and least in R terminology. What you have above is a inner join.
library(dplyr)

table1 %>% select(table1.value = value, id) %>%
  inner_join(table2 %>% select(table2.value = value, id))

If what you want instead is to be able to cross join and filter at the same time, you might have to take a look at data.table, because they can't be combined in dplyr.
   table1 %>% select(table1.value = value, table1.id = id) %>%
     merge(table2 %>% select(table2.value = value, table2.id = id)) %>%
     filter(table1.id == table2.id)

Comment: I do not understand your answer. Are you asking? I am trying to do this in R, not in SQL.
Comment: You can never cross join in any language on an index. This is because the definition of cross join is joining based on all possible combinations without regard to any index
Comment: You my friend, completely lack any knowledge of how cross join works. Please read this link and avoid providing answers and comments about things you do not know about: [link](https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljcrossjoin.html)
Comment: See the edit. I think what you want is an inner join, at least in R terminology.
Comment: if you need cross join, you could try using merge with option all=TRUE. you can specify conditions with merge
Comment: @AmritaSawant, how? can you give me a code sample for the example in my question?
Comment: added below. pl do vote and accept if it answers your question.

Cross join in R with filtering/matching


Displaying a user-customized part on a web site

Question: I'm building a web site (asp.net) for a company that manufactures small customizable anodized aluminum products. Products are a variety of shapes. but mostly flat, domed or ring-shaped. Products can be colored in one of about 15 colors.
The user can specify one or more lines of text and a font, a simple line drawing (e.g., a heart or four-leafed clover), or both. Text is limited to about 5-15 characters per line. The text or drawing is milled into the part and can be colored in a contrasting color.
What I want to do is display the customized product to the user, so that after selecting product, colors, text,, font and artwork the site will display an image of how the finished product will look. Ideally they would be able to rotate the image but that's not critical.
I have digital descriptions (CAD and CNC milling instructions) of all the parts, fonts, and artwork and can translate them into whatever format is needed.
Can this be done with Flash, SilverLight, or some similar technology? Ideas, references, suggestions, and tutorials welcome! Thanks
Answer: It can be done in Flash, but it requires a lot of work:
To get a realistic version of the product displayed, you have to produce pictures, videos and whatever other depictions of all possible shapes and colors of your product, then you simply have to switch between those depending on the user's choice.
Adding the writing is a bit trickier when the surface isn't flat, but you can model a dome or ring-shaped surface with 3D polygons and add the text as an image texture.
It is best to have a set of standard views, maybe 4 or 5 angles, so that you only have to figure each position out once for each similar shape, and afterwards you can just copy the positioning etc.


Java Spring Boot java.lang.NoClassDefFoundError after upgrading spring-boot-starter-parent to version 2.6.6

Question: I have a Spring Boot application that has been using spring-boot-starter-parent version 2.3.9.RELEASE. Due to vulnerabilities, we are required to update the application to use version 2.6.6.
After upgrade, a bunch of my unit tests error out with:
<code>testGetDiscount(com.ally.abmt.integrationapi.util.IntegrationApiUtilTest)  Time elapsed: 0 sec  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/boot/model/naming/CamelCaseToUnderscoresNamingStrategy
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/boot/model/naming/CamelCaseToUnderscoresNamingStrategy
Caused by: java.lang.NoClassDefFoundError: org/hibernate/boot/model/naming/CamelCaseToUnderscoresNamingStrategy
</code>
Does anyone have any ideas about what might be causing this and/or what I might need to do to resolve it?
Comment: basically `NoClassDefFoundError` will throw if we cant find class at runtime, so `CamelCaseToUnderscoresNamingStrategy` class is not available during runtime, Kindly check your `jar` in target folder if you are running by `jar` or check if you are using `runtime` as `` in `pom.xml`
Comment: Are you also using the Hibernate version that Spring Boot 2.6.6 expects (Hibernate 5.6.7.Final)? The `CamelCaseToUnderscoresNamingStrategy` was introduced in Hibernate 5.5. The error suggests you're still using Hibernate 5.4 or earlier.
Comment: A bit more information - I realized that I hadn't really provided much. This application is Maven based. I don't think I can paste pom.xml or anything since my employer would probably take a dim view of that.

After a bit of reading, I tried upgrading the hibernate-core dependency from 5.4.24.Final to 6.0.0.Final since my understanding is that dependency provides all of the model.naming functionality. But no change in behavior. Still the same errors.
Answer: For Spring Boot, every minor version bump can introduce breaking changes. Usually there are one or two versions where classes etc. are deprecated before they are removed. Since you're effectively upgrading 3 minor versions, you missed some of the deprecation warnings you would have gotten if you upgraded from 2.3 to 2.4 to 2.5 to 2.6 separately.
Check out the Spring Boot release notes for version 2.4, 2.5 and 2.6 for the changes made since 2.3. The breaking changes should all be mentioned.
In this case, I found the following entry:

SpringPhysicalNamingStrategy has been deprecated in favor of Hibernate 5.5's CamelCaseToUnderscoresNamingStrategy

Since only your unit tests fail, you may have an older Hibernate version defined. Remove it and use the one Spring Boot provides.


Estimating a finite sum of complex numbers (Rudin Lemma 6.3).

Question: In Rudin's book, Real and Complex analysis, Lemma 6.3. states:

If $z_1,...,z_N$ are complex numbers then, there is a subset $S$ of $\{1,...,N\}$ for which $$\left|\sum_{k\in S} z_k\right|\ge \frac{1}{\pi}\sum _{k=1}^N |z_k|.$$

In the proof he claims the following: Let $\theta_0$ be the value for which $$\sum _{k=1}^N |z_k|\cos^{+}(\alpha_k-\theta),$$
attains it's maximum. Therefore
$$\sum _{k=1}^N |z_k|\cos^{+}(\alpha_k-\theta_0)\ge \frac{1}{2\pi}\int_{-\pi}^\pi\sum _{k=1}^N |z_k|\cos^{+}(\alpha_k-\eta)d\eta=\frac{1}{\pi}\sum _{k=1}^N |z_k|,\tag{1}$$
i.e. the maximum is bounded below by the avergae of the sum over $[-\pi,\pi]$.
Could someone help me to understand why this is true. I can see, for example, that there is a constant $0<C<1$ such that inequality $(1)$ is true for $C$ instead of $\pi$, however, I fail to see why his claim is true.
Moreover, is $1/\pi$ the best constant?
Comment: You have a continuous function $f\colon [-\pi,\pi] \to \mathbb{R}$. Then the maximum of $f$ is not smaller than the average, $$\max \{ f(\theta) : -\pi \leqslant \theta \leqslant \pi\} \geqslant \frac{1}{2\pi}\int_{-\pi}^\pi f(\eta)\,d\eta.$$ In this case, $$f(\theta) = \sum_{k=1}^N \lvert z_k\rvert \cos^+(\alpha_k-\theta),$$ and the average of $\cos^+(\alpha-\theta)$ is $\frac{1}{\pi}$ for all $\alpha$. $1/\pi$ is, iirc, sharp.
Comment: @DanielFischer, sometimes I feel so stupid. I was considering for each $k$, the function $|z_k|\cos^{+}(\alpha_k-\theta)$ and trying to apply your idea. Anyway, what is iirc?
Comment: "If I recall/remember correctly"
Answer: Yes, $1/\pi$ cannot be replaced by a larger constant. Observe that $$
\sup_S\left|\sum_{k\in S } z_k\right|
= \sup_{\theta \in [0,2\pi]} \sum_{k=1}^N |z_k|\cos^+ (\alpha_k-\theta)
\tag1$$
(This relation is also used in the proof of the inequality).
The point being  that maximizing the modulus of some quantity $\Sigma$  amounts to maximizing $\operatorname{Re}(e^{-i\theta}\Sigma)$ over $\theta$. And the maximum of the latter is obtained simply by taking all $z_k$ which contribute positively.
Let $z_k$ be uniformly distributed on the unit circle, so the gap between them is $2\pi/N$. Then
$$\frac{2\pi}{N}\sum_{k=1}^N |z_k|\cos^+ (\alpha_k-\theta)
\approx\int_{ 0 }^{2\pi } \cos^+ (t-\theta) \,dt = 2
$$
no matter what $\theta$ is. (We have convergence of Riemann sum to the integral as $N\to\infty$). Hence ,
$$ \frac{1}{N} \sum_{k=1}^N |z_k|\cos^+ (\alpha_k-\theta)
 \approx \frac{1}{\pi}
$$

For completeness I copy Daniel Fischer's comment:

You have a continuous function $f\colon [-\pi,\pi] \to \mathbb{R}$. Then the maximum of $f$ is not smaller than the average, $$\max \{ f(\theta) : -\pi \leqslant \theta \leqslant \pi\} \geqslant \frac{1}{2\pi}\int_{-\pi}^\pi f(\eta)\,d\eta.$$ In this case, $$f(\theta) = \sum_{k=1}^N \lvert z_k\rvert \cos^+(\alpha_k-\theta),$$ and the average of $\cos^+(\alpha-\theta)$ is $\frac{1}{\pi}$ for all $\alpha$.


How to set 'RowLength' for a textbox in Silverlight?

Question: is it possible to set number of characters per row for a multiline (AcceptsReturn="True") textbox in Silverlight? Like Cols attribute of Textarea in HTML.
Answer: Not really. Normally you just set the height and width to whatever you want. Is there a particular reason why you want a certain number of characters on each line?
[EDIT]
I found some code here that splits a string into equal chunks:
Splitting a string into chunks of a certain size
Using that, I came up with the following. It works ok but needs some tweaking.
private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
    var text = (sender as TextBox).Text.Replace(Environment.NewLine, "").Chunk(8).ToList();

    (sender as TextBox).Text = String.Join(Environment.NewLine, text.ToArray());
    (sender as TextBox).SelectionStart = (sender as TextBox).Text.Length;
}

And the extension method:
public static class Extensions
{
    public static IEnumerable<string> Chunk(this string str, int chunkSize)
    {
        for (int i = 0; i < str.Length; i += chunkSize)
            yield return str.Substring(i, Math.Min(chunkSize, str.Length - i));
    }
}

Comment: The reason is that the TextBox works as a formatter of a message that is about to be shown on an external display with fixed row length. So the user shall see it formatted as it will be shown.

Using precise textbox width is the solution I am using right now but it would be much easier to set number of characters instead of calculating proper textbox width. Especially when the value changes.


How can I print using arrays?

Question: in C # I have to print an array of symbols until fat meal may delay such a thing OOO through a function I have to put the 'X' in a box of my choice. If I run the cycle, however, filled me with X across the row or column. How can I fix without two-dimensional arrays?
  OOO
  OXO
  OOO

My code:
static private void printArr(ref byte tail, byte[]bitmask)
{
    for (int i = 0; i < 3; i++)
    {
        Console.Write('\n');

        for (int j = 0; j < 3; j++)
        {
            if (change(cas, bitmask[i]) == true)
            {
                Console.Write('O');
            }
            else
                Console.Write('X');
        }
    }
}

Comment: Possibly the most bizarre sentence I have ever read on SO.
Comment: @AntP +1. fat meal may delay. wat
Comment: I know little English I used google translator sorry
Comment: @user3223680 Unfortunately the result makes almost no sense and is impossible to understand.
Answer: using System;

class Program
{
    static void Main()
    {
    string[] arr = new string[4]; // Initialize
    arr[0] = "uno";               // First element
    arr[1] = "dos";               // Second
    arr[2] = "tres";              // Third
    arr[3] = "cuatro";            // Fourth

    // Loop over strings
    for (int i = 0; i < arr.Length; i++)
    {
        string s = arr[i];
        Console.WriteLine(s);
    }

    // Bonus: Loop over strings backwards
    for (int i = arr.Length - 1; i >= 0; i--)
    {
        string s = arr[i];
        Console.WriteLine(s);
    }
    }
}

Output
uno
dos
tres
cuatro

cuatro
tres
dos
uno

Comment: Please explain what perceived problem you interpreted from this question and how your answer solves that problem. I don't recognize _"How to for-loop over an array"_ in OP's question.

How can I print using arrays?


How to set multiple data in JCo Table using RFC?

Question: I want to add multiple data in my JCo Table using RFC to SAP server.
Below is my Code.
But problem is only last raw will be set to sap.
What I am missing?
I am using one function for sync data with SAP.
JCO.Function function = null;
JCO.Repository mRepository;

public String updateCustomerToSAP(String bapi){

    String message = null;
    Connection conn = new Connection();
    JCO.client mConnection = conn.open();
    JCO.Table GETZPRTL_VISIT = null;
    mConnection.connect();

    try{
        function = this.createFunction(bapi);
        if(function == null){
            // Not fount
        }else{
            GETZPRTL_VISIT = function.getTableParameterList().getTable("CUSTOMER_VISIT");

            for(int i = 0 ; i < 10 ; i++){
                GETZPRTL_VISIT.appendRow();
                GETZPRTL_VISIT.setValue("0001 "+i,"ID");
                GETZPRTL_VISIT.setValue("john_ro "+i,"USER_NAME");
                GETZPRTL_VISIT.setValue("John "+i,"FIRST_NAME");
                GETZPRTL_VISIT.setValue("Martin "+i,"LAST_NAME");
                GETZPRTL_VISIT.setValue("firstname.lastname@example.com "+i,"EMAIL");
            }

            // Above data is just for and example. I fetch those data from ArrayList and all data are diffrent.

            function.getImportParameterList().setValue("Data1","USER_ID");
            function.getImportParameterList().setValue("type goes here","TYPE");
            function.getImportParameterList().setValue("reason goes here","REASON");
            function.getImportParameterList().setValue("final status","STATUS");
            function.getImportParameterList().setValue("0001","NUMBER");

            mConnection.execute(function);
            message = (String) function.getExportParameterList().getValue("MESSAGE");

        }
    }catch(Exception e){

    }
    conn.disconnect();

    return message;
}

public JCO.Function createFunction(String name) throws Exception{
    try{
        IFunctionTamplate ft = mRepository.getFunctionTamplate(name.toUpperCase());

        if(ft == null)
            return null;
        return ft.getFunction();

    }catch(Exception e){
        throw new Exception("Problem retriving JCO.Function object"+ e);
    }
}

Here CUSTOMER_VISIT is Table which is inside of my RFC.
Structure Example
USER_ID
TYPE
REASON
STATUS
NUMBER
CUSTOMER_VISIT    <= This is Table inside function module.

CUSTOMER_VISIT Table Structure
ID
USER_NAME
FIRST_NAME
LAST_NAME
EMAIL

Comment: one other problem I can see is that setValue() seems to expect the column name first, then the value. You call setValue() with the value first, then the column. Maybe that is just in your sample code. To be honest, at this point I'd step into the debugger and see what may be wrong with your code. Check if the table parameter really contains several rows or if there is some other problem in the application logic.
Comment: if your code sample is complete and unchanged, the table referenced by  GETZPRTL_VISIT would contain 10 rows, all identical. Is it possible there is some kind of filtering on the function module side going on? Table CUSTOMER_VISIT is a table parameter of the function module, not just a structure?
Comment: CUSTOMER_VISIT is table in side function module.
Comment: Everything  working fine if there is only one record. But if there is more than 2 record, it store only last one.
Comment: have you verified that only one record is actually sent to the SAP system? I can't find anything wrong with your code and the question would be if the problem lies within the function module. You could test the function module within the SAP system without having to call it from a JCo connection.
Comment: I test my function module with in SAP system. First I add 3 row of data in Table(CUSTOMER_VISIT) after fill other data (USER_ID, TYPE, REASON, STATUS and NUMBER). And click on Execute. This will run properly. It will save all 3 row in table.
Comment: I tried to add column name first and value as second parameter, But this gives me and error JCO_ERROR_FIELD_NOT_FOUND : field 024687 is not a member of VISIT_REPORT.
Comment: looks like you're right, setvalue() has several overloads and the (string,string) variant needs value first, then column name: https://help.sap.com/javadocs/NW04/current/jc/com/sap/mw/jco/JCO.Record.html#setValue(java.lang.String,%20java.lang.String).
Comment: I also tried this way also.

`ParameterList parameterList = function.getTableParameterList();
table.appendRow();
table.setValue("Value","COLUMN");
parameterList.setValue(table,"VISIT_REPORT");
function.setTableParameterList(parameterList);`

But no success. Only Last raw saved in.
Comment: @DirkTrilsbeek JCo 2 expected the value first and the name of the field second in `setValue(String, String)` while it is vice versa with JCo 3. Brings a lot of fun if you have to migrate from the former to the latter.
Comment: @Lothar sounds like someone at SAP really hates their customers ;)
Comment: @ChiragSavsani Your code misses the retrieval of the repository. If the code you provided is the actual one, `createFunction` should end up with a `NullPointerException` because `mRepository` is `null`, You create a new connection each time you call `updateCustomerToSAP`. If you retrieved the repsository from an older connection, the repository and the connection no longer "fit" together, leading to problems. The way you fill the table parameter is OK.
Comment: @DirkTrilsbeek Don't get me started on this...
Comment: "one other problem I can see is that setValue() seems to expect the column name first, then the value." -- No, in JCo2 it was indeed "value first, column name second"... Very strange indeed... SAP fixed this with JCo3. But in this example obviously JCo2 is still used.
Answer: Can it be the problem is in the ABAP code of the function module? People not familiar with ABAP can easily confuse the "header line of a table" with the "table itself"...
Could it be possible that only the header line is inserted into the database?
You can see, what data JCo sends to R/3, if you activate the JCo trace level. You could also set an external breakpoint on ABAP side and then step through the function module to see first hand, what data it got.


Build Markov Chains

Question: I want to get the transition matrix for building a Markov chain model to build a recommender system. My data is in the form
            Date    StudentID   Subjectid
            201601   123        1
            201601   234        4
            201601   122        2
            201602   123        3
            201602   123        1
            201602   234        2
            201603   122        3

I want to predict the next three subject that the student is most likely to pick.
I am finding it difficult to get this data in the form of transition matrix so that I can build a markov chain model.
I have tried the following code but I am not sure how the transition matrix will be generated. Please help!
              rf <- (data$Subjectid)
              n <- (length(train$Subjectid))
              trf <- table(data.frame(data$Subjectid[1:(n-
               2)],data$Subjectid[1:(n-1)],data$Subjectid[2:n]))
                trf/rowSums(trf)

Answer: To create a transition matrix, there is already a post regarding that. Your data should look something like this:
df1 <- as.data.frame.matrix(table(data[,c("StudentID","Subjectid")]))
#function
trans.matrix <- function(X, prob=T)
{
    tt <- table( c(X[,-ncol(X)]), c(X[,-1]) )
    if(prob) tt <- tt / rowSums(tt)
    tt
}
transition_df <- trans.matrix(as.matrix(df1))

then you can use this:
install.packages('markovchain')
library(markovchain)
...

Comment: are you trying to implement this paper? http://jmlr.csail.mit.edu/papers/volume6/shani05a/shani05a.pdf
Answer: There are probably fancier solutions, but this returns the transition count matrix, if I understood what you are looking for correctly.
df = read.table(text="Date    StudentID   Subjectid
201601   123        1
201601   234        4
201601   122        2
201602   123        3
201602   123        1
201602   234        2
201603   122        3",header=T)

library(dplyr)
library(tidyr)

df1 = do.call(rbind,lapply(split(df,df$StudentID), function(x) {x$prev_id = c(NA,x$Subjectid[1:(nrow(x)-1)]); return(x)} ))

df1$prev_id = factor(df1$prev_id,levels=unique(sort(c(df1$prev_id,df1$Subjectid))))
df1$Subjectid = factor(df1$Subjectid,levels=unique(sort(c(df1$prev_id,df1$Subjectid))))

df1 = df1[!is.na(df1$prev_id),] %>% group_by(Subjectid,prev_id) %>%
  tally %>% spread(Subjectid,n,drop=FALSE,fill=0) %>% as.data.frame

Output:
  prev_id 1 2 3 4
1       1 0 0 1 0
2       2 0 0 1 0
3       3 1 0 0 0
4       4 0 1 0 0

Build Markov Chains


How to query an SQLITE database using BaseX and XQuery?

Question: Do I need to install a driver for SQLite, or is it a problem with the query, perhaps?
nicholas $
nicholas $ basex sqlite.xq
Stopped at /home/nicholas/xquery/sqlite.xq, 1/23:
[sql:error] An SQL exception occurred: No suitable driver found for jdbc:sqlite3://localhost:5432/home/nicholas/.local/share/liferea/liferea.db
nicholas $
nicholas $ cat sqlite.xq
let $id := sql:connect("jdbc:sqlite3://localhost:5432/home/nicholas/.local/share/liferea/liferea.db")
return sql:execute($id, "SELECT title, description FROM items LIMIT 3;")
nicholas $

The example query:
let $id := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")
return sql:execute($id, "SELECT * FROM coffees WHERE price < 10")

I haven't tried with PostgreSQL or MySQL yet.
Answer: Yes, you need to install the driver, that matches the database backend, you use.
The (very good) documentation to BaseX states, in the section "SQL Module":

This module uses JDBC to connect to a SQL server. Hence, your JDBC driver will need to be added to the classpath, too. If you work with the full distributions of BaseX, you can copy the driver into the lib directory. To connect to MySQL, for example, download the Connector/J Driver and extract the archive into this directory.

For SQLite this could be xerial/sqlite-jdbc. Adding this JAR to your classpath (or to the lib/ directory in BaseX installation directory) should get you up running.
It also seems, that your syntax may be wrong, as your example lacks any hint of initialization of the driver, as well as using a connection string, that is different to the one, mentioned in the BaseX documentation. But I don't know SQL well enough, so there may be valid variants to those. Testing the documentation's example:
(: Initialize driver :)
sql:init("org.sqlite.JDBC"),
(: Establish a connection :)
let $conn := sql:connect("jdbc:sqlite:database.db")
return (
  (: Create a new table :)
  sql:execute($conn, "drop table if exists person"),
  sql:execute($conn, "create table person (id integer, name string)"),
  (: Run 10 updates :)
  for $i in 1 to 10
  let $q := "insert into person values(" || $i || ", '" || $i || "')"
  return sql:execute($conn, $q),
  (: Return table contents :)
  sql:execute($conn, "select * from person")
)

I got the documented result:
0
0
1
1
1
1
1
1
1
1
1
1
<sql:row xmlns:sql="http://basex.org/modules/sql">
  <sql:column name="id">1</sql:column>
  <sql:column name="name">1</sql:column>
</sql:row>
<sql:row xmlns:sql="http://basex.org/modules/sql">
  <sql:column name="id">2</sql:column>
  <sql:column name="name">2</sql:column>
</sql:row>
<sql:row xmlns:sql="http://basex.org/modules/sql">
  <sql:column name="id">3</sql:column>
  <sql:column name="name">3</sql:column>
</sql:row>
<sql:row xmlns:sql="http://basex.org/modules/sql">
  <sql:column name="id">4</sql:column>
  <sql:column name="name">4</sql:column>
</sql:row>
<sql:row xmlns:sql="http://basex.org/modules/sql">
  <sql:column name="id">5</sql:column>
  <sql:column name="name">5</sql:column>
</sql:row>
<sql:row xmlns:sql="http://basex.org/modules/sql">
  <sql:column name="id">6</sql:column>
  <sql:column name="name">6</sql:column>
</sql:row>
<sql:row xmlns:sql="http://basex.org/modules/sql">
  <sql:column name="id">7</sql:column>
  <sql:column name="name">7</sql:column>
</sql:row>
<sql:row xmlns:sql="http://basex.org/modules/sql">
  <sql:column name="id">8</sql:column>
  <sql:column name="name">8</sql:column>
</sql:row>
<sql:row xmlns:sql="http://basex.org/modules/sql">
  <sql:column name="id">9</sql:column>
  <sql:column name="name">9</sql:column>
</sql:row>
<sql:row xmlns:sql="http://basex.org/modules/sql">
  <sql:column name="id">10</sql:column>
  <sql:column name="name">10</sql:column>
</sql:row>


Summing even and odd terms of binomial coefficients, with increasing powers of 2 and alternating signs

Question: For a complex number $z$, let $(1+z)^{15}=a_{0}+a_{1} z+\cdots+a_{15} z^{15}$. The value of
$$
\left(a_{0}-4 a_{2}+16 a_{4}+\cdots-2^{14} a_{14}\right)^{2}+\left(2 a_{1}-8 a_{3}+32 a_{5} \cdots-2^{15} a_{15}\right)^{2}
$$
While I was entirely stumped by this question, I found some similar questions on here, specifically A sum involving binomial coefficients, powers and alternating signs. This did not equip me to be able to solve the above question, though, since this problem drops odd terms and even terms, alternates signs, AND has a factor of increasing powers of $2$, not to mention squares the result and then sums them.
I don't see how the sum can even be expressed as a binomial to somehow use calculus, nor do I see any algebraic manipulations; I've only managed to embarrassingly restate the problem statement as
$$ \left(\sum_{k=0}^{7} 2^{2 k}({ }^{15} C_{2 k})(-1)^k\right)^{2}+\left(\sum_{k=0}^{7} 2^{2 k+1}\left({ }^{15} C_{2 k+1}\right)(-1)^k\right)^{2} $$
Comment: Substitute $z=2i$ into $(1+z)^{15}$, the first $(\ldots)^2$ is the real part squared, the second $(\ldots)^2$ is the imaginary part squared.
Comment: To think that mentioning z was a complex number was actually hinting towards something. I would not have thought of that. Thanks!
Comment: Don't worry, you now know how to do this next time. The hint here is $z^2 = -4$.
Answer: A slight variation. We consider the polynomial
\begin{align*}
\color{blue}{F(z)}&\color{blue}{=\left(\sum_{k=0}^7\binom{15}{2k}(-1)^k(2z)^{2k}\right)^2+\left(\sum_{k=0}^7\binom{15}{2k+1}(-1)^k(2z)^{2k+1}\right)^2}\tag{1}
\end{align*}
and with respect to OPs expression we need to calculate $F(1)$.

We obtain from (1)
\begin{align*}
\color{blue}{F(z)}&=\left(\sum_{{k=0}\atop{k\mathrm{\ even}}}^{15}\binom{15}{k}i^k(2z)^{k}\right)^2
+\left(\frac{1}{i}\sum_{{k=0}\atop{k\mathrm{\ odd}}}^{15}\binom{15}{k}i^k(2z)^{k}\right)^2\\
&=\left(\frac{(1+2iz)^{15}+(1-2iz)^{15}}{2}\right)^2+\left(\frac{1}{i}\,\frac{(1+2iz)^{15}-(1-2iz)^{15}}{2}\right)^2\\
&=\frac{1}{4}\left((1+2iz)^{15}+(1-2iz)^{15}\right)^2-\frac{1}{4}\left((1+2iz)^{15}-(1-2iz)^{15}\right)^2\\
&=\left(1+2iz\right)^{15}\left(1-2iz\right)^{15}\\
&\,\,\color{blue}{=\left(1+4z^2\right)^{15}}\\\\
\color{blue}{F(1)}&=\color{blue}{5^{15}}
\end{align*}
in accordance with another given answer.
Answer: Let
$$F= \left(\sum_{k=0}^{7} 2^{2 k}({ }^{15} C_{2 k})(-1)^k\right)^{2}+\left(\sum_{k=0}^{7} 2^{2 k+1}\left({ }^{15} C_{2 k+1}\right)(-1)^k\right)^{2} $$
From binomial expansion we have
$S_1=\sum_{k=0}^{n} (-1)^k {2n+1 \choose 2k} x^{2k}=\frac{1}{2}[(1+ix)^{2n+1}+(1-ix)^{2n+1}]-(1+x^2)^{n+1/2} \cos (2n+1)t$,
$t=\tan^{-1}x.$
$S_2=\sum_{k=0}^{n} (-1)^k {2n+1 \choose 2k+1} x^{2k+1}=\frac{-i}{2}[(1+ix)^{2n+1}-(1-ix)^{2n+1}]=(1+x^2)^{n+1/2} \sin (2n+1)t.$
$F=S_1^2+S_2^2=(1+x^2)^{2n+1},\text{where} x=2, n=7$
So we get $F=5^{15}.$


Why is my parser.next scanner picking up on a parenthesis and number instead of the string that comes before i despite having a delimiter

Question: The document I'm scanning says "enter(10);add;(45.76)" on a single line. It's supposed to read over the parenthesis and semicolons and just get the numbers and strings, as well as read the word "enter" before running the code. It manages to read enter correctly and the first number, but after that when scanning for "equation" it instead grabs 45.67) with the parenthesis. If i remove the (45.67) and leave just add; it works and grabs the add. I'm not sure what's going on wrong here. Any help would be appreciated, as well as any advice on how to get this program to scan the next line in the file if there was another one.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;

public class CPLParser {

 public double parseScript(String inputFile) throws CPLException{
  File file = new File(inputFile);
  try (Scanner Filereader = new Scanner(file)){
   String line = Filereader.nextLine();
   Scanner parser = new Scanner(line);
   parser.useDelimiter("\\(|\\)\\;");
   String enter = parser.next();
   double number = 0;
   String equation = " ";
   double numberTwo = 0;
   double total = 0;

   if (!enter.equals("enter")){
    throw new InvalidProgramStartException("");
   }

   while (parser.hasNext()) {
    if (parser.hasNextDouble()){
     number = parser.nextDouble();
    }
    if (parser.hasNext()){
     equation = parser.next();
    }
    if (parser.hasNextDouble()){
     numberTwo = parser.nextDouble();
    }
    if (equation == "add") {
     double thistotal = number + numberTwo;
     total += thistotal;
    }
   }
   System.out.println(equation);

  } catch (FileNotFoundException ex) {
   System.out.println("Could not find the file");
  } catch (InputMismatchException e) {

  }

  return 0;
 }

}
Answer: There are few issues in your sample code:
Firstly in java you can not compare string with == you should use Equals method to check equality.
Secondly operation should be done after reading entire line,
also there were blank chars were read by scanner we need to handle that
Please have look into below working code and verify the output.
import java.net.MalformedURLException;
import java.net.URL;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
import java.io.*;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
        try {
            Scanner parser = new Scanner("enter(10);add;(45.76)");
            parser.useDelimiter("\\(|\\)|\\;");
            String enter = parser.next();
                System.out.println("enter "+enter);
            double number = 0;
            String equation = " ";
            double numberTwo = 0;
            double total = 0;

            if (!enter.equals("enter")){
                // new InvalidProgramStartException("");
                System.out.println("InvalidProgramStartException");
            }

            while (parser.hasNext()) {
                if (parser.hasNextDouble()){
                    number = parser.nextDouble();
                        System.out.println("number "+ number);
                }
                if (parser.hasNext()){
                    String text= parser.next();
                    // only set equation if its not blank
                    if ("".equals(text))
                    { System.out.println("equation is Blank "+ equation +"...");}
                    else
                    {equation = text;
                    System.out.println("Setting equation "+ equation);}
                }
                if (parser.hasNextDouble()){
                    numberTwo = parser.nextDouble();
                    System.out.println("numberTwo "+ numberTwo);
                }

            }

            if (equation.equals("add")) {
                    double thistotal = number + numberTwo;
                    System.out.println("thistotal "+ thistotal);
                    System.out.println("total "+ total);
                    total += thistotal;
                    System.out.println("total "+ total);
                }
            System.out.println(equation);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Hope this helps!
Comment: Very interesting and helpful, yet for some reason, my scanner is still grabbing "47.56)" as the .nextLine() and I am not sure why. It's not making much sense. Though your code seems to work just fine.


pdfshuffler not working problem with poppler

Question: After a recent update pdfshuffler isn't working anymore. When trying to run pdfshuffler in terminal the following problem occurs:
Error: Could not import pdfshuffler
Cause: /usr/lib/python2.7/dist-packages/poppler.so: undefined symbol: poppler_orientation_get_type

I found several threads on the topic however none of them with a solution to the problem that worked for me.
Answer: went through the same... you need to somehow update python-poppler to 0.12.1-9
(I just installed pdfshuffler and python-poppler package from Yakkety in Xenial; note that in general this is not recommended at all because dependencies can break your system, but these are pretty isolated packages and worked in my system; if you know what you are doing and how to restore broken dependencies, give it a try...)


Contextual type 'NSFastEnumeration' cannot be used with array literal

Question: Swift 3, would you do this?
let changeRequest = PHAssetCollectionChangeRequest(...)
let fastEnumeration = NSArray(array: [PHObjectPlaceholder])
albumChangeRequest?.addAssets(fastEnumeration)

or this?
let changeRequest = PHAssetCollectionChangeRequest(...)
albumChangeRequest?.addAssets([PHObjectPlaceholder] as NSFastEnumeration)

and what is the difference?
Answer: As you have found (your code has some inconsistency and causes other errors, better update it), you cannot use as-casting to specify the type for Array literals as NSFastEnumeration.
You need to find a proper class which conforms to NSFastEnumeration, in your case it's NSArray.
Usually write something like this:
changeRequest?.addAssets([/* needs instances, not type...*/] as NSArray)

Comment: Comment is not a good place to describe your own issue. Better start a new thread of your own. Many people read new threads but rarely find a new comment in an old thread. As for me, I have never seen the same exception and cannot be help of you.


Why do we use numerical models to solve PDE's?

Question: I'm currently learning about modelling the propagation of acoustic waves using numerical models. This is done by solving the wave equation (expressed as a partial differential equation) with something like a finite difference model or a finite element model or something similar.
My question is: Why can we not solve the partial differential equation directly? Why must we use a numerical model to solve the wave equation?
Comment: If you find an explicit solution, let us know...
Comment: If you have a propagation in a nonlinear medium, for example, it could be hard to find the solutions of the wave equation analitycally, so you could need to solve it numerically.
Comment: Check This : http://books.google.co.in/books?id=HftVSGIWVdYC&pg=PA21&lpg=PA21&dq=analytical+solution+PDE+impossible&source=bl&ots=O1HrH_hCfH&sig=NwTnX_L5tJgVE546tYCCYCrYZWc&hl=en&sa=X&ei=qmo-T_a4OZGyrAeorPi3Bw&ved=0CEgQ6AEwBQ#v=onepage&q=analytical%20solution%20PDE%20impossible&f=false
Comment: Even an explicit solution is a rather broad term: if it is expressed as series over some exotic function - are you sure that it is faster to compute (approximately) such series?
Answer: You do not need to, but in the context of your course it makes more sense to do it numerically from the start:
Take the standard wave equation
$$\partial^2_t u(\vec x, t)=c(u)^2\cdot\nabla^2u(\vec x, t)$$
If $c(u)=\mathrm{const}.$, then there is no problem in using the standard analytical methods. But as Riccardo said, if it is not constant, for example in a dispersive or non-isotropic medium, you can solve it by only a simple extension to the numerical model, whereas there might not even exist an analytic solution.


Outbound port for SQL Request

Question: I am connecting an ASP.Net Application to a SQL Server database behind a firewall.  I know that by default, communications from an IIS Web Server to the SQL Server go into port 1433/4.
However, the outbound port on the Web Server seems to be random in the range 1024-65535, as per the Microsoft guidance here.
There are also some comments here, but they don't answer the outbound port question.
Is there a way of restricting that so that firewall can only allow one or a small range of outbound ports?  AM I right in thinking the issue is in IIS (as the originator).
Thanks.
Answer: Enabling 1433/4 will be enough, because IIS is connecting to SQL. There is not connection from SQL to IIS. The only thing you must rember is to preserve session on load balancer/firewall

Outbound port for SQL Request


How do I remove conflicting reference from git repository?

Question: I currently have 2 symbolic references with master in the name as below
git ls-remote firstname.lastname@example.com:company/project.git master
9547e4ba01d67e1ff3xxxxxd5110eaaf2f48    refs/for/master
06106b7f1005dbb9f1xxxxxxxx456d2be84346c refs/heads/master

How do I remove or rename the refs/for/master so the ls-remote command only gives one result like so -
git ls-remote firstname.lastname@example.com:company/project.git master
06106b7f1005dbb9f1xxxxxxxx456d2be84346c refs/heads/master

Answer: Option 1: Deleting the Reference
If you want to remove the refs/for/master reference, just delete it from the remote (using one of the following):
git push email@example.com:company/project.git :refs/for/master
git push email@example.com:company/project.git --delete for/master

Option 2: Renaming the Reference
This is one way you can rename it, though it's significantly more work. First, you'll need to fetch the object that refs/for/master refers to. Only way I know how is to edit your repo's .git/config to fetch it.
For convenience, let's say that you add firstname.lastname@example.com:company/project.git as a remote called origin to your local repo:
git remote add origin email@example.com:company/project.git

Then let's also say that you set up your fetch configuration in your local clone's .git/config file to be the following:
[remote "origin"]
    url = firstname.lastname@example.com:company/project.git
    fetch = refs/for/*:refs/remotes/origin/for/*

Then once you git fetch origin, you can rename the reference to something else and push it again (you'll still need to delete the old reference though):
git push origin :refs/for/master origin/for/master:for/master

:refs/for/master deletes the old reference, and origin/for/master:for/master pushes the old copy of that reference as a new remote reference for/master.
You can read more about fetch refspec configuration for remote repos in chapter 9.5 Git Internals - The Refspec of the FREE online Pro Git book.
Comment: For `git push` documentation, see [git-push(1) Manual Page](https://www.kernel.org/pub/software/scm/git/docs/git-push.html).


Optimal strategy for finding a partition point where the test function has a linear cost

Question: Given (where $x, t\in\mathbb{N}$) $$
f(x) = \begin{cases}
1 & x\lt t\\
0 & x \geq t
\end{cases}
$$
and the cost of computing $f(x)$ is $x$. The problem is then finding $t$ at minimal cost.
Intuitively, you could do an exponential search first, where at each iteration $i\geq 0$ you compute $f(2^i)$, and once you have found the lowest $k$ such that $f(2^k)=0$, you do a binary search within the interval $[f(2^{k-1})+1, f(2^k)-1]$, but I don't know how to prove the optimality of that strategy.
Analysis of the provided strategy
The first stage, the exponential search, costs:
$$C_1=\sum_{i=0}^k2^i=2^{k+1}-1$$
Now the interval to binary search is $[z_1, z_{k+1}]=[2^{k-1} + 1, 2^k - 1]$. The second stage, $C_2$, costs:
$$
C_2=\sum_{i=0}^{k-2}(2^k-2^j)=\left(k-\frac{3}{2}\right)2^k+1\\
$$
The reason is because the worst case is going always towards the highest end of the interval (e.g., $f(x)=1$ for every $x\in I$); in other words, when $t=2^k$. At each stage $i\geq 2$ we then compute $f(z_i)$, where $z_i$ is the center of the interval $I_i=[z_{i-1}+1, z_{k+1}]$, which, starting with $z_2=2^k-2^{k-2}$, gives you the sequence $2^k-2^{k-i}, 2\leq i\leq k$.
Finally, the overall costs $C$ is $$C=C_1+C_2=\left(k+\frac{1}{2}\right)2^k=t\left(\log_2t+\frac{1}{2}\right)$$
An equivalent worst case is when $t=2^k-1$ (which also implies going upwards until the end of the original interval), in which case replace $t$ by $t+1$ above; in any case, the absolute cost is the same.
Any better strategy for should improve this worst-case cost.
Comment: If you know $1\le t\le8$ then doing odd numbers in reverse order has a worst case of $19=7+5+3+4$, but bisection has a worst case of $20=5+7+8$
Comment: Erk, sorry, I wasn't thinking straight
Comment: Do you want to minimize average cost over all $t$ in some range, or maximum cost (again over all $t$ in some range), or some other function? Note that for every certain $t$ there is a strategy which computes $f(t)$, $f(t - 1)$ and nothing else.
Comment: @Empy2 no if your bisection strategy is by rounding down: 4 + 6 + 7 = 17. Besides, why did you check for 3 and then 4, instead of 3 and then 1? In that case it gives you 16, which is better than bisection.
Comment: A first guess of $4$ divides the range into $1,2,3$ and $4,5,6,7,8$ so it's not bisection.  If $t$ turns out to be $4$ then I know after $7,5,3$ it is either 3 or 4, so I need to test 4.
Comment: @Empy2 I think it's still a bisection because after testing for 4, what I have left (the unknowns) are 1,2,3 to the left and 5, 6, 7, 8 to the right, which is balanced. If I check for $5$, and the result turns out to be $1$, it means that $t$ is higher and I have discarded 5 elements, with 3 elements still to be checked, which isn't balanced.
Comment: @Smylic I want to minimize the maximum cost given any unbounded $t$ (although an apparently sound strategy is trying to find bounds first, and that's why it sounds logical to me starting by an exponential search). On the other hand, I can't quite see how an strategy for this particular problem can have a better average than other strategy with a better maximum cost. If there are two strategies with important differences in average costs, I would then like to see both if possible, out of curiosity.
Answer: EDIT  4 February 2024
I have run programs to find the cheapest options.  I started with the narrowest intervals of one or two numbers, then calculated the cheapest options for wider and wider intervals.
When the aim is to minimize the cost in the worst case, a high early guess can bring down the costs of high numbers, although the cheaper low numbers become more expensive.  This works best when the ratio between the smallest and largest numbers is large.
When the aim is to minimize the average cost, bisection works best when the range (count of possible numbers) is a power of two.
When the range is between $2^{k+1}$ and $3×2^k$ numbers, it seems best to divide the range so the lower piece has a range of $2^k$ numbers.
When the range is between $3×2^k$ and $2^{k+2}$, it seems best to divide the range so the upper piece has a range of $2^{k+1}$ numbers.
This starts to break down with $97$ numbers, which is very near $3×32$.
End of edit
January 25 2024
Too long for a comment.
My suggestion is for an interval from $a+1$ to $a+2^k$.  Test, in turn, $a+\frac342^k,a+\frac242^k$ and $a+\frac142^k$ until only a quarter of the range is possible.  Then apply bisection to the quarter that remains.
If the range is $a+1\le t\le a+2^k$, then bisection costs $$ak+(k-1)2^k+1$$ in the worst case, which is $t=a+2^k-1$ or $t=a+2^k$.
For the method mentioned above, the worst cases for the four quarters are
$$(k-1)a+(4k-6)2^{k-2}+1,(t=a+2^k)\\
ka+(3k-2)2^{k-2}+1,(t=a+\frac342^k)\\
(k+1)a+(2k+1)2^{k-2}+1,(t=a+\frac122^k)\\
(k+1)a+(k+3)2^{k-2},(t=a+\frac142^k)$$
Bisection's worst case is worse than the first two, and the third is worse than the fourth if $k\gt2$.  Bisection is worse than the third case if $$a\lt (2k-5)2^{k-2}$$
If the interval is from $2^k+1$ to $2^{k+1}$, as mentioned by OP, and $k\gt4$, then this method is an improvement in the worst case.
Comment: I haven't been able to replica your four formulas. First, you assume you know $t$ is in the interval $[a+1, a+2^k]$, which implies some previous process have already determined that's the range, are you considering the cost of computing $f(a+1)$ and $f(a+2^k)$, or you assume that such "previous process" have already paid the cost? Or do you assume the previous process has paid the cost for computing $f(a)$ and $f(a+2^k+1)$?
Comment: Same for the quarters, are you considering that you have to pay the cost of computing the three internal points, and thus, regardless of the quarter $t$ belongs to, you have to pay a fixed cost of $3(a+2^{k-1})$? I haven't been able to replicate your formulas and with so many unknowns I don't know where is my mistake.
Comment: Besides, I have added my own analysis of my original proposal to my question.


Dashboard above the fold? Is it possible

Question: curious to know is it possible to provide contents in dashboard above the fold -no scroll in page. Attaching the reference template. Please provide your suggestions. FYI, it is a KPI strategic kind of dashboard. User only views data in form of table/chart, download CSV, PDF.
Comment: Not entirely clear what the question is here.
Comment: can we have no page scroll dashboard?
Comment: I am still not sure what you're asking. Do you want to **not** have a scrollbar?
Comment: YES. do not want scrollbar in the dashboard. have multiple widgets on the page. Above reference template.
Comment: If you don't want a scrollbar then you can simply limit the no. of widgets per page and ask the user to add pages/tabs if they want more widgets. Is that what you wanted to know?
Comment: You can switch off scrollbars, but why would you? What will you do about overflowing content, as the user changes browser window size or accesses the website via mobile, etc?
Comment: This is desktop alone application. For overflowing content can we show like i shown in reference image with a drop  down to access each widget.
Answer: Why don't you develop the dashboard responsively. There are many libraries whose components are responsive in nature and will adjust to the size of your screen.
What we did developing a dashboard (before the days of responsive) was that we took to resolution of the screen where the dashboard was to be displayed (in this case an LCD screen back then) and design a full screen view fit for the LCD screen (no horizontal or vertical scrolling) and a regular computer view that just kept scrolling vertically until all the information was displayed. The computer view included all the actions like export, and the full screen LCD display included only information such as gauges, bar charts and tables.
Answer: Scrolling is inevitable: Allow users to arrange content in order of importance for them.
Scrolling is inevitable, and since viewport size is hard to control for, allow your users ability to arrange content according to what's most important for them. Bias towards the top of the viewport.
You have 2 choices for the user for the design you have presented:
1. For Data Tables: Allow sorting and pinning.

download bmml source – Wireframes created with Balsamiq Mockups
This allows you to:

Keep content above the fold (in conjunction with sizing the elements for various viewports)
Let the user decide what is important for them to view first
If you cap the number of table rows, you might test if there's other visualization types that belong with a tabular view, rather then a full switch to another type (but I don't know your users)

2. For graphic visualization: break data into arrangeable modules.

download bmml source
This allows the same 'above the fold' ability to the users.
You're fortunate in that for strategic dashboards, time and consequences are not as immediate as in an Operational Dashboard, where if I can't see it, it doesn't exist (and disaster may strike).
Scrolling will still exist, but you can at least give more power to your users for the top of the viewport.
Comment: Thanks for above suggestions. This is Desktop application. Consider the scenario where 1. For Data Tables: Allow sorting and pinning. -> I have 10 tables like you have shown so scroll needs to be on screen to access all the tables. But my ask is can we provide a way without scroll on page like i shown in reference.


Show the structure of the table in SQL

Question: Can someone explain things a little better to me? How do I show the structure of a table?
I run the select * from table; and of course it displays all that's in the table. But, I am being asked to show the structure of the table. What does that mean, and what is the command?
Here's my table below.
SQL> select * from dept;

DEPTNO DNAME          LOC
---------- -------------- -------------
    10 ACCOUNTING     NEW YORK
    20 RESEARCH       DALLAS
    30 SALES          CHICAGO
    40 OPERATIONS     BOSTON

 SQL>

Answer: Try this out: describe table_name
Comment: Or `desc table_name` but It works with Oracle and not with MSSQL.
Answer: To list columns and data types, I typically use
SELECT COLUMN_NAME, DATA_TYPE FROM ALL_TAB_COLUMNS WHERE TABLE_NAME='your_table_name';

It's been a while since I've worked with Oracle though.  ALL_TAB_COLUMNS might actually be ALL_TAB_COLS.
If you need to display the full CREATE TABLE statement, see How to get Oracle create table statement in SQL*Plus
Comment: Its just not clicking for me.
Comment: @user770022 Yes, I believe `DESCRIBE` is supported in Oracle as well.
Answer: You can use sqlplus command describe <SCHEMA_OWNER.TABLE>
https://docs.oracle.com/cd/B19306_01/server.102/b14357/ch12019.htm

Show the structure of the table in SQL


How to set up a basic military in Dwarf Fortress?

Question: Alright, I lost a fortress last night due to neglecting my military (well, and not closing my airlock quickly enough.). I've been neglecting my military due to the fact the interface is the single most painful part of the game (that I've yet uncovered), and much of it is badly documented. Tasks are made easy with Dwarf Therapist, but there doesn't seem to be equivalent software for the military. The wiki explains how to use the military interface, but doesn't go into detail on how to best use the military.
So, how should I set up a basic, but working, military in DF2012? What weapons and armour should I forge, how do I get them to equip it, do I need to use a danger room, how do I train crossbow men, what type of training schedule should I use, etc.
Comment: Have you tried reading the [military quickstart guide](http://dwarffortresswiki.org/index.php/DF2012:Military_quickstart) instead?
Comment: If you make that an answer, and add equipment advice (Mail shirt? Breastplate? Axes or swords, etc) (Either to the wiki or your answer) I'd be willing to accept that.
Comment: @Canageek That's quite a question...
Answer: This is something I always have difficulty with. This answer is a combination of past experience, the military chapter of Getting Started with Dwarf Fortress and the Military information on the wiki.
The first thing you'll want to do is carefully pick the dwarves to form your budding militia. You'll see  it suggested in several places to avoid picking females, or dwarves with family as that can lead to problems when and if they eventually die in a horrible manner. I disagree, as that can take away some of the most poignant stories the game can produce. Regardless, you'll want to give them the profession Soldier, so it's easy re-draft them if you ever need them for something else.
Now create a squad w/ your selected dwarves (or use the squad screen to do this...)
Once you've got a half dozen dwarves or so in your squad you'll want to equip them. There are several default uniforms to pick from. I like marksdwarves, but that does add the complication of ammunition. Eventually you'll want to have both melee and ranged squads, and very possibly a mix for surprise situations.
Early on you'll probably need to armor your dwarves in leather, but you definitely want to switch to metal armor at the first opportunity. If you create a custom uniform don't forget you'll need to set it on your dwarves. Especially if it's post squad creation once you've completed those half-dozen sets of beautiful steel armor.
Next you'll need to set up a barracks for your milita to train in. If your barracks is near your fortress entrance (often a good idea) and far from your regular sleeping quarters you may want to force your militia to sleep in the barracks... of course this could mean less happy thoughts, depending on how fancy the dwarves home is (assuming it even has one assigned!)
Archery targets, and properly equipping your marksdwarves is a complicated set of affairs, and I've gotten it wrong often enough. Check your equipment and be sure your dwarves have the type and amount of bolts that they'll need. I like to make bone bolts and use those for practice and reserve the metal ones for real combat.
Danger rooms, considered an exploit by some people can help train the defensive skills of the dwarves.
Possibly the most important thing is going to be setting up proper training for your dwarves. Once you get a couple of squads going you can rotate them between active/off duty so they all get trained equally, but you also always have some ready dwarves to fight.
Comment: You are forgetting the Dwarven Child Care system. http://www.bay12forums.com/smf/index.php?topic=91093.0
Comment: I usually don't bother with a leather industry, and go right for metal. Is iron armour OK? I'm having trouble finding iron in my current fort, should I try to make bronze? I usually go for training 1 month/rest 1 month, with 2 squads as soon as I can.
Comment: One of the benefits of skipping leather is that metal armor weighs more, so your dwarves will get stronger faster. See this chart: http://dwarffortresswiki.org/index.php/Metal#Weapon_and_armor_quality for different metals relative combat strength.
Comment: I've found some Adamantine. I wonder if I should mine it and make armour? I think that sounds like it would attract invasions way before I'm ready.
Comment: Is a danger room essential, or can I just have them train?
Comment: Aye, that's the main reason to start w/ leather... it is almost worthless so doesn't increase the  value of your fort by a ton too early. And a danger room isn't essential, but probably better to have it than not.
Comment: How do you use different types of bolts for training and real combat?
Answer: @aslum's answer goes into detail about some in-game mechanics, but there's a strong option if you're embarking on a new fort - namely, to bring along 2 dwarves with 5 Weapon / 5 Teacher skill levels and set them to train. This allows you to get a few expert dwarves very quickly and is an effective way to kickstart your military from year 1
See this !!SCIENCE!! thread on the forum:
Drunken masters - how to use the Teacher skill


How can I get to the northern-most part of Ortan Fields?

Question:
I'm trying to figure out how to get to the area indicated with the white arrow. There's a ledge where the red line is that appears to be too high to jump up.
Is there a plan later that lets you jump higher? Am I missing something obvious regarding teleporters?
Answer: There is a plan that lets you jump higher. It is named Jumping Star and is acquired in chapter 5 via The Chirper (that is, those small conversations on the world map). To craft the plan requires 16 MB and an AG System.
To get the AG System you'll need to craft the Add Enemies plan for Mechtro Factory and defeat the Herobo. It's a robotic enemy you'll find to your right, not the Child Whales up ahead.
If you need to get a Random Encounters chip to craft the Add Enemies plan, you can get them from Dangerous Shampuru in Zeca Ruins No. 1. They're the dangerous monster that appear if you do not have Add Enemies for Zeca Ruins No. 1 activated. There's also one in a one-time treasure in Thelad Sanctuary.


sort element inside a vector c++

Question: I have a text file points.txt
which is formatted by Points/NotPoints , X ,Y
Points, [3, 3]
NotPoints, [0, 0]
Points, [4, 4]
NotPoints, [0, 0]

What I want to do is retrieve the X values from the textfile and place it into a vector and
sort the X values by either ASC or DSC order.
I found a similar post for my question
www.stackoverflow.com/questions/7102246/sorting-a-vector-of-objects-in-c#=
but the thing is, when I tried to do this at main.cpp,
sort(pointsVector.begin(), pointsVector.end(),sortOrder()) ;

it shows an error,Non static members sortOrder found in multiple base-class subobjects of type Points.
see my codes below for on my implementation.
Some Requirements for my task,
I must initialize int x as protected variable as there are other class inheriting it ,
I can't use struct therefore I am using get and set

Codes
Points.h
#ifndef __Points__Points__
#define __Points__Points__
#include <iostream>

class Points {
    friend class main;

protected:
     int x;
     int y;

private:
     friend bool sortOrder (const Points & rhs, const Points & lhs);
public:
    Points() {
        x=0;
        y=0;
    };//default Constructor

    Points (int x , int y);
    int getX();
    int getY();

    void setX(int x);
    void setY(int y);

    bool sortOrder (const Point2D & rhs, const Point2D & lhs) {
        return lhs.x < rhs.x;
    }
};
#endif

Points.cpp
#include "Points.h"

Points::Points(int x , int y) {
    setX(x);
    setY(y);

}

int Points::getX() {
    return x;
}

int Points::getY() {
    return y;
}

void Points::setX(int x)   {
    this->x = x;
}

void Points::setY(int y)   {
    this->y = y;
}

main.h
 #ifndef Points_main_h
 #define Points_main_h
 #include <iostream>
 #include "Points.h"
 #include <vector>

class main : public Points  {

private:
    int input;
    std::string type,line;
    std::string pointX, pointY;
    std::vector<Points> pointsVector;
 public:
    void mainMenu();
    void getPoint2DRecordsFromFile();
};
#endif

main.cpp
 #include <iostream>
 #include "main.h"
 #include "Points.h"
 #include <fstream>
 #include <sstream>
 #include <string>
 #include <vector>
 #include <stdio.h>
 #include <algorithm>

class main outputMethod;

void main::getRecordsFromFile() {

    std::ifstream readFile;
    //put your text file name inside the ""
    readFile.open("points.txt");
    if (!readFile.is_open()) {
        std::cout <<" "<< std::endl;
        std::cout << "File Not Found!" << std::endl;
        std::cout <<" "<< std::endl;
    }
    else    {
        while (readFile.good()) {
            while(getline(readFile,line))   {
                std::stringstream iss(line);
                getline(iss, type,',');
                if(type == "Points")  {

                getline(iss, pointX,'[');
                getline(iss, pointX,',');

                getline(iss, pointY ,' ');
                getline(iss, pointY,']');

                Points pointsConsturctor(std::stoi(pointX),std::stoi(pointY));
                pointsVector.push_back(pointsConsturctor);
                }
            }
        }
    }
    readFile.close();

    /*error!
    Non static members sortOrder found in multiple base-class subobjects of type Points*/
    sort(pointsVector.begin(), pointsVector.end(),sortOrder());

    for (int i = 0; i<pointsVector.size(); i++) {
        std::cout << pointsVector[i].getX() << "," << pointsVector[i].getY() << std::endl;
    }
}

void main::mainMenu() {

    std::cout << "1. Read data " << std::endl;
    std::cout << "2. sort " << std::endl;
    std::cin >> input;

    switch ( input ) {
        case 1:
            std::cout << "In Progress!" << std::endl;
            break;
        case 2:
            getRecordsFromFile();
            break;
        default:
            break;
        std::cin.get();
    }

}

int main()  {
    outputMethod.mainMenu();
}

Comment: You should define `sortOrder()` outside of class `Points`; also, name the 1st parameter as `rhs` and 2nd parameter as `lhs` is _very_ counterintuitive.
Answer: Note that in class Points you have defined sortOrder twice (as friend function and as method):
friend bool sortOrder (const Points & rhs, const Points & lhs);

bool sortOrder (const Point2D & rhs, const Point2D & lhs) {
    return lhs.x < rhs.x;
}

Answer: Since sortOrder is a function, when you do
sort(point2DVector.begin(), point2DVector.end(),sortOrder()) ;

you are actually attempting to call the function. Since you don't provide the wanted arguments you will get an error. Instead just pass it without the parentheses:
sort(point2DVector.begin(), point2DVector.end(), &Points::sortOrder) ;

The other error is that it's a member function, and all member functions have a hidden first argument that is the this pointer in the function, so just doing the above won't work either. You either have to make the function a free-standing function, or make it a static member function.
Answer: You're declaring sortOrder as friend when you're actually defining it as a member function. friend is intended to give functions access to a class which are not part of the class themselves.
Furthermore, the two declarations differ in the parameter types - the one takes two Points, the other two Point2D - where does this Point2D type come from?
So:

Put the sortOrder function outside of your class declaration (or make it static as suggested by Joachim Pileborg)
Correct the parameter types
Remove the parenthesis after sortOrder in the std::sort call - like it is at the moment, you're trying to call the function.
Comment: thanks for your advice and sorry for the typo, it should be Points. not Points2D
Answer: When you write sortOrder() compiler think you are calling a function, but what you really need for this parameter s a function or a functor(a class that act like a function). So you can either write a function or a functor or use a lambda expression. Or in simplest case you can make sortOrder an static function and call it like this:
sort(point2DVector.begin(), point2DVector.end(),&Points::sortOrder)

sort element inside a vector c++


How do I implement SELU in TensorFlow.jl?

Question: I would like to use the SELU unit with the julia TensorFlow library.
How do I do it?
It is in the python library.
Before then there was code for it in [python by Günter](https://github.com/bioinf-jku/SNNs/blob/master/SelfNormalizingNetworks_MLP_MNIST.ipynb]
def selu(x):
    with ops.name_scope('elu') as scope:
        alpha = 1.6732632423543772848170429916717
        scale = 1.0507009873554804934193349852946
        return scale*tf.where(x>=0.0, x, alpha*tf.nn.elu(x))

where doesn't seen to work right in TensorFlow.jl
Comment: Crossref: https://github.com/malmaud/TensorFlow.jl/issues/335
Comment: Nice and useful
Answer: It is simply:
selu(x) = 1.0507select(x.<0, 1.76326exp(x) .- 1.0 , x)

where is not currently exported by TensorFlow.jl, though it can be found nonexported as TensorFlow.Ops.where.
I personally kinda dislike it, and prefer to use find or select  depending on if I want indexes, or if I want to chose the output. (To me, they are unrelated operations. And not worthy of multiple dispatch on the name where)
In this case we want the later so use select
You can fancy the function up a bit if you want to give the resulting node a name.
But that is all there really is do it.
Example of use:
julia> using TensorFlow

julia> sess=Session()
Session(Ptr{Void} @0x00007fa626702170)

julia> selu(x) = 1.0507select(x.<0, 1.76326exp(x) .- 1.0 , x)
selu (generic function with 1 method)

julia> run(sess, selu(constant(1.0)))
1.0507

julia> run(sess, selu(constant(0.0)))
0.0

julia> run(sess, selu(constant(-1000.0)))
-1.0507

julia> run(sess, selu(constant(1000.0)))
1050.7


How to add elements in List containing object

Question: public class Role
{
    public string RoleName { get; set; }
    public int RoleId { get; set; }

    public Role(int roleid, string roleName)
    {
        RoleName = roleName;
        RoleId = roleid;
    }
}

public class RoleManagement
{

    public List<Role> RoleList = new List<Role>();
    RoleList.Add(1, "Software Engineer");
}

I am trying to add some values to the list
I am facing a errors such as

Type Expected

Tuple must contain atleast two elements

How can  i add some elements into the list
Comment: C# is a language of types. What is the type of `RoleList`? What is the type of the parameter(s) to `RoleList.Add()`? What type(s) are you passing? How can you create an object of the correct type(s) to pass to `RoleList.Add()`?
Answer: You need to construct the Role object first, you can not add constructor parameters directly to the list:
RoleList.Add(new Role(1, "Software Engineer"));

Edit:
RoleList is an object of type List<Role>, in other words it's a List of objects of type Role. The Add method requires a single parameter, which should have the type Role (or derived). When calling RoleList.Add(1, "Software Engineer") you pass two parameters - of type int and string, while the method Add only accepts one: List<Role>.Add(Role item). In which case you should be getting compiler error CS1501 No overload for method 'Add' takes 2 arguments.
To construct a Role object you must use the new keyword and provide constructor parameters if required: new Role(1, "Software Engineer").
Comment: Can you be little precise ?
Comment: I would do a google search on Tuple it's really straight forward what @Maku has posted as an Answer in my Opinion


Global IP address programmatically

Question: I need to get the Global IP address in my iOS app.
I searched but couldn't find any posts regarding getting Global IP address. Most of them were for getting local IP address.
I tried this code: How to find IP Address of iPhone. But this returns the local IP address.
For my app, I need to get the IP address as shown by the websites e.g.:
http://myipaddress.com/show-my-ip-address/ and
http://whatismyipaddress.com/
Is it possible to get the Global IP address in iOS app programmatically? One option is to use web services like above but response from these websites will be HTML. Is there any free web service which would return a simple JSON or XML?
Answer: ** EDIT 06/29/16: ** I've updated the URL of the API because the older one does not work anymore.
You can use: https://api.ipify.org/?format=text
It's a plain string. You can get the responseObject and store and use it in your app. I recommend AFNetworking, it's a simple call and return and you do not need JSON or xml.
NSURL *URL = [NSURL URLWithString:@"http://api-sth01.exip.org/"];
NSString *URLPath = @"?call=ip";

// Start Connection
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:URL];
[httpClient setDefaultHeader:@"Accept" value:@"application/json"];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET" path:URLPath parameters:nil];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
[operation  setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    // SAVE responseObject to your app

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    // Failed
    NSLog(@"error: %@",  operation.responseString);

}];

[operation start];

But if you want JSON, you can use: https://api.ipify.org/?format=json
Comment: Thanks! Never thought it would be that easy :)
Comment: who is the owner of the web service btw , imean is it created by some user like us or some BIG NAME company . actually i wanna confirm the security while using it , any possible threat ??
Comment: I created an updated version of this with a better API: http://www.guilmo.com/how-to-get-user-external-ip-and-geolocation-data-in-ios/
Answer: No - it's not possible to programmatically retrieve your external (global) IP address strictly using code. Regarding using a service to view your external IP I would look into what you're eluding to: parsing or scraping the HTML returned from the two sites you mentioned or also CheckIP.
[NSData dataWithContentsOfURL:url]

An example of what CheckIP returns is below which is pretty simple and could easily be grabbed using RegEx

  <title>
   Current IP Check
  </title>

  Current IP Address: 18.104.22.168

EDIT:
using the URL from @gmogames' answer all you would have to do is the following to get the data into a string:
NSURL *theURL = [[NSURL alloc] initWithString:@"http://api-sth01.exip.org/?call=ip"];
NSString* myIP = [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:theURL]
                                     encoding:NSUTF8StringEncoding];

Global IP address programmatically


Finding range of function given domain and equation

Question: I just encountered a new type of question in my textbook that I'm not sure how to do. It says:
The one-one function $f$ is defined on the domain $x>0$ by $f(x)=\frac{2x-1}{x+2}$
I've been asked to find the range, $A$, of $f$ and obtain an expression for the inverse $f^-1(x)$, for $x∈A$
Would someone please explain to me how to do this?
Thank you!
Edit: I know how to find the inverse, it's the range $A$ that's troubling me.
Answer: Since the given function is continuous and bijective, you know that its range will be from $\inf_{(0,+\infty)} f$ to $\sup_{(0,+\infty)} f$, possibly including or excluding these two particular values.
In this case, the derivative of $f$ is always positive, so it attains its inferior bound for $x\to 0^+$, that is $-\frac12$, while its superior bound is given by $x\to+\infty$ and equals $2$; $f$ never actually reaches it, but it has a horizontal asymptote at this value.
Given this information, the range is $\bigl(-\frac12,2\bigr)$.
You can find the inverse simply by putting $y=f(x)$ and solving for $x$, i.e. solving the equation
$$
(x+2)y=2x-1.
$$
Comment: Observe that $\;f(-7)=\frac{-15}{-5}=3\notin\left(-\frac12,\,2\right)\;$
Comment: The function is defined on the domain $(0,+\infty)$.
Comment: I don't quite understand the inf and sup bits and the derivative that you mentioned, can you please explain it to me?
Comment: By Darboux's theorem, the range of $f$ is an interval $(a,b)$, and (I would say this is by definition) $a=\inf_{(0,+\infty)} f$ and $b=\sup_{(0,+\infty)} f$.
I used the derivative to see if $f$ had some extrema: since $f'(x)\ne 0$ for all $x\in(0,+\infty)$, those extrema are found at the boundary.
Lastly, $f'>0$, so the lower bound is at $x\to 0^+$ while the upper bound at $x\to+\infty$, because $f$ is increasing.
Answer: Note that the inverse map $f^{-1}$ satisfies $f^{-1}(f(x)) = x$. For some $x >0$ say $y = f(x)$. Then $$y= f(x) = \frac{2x - 1}{x+2} = \frac{2f^{-1}(f(x)) - 1}{f^{-1}(f(x)) + 2} = \frac{2f^{-1}(y) - 1}{f^{-1}(y) + 2}.$$ Now you can solve for $f^{-1}(y)$ which will tell you what the inverse map looks like.
As for finding the range, you need to find all values $y \in \mathbb R$ such that there is an $x > 0$ with $f(x) = y$. Another post has already addressed this.


Cannot log-in into my linux ubuntu and lost my home directory and its files

Question: So today i was learning a bit of linux using my linux ubuntu 20.04, i was learning about autofs. I installed autofs and configured it as was shown on the video i was watching. So it was time to create a user on ubuntu device that i presume is used to connect two machines so that they can share the shared files/filesysyem as i had to also create the same user eith the same userid on my other linux device.
So i then went on to create my new user called "user1" using the 'useradd'command, but when i tried to login to this user i noticed that as my prompt im only getting the $ sign, instead of (uname)@(hostname)$, so i thought to myself maybe its because i did not set the home directory for the new user, so i then executed the following command 'chmod -s /bin/bash -m -d /home/user1/ user1' (note that i was in my main home directory when i executed this command. The main directory of which i lost all my data). So after executing this command i was then able to login to user1 and the command prompt was actually correct. But then i immediately noticed that when i logged into that user i was in the /root home directory.
When i tried to ls my main home directory i was getting nothing back, so i then momentarily exited my terminal and tried to access my files using my gui and i noticed that i had no more files in my computer, i thought maybe it was just an error i could reslove by restarting my computer, but when i restarted it  i could not login as myself nor as root, when i try to login as myself i get stuck in a login loop, when i try to login as root it doesnt allow me either, i even tried password recovery and it still wont allow me to login.
On the login screen when i access the tty3 it allows me to login as myself and as root but under my home directory my data seems to be losy forever.
Can someone please help me to login to my computer at least, the data i have lost can mostly be recovered but at this moment i cant even access my GUI
Comment: `adduser` is more user friendly than `useradd`. The reason you were seeing only `$` is because you were using the wrong shell. `useradd` also doesn't create a home directory unless you tell it to. Now you might have broken your system in the actions you have taken.  I suggest that you reinstall and restore from backups. Try to research commands before running them so that you don't make mistakes as frequently and always have backups in case you need to start over.  See: https://askubuntu.com/a/345986 and https://serverfault.com/a/267101
Comment: Why have you entered `chmod -s /bin/bash ...`? I'm not sure, but get a live boot usb stick, mount your rootfs, and do a `chmod 755 /mnt/bin/bash`. With some luck your old system should now work again.
Comment: PS mount your original rootfs to `/mnt`. And also do a `chmod 755 /mnt/usr/bin/bash`.
Comment: Okay just to edit on that, i was trying to use testdisk to recover my files, it turns out they not actually deleted, when i enter testdisk i can copy home directory with all its files and when i try to copy it to my /home directory it tells me permission denied, though im logged as root and the owner of the directory is root, but when i try to copy it to another directory it works. Yet i still cant access my gui, i think there might be a problem with the mounting of the /home directory, because when i use tty3 and type ls -l, the size of /home is 0, using testdisk the whole directory is there.
Answer: So basically i heavent solved the whole problem completely, but i have a solution which is just as good. So with the use of testdisk through tty3 i was able to enter the /home/(USER) directory and copy everything to a created directory /backups. I then went on to delete all Usernames from the /etc/passwd, /etc/shadow & /etc/group directory.
Then i created a new directory /Home/(User) where i copied all the files from /backup to, i then proceeded to create a user using "useradd" command because for some reason it wasnt allowingg me to use "adduser". After creating the user i used "usermod" to set the home directory for the new user, after that i went to /etc/passwd to set the shell to /bin/bash for the user. I then rebooted my computer and i was able to use ny computer as normal.
My only issue is that i still cant access my /home directory and it taking up about 66g of my storage space...


What does Heavy Armor Training mean by "only taking Health damage from sonic attacks"?

Question: The description for Heavy Armor Training (SWAT level 5 perk) states:

While you have body armor, you only take Health damage from sonic attacks and clots can't grab you. You begin each game with 50% Armor.

However, the only thing that does "sonic attacks" are Sirens who have only done health (and not armor) damage since Killing Floor 1. What exactly does this perk do in terms of damage prevention?
Answer: After playing around with the SWAT class for a while and then playing with a without perks, apparently the wording of the perk is misleading.

you only take Health damage from sonic attacks

does not mean sonic attacks don't deal armor damage anymore, as they have never done armor damage. What this really means is that the only source of Health damage is from sonic attacks while you have armor on.
Thus, what Heavy Armor Training does is give you 50% armor to begin a game with. With armor on, you will be unable to be grabbed by Clots and you will not begin to take Health damage until you no longer have armor on, with the exceptions being Sirens' sonic attacks (and fall damage).
Others have been able to confirm this behavior. See this thread:

HAT prevents damage to health from non-sonic attacks but description is confusing until you actually use perk and notice effects.
There are some other things that dip straight into health damage. From the top of my head, I can only think of fall damage and Hans drains.


Quarried Stones in Skyrim

Question: How do I get the quarried stone for my house in Skyrim? I've found the mines for it, but after I mine I don't receive any of the stones.
Comment: it's unlimited mining for 4000 units per month. I guess what you're doing is bugged out.
Answer: Quarried stone and clay can be found in small infinite deposits near the location you are building your home.
The wiki has a full list of where you can find these deposits.
Stone deposit:

Quarried Stones in Skyrim


Numerical simulation of SDE with Lévy noise in Python - Overflow issue

Question: My goal is to simulate a SDE with alpha-stable noise in Python. This is my code:
import numpy as np
import scipy.stats as stats

N = 500 #time steps
T = dt*N #total time
ts = np.arange(0,T, dt, dtype=np.float64)

xs = np.zeros(N, dtype=np.float64)
xs[0] = 0 #inital condition

sigma = 0.001 #noise level
a = 0.5 #alpha

for i in range (N-1):
    xs[i+1] = xs[i] + dt*(xs[i]*xs[i] - xs[i]) +  sigma*np.sqrt(dt)*stats.levy_stable.rvs(alpha=a,beta=0)

For $\alpha < 1 $ I will at times run into the following warnings:
RuntimeWarning: overflow encountered in double_scalars
  xs[i+1] = xs[i] + dt*(xs[i]*xs[i] - xs[i]) +  sigma*np.sqrt(dt)*stats.levy_stable.rvs(alpha=a,beta=0)
RuntimeWarning: invalid value encountered in double_scalars
  xs[i+1] = xs[i] + dt*(xs[i]*xs[i] - xs[i]) +  sigma*np.sqrt(dt)*stats.levy_stable.rvs(alpha=a,beta=0)

I think I understand why these errors occur: For small $\alpha$ the distribution becomes increasingly heavy tailed and has infinite variance, making it very likely that at some point the simulation takes too many jumps in one direction and falls off the edge.
My question is about how to best deal with this in a practical setting. Would it be legitimate to constrain the simulation to stay within the range numpy is ok with? Is there a more elegant approach? And did I diagnose this issue correctly?
Any thoughts appreciated!
Comment: Are you sure that the power of `dt` that you need is the square root? It is for Brownian motion, for Poisson processes however it is the first power.
Comment: Dear @LutzLehmann, you are probably right, good call for me to look more closely into how the Euler-Maruyama scheme works for non-Gaussian noise. Thanks! However, this does not remove my issue, if I understand it correctly. Linear scaling will reduce the noise level, but not enough to prevent this issue.
Comment: What exactly is `dt`, you use it without defining it, this is always dangerous.
Answer: You have two problems:

you must use $dt^{1/\alpha}$ not $dt$
the SDE you choose is  peculiar since the associated ODE is peculiar and has a blow out for $x_s(0)> 1$

The problem n.2 is IMHO the main cause of the Python error you got
Ciao!


Can't working out incorrect syntax near the keyword 'LEFT'

Question: I've hit a wall with the SQL query I'm working on currently. I'm still learning SQL so apologies if this is an easy fix. I'm getting a syntax error on my second LEFT JOIN and for the life of me I can't figure out why.
SELECT DISTINCT
    ci.CatalogItemID AS EID
FROM
    LodgingCatalogMaster.[dbo].[CatalogItem] ci
LEFT JOIN
    LodgingCatalogMaster.[dbo].[CatalogItemAttribute] cia ON ci.catalogitemid = cia.catalogitemid
WHERE
    ci.[TableTypeID] = 1
    AND ci.catalogitemid NOT IN (SELECT cia.CatalogItemID
                                 FROM LodgingCatalogMaster.[dbo].[CatalogItemAttribute] cia
                                 WHERE cia.attributeID IN (2001, 361, 1073742653))
    AND ci.TableTypeID = 1
    AND ci.CatalogItemStatusTypeID = 1
LEFT JOIN
   LodgingCatalogMaster.[dbo].[SKUGroupBusinessModel] skugbm ON ci.catalogitemid = skugbm.SkuGroupCatalogItemID
WHERE
    skugbm.MerchantContract = 1 OR skugbm.DirectAgencyContract = 1;

Comment: Because you can't add joins after a where clause.
Comment: You have a WHERE clause in the middle of you joins.  Is that `WHERE` clause supposed to indicate it's part of a sub query being joined to `LodgingCatalogMaster`?  It's hard to tell without the entire qurey.
Answer: Move your LEFT JOIN above your WHERE clause as shown below. The only thing that you should see after a WHERE clause is a GROUP BY or ORDER BY clause.
SELECT DISTINCT ci.CatalogItemID AS EID
FROM LodgingCatalogMaster.[dbo].[CatalogItem] ci
LEFT JOIN LodgingCatalogMaster.[dbo].[CatalogItemAttribute] cia
        ON ci.catalogitemid = cia.catalogitemid
LEFT JOIN LodgingCatalogMaster.[dbo].[SKUGroupBusinessModel] skugbm
        ON ci.catalogitemid = skugbm.SkuGroupCatalogItemID
WHERE ci.[TableTypeID] = 1
AND ci.catalogitemid NOT IN (
               SELECT cia.CatalogItemID
               FROM LodgingCatalogMaster.[dbo].[CatalogItemAttribute] cia
               WHERE cia.attributeID in (2001, 361, 1073742653)
               )
    AND ci.TableTypeID = 1
    AND ci.CatalogItemStatusTypeID = 1
    AND (skugbm.MerchantContract = 1 OR skugbm.DirectAgencyContract = 1);

Answer: I would change both of your WHERE statements to AND.  Since you have left joins the WHERE clause could effectively change them to INNER JOINS.
SELECT DISTINCT ci.CatalogItemID AS EID FROM LodgingCatalogMaster.[dbo].[CatalogItem] ci

LEFT JOIN LodgingCatalogMaster.[dbo].[CatalogItemAttribute] cia
        ON ci.catalogitemid = cia.catalogitemid AND ci.[TableTypeID] = 1  AND ci.catalogitemid NOT IN (
               SELECT cia.CatalogItemID
               FROM LodgingCatalogMaster.[dbo].[CatalogItemAttribute] cia
               WHERE cia.attributeID in (2001, 361, 1073742653)
               )
    AND ci.TableTypeID = 1
    AND ci.CatalogItemStatusTypeID = 1

LEFT JOIN LodgingCatalogMaster.[dbo].[SKUGroupBusinessModel] skugbm ON ci.catalogitemid = skugbm.SkuGroupCatalogItemID AND skugbm.MerchantContract = 1 OR skugbm.DirectAgencyContract = 1;


Holomorphic function $h(x+iy)$ for x>0

Question: $$h(x+iy)=x^x+iv(x,y)$$ for $x>0$ where $v$ is real function
can h be holomorphic? if yes, why?
As far as i understand, for a function to be holomorphic,it must be possible to infinitely differentiate the function.But i am a little confused with harmonic functions too. Can someone explain that elegantly, thanks
Answer: This should be an easy application of the Cauchy reimann equations.
For a function $u(x,y)+iv(x,y)$, we know that its holomorphic if and only if
$$\frac{\partial u}{\partial x} = \frac{\partial v}{\partial y}$$
And
$$\frac{\partial u}{\partial y} = -\frac{\partial v}{\partial x}$$
The second equation is easy to work with for us, because $\frac{\partial u}{\partial y}=0$. So $\frac{\partial v}{\partial x}=0$ also. So $v$ doesn't depend on $x$.
Now let $h(x) =\frac{\partial u}{\partial x} $. I only care that $h$ doesn't depend on $y$ and it is not constant. Then $h(x)= \frac{\partial v}{\partial y}$. So $v(x,y)= y h(x) + \hat{h}(x)$ for some $\hat{h}$. But this contradicts the previous paragraph, that says $v$ cannot depend on $x$.
Comment: More generally, if $u$ only depends on $x$, $\frac{\partial u}{\partial x}$ must not depend on $x$, so $u(x)=ax+b$ for some real $a,b$.
Comment: The idea is when you anti-differentiate, you need to account for constants. You might remember this from calculus. But when we're just differentiating with respect to $y$, then $x$ is a constant. So instead of just a adding a constant, it could be any function of $x$. There should be plenty of descriptions of multi-variable anti-differentiating on this site.
Comment: i dont understand the last line in your answer. how can v(x,y)= ...?? i was lost there.
Comment: Anti-differentiate with respect to $y$.
Comment: what does h hat mean? can you give a little details there please as i am really new.
Answer: No, that's impossible. The real (and imaginary) part of a holomorphic function is harmonic, and $x^x$ is not.
Comment: why is $x^x$ not harmonic?
Comment: Because its second derivative is non-zero. Recall that a function $u = u(x,y)$ is called **harmonic** if $\Delta u = u''_{xx} + u''_{yy} = 0$. In particular if $u$ is a harmonic function of two variables that is independent of $y$, $u''_{xx} = 0$, so $u$ must be affine which $x^x$ is not.

Holomorphic function $h(x+iy)$ for x>0


Idiomatic iterator + mutation on a struct in Rust?

Question: I just ended up writing this code:
/// Watcher to look for changes in files
pub struct Watch<'a> {
  glob:Option<Glob>,
  ruv:Vec<*mut c_void>,
  paths:Vec<Path>,
  pub callback:Option<|Path, WatchEvent|: 'a>
}

impl<'a> Watch<'a> {

  /// Start watching for changes in any of the files matching known patterns
  pub fn watch(&mut self, path:&str) {
    let g = self.glob.take().unwrap();
    for path in g.iter(path) {
      match self.add_unique(&path) {
        Some(p) => { self.bind(&path); },
        None => {}
      }
    }
    self.glob = Some(g);
  }

  /// Check for a matching path
  fn add_unique(&mut self, path:&Path) -> Option<Path> {
    let mut found = false;
    for i in self.paths.iter() {
      if i.as_str().unwrap().as_bytes() == path.dirname() {
        found = true;
        break;
      }
    }
    if !found {
      self.paths.push(Path::new(path.dirname()));
      return Some(Path::new(path.dirname()));
    }
    return None;
  }

...

}

I'm particularly unhappy about having to move glob out of the Watch instance so that I can iterate over path matches and update the state of the object.
I tried a few approaches to this, but all the other alternatives involved creating temporary vectors which is completely infeasible (the glob might match hundreds of files, but I only care about unique paths in the tree of files so that they can be bound to libuv's file events api; I definitely do not want to create a vector that contains a gigantic list of every matching file).
How could this be written in a more idiomatic form?
I feel like it could be simplified considerably using functional calls, but the exact semantics for it elude me.
In essence what I'm trying to achieve here is:
for every filename in g.iter(path)
  if the path of the filename is not known yet
    call bind() on the path
    save the filename so future calls to watch() dont duplicate watch it

Here's a playpen with dummy data showing it in action: http://is.gd/09wYTS
Edit: And here's why I have to move Glob out to iter() on it: http://is.gd/FGlmw5
Answer: As I see it, this is typical problem of iterator invalidation. You are trying to modify structure that you are iterating over. When written in C++ it would compile but "magical" things can happen.
Idiomatic way to handle such situations is to create temporary structure for item that you want to insert and then insert them outside of the for loop.
Something along the lines:
pub fn watch(&mut self, path:&str) {
  let temp = Vec::new();
  for path in self.glob.iter(path) {
    match self.would_add_unique(&path) {
      Some(p) => { self.bind(&p); temp.push_back(&p); },
      None => {}
    }
  }

  for item in temp.iter() {
    self.add_unique(&item);
  }
}

Or you can redesign your structures so they do not act as single value.
Comment: Fair enough. I'm not really happy creating an arbitrary temporary vector (which might be large) either, but I guess it's better than moving a value out.


how to use ajax synchronize function without refresh function in few seconds

Question: I want to display the contents of the mysql database with the ajax function. is it possible to make the ajax function "synchron" with mysql database, without "auto_refresh" to ajax function in the next few seconds.
if the function is available. I want to apply it to my "messenger app", in terms of displaying new messages available, without performing the "refresh ajax" function once every 1 second
Comment: Where is your code ?
Answer: Web pages are a Stateless communication system. There is NO link between the server and browser except a "request->receipt" where the browser says "gimme" and the server says "k, here". After that the link is broken.
What this means is that NO, you can not get a signal in a web page without requesting the information (ie every second or some other interval) unless you use a workaround (which will, invariably, still require that workaround system to send and receive a signal at necessary intervals).
If you can install an app on the workstation, that's a different story. That app could then listen on a specific port (assigned through the client's firewall) and you're all set since the server can be informed of the firewall port and send the packet accordingly. But web browsers only check for and receive data after sending data at present.
That being said, there are plenty of messenger apps out there which utilize javascript/ajax methods to accomplish this task. By polling, with tiny packets. (such as those mentioned by Kishor Malakar)
Answer: If you are looking for real time updates from the server, look into socket.io in node.js. Otherwise you will have to keep checking for updates in interval. That wouldn't be a very good idea.