Q:

Calculate mean, median and mode from grouped frequency table

If we have only grouped frequency table; for example
                                    (mk) (frequency) (cumulative freq)
1                             (37.9,43.1]     4      4
2                             (43.1,48.2]    16      20
3                             (48.2,53.3]    7       27

how can we calculate median, mode and mean using R?
The theorical relations:
Mean
we find the mean of each interval,suppose xi,whose frequency fi;
then mean is
sumof(xi*fi)/sumof(fi)

for my example
sum=4*(37.9+43.1)/2+16*(43.1+48.2)/2+7*(48.2+53.3)/2
mean=mean/27=46.2

Median
we find the interval which his cumulative frequency
-sum over all previous intervals including this interval)equal or greater than n/2
-n is the total frequency- for our example n=27 and the required interval is (43.1,48.2]
then if we use lmin  the begin of this interval here lmin=43.1,lmax the end of this interval,lmax=48.2,fi the frequency of this interval,fi=16, Fi the cumulative frequency,Fi=20 then
median is
median=43.1+( ( 27/2-(20-16) )/16 ) *(48.2-43.1)=46.128

the relation of mode is familiar to median.

A:

1) Means Read in the data into character vector L and replace everything that is not a digit or dot with a space.  Then re-read it creating data frame DF whose columns are V1, V2 and V3.  Compute the means of the boundary values of each row and replicate them V3 times giving a vector r containing 4+16+7 elements.  Then take the mean, median and mode of that.  (The median and mode estimates from this may not be very good.)
# test data
Lines <- "(mk) (frequency)
(37.9,43.1]     4
(43.1,48.2]    16
(48.2,53.3]     7"

# replace textConnection(Lines) with "myfile.txt", say
L <- readLines(textConnection(Lines))
DF <- read.table(text = gsub("[^0-9.]", " ", L), skip = 1, as.is = TRUE)

r <- with(DF, rep((V1 + V2)/2, V3))

mean(r)
## [1] 46.209

median(r)
## [1] 45.65

tab <- table(r) # frequency table
as.numeric(names(tab))[which.max(tab)]
## [1] 45.65

This also works directly:
with(DF, weighted.mean((V1+V2)/2, V3))
## [1] 46.209

2) Normal Another approach is to assume normality (or other distribution) and minimize the negative likelihood:
neglik <- function(x) {
   m <- x[1]
   s <- x[2]
   with(DF, -prod(V3*(pnorm((V2-m)/s) - pnorm((V1-m)/s))))
}
optim(c(mean(r), sd(r)), neglik)$par
## [1] 45.6422  3.8841

We can then estimate the mean, median and mode as 45.6422 .
3) Piecewise uniform One possible assumption is that the pdf is uniform within frequency ranges so:
pdf <- function(x) with(DF, {
   if (length(x) > 1) return(sapply(x, pdf))
   if (x <= min(V1) || x >= max(V2)) return(0)

   k <- sum(x > V1)
   p <- V3/sum(V3) / (V2 - V1)
   p[k]
})

cdf <- function(x) {
   if (length(x) == 1) integrate(pdf, -Inf, x)$value else sapply(x, cdf)
}

# or without integration - gives same answer as cdf
cdf2 <- function(x) with(DF, {
  xx <- unique(sort(c(V1, V2)))
  yy <- c(0, cumsum(pdf((V1 + V2)/2) * (V2 - V1)))
  approx(xx, yy, xout = x, rule = 2)$y
})

# mean
integrate(function(x) x * pdf(x), min(DF$V1), max(DF$V2))$value
## [1] 46.20939

# median - alternately could use cdf2 in place of cdf
uniroot(function(m) cdf(m) - .5, range(c(DF$V1, DF$V2)))$root
## [1] 46.12813


Q:

Power Rasberry Pi Zero W using LiPo 11.4V and 7805 converter

In order to power a Raspberry Pi Zero W, I'm using the 7805 converter to lower the ~11.4V from a LiPo Battery to 5V. The resulted voltage is about 4.96V.
The Raspberry Pi starts to boot for about 20 seconds, then it reboots.
I'm also using the recommended capacitors for the 7805.
There are no peripherals connected, only ssh/spi/i2c enabled.
Where should I look? Thanks!

A:

The 7805 is a rather poor choice for this task since it is a so called linear voltage regulator. This means that it has no choice but to convert the voltage drop into heat. In this case 11.4 V - 5 V = 6.4 V. In other words, the regulator is going to produce more heat than the Pi itself and sucking your LiPO battery empty at the same time.
According to the datasheet and assuming the TO-220 package without heat sink has a thermal resistance junction-ambient (R_thJA) of 50 K/W (and even lower values for other packages such as D2PAK, DPAK, and TO-220FP). With P_D = (T_J(max) – T_A) / R_thJA and at an ambient temperature (T_A) of 25°C and the maximum junction temperature (T_J(max)) of 125°C - where the internal thermal-overload protection should kick in - a maximum power dissipation (PD) of 1.67 W is possible, which would be reached at about 260 mA. Besides wasting energy - not a preferable thing for a mobile application - operating the regulator at a higher temperature can affect reliability.
Now Power consumption of Pi Zero W? suggests the the Pi Zero W with WiFi enabled should consume less than that 260 mA which indicates it should be possible to run the Pi with this setup. Luckily the effect is rather simple to test - just check the temperature of the regulator. Warning, might be hot...
Possible (short term) solutions:

add a heat sink to reduce R_thJA and get some more headroom
reducing power dissipation with dropping resistor according to this circuit (note a required high power rating of the resistor, which will now share the burden with the regulator), (source):

Better (long term) solution:

go for a switching regulator, i.e. a step-down UBEC


Q:

cannot use v-for on stateful component root element in VueJS

I'm trying to build small application on Vuejs 2.0 where I'm having component file named Text.Vue and following are the components:
<template>

{{ item.title }}

             {{ item.created_at }}

             John Doe

            Design, Branding

             5 Comments

                {{ item.content }}

            Read More

</template>

While doing npm run dev or compiling the asset file I'm getting and error:

Cannot use v-for on stateful component root element because it renders multiple elements.

I don't know where I'm doing mistake, help me out in this.
Thanks

A:

When creating a component there needs to be 1 root element, try wrapping your code in a
 tag. It should solve the issue;
i.e.

        // Your code...

A:

Because vue2.0 use latest grammar is to do。
for example:
<template>

</template>


Q:

Buñuel's movies in languages other than Spanish or French

I read somewhere that Buñuel made movies in three languages.  All I know are his movies in Spanish and French.  Is that true and in which other languages has he directed movies and what are those movies?

A:

According to imdb, he directed two movies in english: Robinson Crusoe (1954) and The Young One (1960).
Filmography in wikipedia includes movies in french, spanish and english.


Q:

A class like UITextView, but with the ability to handle URL clicks

I am wondering if there is something already like this out there.  But I basically want something like UITextView to display text with embedded links.  However, I want to be able to handle the URL clicks as a delegate.
I've read a few posts like the following:
How to intercept click on link in UITextView?
However, I really don't want to override the openURL method.  My app works with lots of webServer data, and I don't want to keep creating exceptions for different hosts in the openURL method.
I guess my questions is, is there another way to intercept the click on UITextView?
My alternative is to write my own, with a UIScrollView, and use a TTTAttributedLabel (https://github.com/mattt/TTTAttributedLabel) inside it.  But am looking for suggestions, or alternatives.
Thanks.

A:

You may use UIWebView + Local HTML instead of UITextView.
And use the -(BOOL )webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType )navigationType delegate to handle the URL clicks,like:
-(BOOL )webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType )navigationType
{

  NSURL * clickedURL=[request URL];

  //Do something here.

  return NO;

}


Q:

Problems dropping an index in postgres using liquibase

I'm hitting an issue in liquibase where I can't drop an index in my postgres db. The error reported by liquibase is
Unexpected error running Liquibase: ERROR: index "value_idx" does not exist [Failed SQL: DROP INDEX VALUE_IDX]

I have connected to the database using psql and verified that the index does indeed exist (if the changeset is run without the drop index stanza)
\d data
          Table "someschema.data"
 Column |         Type          | Modifiers
--------+-----------------------+-----------
 value  | character varying(36) | not null
Indexes:
    "value_idx" UNIQUE, btree (value)

When running Liquibase updateSQL the DROP INDEX statement it generates is:
DROP INDEX VALUE_IDX;

My changelog is as follows:
<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">

    <preConditions>
        <dbms type="postgresql"/>
    </preConditions>

    <changeSet author="beresfordt" id="1">

        <sql>
            CREATE SCHEMA SomeSchema;
        </sql>

        <createTable tableName="data" schemaName="someschema">
            <column name="value" type="varchar(36)">
                <constraints nullable="false"/>
            </column>
        </createTable>

        <createIndex indexName="VALUE_IDX" schemaName="someschema"
                     tableName="data" unique="true">
            <column name="value" type="varchar(36)"/>
        </createIndex>

        <dropIndex catalogName="someschema"
                schemaName="someschema"
                tableName="data"
                indexName="VALUE_IDX"/>
    </changeSet>
</databaseChangeLog>

I have also tried the following dropindex stanza:
        <dropIndex catalogName="someschema"
                schemaName="someschema"
                tableName="data"
                indexName="someschema.VALUE_IDX"/>

But I get a similar error:
Unexpected error running Liquibase: ERROR: index "someschema.VALUE_IDX" does not exist [Failed SQL: DROP INDEX "someschema.VALUE_IDX"]

I am using Liquibase: 3.4.2 and Postgres: 9.5.1
Edit:
Tried on 3.3.0 and it works.
Bug raised in liquibase's jira: https://liquibase.jira.com/browse/CORE-2677

A:

This is caused by a bug which exists in, at time of writing 3.4.1 and 3.4.2 of Liquibase.
This has been raised on Liquibase jira: https://liquibase.jira.com/browse/CORE-2677
edit:
This seems to have been resolved in the current head: '03b020ab895eb02c0e0aba90461cb7c628fa033f'
edit 2:
Update from Liquibase:

The fix should be out with 3.5


Q:

Vimdiff: displaying the total number of changes

When diffing two files in (g)vim, is it possible to display the total number of changes? I suppose this is equivalent to counting the number of folds, but I don't know how to do that either.
Ideally I would like a message which says something like "Change 1 of 12" which would update as I cycled through the changes with ]c.
I am having great success converting some members of my office to the wonders of Vim, but Vimdiff is a consistent bugbear.

A:

Here is a slightly more refined solution. It uses the same technique as my previous answer to count the diffs, but it stores the first line of each hunk in a list asigned to a global variable g:diff_hunks. Then the number of hunks below the cursor can be found by finding the position of the line number in the list. Also notice that I set nocursorbind and noscrollbind and reset them at the end to ensure we don't break mouse scrolling in the diff windows.
function! UpdateDiffHunks()
    setlocal nocursorbind
    setlocal noscrollbind
    let winview = winsaveview()
    let pos = getpos(".")
    sil exe 'normal! gg'
    let moved = 1
    let hunks = []
    while moved
        let startl = line(".")
        keepjumps sil exe 'normal! ]c'
        let moved = line(".") - startl
        if moved
            call add(hunks,line("."))
        endif
    endwhile
    call winrestview(winview)
    call setpos(".",pos)
    setlocal cursorbind
    setlocal scrollbind
    let g:diff_hunks = hunks
endfunction

The function UpdateDiffHunks() should be updated whenever a diff buffer is modified, but I find it sufficient to map it to CursorMoved and BufEnter.
function! DiffCount()
    if !exists("g:diff_hunks")
        call UpdateDiffHunks()
    endif
    let n_hunks = 0
    let curline = line(".")
    for hunkline in g:diff_hunks
        if curline < hunkline
            break
        endif
        let n_hunks += 1
    endfor
    return n_hunks . '/' . len(g:diff_hunks)
endfunction

The output of DiffCount() can be used in the statusline, or tied to a command.


Q:

meteor mongodb _id changing after insert (and UUID property as well)

I have meteor method that does an insert.
Im using Regulate.js for form validation.
I set the game_id field to Meteor.uuid() to create a unique value that I also route to /game_show/:game_id using iron router.
As you can see I'm logging the details of the game, this works fine. (image link to log below)
file:  /lib/methods.js
Meteor.methods({
create_game_form : function(data){

    Regulate.create_game_form.validate(data, function (error, data) {
      if (error) {
        console.log('Server side validation failed.');
      } else {
        console.log('Server side validation passed!');
        // Save data to database or whatever...
        //console.log(data[0].value);
        var new_game = {
            game_id: Meteor.uuid(),
            name : data[0].value,
            game_type: data[1].value,
            creator_user_id: Meteor.userId(),
            user_name: Meteor.user().profile.name,
            created: new Date()
        };
        console.log("NEW GAME BEFORE INSERT:  ", new_game);
        GamesData.insert(new_game, function(error, new_id){

            console.log("GAMES NEW MONGO ID: ", new_id)
            var game_data = GamesData.findOne({_id: new_id});

            console.log('NEW GAME AFTER INSERT:  ', game_data);
            Session.set('CURRENT_GAME', game_data);

        });
      }
    });
  }
 });

All of the data coming out of the console.log at this point works fine
After this method call the client routes to /game_show/:game_id
Meteor.call('create_game_form', data, function(error){
    if(error){
        return alert(error.reason);
    }
    //console.log("post insert data for routing variable " ,data);

    var created_game = Session.get('CURRENT_GAME');

    console.log("Session Game ", created_game);
    Router.go('game_show',  {game_id: created_game.game_id});

});

On this view, I try to load the document with the game_id I just inserted
Template.game_start.helpers({
game_info: function(){
    console.log(this.game_id);
    var game_data = GamesData.find({game_id: this.game_id});
    console.log("trying to load via UUID ", game_data);
    return game_data;
}
});

sorry cant upload images... :-(
https://www.evernote.com/shard/s21/sh/c07e8047-de93-4d08-9dc7-dae51668bdec/a8baf89a09e55f8902549e79f136fd45
As you can see from the image of the console log below, everything matches

the id logged before insert
the id logged in the insert callback using findOne()
the id passed in the url

However the mongo ID and the UUID I inserted ARE NOT THERE, the only document in there has all the other fields matching except those two!
Not sure what im doing wrong.  Thanks!

A:

The issue is your code is running on the client side (or at least it looks like from the screenshot).
In meteor, Meteor.methods that run on the client side are simulation stubs. What this means is you put stuff in there that creates 'fake' data so that you can avoid the user feeling latency.  This is because it would take 1-4 seconds for the server to reply with what was actually inserted in the database. This isn't really an issue though.
The reason this causes you trouble is the method is run twice (one on the server and one on the client), so it generates two different Meteor.uuids since they are random. So this is why you have the inconsistency. What you see is the 'fake' one initially, then the server sends down the real one.
This is how Meteor makes it look like data has been inserted instantly, even though its not fully yet inserted.
To fix this get rid of the the .method you have on the client so that you only have one running on the server. You would need to get the game_id from the server though and not from the client.
If you want to keep the latency compensation, pass the Meteor.uuid in data like you do your other form data. This way the game_id will be consistent on both the server and client.


Q:

SQL retrieving 1st run data from a date range

I need to retrieve 1st run information from an Oracle database for a particular date range.  First run means ignoring rows where serial numbers that are run at a later time.
Note: 1 = Passed, 0 = Fail
Example of my data is:
SERIALNUM   TIMESTAMP_          PASSED  …{more data}
    001     2015-01-07T11:22:50     0
    002     2015-01-07T11:24:00     0
    003     2015-01-07T11:25:50     1
    001     2015-01-07T11:26:50     1
    004     2015-01-07T11:28:50     1
    005     2015-01-07T11:29:50     1
    006     2015-01-07T11:31:50     1
    002     2015-01-07T11:30:50     0
    002     2015-01-07T11:33:50     1
    007     2015-01-07T11:35:50     1
    008     2015-01-07T11:36:50     1
    0010    2015-01-07T11:39:50     1
    009     2015-01-07T11:37:50     1

Desired results, 10 units tested, 2 failed, 8 passed.
Using Excel to get my proper 1st run data I:
[step1] Delete rows outside of my date range.
[step2] Sort by SERIALNUM (1st level) TIMESTAMP_ (2nd level).
[step3] Remove Duplicate SERIALNUM.
[step4] Then count the number of passed units (1 = pass).

This gives me my desired results.
Changing the order gives me undesired results.
I can get the data from the database from my selected range by using:
SELECT SERIALNUM, TIMESTAMP_, PASSED
FROM dbTble
WHERE TO_DATE('01/07/2015 09:00:00', 'MM/DD/YYYY HH24:MI:SS') <= TIMESTAMP_
AND TIMESTAMP_ < TO_DATE('01/07/2015 14:59:59', 'MM/DD/YYYY HH24:MI:SS')
ORDER BY SERIALNUM, TIMESTAMP_

It seems like I should be using subquery, but I saw a note that subquery cannot be sorted.
How can I accomplish this with SQL command?

A:

This will get the first run (only) of runs within the date range. If there is a run for a particular serialnum earlier than the minimum date of the range, it won't be excluded:
SELECT serialnum, timestamp_, passed FROM (
    SELECT serialnum, timestamp_, passed
         , ROW_NUMBER() OVER ( PARTITION BY serialnum ORDER BY timestamp_ ) AS rn
      FROM dbtable
     WHERE TO_DATE('01/07/2015 09:00:00', 'MM/DD/YYYY HH24:MI:SS') <= timestamp_
       AND timestamp_ < TO_DATE('01/07/2015 14:59:59', 'MM/DD/YYYY HH24:MI:SS')
) WHERE rn = 1
 ORDER BY serialnum, timestamp_

The window function ROW_NUMBER() ranks according to earliest (use DESC after timestamp_ to force latest).
Hope this helps.


Q:

Can I flag a single post multiple times?

Why can I flag something multiple times, and why can I get different results from each flag?
I flagged a post one day, for "misinformation".  Another day, while I was reviewing, I came to the same post, but not recognizing it, I flagged it again, for the same reason.  I was surprised when, looking back at my flagging history, I found that I had flagged it twice, and that both flags were deemed valid.  I decided that though it was strange, I would try again.  My third and identical flag was deemed invalid, so that I have a total of three identical flags on the same post, two of which are valid, and one of which is invalid.  Why is this?
(There is another post I have flagged three times identically, and each time the flag was considered valid.)

A:

I dismissed your flag because moderators aren't supposed to make judgements on whether a particular answer is "right" or "wrong". Wrong posts should be downvoted; only non-answers, answers with extremely poor quality, spam answers, and offensive answers should be deleted.
As for why the same flag may be dismissed multiple ways, that's because each individual flag must have a decision made. While I agree with your flag, there's nothing I can do about it. Other mods may take a different stance, because this is the type of borderline case where an argument for both "valid" and "invalid" can be made.


Q:

Maven fails to read resource of a sub-module when called by aggregator pom

I have several modules that I run "mvn clean install" and have to maintain the order of them. To make my life easier and not having to change TFS or anything, I thought about creating project aggregator that will have all my sub-modules, while they know nothing about this aggregator.
My project structure:
projectaggregator
|
+- submodule1
|
+- submodule2

aggregator/pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.my.package</groupId>
    <artifactId>projectaggregator</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>
    <name>Project Aggregator</name>

    <modules>
        <module>../submodule1</module>
        <!--<module>../submodule2</module>-->
    </modules>
</project>

And build fails with following error:
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] submodule1
[INFO] Project Aggregator
[INFO]
[INFO] Using the MultiThreadedBuilder implementation with a thread count of 8
[INFO]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] Building Project Aggregator 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] Building submodule1 1.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- swagger-codegen-maven-plugin:2.3.1:generate (default) @ submodule1 ---
[INFO] reading from src/main/resources/yaml/decision.yaml
[INFO] reading from src/main/resources/yaml/decision.yaml
[ERROR] failed to read resource listing
java.io.FileNotFoundException: src\main\resources\yaml\decision.yaml (The system cannot find the path specified)
    at java.io.FileInputStream.open0(Native Method)
...
[INFO] No .swagger-codegen-ignore file found.
[ERROR] java.lang.RuntimeException: missing swagger input or config!

...
[INFO] --------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] submodule1 ....................................... FAILURE [  3.983 s]
[INFO] Project Aggregator ............................... SUCCESS [  0.003 s]
[INFO] --------------------------------------------------------------------
[INFO] BUILD FAILURE

submodule1/pom.xml:
...
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-codegen-maven-plugin</artifactId>
            <version>2.3.1</version>
        </dependency>
    ...

Clearly submodule1 fails to find resources since we are running submodule1 through aggregator.
Is there any way of resolving relative path to resources without having to modify submodule1 pom file?

A:

I faced the same issue when performing a multimodule build with swagger. Apparently a limitation with the swagger plugin when looking at paths of resources.
We can work around this by using maven variables ${project.basedir} in our swagger plugin configuration  :
<plugin>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>2.2.1</version>
    <executions><execution>
        <goals><goal>generate</goal></goals>
        <phase>generate-sources</phase>
        <configuration>
            <inputSpec>${project.basedir}/src/main/resources/yaml/decision.yaml</inputSpec>
        </configuration>
    </execution></executions>
</plugin>

Referenced from here - https://github.com/swagger-api/swagger-codegen/issues/3583


Q:

Why the votes to close on a perfectly legitimate question?

How can I get a list of tables in a SQL Server database along with the primary key using ONLY C#?
Why did two people vote to close on a legitimate question? It seems they were annoyed that their answers were deemed worthless and obviously not the answer to what I was asking.

A:

The first revision of that question was indeed a duplicate of this one.
Once you clarified you needed something else, people stopped voting to close.


Q:

Make an activity the default activity as soon as it is started for the first time

I have written an Android application that checks if a string entered in the EditText is the same as the one stored in the shared preferences if it's wrong, a Toast appears telling the user that the string he just entered is incorrect and this is true a new activity is open. I would like this open activity to be opened every time the user opens the application.
Here is what I try:
private PreferenceHelper preferenceHelper;
private ParseContent parseContent;
private final int RegTask = 1;
private EditText editText;
private Button button;
private String string;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login2);

    parseContent = new ParseContent(this);
    preferenceHelper = new PreferenceHelper(this);

    editText = findViewById(R.id.code);
    button = findViewById(R.id.abonnement);

    final SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);

    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            string = editText.getText().toString();
            if (string.equals(pref.getString("code", null))){
                Intent intent = new Intent(Login.this, WelcomeActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }else {
                Toast.makeText(Login.this, "Désolé mais votre code est incorrect",Toast.LENGTH_LONG).show();
            }
        }
    });
}

When the user enters the correct code, ie the previously registered code in the preference shared, WelcomeActivty.class opens but when the user exits the application and enters again, Login.class is always displayed while I would like WelcomeActivity.class to be launched every time the user enters the application again....How can I do this please ?!

A:

Note: I made a login system (without password), even if you are not working on a login system, I still think this technique can still apply in your case.
Try to add another sharedpreference that stores a boolean value to check whether the user is online or not. For instance, in your LoginActivity, add

editor.putBoolean("isOnline", true); editor.apply();

when you click the login button.
Similarly, when you logout, just put

editor.putBoolean("isOnline", false); editor.apply();

This is how I did according to your issues.
MainActivity.java (This is the login activity)
  public class MainActivity extends AppCompatActivity {

    SharedPreferences pref;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText et = findViewById(R.id.et);
        Button btnRegister = findViewById(R.id.btn_register);
        Button btnLogin = findViewById(R.id.btn_login);

        pref = getSharedPreferences("MyPref", MODE_PRIVATE);
        editor = pref.edit();

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                editor.putString("username", et.getText().toString());
                editor.putBoolean("isOnline", false);
                editor.apply();
            }
        });

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (et.getText().toString().equals(pref.getString("username", null))) {

                    Intent intent = new Intent(getApplicationContext(), WelcomeActivity.class);
                    intent.putExtra("name", et.getText().toString());
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

                    editor.putBoolean("isOnline", true);
                    editor.apply();

                    startActivity(intent);
                    finish();
                }
                else {
                    Toast.makeText(MainActivity.this, "Incorrect input", Toast.LENGTH_LONG).show();
                }
            }
        });

// This is when user has not clicked the log out button, then we go to the WelcomeActivity instead
        if (pref.getBoolean("isOnline", false)) {

            startActivity(new Intent(getApplicationContext(), WelcomeActivity.class));
            finish();
        }
    }
}

WelcomeActivity.java (the activity we visit after login)
public class WelcomeActivity extends AppCompatActivity {
    SharedPreferences pref;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        pref = getSharedPreferences("MyPref", MODE_PRIVATE);
        editor = pref.edit();

        editor.putBoolean("isOnline", true);
        editor.apply();

        Button btnLogout = findViewById(R.id.logout);
        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // When user clicks on the logout button, we set this to false. So everything will be back to normal.
                editor.putBoolean("isOnline", false);
                editor.apply();

                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    finishAffinity();
                }
                else {
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    finish();
                }
            }
        });
    }
}


Q:

Block numeric in EditText android using input filter

I want to do it programmatically by input filter not in xml like e.g - android:digits="aA".
Here is my code
public static void RemoveCharacter(EditText text, String character, int length) {
final String blockCharacterSet = character;
// final String blockCharacterSet = "\"+[]&~#^|$%*!@/()-'\\\":;,?{}=!$^';,?×÷<>{}€£¥₩%~`¤♡♥_|《》¡¿°•○●□■◇◆♧♣▲▼▶◀↑↓←→☆★▪:-);-):-D:-(:'(:O\";
InputFilter[] filter1 = new InputFilter[2];
filter1[0] = new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end,
                               Spanned dest, int dstart, int dend) {
        if (source != null && blockCharacterSet.contains(("" + source))) {
            return "";
        }
        return null;
    }
};
filter1[1] = new InputFilter.LengthFilter(length);

text.setFilters(filter1);

}

It is completely working in Moto G,nexus devices but not working in Samsung devices.

A:

Well, if you really want to do it with InputFilter it will be a little bit more complex than that.
Different keyboards act really differently, so i my guess is your solution won't be working with Swype/Swift keyboards.
Probably try using something like this:
    final Set<Character> blockSet = new HashSet<>();
    blockSet.addAll(Arrays.asList('1', '2', '3', '4','5', '6', '7', '8', '9', '0'));

    InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            for (int i = start; i < end; i++) {
                if (Character.isDigit(source.charAt(i))) {
                    char[] v = new char[end - start];
                    TextUtils.getChars(source, start, end, v, 0);
                    String s = new String(v);

                    if (source instanceof Spanned) {
                        CharSequence sp = new SpannableString(s);
                        TextUtils.copySpansFrom((Spanned) source,
                                start, end, null, (Spannable) sp, 0);

                        boolean containsDigit = true;
                        while (containsDigit) {
                            containsDigit = false;
                            for (int j = 0; j < sp.length(); j++) {
                                if (blockSet.contains(sp.charAt(j))) {
                                    sp = TextUtils.concat(sp.subSequence(0, j), sp.subSequence(j + 1, sp.length()));
                                    containsDigit = true;
                                    break;
                                }
                            }
                        }

                        return sp;
                    } else {
                        s = s.replaceAll("\\d", "");
                        return s;
                    }
                }
            }
            return null; // keep original
        }
    };


Q:

Computed destructuring of nested Objects

It's convenient to extract properties from Objects by destructuring:
let o = {id: "100", name: "Jane Doe", address: {id:1, city:"Fargo"}},
 key = "address";

let {address: {id: id}} = o; // 1

Destructuring patterns can be computed as well:
let {[key]: {city: city}} = o; // Fargo

But it seems apparently not possible to extract properties of nested objects dynamically:
key = "address.city";
({[key]: city} = o); // undefined

Is it possible to destructure nested Objects with computed patterns?

A:

No, this is not possible. Destructuring is only for objects whose structure you know about. You could of course do
var keys = ["address", "city"];
var {[keys[0]]: {[keys[1]]: city}} = o;

but not for arbitrarily nested objects. You'll have to use a recursive function for that which walks the property path. See the question Convert JavaScript string in dot notation into an object reference and many others for that.


Q:

How to read a file in shell script

I am new to shell scripting. I am trying to a script.
I have a log file, which saves the data every minute. The script needs to detect a keyword in that log file, if the keyword is present on it.
I was trying as below:
read jeeva/sample/logs.txt
grep keyword

I know my script is idiotic. Please help me with this.

A:

perhaps you want to write it this way
$ if grep -q keyword jeeva/sample/logs.txt;
  then echo "found";
  else echo "not found";
  fi

-q option is to suppress the output when the keyword is found.


Q:

some dynamic dropdownlists don't update -- autopostback = true

I have a web page that has developed an issue with only some of the dropdownlists. As indicated autopostback = true and yes I'm accounting for the !postback.
Line of Business, Director and Agent all post back without issue but the Senior Manager and Manager postback with the first value on the list regardless of selection.
here is the asp
<asp:TableRow>
            <asp:TableCell CssClass="tc1" Width="17%">
                <asp:Label ID="lblLob" runat="server">Line Of Business: </asp:Label>
            </asp:TableCell>
            <asp:TableCell CssClass="tc1">
                <asp:DropDownList ID="cmbLoB" runat="server" AutoPostBack="true" OnSelectedIndexChanged="reSelect"></asp:DropDownList>
                 <asp:RequiredFieldValidator ID="rfvLoB" runat="server" ControlToValidate="cmbLoB" InitialValue="0" ErrorMessage="Please select a Line of Business"></asp:RequiredFieldValidator>
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell ID="tcRange" CssClass="tc1" runat="server" Width="15%">
                <asp:Label ID="lblDateRange" runat="server">Report Range: </asp:Label>
            </asp:TableCell>
            <asp:TableCell CssClass="tc1">
                <asp:DropDownList ID="cmbDateRange" runat="server" AutoPostBack="true" OnSelectedIndexChanged="reSelect"></asp:DropDownList>
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
        <asp:TableCell CssClass="tc1"><asp:Label ID="lblStartDate" runat="server" Text="Start Date: "></asp:Label></asp:TableCell>
        <asp:TableCell CssClass="tc2"><asp:TextBox ID="txtStartDate" runat="server" AutoPostBack="true"></asp:TextBox><asp:CalendarExtender
                ID="calStartDate" runat="server" TargetControlID="txtStartDate" Format="yyyy-MM-dd">
            </asp:CalendarExtender>
        </asp:TableCell>
        <asp:TableCell CssClass="tc1"><asp:Label ID="lblEndDate" runat="server" Text="End Date: "></asp:Label></asp:TableCell>
        <asp:TableCell CssClass="tc2"><asp:TextBox ID="txtEndDate" runat="server" AutoPostBack="true"></asp:TextBox><asp:CalendarExtender
                ID="calEndDate" runat="server" TargetControlID="txtEndDate" Format="yyyy-MM-dd"></asp:CalendarExtender>
        </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell CssClass="tc1" Width="17%">
                <asp:Label ID="lblDirector" runat="server">Senior Leader: </asp:Label>
            </asp:TableCell>
            <asp:TableCell CssClass="tc1">
                <asp:DropDownList ID="cmbDirector" runat="server" AutoPostBack="true" OnSelectedIndexChanged="reSelect"></asp:DropDownList>
            </asp:TableCell>
            <asp:TableCell CssClass="tc1" Width="17%" ID="tdlblAggregate" runat="server" Visible="false">
                <asp:Label ID="lblAggregate" runat="server">Aggregation Level: </asp:Label>
            </asp:TableCell>
            <asp:TableCell CssClass="tc1" ID="tdcmbAggregate" runat="server" Visible="false">
                <asp:DropDownList ID="cmbAggregate" runat="server" AutoPostBack="true" OnSelectedIndexChanged="reSelect">
                <asp:ListItem Value="LoB" Text="Segment"></asp:ListItem>
                <asp:ListItem Value="SM" Text="Senior Manager"></asp:ListItem>
                </asp:DropDownList>
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell CssClass="tc1">
                <asp:Label ID="lblSManager" Visible="true" runat="server">Senior Manager: </asp:Label>
            </asp:TableCell>
            <asp:TableCell CssClass="tc1">
                <asp:DropDownList ID="cmbSManager" runat="server" AutoPostBack="true" OnSelectedIndexChanged="reSelect"></asp:DropDownList>
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell CssClass="tc1">
                <asp:Label ID="lblManager" Visible="true" runat="server">Manager: </asp:Label>
            </asp:TableCell>
            <asp:TableCell CssClass="tc1">
                <asp:DropDownList ID="cmbManager" runat="server" AutoPostBack="true" OnSelectedIndexChanged="reSelect"></asp:DropDownList>
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell CssClass="tc1">
                <asp:Label ID="lblAgent" Visible="true" runat="server">Associate/Specialist: </asp:Label>
            </asp:TableCell>
            <asp:TableCell CssClass="tc1">
                <asp:DropDownList ID="cmbAgent" runat="server" AutoPostBack="true" Visible="true" OnSelectedIndexChanged="reSelect"></asp:DropDownList>
            </asp:TableCell>
        </asp:TableRow>

And the code behind:
            DataTable SLTSelectDistinct = SLTSelect.DefaultView.ToTable(true, "sltID", "sltName");
            DataView sltSelect = new DataView(SLTSelectDistinct);
            DataRow sltRow = SLTSelectDistinct.NewRow();
            sltRow[0] = "0";
            sltRow[1] = "-- Please Select --";
            SLTSelectDistinct.Rows.Add(sltRow);

            sltSelect.Sort = "sltName";
            cmbDirector.DataValueField = "sltID";
            cmbDirector.DataTextField = "sltName";
            cmbDirector.DataSource = sltSelect;
            cmbDirector.DataBind();

            DataTable SMSelectDistinct = SMSelect.DefaultView.ToTable(true, "smID", "smName");
            DataView smSelect = new DataView(SMSelectDistinct);
            DataRow smRow = SMSelectDistinct.NewRow();
            smRow[0] = "0";
            smRow[1] = "-- Please Select --";
            SMSelectDistinct.Rows.Add(smRow);

            smSelect.Sort = "smName";
            cmbSManager.DataValueField = "smID";
            cmbSManager.DataTextField = "smName";
            cmbSManager.DataSource = smSelect;
            cmbSManager.DataBind();

            DataTable MSelectDistinct = MSelect.DefaultView.ToTable(true, "mID", "mName");
            DataView mSelect = new DataView(MSelectDistinct);
            DataRow mRow = MSelectDistinct.NewRow();
            mRow[0] = "0";
            mRow[1] = "-- Please Select --";
            MSelectDistinct.Rows.Add(mRow);

            mSelect.Sort = "mName";
            cmbManager.DataValueField = "mID";
            cmbManager.DataTextField = "mName";
            cmbManager.DataSource = mSelect;
            cmbManager.DataBind();

            DataTable ASelectDistinct = LoBSelect.DefaultView.ToTable(true, "C_AGT", "aName");
            DataView aSelect = new DataView(ASelectDistinct);
            DataRow aRow = ASelectDistinct.NewRow();
            aRow[0] = "0";
            aRow[1] = "-- Please Select --";
            ASelectDistinct.Rows.Add(aRow);

            aSelect.Sort = "aName";
            cmbAgent.DataValueField = "C_AGT";
            cmbAgent.DataTextField = "aName";
            cmbAgent.DataSource = aSelect;
            cmbAgent.DataBind();

A:

It is probably that you have 0 as the value of one of your actual options as well so when the page refreshes the selected value of the dropdown is 0 which also happens to be the value of the default "Select One" option.


Q:

Richtext in Django renders wrong

I'm using wagtail 2.3 on Django 2.1, and for a specific loop, the richtext elements which contain an tag are rendered wrong.
This is the template used:

  {% for interaction in value.interactions %}

{{ interaction.drug_name }}

{{ interaction.interaction_type }}

          {{ interaction.description | richtext }}

  {% endfor %}

The snippet below shows 3 elements being rendered. The first two are rendered correctly inside their , however the third one isn't:

Paracetamol

Low risk and no synergy

...

Ibuprofen

Low risk and no synergy

content....

Tricyclics

Dangerous

          beginning of content...

          link in original content

        end of content

Thanks.

A:

This isn't really a Wagtail issue. Here Wagtail is simply doing what your template is telling it to do, and placing a link inside another link, which isn't valid HTML. Your browser is then trying to recover from that by closing the link before opening the new one, which is what you're seeing in (presumably) the developer toolbar. If you use the browser's 'view source' option instead, you'll see the (invalid) nested links.
You'll need to either find a different way of implementing your Javascript interaction that doesn't require nesting links, or disallow links in that field via the features argument on the RichTextField / RichTextBlock.


Q:

Cannot make static reference to the non-static type t

I am trying to create a static method that returns a Generic Object of the same class which the static method is a member of but there is compilation error on the return type as

Cannot make a static reference to the non-static type T

Looking at other solutions on stack overflow I found this
(Generics)Cannot make a static reference to the non-static type T
where a responder has provided an answer which says that for static methods, we must also include the target type  before the return type but even this does not work
public class Condition<T extends Node> {

private boolean isInitialized=false;
private ConditionType type;
private NodeType nodeType;
private String propertyName;
private Predicate<T> onlyIfTest;
private Predicate<T> predicates;

private Condition() {

}

//Here at the return type i get the error Cannot make static...
public static Condition<T> include(NodeType type,String propertyName) {
    Condition<T> condition = new Condition<T>(); //and an error here too
    condition.type = ConditionType.INCLUDE;
    condition.nodeType = type;
    condition.propertyName = propertyName;
    condition.isInitialized =true;
    return condition;
}

The error that i get is Cannot make a static reference to the non-static type T. How can i make it work with a static method.

A:

You've already had your answer:

we must also include the target type before the return type

but didn't apply it.
public static <T extends Node> Condition<T> include(NodeType type, String propertyName)


Q:

Orientation doesn't change (Actionbar and ICS)

I have a problem with ICS and the Actionbar. At start, when i changed the orientation, it worked, but now when i change the orientation, i have this error :
Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment
com.descartes.application.MainActivity$DummySectionFragment:
make sure class name exists, is public, and has an empty constructor that is public

Caused by: java.lang.InstantiationException:
can't instantiate class com.descartes.application.MainActivity$DummySectionFragment;
no empty constructor

Here is the main code :
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
 * sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will
 * keep every loaded fragment in memory. If this becomes too memory intensive, it may be best
 * to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;
private static int SCAN = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Loc lc = new LocImpl(this);
    Localisation loc = lc.localiser();
    System.out.println(loc.toString());
    // Create the adapter that will return a fragment for each of the three primary sections
    // of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the action bar.
    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    // When swiping between different sections, select the corresponding tab.
    // We can also use ActionBar.Tab#select() to do this if we have a reference to the
    // Tab.
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by the adapter.
        // Also specify this Activity object, which implements the TabListener interface, as the
        // listener for when this tab is selected.
        actionBar.addTab(
                actionBar.newTab()
                        .setText(mSectionsPagerAdapter.getPageTitle(i))
                        .setTabListener(this));
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

// Ecouteurs qui correspondent à chaque bouton présent dans la page
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_camera:

            // app icon in action bar clicked; go home
            Intent intent = new Intent(this, ScanBarActivity.class);
            intent.putExtra("METHODE", "SCAN");
            startActivityForResult(intent, SCAN);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, switch to the corresponding page in the ViewPager.
    mViewPager.setCurrentItem(tab.getPosition());
}

public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
 * sections of the app.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        Fragment fragment = new DummySectionFragment();
        Bundle args = new Bundle();
        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0: return getString(R.string.title_section1).toUpperCase();
            case 1: return getString(R.string.title_section2).toUpperCase();
            case 2: return getString(R.string.title_section3).toUpperCase();
            case 3: return getString(R.string.title_section4).toUpperCase();
        }
        return null;
    }
}

/**
 * A dummy fragment representing a section of the app, but that simply displays dummy text.
 */
public class DummySectionFragment extends Fragment {
    public DummySectionFragment() {
    }

    public static final String ARG_SECTION_NUMBER = "section_number";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        Bundle args = getArguments();
        switch (args.getInt(ARG_SECTION_NUMBER)){
        case 1:
             return inflater.inflate(R.layout.page_accueil, container, false);
        case 2:

            break;
        case 3:

            break;
        case 4:

            break;
        }
        TextView textView = new TextView(getActivity());
        textView.setGravity(Gravity.CENTER);
        textView.setText(Integer.toString(args.getInt(ARG_SECTION_NUMBER)));
        return textView;

    }
}

}

I don't understand where is the error, so i ask to you, can you help me ?

A:

Change
public class DummySectionFragment extends Fragment

to
public static class DummySectionFragment extends Fragment

(or move DummySectionFragment to a separate class file).


Q:

How to write equations in html?

I want to write some complex mathematical equation in my web page. Is there any plugin or anything for this?

A:

Try mathjax http://www.mathjax.org/ . I personally find it very good.

A:

For complex equations, MathJax is the current practical solution. MathML is a more structural approach in principle, but browser support is rather limited and often of questionable quality.
However, complexity is relative. To some people, E = mc² or ∂/∂t + v ⋅ ∇ might be complex, and such constructs can be written fairly well using just HTML with some help from CSS; see my page Math in HTML (and CSS).

A:

You could try this. Kind of out of date so not sure how it'll work:
http://www.w3.org/Math/
For Firefox, they have a pretty descriptive article on MathML


Q:

multithreading in C using -lpthread

So I designed a server to accept multiple clients in real time where the clients will 'speak' and the server will 'repeat' it. The clients will remain active constantly until I quit it. I tried implementing this using the -lpthread but the server will accept all the client connections, but then ignore all commands received except from the first client. Here is what I tried so far:
int main(int argc, char *argv[]) {
    pthread_t client_thread;
    pthread_attr_t attr;
...
while(1) {  /* main accept() loop */

    sin_size = sizeof(struct sockaddr_in);
    if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, \
    &sin_size)) == -1) {
        perror("accept");
        continue;
    }
    printf("server: got connection from %s\n", \
        inet_ntoa(their_addr.sin_addr));

    pthread_attr_t attr;
    pthread_attr_init(&attr);

    for (int i = 0; i < MAX_CLIENTS; i++) {
        pthread_create(&client_thread, &attr, decider, new_fd);
        pthread_join(client_thread,NULL);
    }
...

Currently, the only options I can choose between are multithreading or thread pooling. Thanks.

A:

You call pthread_create and then immediately pthread_join.
The problem with that is that pthread_join will wait for the thread to exit, making your code serial instead of parallel.
If you want to dynamically create a thread when you receive a connection, then create one thread. Don't create MAX_CLIENT threads in a loop, where all threads handle the very same connection.

If you want to use a thread-pool, then create all threads first before the "main accept() loop", and simply have them do nothing (to begin with). Then use a (protected) queue where you add new connections, and the threads check this queue for new connections, and the one thread that doesn't already handle a connection will pick it up and process it.
In pseudo-code, something like this:
thread_function()
{
    while (true)
    {
        sleep_while_queue_is_empty();
        get_descriptor_from_queue();

        handle_connection();
    }
}


Q:

Type Class for Complex Numbers

I need to implement a custom type class for Complex DSP and Complex Ring operations. I'm aware about DspTools project, but purposely want to exclude it from consideration.
I've got a hardware module, which I want to instantiate with diff type classes: UInt, SInt, FixedPoint, Real and Complex(FixedPoint, FixedPoint).
Here's my minimal class:
class Complex[A <: Data, B <: Data] (val re:A, val im:B) extends Bundle {
  override def cloneType: this.type = new Complex(re, im).asInstanceOf[this.type]
}

object Complex {
  def apply[A <: Data, B <: Data](re:A, im:B) = new Complex(re, im)
  implicit def UInt2Complex(re:UInt, im:UInt) = Complex(re,im)
}

When I instantiate this with different data types from Chisel3.Core, the code compiles and works.
However, when I try to do :
import chisel3.core.{FixedPoint => FP}
...

  val inType  = Complex ( FP(20.W,10.BP), FP(20.W,10.BP))
  val outType = Complex ( FP(20.W,10.BP), FP(20.W,10.BP))
...

I get the code compiled, but FIRRTL emits an error:
[info] using --backend-name verilator
[info]   chisel3.core.Binding$RebindingException: Attempted reassignment of binding to chisel3.core.FixedPoint@d
[info]   at chisel3.core.Data.binding_$eq(Data.scala:250)
What's wrong with this? How to fix the issue?

A:

The issue is that Chisel needs fresh clones of any Data when it recursively calls cloneType, and you're simply passing re and im to the Complex constructor resulting in the exact same objects. Put a little more concretely:
val a = Complex(UInt(8.W), UInt(8.W))
val b = a.cloneType
a.re eq b.re // This will be true and it *must* not be

This is kind of an age old problem that we don't have a great solution to, in your case, you should call .cloneType on re and im in Complex.cloneType
I know you aren't using DSPTools, but it can still provide a reference and they do that: https://github.com/ucb-bar/dsptools/blob/fe8f9d08987f3a403f6281ba4face1c26b627b71/src/main/scala/dsptools/numbers/chisel_concrete/DspComplex.scala#L75


Q:

Crash on newer android version

I had done an app. Work nicely in emulator Nexus 5x API26 x86.
However it crash run in some other android version
https://play.google.com/store/apps/details?id=tk.myessentialoils.reprogramyourmind
Crash 1
LGE V20 (elsa), 4096MB RAM, Android 7.0

java.lang.IllegalArgumentException:    at java.util.Random.nextInt
  (Random.java:391)   at
  tk.myessentialoils.reprogramyourmind.MyService$TimeDisplayTimerTask$1.run
  (MyService.java:92)

Can anyone go through my java classes and show me how to optimize them?
    private class TimeDisplayTimerTask extends TimerTask {
        @Override
        public void run() {

                mHandler.post(new Runnable() {
                @Override
            //this is the line 92 crash, randomStr
                public void run() {
                    String randomStr = array[new Random().nextInt(array.length)];

                    final Toast Notify = Toast.makeText(getApplicationContext(),randomStr, Toast.LENGTH_LONG);
                    TextView toastMessage = (TextView) Notify.getView().findViewById(android.R.id.message);
                    toastMessage.setTextColor(Color.RED);
                    toastMessage.setTextSize(21);
                    Notify.getView().setBackgroundColor(Color.TRANSPARENT);
                    Notify.setGravity(Gravity.CENTER, 0, 0);
                    Notify.show();

                    Handler cancelToast = new Handler();
                    cancelToast.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Notify.cancel();
                        }
                    }, DISPLAYTIME);

                }
            });
        }
    }

A:

thanks for the comment.
That's my thinking too. Most probably the array.length is 0 or not being passed.
So my solution will be to implement a check, if length = 0 then break the code.


Q:

How to navigate to C drive in bash on WSL-Ubuntu?

I've installed bash on Ubuntu on Windows feature on Windows 10 and I want to change directory this path on my C:\ drive:
C:/wamp64/www

What should I do ?

A:

In Windows Subsystem for Linux (WSL) The C:\ drive is mounted as /mnt/c/, D:\ is mounted as /mnt/d/ et cetra. Therefore, C:/wamp64/www should be at /mnt/c/wamp64/www. Try:
cd /mnt/c/wamp64/www

in the Ubuntu terminal to go to that folder. Note, the first / before mnt and remember that in Ubuntu file and folder names are case sensitive. So wamp64, WAMP64, wAmP64, and WaMp64 are 4 different folders! See https://superuser.com/questions/1116625/how-can-i-access-case-sensitive-paths-on-windows-created-with-bash-on-ubuntu-on for a bit more on using case sensitive file names in WSL.
References:
https://blogs.msdn.microsoft.com/wsl/2016/06/15/wsl-file-system-support/
https://superuser.com/questions/1066261/how-to-access-windows-folders-from-bash-on-ubuntu-on-windows
Hope this helps


Q:

Where is Crystal Reports Page Setup Menu

This my Report Page :

I Searched for Page Setup but i can't find it any where.

A:

I found it.Right-click on page --> Design -->then Page Setup


Q:

How would i write this in F# or another functional language

I know in F# you declare variables when you assign them. I'm sure you can declare vars in a C way but how might i write this
long id=0
using (SQLiteDataReader r = command.ExecuteReader())
{
    while (r.Read())
    {
        id = r.GetInt64(0);
        //...
        break;
    }
}
//use id in sqlite now that it isnt locked

A:

First of all, I'm not sure if you need any looping in your example at all. Your code always returns the value from the first row. I'll complicate the example a little bit and assume that you may not want to get certain IDs as the result (so you may need to do some looping).
The usual way for writing looping constructs in functional languages is to use recursion (in many cases, you can avoid using recursion explicitly, because there are many useful higher-order functions that you can use directly). In this case, you can write a simple recursive function read that calls r.Read() once - if it succeeds then it returns the ID, if not, it calls itself recursively to read the next line:
let id =
  ( use r = command.ExecuteReader()
    let rec read() =
      if r.Read() then
        let id = r.GetInt64(0)
        if weWantThisId id then id  // this is the ID we want
        else read()                 // continue reading IDs
      else 0                        // default value / throw
    read() )

The read function is written as a local function in a scope that initializes the id value. This means that when F# assigns value to id, it will run ExecuteReader and then run the local function read (this is a way to write the initialization as a single expression). Of course it may be more readable to write a fetchId function as Jon suggests (in F#, you'll again use recursion):
let fetchId() =
  use r = command.ExecuteReader()
  let rec read() =
    if r.Read() then
      let id = r.GetInt64(0)
      if weWantThisId id then id
      else read()
    else 0
  read()

A:

Rough translation:
let mutable id = 0L
(
    use r = command.ExecuteReader()
    let mutable finished = false
    while not(finished) do
        if r.Read() then
            id <- r.GetInt64(0)
            // ...
            finished <- true
        else
            finished <- true
)
// ...


Q:

how to make countdown running in background using eclipse

this is the problem.i cant't click the button while countdown is running.i have to wait until countdown stop.My question is how to make countdown running in background.or any suggestion.please help me !
    public static void main(String args[]){
        scrbutton myWindow = new scrbutton();  //set window design
        myWindow.setSize(300,70);
        myWindow.setVisible(true);
        myWindow.setResizable(false);

    }

    public scrbutton() {

        super("Clicker");     //Title
        setLayout(new FlowLayout());
        addWindowListener(this);
        add(kotak);
        add(kotak2);                         //add and design you components
        add(kotak3);
        add(enter);
        enter.addActionListener(this);
        kotak.setText("0");
        kotak2.setText("Times remaining: 60");
        kotak.setEditable(false);
        kotak2.setEditable(false);
        kotak3.setEditable(false);

    }

    public void actionPerformed(ActionEvent e)    //What will run through the program?
    {

    click++;
    kotak.setText("\r"+click);                              //display number of click
    if (click >=10){
        kotak3.setText("You Win!");
        enter.setEnabled(false);
    }else{
        kotak3.setText("try again");
        }

    for(int x=60; x>=0; x--)

         {System.out.print(x+"\r");             // use print than println if you use (/r).
         try {Thread.sleep(100);}               // 1000ms=1second thus its sleep(delay) 1 second between each iteration.
         catch (InterruptedException e1){}

         }
    }

 public void windowClosing(WindowEvent e) {
     dispose();
     System.exit(0);
}

public void windowOpened(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}

}

A:

I'm going to go out on a limb here, as I don't do Java, but I'd say you need to have the application be multi-threaded - you need your main thread not to be blocked by the executing thread of the timer.  Create a new thread with callback to increment the timer, kick the thread off, then terminate the thread when no longer needed.


Q:

Docker toolbox cannot allocate memory

I'm trying to get Docker running a container locally on my mac that I've been working on in the cloud. I did the docker commit/save/load find. But when I got to run it locally after I installed docker toolbox I get this error
docker logs es-loaded-with-data
Java HotSpot(TM) 64-Bit Server VM warning: INFO: os::commit_memory(0x00000006c5330000, 4207738880, 0) failed; error='Cannot allocate memory' (errno=12)
Starting elasticsearch: #
# There is insufficient memory for the Java Runtime Environment to continue.
# Native memory allocation (mmap) failed to map 4207738880 bytes for committing reserved memory.
# An error report file with more information is saved as:
# //hs_err_pid16.log

Java HotSpot(TM) 64-Bit Server VM warning: INFO: os::commit_memory(0x00000006c5330000, 4207738880, 0) failed; error='Cannot allocate memory' (errno=12)
Starting elasticsearch: #

If I do docker info
then I get

Total Memory: 1.956 GiB

clearly 2 Gb isn't enough. How do I increase it so my container will run?

A:

Docker on Mac OS runs inside a virtualbox VM with either docker-machine (or older boot2docker). I am not sure if docker-machine supports modifying the VM RAM directly, but you can probably just start the VirtualBox.app and modify the amount of VM Memory directly. Restart the VM et voilá.


Q:

Which organization types are targeted by DevOps transformation?

Due to my lacking vocabulary in this context I am not sure how to designate the two types of organizations I would like to talk about before I can put my question. Anybody capable of better wording feel free to improve this.
Probably there are mixed types but I suppose I have to polarize a little bit to make the point.
OrgType1: "digitalized product organizatons" either B2B or B2C, they have their products, as they become more and more digital, they have some own IT product teams and IT operations. They have found out that they need (more than before) product diversification quite recently.
OrgType2: "digital consulting service organizations" (not necesarily just IT consulting but they are typical example here) these guys are B2B only, if they have sustainable products and related operations then it is rather a side effect.
Rather, their software product lifecycle is limited to just one or several projects, and that diversification has always been their core business. Actually, the real product is here much more every single member of this organization who depending on the role might, but by far not always does, develop software.
OK then, so OrgType1 is clearly what we already know that DevOps is of a great help, because there are established delivery processes, they get disrupted, need to be optimized, and so on and so forth. Well, bigger organizations consist of many parts, regional business units, business lines, departments, and every one has its combination between operations and their-own-breed-of Devops. Okay - anyway there can be some evolution.
OrgType2 can care about DevOps only so much as it is important for their customer (or they even sell DevOps consulting ;) but then if it comes to onsite software development, you somehow start from zero in almost every project, and this is magnified as with OrgType1 through all departments, business units and so on but it is worth because every "DevOps entity" starts just with 1-2 people who need to discover what they are up to. Seems like OrgType2 is "siloed by design" in a much more dense way which makes it also somehow scalable and persistent.
This all considered and taken into account, the question from my current perspective is: how do DevOps practices apply for the OrgType2, maybe there are resources where this has been explored?

A:

DevOps applies to Organization Type 2, the Business to Business entity as much if not more than the first Organization type. There are two possible scenarios here:
Scenario 1
In the first they are selling a product or service to businesses. In terms of DevOps, this makes them virtually indistinguishable from Organization Type 1. Though their customer is a business/group of individuals, they are providing a product or service to a customer. This customer just happens to be a business instead of a private individual, this is is irrelevant to execution of DevOps. Contracted with specific software goals, clearly defined requirement or otherwise, the best value and customer service will be provided by a DevOps model for reasons that do not need to be restated here.
Scenario 2
This scenario happens to be a bit more exceptional as in this case, Organization Type 2 is providing consulting services to a business. Presumably and usually, a business hires a consultant for business assistance within the consultant's domain of expertise. Businesses have technical support for assistance with specific technologies and can contract en engineer for migrations, but when issues such as risk management, overall architectural design, process, flow and high-level questions arise, this is when a consultant is hired for their business advice.
This is why it is important to remember that DevOps is not a role. I would argue that DevOps represents a business or organizational management processes - or even a philosophy. It is more or less a specific way of implementing an agile methodology that has been extended well beyond just development to encompass many disciplines and departments. As such, DevOps is a package deal - in order to be successful at DevOps, you have to be committed to a specific business philosophy of organizational management.
In fact, in order to illustrate this point, In "The Phoenix Project", Board member Erik Reid repeatedly drags the Book's main character, Bill Palmer, to a parts manufacturing plant in order to illustrate and teach Bill things about technology and software development by drawing business lessons from the manufacturing sector.
This is authors Gene Kim, Kevin Behr and George Spafford's way of driving home the point that DevOps is more than just way of doing things, or specific technologies, but is a philosophy of business simply known by various nom de plumes.
So, in order to provide the best value to the company to which a consultant is consulting, it is incumbent upon the consultant to demonstrate and explain the value of DevOps and assist a company in successfully executing on this business philosophy and guide the company to specific technologies and ways of doing that. In short, it is the consulting companies job to act as an "Erik Reid" to whatever business has contracted their consulting services.
In short, DevOps should be very important to Organization Type 2 because it is their job as a consultant to explain to their customer why it is important - they should always be selling DevOps consulting. Consultants working with a company who refuses to consider DevOps should consider politely suggesting that perhaps they aren't the right fit. their customer can hire a generic code monkey from anywhere if they want to continue to (unsuccessfully) continue to do projects the way they have always done them.


Q:

Find the number of n-digit ternary sequences with no "012" subsequences

My colleague challenged me to solve this problem. I approached this by partitioning by the first digit...
Consider the 3 cases for the first digit of the sequence (0, 1, 2). If we have no restrictions, finding the number of ways to create all possible n-digit ternary sequences is trivial to express as a recurrence relation:
$0: a_{n-1} \ ways$
$1: a_{n-1} \ ways$
$2: a_{n-1} \ ways$
So the possible ways to form all possible n-digit ternary sequences can be expressed as: $a_n = 3a_{n-1}$

But if we can't have a "012" subsequence in the n-digit string, then things get a bit harder, but not by much. We can still partition by the first digit. If we have a zero, we may run into the problem where we have a "012" subsequence, but the number of ways for when 1 or 2 is the first digit is the same:
$0: ?$
$1: a_{n-1} \ ways$
$2: a_{n-1} \ ways$
How can we exclude the "012" subsequences? I did this by sub-partitioning when 0 is the first digit. If we have 00 as our first 2 digits, then  we won't have the problem where "012" is a subsequence. There are $a_{n-2}$ ways to do this because we've already chosen the first 2 digits. The same applies for 02; we won't get the problematic sequence (i.e. 012).
If 01 are our first 2 digits, then we may have a problem. The only possible choices are 010 and 011 - 2 choices. We decided on the first 3 digits, so we have $2a_{n-3}$ ways to choose the remaining digits to form the n-digit string.
Here is my full partition:
$0:$
$ \ \ 00: a_{n-2} ways$
$ \ \ 01: 2a_{n-3} ways$
$ \ \ 02: a_{n-2} ways$
$1: a_{n-1} \ ways$
$2: a_{n-1} \ ways$
By the Addition Principle, I can sum all parts of the partition. This gives me:
$$a_n = 2a_{n-1} + 2a_{n-2} + 2a_{n-3}$$
or the cleaner:
$$a_n = 2(a_{n-1} + a_{n-2} + a_{n-3})$$
Am I correct?

A:

This doesn't quite work. It is not the case that inserting $00$ or $010$ in front of a legal sequence necessarily gives a legal sequence.  A simpler approach might be to note that inserting any digit in front of a legal sequence of length $n-1$ results in a legal sequence of length $n$ unless the inserted digit is $0$ and the sequence began with $12$.  But inserting $12$ in front of a legal sequence of length $n-3$ always produces a legal sequence of length $n-1$, so we know that among the $a_{n-1}$ legal sequences of length $n-1$ there are $a_{n-3}$ that start with $12$.  Therefore
$$
a_n=3a_{n-1}-a_{n-3}.
$$


Q:

Car stumbles and stalls after adding fuel additive

I have recently replaced the fuel filter and added a fuel additive of my Cayenne, both are bought from Porsche company, but the very next day I drove my car and it starts to stumble and stalls. Would this be a clogged injectors and how can I resolve the issue?

A:

There are a few potential issues as far as I can see. I'm drawing from my own experience with fuel systems and from a few of the comments.
First, is/was your tank full when you put in the fuel additive? Fuel additives should always be mixed into a full tank of gas. The best way to add it is have a half tank, add the additive, then top the tank up. You need to have it diluted by the gas. If you indeed have less than half a tank, try filling it all the way up to make sure the additive is diluted and mixed in with the fuel.
Next, double check all of the connections you fiddled with. Check that your connections are fuel-tight, and that none of the hoses accidentally got holes in them. Even a small bit of air or fuel leakage can cause major problems. I know you said you checked them, but check again.
Finally, make sure your fuel filter is the right way around. They only work in one direction, so make sure that it is oriented correctly.
Hope this helps!


Q:

URLImage not always loading

When using URLImage with my code without the line Label lb=new Image(img) I'm only lucky to get the image from webserver from time to time (no request is sent looking in network monitor). When I have this 'false' label I get the image everytime.
Is'nt there a way I can make sure image is loaded every time without this false label?
And a bonus question: is there a way to see when picture have been loaded? or an event for it?
My code:
        ryd_storage("skytteimage", true);
        EncodedImage placeholder = EncodedImage.createFromImage(Image.createImage(CN.getDisplayWidth(),CN.getDisplayWidth(), 0xf0f00000), false);
        URLImage img;
        String hurl="https://frederikssund-bueskydning.dk/medlemmer/profil/" +pc;
        img = URLImage.createToStorage(placeholder, "skytteimage",hurl, URLImage.RESIZE_SCALE_TO_FILL);
        img.fetch();
        Label lb=new Label(img);

A:

URLImage is meant to be seamless. It's fetched with the purpose of showing not with the purpose of download alone and in that regard it would be sub-optimal as it's asynchronous. It doesn't provide any events (again seamlessness is key).
I'm assuming you just want to download an image to storage which can be done with ConnectionRequest:
ConnectionRequest cr = new ConnectionRequest(imageUrl, false);
cr.downloadImageToStorage(imageStorageFileName, img -> {
    // you will get an img object here and it's cached in the file system
});


Q:

PHP-CRUD-API - best way for authentication

I'm using PHP-CRUD-API and everything works perfectly. I'm thinking about simple in use authentication, what are your refering? I'm front-end dev, so I'm looking very easy to implementation script.

A:

Take a look at PHP-API-AUTH, it is a "Single file PHP script that adds authentication to a PHP-CRUD-API project". It does exactly what you ask for.
Disclaimer: I'm the author of PHP-CRUD-API.


Q:

How to get Redis to start on Heroku?

I've added the Redistogo nano add-on on Heroku and I've tested it out in the console successfully. However when my app tries to connect with Redis I get the following error:
Heroku Log file:
2011-10-12T08:19:50+00:00 app[web.1]: Errno::ECONNREFUSED (Connection refused - Unable to connect to Redis on 127.0.0.1:6379):
2011-10-12T08:19:50+00:00 app[web.1]:   app/controllers/sessions_controller.rb:14:in `create'

Why is it trying to access Redis on localhost?
My Redis.rb in the config/initializers folder has this, which is almost certainly the problem.
#What's pasted below is pasted ad verbatim. I don't know what to change the values to.

uri = URI.parse(ENV["REDISTOGO_URL"])
REDIS = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)

A:

Are you using Resque?  If so, you'll need to tell Resque which Redis to use.
Resque.redis = REDIS

If not, then the code you've posted about is NOT setting your REDIS connection up.

A:

Try this:
heroku config --long | grep REDIS

to see what your REDISTOGO_URL is. You might have set it accidentally.


Q:

Get free disk space of a Windows mount point remotely

Does anyone know of a way to get the free disk space of a Windows mount point on a remote system without using WMI?
For example, GetDiskFreeSpaceEx returns the following values:
C:\ - 29 GB
C:\MountedDir - 50 GB

When run remotely on a Windows 2003 server (orig_server is 2008 R2) it reports the following:
\\orig_server\C$ - 29 GB
\\orig_server\C$\MountedDir - 29 GB

Anyway to get the true space of MountedDir remotely without WMI?
[UPDATE]
I found that if the target server AND the requesting server are both Windows 2008 R2 I get:
\\orig_server\C$ - 29 GB
\\orig_server\C$\MountedDir - 50 GB

Apparently Windows 2008 R2 (only if both are 2008?) fixes this.  Does anyone know of any documentation that confirms this and explains the boundaries of the scenario?

A:

I would guess that the original SMB protocol does not support mount points, when both the server and client is >=NT6, they can use SMB2 which probably why it works correctly when both are Server 2008


Q:

Escaping wildcard file paths perl

I have an array of files:
my @plistFiles = glob('Logs/*/*.plist');

which I need to escape, that will contain '(' and ')' as well as the usual spaces.
Here is one of the file paths @plistFiles will return:
Logs/Run 1 (13)/Automation Results.plist

I currently have this code for escaping spaces in file paths which I pass to a command in the Terminal in OSX:
$plistFile =~ s/\ /\\\ /g;

So how can I edit this regex to also escape ( and )?
Would this be correct just for escaping ( and )?:
$plistFile =~ s/\(\d)/\\\(\d\\\)/g;

A:

To convert e.g. (13) to \(13\), you could write:
$plistFile =~ s/ /\\ /g;
$plistFile =~ s/\((\d+)\)/\\($1\\)/g;

But I think you're probably better off just escaping all instances of ( and ), whether or not they surround numbers:
$plistFile =~ s/([ ()])/\\$1/g;


Q:

Setting limits over and under the integrals in an entire group

Is there a command to print the integration limits over and under the integral symbols in an entire group / the entire document without writing \int\limits every time? That is, i'd like to be able to write
{\mysterycommand
    \int_a^b (f + g) = \int_a^b f + \int_a^b g
}

instead of
\int\limits_a^b (f + g) = \int\limits_a^b f + \int\limits_a^b g

A:

With amsmath it's easy to get all integrals with limits above and below (which I wouldn't recommend, though):
\documentclass{article}
\usepackage[intlimits]{amsmath}

\begin{document}

\[
\int_a^b (f + g) = \int_a^b f + \int_a^b g
\]

\end{document}

Your \misterycommand can be defined easily:
\documentclass{article}
\usepackage{amsmath}

\makeatletter
\newcommand\mysterycommand{\let\ilimits@\displaylimits}
\makeatother

\begin{document}

No limits:
\[
\int_a^b (f + g) = \int_a^b f + \int_a^b g
\]
Limits:
\[\mysterycommand
\int_a^b (f + g) = \int_a^b f + \int_a^b g
\]

\end{document}

Now that you see the result, I hope you understand why limits are usually set on the side.


Q:

Finding value in one data.frame and transfering value from other column

I don't know if I will be able to explain it correctly but what I want to achieve really simple.
That's first data.frame. The important value for me is in first column "V1"
    > dput(Data1)
structure(list(V1 = c(10L, 5L, 3L, 9L, 1L, 2L, 6L, 4L, 8L, 7L
), V2 = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "NA", class = "factor"),
    V3 = c(18L, 17L, 13L, 20L, 15L, 12L, 16L, 11L, 14L, 19L)), .Names = c("V1",
"V2", "V3"), row.names = c(NA, -10L), class = "data.frame")

Second data.frame:
   > dput(Data2)
structure(list(Names = c(9L, 10L, 6L, 4L, 2L, 7L, 5L, 3L, 1L,
8L), Herat = c(30L, 29L, 21L, 25L, 24L, 22L, 28L, 27L, 23L, 26L
), Grobpel = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L), .Label = "NA", class = "factor"), Hassynch = c(19L, 12L,
15L, 20L, 11L, 13L, 14L, 16L, 18L, 17L)), .Names = c("Names",
"Herat", "Grobpel", "Hassynch"), row.names = c(NA, -10L), class = "data.frame"

)

The value from first data.frame can be find in 1st column and I would like to copy the value from 4 column (Hassynch) and put it in the second column in first data.frame.
How to do it in the fastest way ?

A:

library(dplyr)
left_join(Data1, Data2, by=c("V1"="Names"))
#    V1 V2 V3 Herat Grobpel Hassynch
# 1  10 NA 18    29      NA       12
# 2   5 NA 17    28      NA       14
# 3   3 NA 13    27      NA       16
# 4   9 NA 20    30      NA       19
# 5   1 NA 15    23      NA       18
# 6   2 NA 12    24      NA       11
# 7   6 NA 16    21      NA       15
# 8   4 NA 11    25      NA       20
# 9   8 NA 14    26      NA       17
# 10  7 NA 19    22      NA       13

# if you don't want V2 and V3, you could
left_join(Data1, Data2, by=c("V1"="Names")) %>%
  select(-V2, -V3)
#    V1 Herat Grobpel Hassynch
# 1  10    29      NA       12
# 2   5    28      NA       14
# 3   3    27      NA       16
# 4   9    30      NA       19
# 5   1    23      NA       18
# 6   2    24      NA       11
# 7   6    21      NA       15
# 8   4    25      NA       20
# 9   8    26      NA       17
# 10  7    22      NA       13


Q:

Run/Debug it:test from intellij

Does anybody know if it is possible to run and debug activator it:test from intellij? Especially the debugging of the tests would save me a lost of time developing them.
it:test can AFAIK only be run with the activator command, which I cannot call using intellij run configuration.

A:

You can create an "SBT Task" run configuration from IntelliJ that calls the it:test task. You can run and debug this normally.

If you have the setting fork in IntegrationTest := true it is a little more complicated. You will also need to add debug settings to the javaOptions in sbt; for example:
javaOptions += "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005"

and in IntelliJ create a Remote run configuration that attaches to the port you configured in sbt:

You can now run the sbt task and then run the remote config for debugging.


Q:

Track currentTime with Audio file in Progress bar/element (Angular 4)

So I am making a music player. When a user clicks on a song, I would like a progress bar to visualize where the current time is on the audio file. This is what i have so far:
HTML (player.component.html)
<progress value="{{songTime}}" max="100"></progress>

Typescript (player.component.ts)
paused: boolean = true;
  songInfo: any = "lol";
  songFile: any = "";
  songTime: any = "";
  audio = new Audio();

  playSong(){
    this.audio.src = this.songFile;
    this.audio.play();
    this.songTime = this.audio.currentTime;
    console.log(this.songTime)
    this.paused = false;
  }

This console.log returns the value of 0 which is the current time when you start each song.
I am trying to, I guess, dynamically change that value as the song progresses and have that reflect visually in the progress bar.

A:

You just need to add a timeupdate event listener to the audio player.
this.audio.addEventListener("timeupdate", (currentTime)=>{
// Code to update progress bar goes here
});


Q:

How to fix flexmojos: Type was not found - UncaughtErrorEvent (Flex 4.1)

I'm using flexmojos 3.8 with flex compiler 4.1.0.16248
My Project compiles fine in Flash Builder, but with flexmojos / maven I get the following Error:
Type was not found or was not a compile-time constant: UncaughtErrorEvent

The Flex Code looks like this:
loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onUncaughtError);

The Flex Compiler 4.1 should know the type UncaughtErrorEvent -  Why does it fail?

A:

Found the Solution:
flexmojos mailing list
<dependency>
  <groupId>com.adobe.flex.framework</groupId>
  <artifactId>flex-framework</artifactId>
  <version>${flex.version}</version>
  <type>pom</type>
  <exclusions>
    <exclusion>
      <groupId>com.adobe.flex.framework</groupId>
      <artifactId>playerglobal</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>com.adobe.flex.framework</groupId>
  <artifactId>playerglobal</artifactId>
  <version>${flex.version}</version>
  <classifier>10.1</classifier>
  <type>swc</type>
</dependency>
<plugin>
    <groupId>org.sonatype.flexmojos</groupId>
    <artifactId>flexmojos-maven-plugin</artifactId>
    <extensions>true</extensions>
    <configuration>
        ...
        <targetPlayer>10.1</targetPlayer>
        ...
    </configuration>
</plugin>


Q:

Time dependent workflow should not fire after criteria field changed

I've two field Date and a Picklist field Named Status with value;Active,Inactive,Pending.
I've written a time based workflow rule .
Evaluation Criteria: Evaluate the rule when a record is created, and any time it's edited to subsequently meet criteria.(because it should not fire after changing the other data)
Criteria: Status = Active
Action :fire email 1 hr before Date.
now when criteria matched, workflow fired and action will be in the Queue and it will fire at 1 hr before scheduled date. Its working fine.
The requirement is, when action will in queue and in mean time when I've changed the Status field to Inactive then action should not be fired. because record is not active.
Please suggest the workaround. thanks.

A:

As per Salesforce docs

Example: Consider two rules that are identical, except the evaluation
  criteria of Rule 1 is "On create only" and Rule 2 is "When a record is
  created, and anytime it's edited to subsequently meet criteria." If
  you create a record that matches both rules, Salesforce executes the
  immediate actions and queues the time-dependent actions of both rules.
  If you then update the record and it no longer meets the rule
  criteria, Salesforce removes the pending actions for both rules. If
  you then update the record so it meets the rule criteria again,
  Salesforce only executes the actions associated with Rule 2.

So if your record doesn't match the criteria salesforce remove that action so you don't need to do anything.
Reference


Q:

How to edit DefualtTableCellRenderer in Java?

I am having a problem with editing the DefaultTableCellRenderer.
I would like to right align just the 2nd column in my table. However, the code below  right aligns all the columns, and not just the 2nd one!
Can anyone see where I am going wrong?
for (int i=0; i < tblMenu.getModel().getColumnCount(); i++)
{
    DefaultTableCellRenderer renderer =
        (DefaultTableCellRenderer) tblMenu.getCellRenderer(i, 1);

    renderer.setHorizontalAlignment(JTextField.RIGHT);
}

A:

You can override the default renderer on your table with an anonymous inner class.  Something like the following (untested) code might work:
table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            if (column == 2) {
                setHorizontalAlignment(JTextField.RIGHT);
            }
            return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        }

    });


Q:

POST to PHP from different HTML files using AJAX?

I have 3 HTML file that I am using to upload the pictures to a specific folder and sub folder. The problem that I am facing is when I POST from 1st and 2nd HTML page I can move the image to the specific folder and sub-folder but as soon as I POST the FILE from the 3rd HTML, it gives me a success alert but the image is not uploaded. Below are the codes.
PHP:
 if(isset($_POST))
{
    session_start();
    //The target location for the image to be stored.
    $_SESSION['str'];
    $_SESSION['str1'];
    $_SESSION['str2'];
    //To rename the file
    $_SESSION['img'];
    $_SESSION['img1'];
    $_SESSION['img2'];

     //1st IF statement
     if(!empty($_FILES["info_file"]["name"])){

     move_uploaded_file($_FILES['info_file']['tmp_name'], $_SESSION['str'].$_SESSION['img']);

    }
    else
        {
        //2nd IF statement
        if(!empty($_FILES["info_file1"]["name"])){
            move_uploaded_file($_FILES['info_file1']['tmp_name'], $_SESSION['str1'].$_SESSION['img1']);
        }
        else
        {
            if(!empty($_FILES["info_file2"]["name"]))
            {
            move_uploaded_file($_FILES['info_file2']['tmp_name'], $_SESSION['str2'].$_SESSION['img2']);
            }
        }
        }
}

HTMLs:
1st.

SMArt-InterAct

相片上載

  <form enctype="multipart/form-data" id="form" method="POST">
     <input type="file" required id="imageid" name="image" onChange="readURL(this);" />

     <input type="button" class="test" value="上傳"/>
  </form>

A:

I found the answer myself for this question. Just posting the if-else part and not the whole code.
 //1st IF statement
           if(!empty($_FILES["info_file"]["name"]))
      {
         move_uploaded_file($_FILES['info_file']['tmp_name'], $_SESSION['str'].$_SESSION['img']);
         echo "$asd";
     }
         if (!empty($_FILES["info_file1"]["name"])){
                move_uploaded_file($_FILES['info_file1']['tmp_name'], $_SESSION['str1'].$_SESSION['img1']);
            echo "$asd1";
            }

      if(empty($_FILES["info_file"]["name"]) || empty($_FILES["info_file1"]["name"]) ){

   move_uploaded_file($_FILES['info_file2']['tmp_name'], $_SESSION['str2'].$_SESSION['img2']);


Q:

Print array values based in sorting list and ascending order

Please your help. I have the array "values" that I want to sort by 2 conditions.
First condition: Using the sort list defined in array "sortlist".
Second condition: From smallest to largest.
With my current script I've been able to print the values in correct order for first condition (sort list), but I don't have an idea how to apply the second sorting condition (smallest to largest).
ruby -e'
values = [ "Ghu_1","Prw_1","Prw_3","Prw_5","Vep_3","Hom_2","Vep_1","Hom_1","Prw_2","Vep_2","Prw_4" ]
sortlist = [ "Hom","Vep","Ghu","Prw" ]

sortlist.each{ |s|
 values.each{ |v|
     puts v if v.include?(s)
 }
}'

Current Ouput  #  Desired output
   Hom_2       #      Hom_1
   Hom_1       #      Hom_2
   Vep_3       #      Vep_1
   Vep_1       #      Vep_2
   Vep_2       #      Vep_3
   Ghu_1       #      Ghu_1
   Prw_1       #      Prw_1
   Prw_3       #      Prw_2
   Prw_5       #      Prw_3
   Prw_2       #      Prw_4
   Prw_4       #      Prw_5

UPDATE
Thank Sebastian. Excellent.
It almost work since I noticed that if the characters after "_" are not numbers the second sort is not correct. For example below output is incorrect for values of Pwr_XXX
 ruby -e'
 values = [ "Ghu_Klca","Prw_Rkdg","Prw_Ceteu","Prw_Eriir","Vep_Msas23","Hom_Ttgr5","Vep_Qsccas","Hom_Ftjh","Prw_jpolq","Vep_Szbqh","Prw_Lmnajh" ]
 sortlist = [ "Hom","Vep","Ghu","Prw" ]

 puts sortlist.flat_map{ |s|
   values.select{ |v|
     v if v.include?(s)
   }.sort
 }'

2nd Update
I mean that the first sort is based on sortlist array. The second sort is ascending based in characters after "_". In this case the firt letter for Prw values are
C, E, j, L and R. But the current output is C, E, L, R and j. So, j is at the end and should be after L. I hope make sense.
Current output        Expected output
Hom_Ftjh          #      Hom_Ftjh
Hom_Ttgr5         #      Hom_Ttgr5
Vep_Msas23        #      Vep_Msas23
Vep_Qsccas        #      Vep_Qsccas
Vep_Szbqh         #      Vep_Szbqh
Ghu_Klca          #      Ghu_Klca
Prw_Ceteu         #      Prw_Ceteu
Prw_Eriir         #      Prw_Eriir
Prw_Lmnajh        #      Prw_jpolq
Prw_Rkdg          #      Prw_Lmnajh
Prw_jpolq         #      Prw_Rkdg

A:

Looking at your code, what you could do is to create an empty array, and then inside your values.each iteration, to push each element to your empty array if that element include the element from the sortlist
new_list = []
sortlist.each{ |s|
  values.each{ |v|
    new_list << v if v.include?(s)
  }
}

Then use group_by to group them by its first character:
p new_list.group_by{|e| e[0]}
# => {"H"=>["Hom_2", "Hom_1"], "V"=>["Vep_3", "Vep_1", "Vep_2"], "G"=>["Ghu_1"], "P"=>["Prw_1", "Prw_3", "Prw_5", "Prw_2", "Prw_4"]}

Then use flat_map to get a "plain" array with all your values, but inside the iteration sort each values for each key in the hash:
p new_list.group_by{|e| e[0]}.flat_map{|_,v| v.sort}
# => ["Hom_1", "Hom_2", "Vep_1", "Vep_2", "Vep_3", "Ghu_1", "Prw_1", "Prw_2", "Prw_3", "Prw_4", "Prw_5"]

Or a flat_map, select and sort_by combination (2nd update):
values = [ "Ghu_Klca","Prw_Rkdg","Prw_Ceteu","Prw_Eriir","Vep_Msas23","Hom_Ttgr5","Vep_Qsccas","Hom_Ftjh","Prw_jpolq","Vep_Szbqh","Prw_Lmnajh" ]
sortlist = [ "Hom","Vep","Ghu","Prw" ]

p sortlist.flat_map{ |s|
  values.select{ |v|
    v if v.include?(s)
  }.sort_by(&:downcase)
}
# => ["Hom_Ftjh", "Hom_Ttgr5", "Vep_Msas23", "Vep_Qsccas", "Vep_Szbqh", "Ghu_Klca", "Prw_Ceteu", "Prw_Eriir", "Prw_jpolq", "Prw_Lmnajh", "Prw_Rkdg"]

Use sort_by(&:downcase) to "ignore" case when sorting.


Q:

JSON Parser returning null for fieldname

I have the following code and when I run it with a valid JSON,it returns null for fieldname.
I have been scratching my head over this for hours now.
    JsonFactory jFactory=new JsonFactory();
    JsonParser parser=jFactory.createJsonParser(bytes);

    while (parser.nextToken() != JsonToken.END_OBJECT) {
        String field_name=parser.getCurrentName();
        System.out.println("fieldName: "+field_name);
        parser.nextToken();
        if(field_name.equals("value")){
            System.out.println("value found");
            data=parser.getBinaryValue();
            out.write(new String(data));
        }//if
    }//while
    parser.close();

JSON sample:
      {
     "mimetype" : "text/plain",
     "value" : "c2FzCg=="
      }

A:

You are almost there. You just need a nextToken before the while structure, in order to skip the JsonToken.START_OBJECT.
Like this:
parser.nextToken();
while (parser.nextToken() != JsonToken.END_OBJECT) {


Q:

Interrupt a GET request from a Website

im working on a Website where you can browse through images rapidly by pressing a key, so i've got the Javascript and everything set up (It simply rewrites a div with .innerHTML to display a new image)
However, if you press the key a few times, it loads up each image even if its not required anymore. This delays the loading of the image the user actually wants to see, so the site slows down (and traffic is used inefficiently etc etc)
It looks like this in the Chrome inspector:
http://i.stack.imgur.com/IkzEC.png
While it could actually cut off the current GET operator because the old image isn't required anymore.
Is there any way to interrupt it? If possible without using a completely different technic to load the images up (AJAX)
Thanks in advance!
Edit: Crazy Train's idea with iframes works! Thank you!

A:

You could use this snippet to cancel a request:
try {
    window.stop();
} catch(e) {
    document.execCommand('Stop');
}

Another safety trick you might want to pull is to trigger the request after a few milliseconds.
Update: XMLHttpRequest has abort method. Call it before sending a new request.abort