text:
Q: How can I speed up a MySQL restore from a dump file? I am restoring a 30GB database from a mysqldump file to an empty database on a new server. When running the SQL from the dump file, the restore starts very quickly and then starts to get slower and slower. Individual inserts are now taking 15+ seconds. The tables are mostly  MyISAM with one small InnoDB. The server has no other active connections. SHOW PROCESSLIST; only shows the insert from the restore (and the show processlist itself).
Does anyone have any ideas what could be causing the dramatic slowdown?
Are there any MySQL variables that I can change to speed the restore while it is progressing?

A: This link shows what one can do to speed up restoring process.
http://dev.mysql.com/doc/refman/5.5/en/optimizing-innodb-bulk-data-loading.html
One can put put the commands at the top of the dump file
SET @OLD_AUTOCOMMIT=@@AUTOCOMMIT, AUTOCOMMIT = 0;
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS = 0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS = 0;

And put these statements at the end of the dump file
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
SET AUTOCOMMIT = @OLD_AUTOCOMMIT;
COMMIT;

This worked for me. Happy restoring :-)

A: One thing that may be slowing the process is the key_buffer_size, which is the size of the buffer used for index blocks. Tune this to at least 30% of your RAM or the re-indexing process will probably be too slow.
For reference, if you were using InnoDB and foreign keys, you could also disable foreign key checks and re-enable it at the end (using SET FOREIGN_KEY_CHECKS=0 and SET FOREIGN_KEY_CHECKS=1).

A: If you have the physical copy of the dump file (the DB directory), you can just copy it to the new server if the new server have the same MySQL version and it will work fine. This work fine with MyISAM and for me I think it is better than restoring the data based on the logical SQL dump file.

A: This will do:
mysql --init-command="SET SESSION FOREIGN_KEY_CHECKS=0;SET UNIQUE_CHECKS=0;" -u root -p < Backup_Database.mysql

A: if you have multiple tables chances are you might benefit from mk-parallel-restore.

A: The only reason I can image why the restore would gradually slow down is indexing. Investigate turning off indexing until the end and then let it do the whole lot at once.

A: I suggested you ,

*

*Check your tables: Do it has triggers? Clear all triggers

*SET: AUTOCOMMIT=0, UNIQUE_CHECKS=0, FOREIGN_KEY_CHECKS=0 (AND DON'T FORGET TO ROLLBACK THIS CHANGES)

*USE COMMAND LINE LIKE mysql -u  root -pPasss requests < mydb.sql

*Check your database file size

Good Luck


text:
Q: Get complete Map from Redis if a key contains a String I am able to add and get a particular user object from Redis I am adding object like this:
 private static final String USER_PREFIX = ":USER:";
 public void addUserToRedis(String serverName,User user) {
    redisTemplate.opsForHash().put(serverName + USER_PREFIX + user.getId(),
   Integer.toString(user.getId()),user);
    }

If a userId is 100 I am able to get by key: SERVER1:USER:100
Now I want to retrieve all Users as Map<String,List<User>> ,
For example, get all users by this key SERVER1:USER: Is it possible ? Or I need to modify my addUserToRedis method? Please suggest me.

A: I would recommend not using the "KEYS" command in production as this can severely impact REDIS latencies (can even bring down the cluster if you have a large number of keys stored)

Instead, you would want to use a different command than plain GET/SET.

It would be better if you use a Sets or Hashes
127.0.0.1:6379> sadd server1 user1 user2
(integer) 2
127.0.0.1:6379> smembers server1
1) "user2"
2) "user1"
127.0.0.1:6379>

Using sets you can simply add your users to server keys and get the entire list of users on a server.

If you really need a map of < server, list < users > > you can use hashes with stringified user data and then convert it to actual User POJO at application layer
127.0.0.1:6379> hset server2 user11 name
(integer) 1
127.0.0.1:6379> hset server2 user13 name
(integer) 1
127.0.0.1:6379> hgetall server2
1) "user11"
2) "name"
3) "user13"
4) "name"
127.0.0.1:6379>

Also do note that keeping this much big data into a single key is not an ideal thing to do.

A: Finally I came up with this solution with wildcard search and avoiding KEYS, and here is my complete method:
  public Map<String, User> getUserMapFromRedis(String serverName){
    Map<String, User> users=new HashMap<>();
     RedisConnection redisConnection = null;
     try {
            redisConnection = redisTemplate.getConnectionFactory().getConnection();
           ScanOptions options = ScanOptions.scanOptions().match(serverName + USER_PREFIX+"*").build();
           Cursor<byte[]> scan = redisConnection.scan(options);
           while (scan.hasNext()) {
           byte[] next = scan.next();
           String key = new String(next, StandardCharsets.UTF_8);
           String[] keyArray=key.split(":");
           String userId=keyArray[2];
           User user=//get User by userId From Redis
           users.put(userId, user);
           }
           try {
           scan.close();
      } catch (IOException e) {

      }
       }finally {
       redisConnection.close(); //Ensure closing this connection.
       }
     return users;
    }

A: i dont use java but here's how to use SCAN
const Redis = require('ioredis')
const redis = new Redis()

async function main() {
    const stream = redis.scanStream({
        match: "*:user:*",
        count: 100,
    })

    stream.on("data", (resultKeys) => {
        for (let i = 0; i < resultKeys.length; i++) {
            // console.log(resultKeys[i])
            // do your things here
        }
    });
    stream.on("end", () => {
        console.log("all keys have been visited");
    });
}

main()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Play has removed my app, but I can't find the offending lines in the Manifest? Sorry if this isn't the right place to post this, I don't find myself in this part of the internet very often haha.
So awhile back Google sent out those emails regarding apps being taken down if they use certain permissions relating to calls and SMS usage. I may have ignored said emails for a bit too long, and well, here we are.
The problem is, I'm not by any means a good programmer, especially with Java. Long story short, the only places I can find the offending lines is in the manifest class file, which of course I can't change. I don't see them in the xml file.
Is there a different place I should be looking, generally speaking? The code is a bit hacky and most of it was already written when I got ahold of it, which is why I'm hoping someone can kind of just point me in the right direction if nothing else.
In the email I received, the specific permissions were READ_CALL_LOG and WRITE_CALL_LOG. The only thing that would be remotely related (that I can find) is read_contacts.
Responses are appreciated!

A: If you can't find them in the AndroidManifest.xml file then chances are the permission is coming from a 3rd party library you use.
There's a whole page of documentation here on how this works in Android Studio. If you want to see where the permissions came from, the docs say how to do this:

Even before you build your APK, you can see a preview of what your merged manifest looks by opening your AndroidManifest.xml file in Android Studio, and then clicking the Merged Manifest tab at the bottom of the editor.
The Merged Manifest view shows the results of the merged manifest on the left and information about each merged manifest file on the right, as shown in figure 2. The elements that were merged in from lower-priority manifest files are highlighted in different colors on the left. The key for each color is specified under Manifest Sources on the right.


text:
Q: Will Xampp affect by log4j? We have installed Xampp in D Drive at windows server 2016 suddenly that Drive changed its format from NTFS to RAW..
System admin suspect that it will affected by log4j due to the usage of apache service so that only Drives are encrypted.. But We were not use any log4j in our server because we use php and mysql..
Can anyone help me with this issue?

A: Just did a quick check on this and although log4j is part of the Apache foundation, Apache httpd is not written in Java so it does not include log4j. As far as I'm aware, none of the XAMPP components are written in Java.


text:
Q: difficult to do sth / passive voice I have some doubts about the following issue. Let's say that we have a sentence:

It's difficult to perform the calculations.

Now, I want to make "the calculations" the subject of this sentence, so I write:

(1) The calculations are difficult to be preformed.

But is it correct not to use the passive voice? Something like that:

(2) The calculations are difficult to preform.

I thought that the passive is mandatory in such cases, but then I saw the following example from Cambridge Dictionary:

This meat is difficult to chew.

So, it isn't fully clear to me how to use it correctly. I would write something more like

This meat is difficult to be chewed.

Could anyone comment on that issue?

A: Clarifying the Meaning of a Passive Verb.
I perform calculations. Calculations are difficult to perform.
The calculations are performed by me. [passive]. The second sentence cannot be made into a passive. You need an action verb, not a adjectival phrase. "are difficult" cannot be made into a passive.
You need a subject + an action verb at the very least.
Active Sentence: He makes pies. Passive Sentence: The pies are made by him.
The computer performs calculations.
Calculations are performed by the computer.
You take the object and add "is" or "are" plus the past participle of the action verb then by plus the person or thing.
For example:
Active Sentence:
They draw pictures.
"pictures" are the object.
"are drawn" is the verb.
"by them" is the agent.
Passive sentence:
Pictures are drawn by them.


text:
Q: Inner join with of 3 tables I have three tables which I am trying to join using the sample in this question. However I am getting below error.
Error:
#1054 - Unknown column 'referrer.Referrer_Name' in 'field list'

Code:
    SELECT pupils.Pupils_Surname,
            pupils.Pupils_FirstName,
            referrer.Referrer_Name,
            progress_track.test_1,
            progress_track.test_2,
            progress_track.test_3,
            progress_track.test_4,
            progress_track.test_5,
            progress_track.test_6,
            progress_track.test_7,
            progress_track.test_8,
            progress_track.test_9,
            progress_track.test_10
    FROM pupils
    INNER JOIN progress_track ON progress_track.Progress_Report_Pupils_ID=pupils.Pupils_ID;
    INNER JOIN referrer ON  pupils.Pupils_Referrer, referrer.Referrer_ID ;

A: Please remove the semicolon at the end of the first inner join statement. Because, the query is tried to terminate the statement after the first semicolon of the query itself. So, this is the reason for the column Referrer_Name is not referring the table:"referrer".
original:

FROM pupils
      INNER JOIN progress_track ON progress_track.Progress_Report_Pupils_ID=pupils.Pupils_ID;
      INNER JOIN referrer ON  pupils.Pupils_Referrer, referrer.Referrer_ID ;

Use this:

FROM pupils
      INNER JOIN progress_track ON progress_track.Progress_Report_Pupils_ID=pupils.Pupils_ID
      INNER JOIN referrer ON  pupils.Pupils_Referrer = referrer.Referrer_ID ;

A: First let me highlight the faults in your query:
1) The query ended unexpectedly for a typo
2) The last INNER JOIN contained syntax error.
I've highlighted the faults in the image given below:

Remedy:
SELECT
    pupils.Pupils_Surname,
    pupils.Pupils_FirstName,
    referrer.Referrer_Name,
    progress_track.test_1,
    progress_track.test_2,
    progress_track.test_3,
    progress_track.test_4,
    progress_track.test_5,
    progress_track.test_6,
    progress_track.test_7,
    progress_track.test_8,
    progress_track.test_9,
    progress_track.test_10
FROM
    pupils
INNER JOIN progress_track ON progress_track.Progress_Report_Pupils_ID = pupils.Pupils_ID
INNER JOIN referrer ON pupils.Pupils_Referrer = referrer.Referrer_ID;

In response to your comment:

Could you please post this as an answer. It worked but it still did
  not show any data from the referrer table

*

*If the join condition doesn't meet then there's no way you can see
data unless you use LEFT JOIN. Please check your data first.

*Please ensure that you have data which meets these two conditions :
progress_track.Progress_Report_Pupils_ID = pupils.Pupils_ID
referrer.Referrer_ID = pupils.Pupils_Referrer


text: Q: How to use Visual Studio to view/navigate asp.net core source code? Currently if you press F12/go to definition, it will show metadata without acutal implementions. I know we can go to Github to view the source code but it is hard to navigate source code in browser. I can also use debugging with some required setting to view the source code in VS, but I don't want to use debug mode to view source code as I need to run the project, I just want to press F12 to see the source code, is a way to achieve this?


text:
Q: Can I assign Vue.js data property to a local variable along with it's setter? Please see this minimum example:
<template>
  <div>
    {{ count }}
    <button @click="click">Click</button>
  </div>
</template>

<script>

export default {
  data() {
    return {
      count: 0
    }
  },
  methods: {
    click() {
      this.count++
    }
  }
};
</script>

I have a count data property and a button that will increase the count.
Now, I want to do this a little differently like this(for some reason)
click() {
  let count = this.count
  count += 1
}

I want to assign my data property to my local variable first, and then increase the local variable count, and hopefully, triggers Vue's reactivity.
I know Vue use Object.defineProperty's setter to data property, how can I clone those setters?
Is it possible to do this?
Update
What I want to do is trying to simplify below code
<script lang="ts">
export default {
  data() {
    return {
      isALoading: false,
      isBLoading: false
    };
  },
  methods: {
    hitAPI(type: "A" | "B") {
      if (type === "A") {
        this.isALoading = true;
        fetch(someAPI)
          .then(() => {
            this.isALoading = false;
          })
          .catch(() => {
            this.isALoading = false;
          });
      } else {
        this.isBLoading = true;
        fetch(someAPI)
          .then(() => {
            this.isBLoading = false;
          })
          .catch(() => {
            this.isBLoading = false;
          });
      }
    }
  }
};
</script>

A: It's not possible to "copy" a setter like that into a local variable.
You can abstract the property behind a method or another object with its own setter:
click() {
  const self = this
  const wrapper = {
    get count() { return self.count },
    set count(x) { self.count = x }
  }

  wrapper.count++
}

I sense this is an XY problem; why do you want to do this? What are you trying to achieve?
You are best to just reassign back the local variable to the data property to trigger the update:
click() {
  let count = this.count

  // Modify local var
  count++

  // Assign back to trigger the update
  this.count = count
}

UPDATE
You can dynamically access the property by its string name:
hitAPI(type: "A" | "B") {
  const prop = type === "A" ? "isALoading" : "isBLoading"
  this[prop] = true

  fetch(someAPI).finally(() => {
    this[prop] = false
  })
}

Alternatively with async/await:
async hitAPI(type: "A" | "B") {
  const prop = type === "A" ? "isALoading" : "isBLoading"
  this[prop] = true

  try {
    await fetch(someAPI)
  } finally {
    this[prop] = false
  }
}


text:
Q: multiprocessing nested for I'm currently trying to get a result out of the process showed below. However, it is taking too long for the number of steps needed. I would like to speed up the result.
How can I implement multiprocessing for this situation?
Within the class I am building, I have the following definition
    def class_corr(self,Delta,xi_q,Q,counter):
        to = self.t
        npts = 512
        x0 = 12
        dx =2*x0/npts
        norm=0
        classic=0
        for n in range(0,npts+1):
            qi = -x0+n*dx
            for m in range(0,npts+1):
                pj = -x0+m*dx
                for k in range(0,npts+1):
                    xi_pk = -x0+k*dx
                    f1    += dx**3*wt(qi,pj,qo,po,to)*F(qi,xi_pk,Delta, Q)
                    fn += dx**3*wt(qi,pj,qo,po,to)*G(qi,xi_pk,xi_q,Delta,Q)
        if counter:
            return  [f1, fn/f1]
        return  fn/f1

Is it even reasonable to use multiprocessing?
So far, I have checked these:

*

*Multiprocessing nested python loops

*Python multiprocessing for dummies
but I haven't been able to implement those nor gotten a solution.

A: As I think about it, what you really have here is a dynamic programming style problem. You keep recalculating the same terms. For instance, you only need to calculate dx^3 once, yet you do it npts^3 times. Similarly, you only need to calculate each 3*wt(qi,pj,qo,po,to) term once, but you do it 2*npts times.
Try something like:
def class_corr(self,Delta,xi_q,Q,counter):
    to = self.t
    npts = 512
    x0 = 12
    dx =2*x0/npts
    dx3 = dx**3
    norm=0
    classic=0
    for n in range(0,npts+1):
        qi = -x0+n*dx
        for m in range(0,npts+1):
            pj = -x0+m*dx
            wt_curr = wt(qi,pj,qo,po,to)
            for k in range(0,npts+1):
                xi_pk = -x0+k*dx
                f1 += dx3*wt_curr*F(qi,xi_pk,Delta, Q)
                fn += dx3*wt_curr*G(qi,xi_pk,xi_q,Delta,Q)
    if counter:
        return  [f1, fn/f1]
    return  fn/f1

Additionally, you calculate F & G npts more times than you need to. It looks as though each only varies with qi and xi_pk (xi_q, Delta and Q don't seem to vary in this method). If you tried using some sort of 2-layer defaultdict to record the qi and xi_pk values for which you've already calculated F (or G), you would then save lots of unnecessary calls and calculations of F (or G).
(PS - I know this wasn't the approach you're looking for, but I think it addresses the core of your problem. You're spending a lot of time recalculating terms you've already calculated.)


text:
Q: Play wav file as bytes received from server I am receiving a raw data wave file from server, and I need to play this array of bytes on the client side.
I tried to use decodeAudioData like in this link  but i got the error :

DOMException : Unable to decode Audio data.

It is logical because my raw data is not a regular mp3 file, it is a wave that needs to be played with 8000Hz rate and 1 channel and 16bits per sample.
Is there a function to play a byte array received from server with a certain rate and a number of channels

A: I managed to play the bytes on browser using this method :
function playWave(byteArray) {
    var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    var myAudioBuffer = audioCtx.createBuffer(1, byteArray.length, 8000);
    var nowBuffering = myAudioBuffer.getChannelData(0);
    for (var i = 0; i < byteArray.length; i++) {
        nowBuffering[i] = byteArray[i];
    }

    var source = audioCtx.createBufferSource();
    source.buffer = myAudioBuffer;
    source.connect(audioCtx.destination);
    source.start();
}


text:
Q: Bot can't connect to voice channel - discord.py rewrite I am making a discord bot using the discord.py rewrite and I have recently run into a problem.
I have made a command to join a user's voice channel. The thing is, my command works perfectly fine when I run it on my local PC, but now that I'm trying to run it on a raspberry pi it fails when connecting to the voice channel.
I have tried installing all dependencies but I just can't get it to work.
Code for the command:
@bot.command()
async def join(ctx):
    channel = ctx.message.author.voice.channel
    voice = get(bot.voice_clients, guild=ctx.guild)

    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()

    await ctx.send("I joined the channel!")

There are no exceptions raised.

A: You are using a bad way to connect to the voice channel.
Try using this code.
It identify where the user is and connect in that voice channel.
   @bot.command(name='join', invoke_without_subcommand=True)
    async def join(ctx):
       destination = ctx.author.voice.channel
       if ctx.voice_state.voice:
         await ctx.voice_state.voice.move_to(destination)
         return

       ctx.voice_state.voice = await destination.connect()
       await ctx.send(f"Joined {ctx.author.voice.channel} Voice Channel")

A: You can run pip install -U discord.py[voice] in your terminal. And try using this code.
@bot.command(pass_context = True)
async def join(ctx):
    if (ctx.author.voice):
        await ctx.author.voice.channel.connect()
    else:
        await ctx.send("Please Join Voice channel to run this command")

@client.command()
async def leave(ctx):
    await ctx.voice_client.disconnect()


text:
Q: delete recently getting sms programatically android in pie devices I am using this link to try delete recent sms. This code works fine and it shows sms deleted successfully in logcat but still not deleted from phone.
I am using this code when I am getting otp from broadcastreciever after that I want to delete my otp sms.
Help me I donot know to achieve that.


text:
Q: "odd" expression in PL/0 Given the following EBNF grammar (found on wikipedia for PL/0), what is an expression preceded by the "ODD" keyword?  I would like to implement the simple language as a small project but I can not seem to figure out what this means. Has anyone head of this before or able to interpret what an odd expression is so that I can write a compiler for the language correctly?
program = block "." .

block = [ "const" ident "=" number {"," ident "=" number} ";"]
        [ "var" ident {"," ident} ";"]
        { "procedure" ident ";" block ";" } statement .

statement = [ ident ":=" expression | "call" ident |
            "begin" statement {";" statement } "end" |
            "if" condition "then" statement |
            "while" condition "do" statement ].

condition = "odd" expression |
            expression ("="|"#"|"<"|"<="|">"|">=") expression .

expression = [ "+"|"-"] term { ("+"|"-") term}.

term = factor {("*"|"/") factor}.

factor = ident | number | "(" expression ")".

A: The EBNF grammar indicates via quotation marks that ODD is a sequence of terminal symbols. This is confirmed by the examples following the grammar on the Wikipedia page. Semantically, it appears to be a predicate testing the parity of numeric values.
BEGIN
  a := x;
  b := y;
  z := 0;
  WHILE b > 0 DO BEGIN
    IF ODD b THEN z := z + a;
    a := 2 * a;
    b := b / 2
  END
END;

A: I believe odd is analogous to a function that determines whether the value of the expression that follows it evaluates to an odd or even (integer) value, and returns 'true' when the value is odd.  In C:
bool odd(int exp) { return (exp & 1) != 0; }


text:
Q: how add text in string using sed I have command to find domain name of user which shows correct domain
domain=$(ui $user |grep -oP 'UDomain:.\K.*')
echo $domain

now I want to add domain in command
sed -i '/DB_COLLATE/a \ define('FTP_USER', 'design@$domain');' file.php

how can I do that . When I use above method it gives me error
This command give me error
syntax error near unexpected token `)'


text:
Q: hadoop streaming with anaconda(python) not working I am running a python script with hadoop streaming.
I have both python 2.7 and anaconda installed.
When I run the hadoop stream with python script using
#!/usr/bin/env python
It works fine.
But when I use anaconda
#!/opt/anaconda/python2.7/bin/env python

It doesnt work.
 The MR job fails with below exception.
Caused by: java.io.IOException: Cannot run program "/hdfs1/yarn/nm/usercache/appcache/application_1430001030776_13989/container_e48_14776_1301_000/./mymapper.py": error=2, No such file or directory
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1047)
        at org.apache.hadoop.streaming.PipeMapRed.configure(PipeMapRed.java:209)
        ... 23 more
Caused by: java.io.IOException: error=2, No such file or directory
        at java.lang.UNIXProcess.forkAndExec(Native Method)
        at java.lang.UNIXProcess.<init>(UNIXProcess.java:186)
        at java.lang.ProcessImpl.start(ProcessImpl.java:130)
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1028)

Does this means that I cannot use hadoop streaming with anaconda?

A: This is probably because you don't have #!/opt/anaconda/python2.7/bin/env python installed on each dataNode.
When you use hadoop-streaming only the file mymapper.py is sent to the mappers, not python interpreter.
You can fix this by installing anaconda on each machine from your cluster at /opt/anaconda/python2.7/bin/env.
As you can see using the default python interpreter works because it is  available on each machine from your cluster.


text:
Q: How do I make custom (print) text draggable in Raphael JS 2.0? I recently updated to Raphael JS 2.0 and now my text dragging is laggy.
before (1.5): http://jsfiddle.net/jedateach/vZN72/
after (2.0): http://jsfiddle.net/jedateach/YyvSm/
Perhaps someone can fork my jsfiddle to show how it should be done?

A: In Raphael 2.0, instead of Translate, you should make use of the Transform function, which adds a matrix transformation to the svg element.
Here is an example.
Note that the use of "..." in the transform string will append the previous transformations. If you want to store multiple transformations such as size and rotation, you'll need to store the current values, and exclude "...".


text:
Q: Primefaces5 How to change background color in chart (pure java, no jqplot) I have a chart in Primefaces5 and Works fine, but I need change background color using java code only, no jqplot code.

Default color is light but isn't White and my user wants White color.
Any suggestions will be greatly appreciated. Thanks!
Here my code (fragment):
private void createBarModelsN()
{
    graphic2 = initBarModelN();
    graphic2.setTitle("");

    // Indica la posicion del cuadrito con la leyenda de la serie
    // null indica que no mostrara el cuadrito
    graphic2.setLegendPosition( null );
    graphic2.setShadow( false );
    graphic2.setStacked( isStacked );
    graphic2.setAnimate( true );
    graphic2.setBarMargin( 20 );
    graphic2.setBarPadding( 0 );

    String strSeriesColor = "";
    for(int i=0; i < numeroDeSeries; i++ )
    {
        strSeriesColor += arregloColoresDefault[i];
        if( i < numeroDeSeries - 1 )
        {
            strSeriesColor += ",";
        }
    }
    graphic2.setSeriesColors( strSeriesColor );

    Axis xAxis = graphic2.getAxis(AxisType.X);
    Axis yAxis = graphic2.getAxis(AxisType.Y);

    // Para graficar porcentajes se requiere que el eje Y sea de 0 a 100
    yAxis.setLabel( labelEjeY );
    yAxis.setMax(100);
    yAxis.setMin(0);
    yAxis.setTickAngle( 0 );
    yAxis.setTickCount( 11 );
    yAxis.setTickInterval( "10" );

    xAxis.setMin( getValorMinX());
    xAxis.setMax( getValorMaxX());
    xAxis.setTickInterval( "1" );
    xAxis.setLabel( labelEjeX );

}

private BarChartModel initBarModelN()
{
    BarChartModel model = new BarChartModel();
    // Hago el for para obtener cada una de las series
    for( int i=0; i < series.size(); i++ )
    {
        ChartSeries serieX = new ChartSeries();
        int indexArreglo = 0;
        for( int j=getValorMinX(); j <= getValorMaxX(); j++ )
        {
            if( arregloTempo != null && listNSeries != null && listNSeries.size() >= 1
                &&
                arregloTempo.length == ((ArrayList<Integer>)listNSeries.get(i)).size()
            )
            {
                int valorX = ((ArrayList<Integer>)listNSeries.get(i)).get( indexArreglo );
                int valorXTotal = arregloTempo[ indexArreglo ];
                float valorY = 0.0f;
                if( valorXTotal != 0 )
                {
                    valorY = (valorX / (valorXTotal + 0.0f) ) * 100;
                }
                serieX.set( j , valorY );
            }
            indexArreglo++;
        }
        model.addSeries(serieX);
    }
    return model;
}

A: There's a small change on the solution (provided by jKick on the link) since Primefaces 5.1.
Before Primefaces 5.1 you could do:
<p:lineChart extender="customExtender" value="..." />

From Primefaces 5.1 onwards, chart component was removed in favour of p:chart and extender property now needs to be set on your Java code:
LineChartModel lineChart = new LineChartModel();
lineChart.setExtender("customExtender");

And this is your extender Javascript code:
<script>
   function customExtender () {
      this.cfg.grid = {
         background: '#FFF' //Set background to white
      };
    }
</script>

A: Check this: Similar question about changing jQplot graphs. There is parametar in graph configuration called background: '#fffdf6',      // CSS color spec for background color of grid.
Also there is example how to use it. Good luck.


text:
Q: Binding nested validation rules on nested User Controls This is my first question here on SO...I have been a ready for a long time and never needed to ask for help because I usually find what I need, but I am having a hard time with this one...
I am working on a tools suite in WPF. I created a few User Controls as follow:

*

*LabelTextBox (Label on the left and TextBox on the right)

*LabelTextBoxToggle (LabelTextBox on the left and Checkbox on the right)

*LabelTextBoxBrowseFile (LabelTextBox on the left and Browse File Button on the right)

I use Dependency Properties to bind all the properties I need and they all work fine. The problem I ran into recently is getting ValidationRules to work correctly on the base TextBox I use in LabelTextBox when those rules are applied to the LabelTextBoxToggle and LabelTextBoxBrowseFile UserControls, since I have to bind 2 levels down in order to update controls in LabelTextBox. I can get the Validation Rule to run, but I can't get the TextBox control to update its background color accordingly when errors are found, like I do when LabelTextBox isn't nested within another User Control.
So, here's my code below:
Style used for TextBox:
<!-- TextBox Default Style, Supports Validation Rules -->
<Style TargetType="{x:Type TextBox}">
    <Setter Property="Background" Value="{StaticResource TextBoxBGDefault}" />
    <Style.Triggers>
        <Trigger Property="IsKeyboardFocused" Value="True">
            <Setter Property="Background" Value="{StaticResource TextBoxBGHasFocus}" />
        </Trigger>
        <Trigger Property="IsMouseOver" Value="true">
            <Setter Property="Background" Value="{StaticResource TextBoxBGHasFocus}" />
        </Trigger>
        <DataTrigger Binding="{Binding Path=(Validation.HasError)}" Value="true">
            <Setter Property="Background" Value="{StaticResource TextBoxBGHasError}" />
            <Setter Property="BorderBrush" Value="Firebrick" />
            <Setter Property="BorderThickness" Value="1.5" />
            <Setter Property="ToolTipService.InitialShowDelay" Value="2" />
            <Setter Property="ToolTip" Value="{Binding Path=(Validation.Errors)[0].ErrorContent}" />
        </DataTrigger>

    </Style.Triggers>
</Style>

LabelTextBox.xaml:
<Grid x:Name="LayoutRoot" DataContext="{Binding ElementName=ControlRoot, Mode=OneWay, ValidatesOnDataErrors=True}">
    <Grid.RowDefinitions>
        <RowDefinition Height="24" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>

    <Label
        x:Name="NameLabel"
        Width="{Binding Path=LabelWidth, Converter={StaticResource WidthToAutoConverter}}"
        Margin="0"
        HorizontalAlignment="{Binding Path=HorizontalContentAlignment}"
        HorizontalContentAlignment="{Binding Path=LabelHAlign, Converter={StaticResource valueToStringConverter}}"
        VerticalContentAlignment="Center"
        Content="{Binding Path=LabelContent}"
        Padding="10,2,5,2" />
    <TextBox
        x:Name="ValueTextBox"
        Grid.Column="1"
        KeyDown="TextBox_KeyDown_Enter"
        Padding="5,0"
        Text="{Binding TextBoxContent, Mode=TwoWay}"
        TextChanged="TextBox_TextChanged" VerticalContentAlignment="Center" Height="22" VerticalAlignment="Center" />
    <TextBlock
        x:Name="ErrorMsgTextBlock"
        Grid.Row="1"
        Grid.Column="1"
        Margin="0"
        HorizontalAlignment="Left"
        VerticalAlignment="Top"
        Style="{DynamicResource ValidationErrorLabel}"
        Text="{Binding Path=(Validation.Errors)[0].ErrorContent, ElementName=ControlRoot}"
        Visibility="{Binding Path=(Validation.HasError), Converter={StaticResource BooleanToVisibilityConverter}, ElementName=ControlRoot, Mode=OneWay}" TextWrapping="Wrap" />
</Grid>

LabelTextBoxBaseClass:
#region TextBox Dependency Properties
public string TextBoxContent
{
    get { return (string)GetValue( TextBoxContentProperty ); }
    set { SetValue( TextBoxContentProperty, value ); }
}
public static readonly DependencyProperty TextBoxContentProperty =
    DependencyProperty.Register( "TextBoxContent"
    , typeof( string )
    , typeof( LabelTextBoxBaseClass ), new PropertyMetadata( "" )
);

LabelTextBoxToggle.xaml:
<!-- This is the nested UserControl -->
<local:LabelTextBox
    x:Name="LTBControl"
    Margin="0"
    VerticalContentAlignment="Center"
    IsEnabled="{Binding Path=IsChecked, ElementName=ToggleCheckBox}"
    LabelContent="{Binding Path=LabelContent}"
    LabelHAlign="{Binding Path=LabelHAlign}"
    LabelWidth="{Binding Path=LabelWidth}"
    RaiseEnterKeyDownEvent="{Binding RaiseEnterKeyDownEvent, Mode=TwoWay}"
    RaiseTextChangedEvent="{Binding RaiseTextChangedEvent, Mode=TwoWay}"
    TextBoxContent="{Binding Path=TextBoxContent, Mode=TwoWay}" />
<CheckBox
    x:Name="ToggleCheckBox"
    Grid.Column="1"
    Margin="5,0"
    HorizontalAlignment="Center"
    VerticalAlignment="Center"
    HorizontalContentAlignment="Center"
    VerticalContentAlignment="Center"
    Click="ToggleCheckBox_Click"
    IsChecked="{Binding CheckBoxChecked, Mode=TwoWay}" />

MaterialBuilder.xaml:
<UserControl.Resources>
    <BindingGroup x:Key="SRBindingGroup" Name="PropertiesBindingGroup">
        <BindingGroup.ValidationRules>
            <local:AddMaterialRule ValidationStep="ConvertedProposedValue" />
        </BindingGroup.ValidationRules>
    </BindingGroup>
    <srvalidators:StringNullOrEmptyValidationRule x:Key="stringNullOrEmptyValidationRule" ErrorMessage="Custom Dir cannot be null!" />
    <srconverters:ListToStringConverter x:Key="ListToStringConverter" />
    <srconverters:ListToStringConverter x:Key="listToStringConverter" />
    <sys:String x:Key="newLine">\n</sys:String>
</UserControl.Resources>

<StackPanel x:Name="spSetup">

    <!-- This contains a nested UserControl (LabelTextBox), and I can't get its TextBox background to change color, I just get the red border around the whole control on Validation Errors. -->
    <srcontrols:LabelTextBoxBrowseFile
        x:Name="ltbMaterialBlueprint"
        Height="Auto"
        Margin="0,5"
        LabelContent="Material Blueprint:"
        LabelWidth="120"
        LostFocus="ltbMaterialBlueprint_UpdateUI"
        OnButtonClick="ltbMaterialBlueprint_UpdateUI"
        OnTextBoxEnterKeyDown="ltbMaterialBlueprint_UpdateUI"
        TextBoxContent="{Binding MaterialBlueprintFilePath, Mode=TwoWay}">
        <srcontrols:LabelTextBoxBrowseFile.TextBoxContent>
            <Binding
                Mode="TwoWay"
                Path="CustomDirName"
                UpdateSourceTrigger="PropertyChanged"
                ValidatesOnDataErrors="True">
                <Binding.ValidationRules>
                    <srvalidators:StringNullOrEmptyValidationRule ErrorMessage="Custom Dir cannot be empty!" />
                </Binding.ValidationRules>
            </Binding>
        </srcontrols:LabelTextBoxBrowseFile.TextBoxContent>
    </srcontrols:LabelTextBoxBrowseFile>

    <!-- Here I use the base LabelTextBox control by itself and everything works as intended. The TextBox's background color changes to red on Validation Errors. -->
    <srcontrols:LabelTextBox
        x:Name="ltbMaterialName"
        Margin="0,5,10,5"
        LabelContent="Name:"
        LabelWidth="60"
        OnTextBoxTextChange="ltbMaterialName_Validate"
        RaiseEnterKeyDownEvent="True"
        RaiseTextChangedEvent="True">
        <!--  Set-up the TextBox Content to use the ValidationRule by passing this GroupBox's BindingGroup resource as a parameter  -->
        <srcontrols:LabelTextBox.TextBoxContent>
            <Binding
                Mode="TwoWay"
                Path="MaterialName"
                UpdateSourceTrigger="Explicit"
                ValidatesOnDataErrors="True">
                <Binding.ValidationRules>
                    <local:AddMaterialRule
                    BGroup="{StaticResource SRBindingGroup}"
                    CheckForDuplicates="True"
                    CheckForEmptyName="True"
                    IsMaterialName="True"
                    ValidationStep="ConvertedProposedValue" />
                </Binding.ValidationRules>
            </Binding>
        </srcontrols:LabelTextBox.TextBoxContent>
    </srcontrols:LabelTextBox>
</StackPanel>

I know it's probably a DataContext issue, but unlike the other controls and dependency properties, I cannot figure out how to make the base UserControl ui elements update their look when Validation Errors are found. Here's some images of what I mean:
Working TextBox (LabelTextBox control used here):
Working TextBox Example
Broken TextBox (LabelTextBoxToggle control used here, with nested LabelTextBox):
Broken TextBox (nested in UserControl)
Any help or suggestion is very welcomed of course! Thanks for your time!

A: Your problem is similar to mine. I've also created custom control containing text block (as label) and text box (as input). The goal is to have universal control for data input with simple label. The problem was validation. I've also managed easily to bind and validate data, but displaying errors with template on specified textbox that was inside my control... that was the issue and if I understand correctly you have the same problem. So my solution is:
<UserControl x:Class="CapMachina.Common.Controls.FormField_UC" x:Name="FormFieldCtrl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:CapMachina.Common.Controls"
         xmlns:Converters="clr-namespace:CapMachina.Common.Converters"
         xmlns:metro="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">

<UserControl.Resources>
    <Converters:ConditionalValueConverter x:Key="conditionalValueConverter" />
    <Converters:NullableObjectToVisibilityConverter x:Key="nullableObjectToVisibilityConverter" />
  </UserControl.Resources>
  <StackPanel>
    <TextBlock FontWeight="Bold" Text="{Binding Header, ElementName=FormFieldCtrl}" Margin="1" />
    <TextBox x:Name="MainTxtBx" metro:TextBoxHelper.Watermark="{Binding WaterMarkText, ElementName=FormFieldCtrl}" TextWrapping="Wrap"
             Text="{Binding Text, ElementName=FormFieldCtrl, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"
             Margin="1" IsReadOnly="{Binding IsReadOnly, ElementName=FormFieldCtrl}" TextChanged="MainTxtBx_TextChanged" Loaded="MainTxtBx_Loaded">
      <TextBox.Style>
        <MultiBinding Converter="{StaticResource conditionalValueConverter}">
          <Binding Path="IsReadOnly" ElementName="FormFieldCtrl" />
          <Binding Path="ReadOnlyStyle" ElementName="FormFieldCtrl" />
          <Binding Path="DefaultStyle" ElementName="FormFieldCtrl" />
        </MultiBinding>
      </TextBox.Style>
    </TextBox>
  </StackPanel>
</UserControl>

And code behind:
    using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace CapMachina.Common.Controls
{
  public partial class FormField_UC : UserControl
  {
public string Header
{
  get { return (string)GetValue(HeaderProperty); }
  set { SetValue(HeaderProperty, value); }
}

public static readonly DependencyProperty HeaderProperty =
    DependencyProperty.Register("Header", typeof(string), typeof(FormField_UC));

public string Text
{
  get { return (string)GetValue(TextProperty); }
  set { SetValue(TextProperty, value); }
}

public static readonly DependencyProperty TextProperty =
    DependencyProperty.Register("Text", typeof(string), typeof(FormField_UC));

public string WaterMarkText
{
  get { return (string)GetValue(WaterMarkTextProperty); }
  set { SetValue(WaterMarkTextProperty, value); }
}

public static readonly DependencyProperty WaterMarkTextProperty =
    DependencyProperty.Register("WaterMarkText", typeof(string), typeof(FormField_UC));

public bool IsReadOnly
{
  get { return (bool)GetValue(IsReadOnlyProperty); }
  set { SetValue(IsReadOnlyProperty, value); }
}

public static readonly DependencyProperty IsReadOnlyProperty =
    DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(FormField_UC), new PropertyMetadata(true));

public Style ReadOnlyStyle { get; set; }
public Style DefaultStyle { get; set; }

public FormField_UC()
{
  ReadOnlyStyle = Application.Current.FindResource("ReadOnlyTextBox") as Style;
  DefaultStyle = Application.Current.FindResource("DefaultTextBox") as Style;
  InitializeComponent();
}

private void MainTxtBx_TextChanged(object sender, TextChangedEventArgs e)
{
  if (string.IsNullOrEmpty(MainTxtBx.Text) && IsReadOnly)
    Visibility = Visibility.Collapsed;
  else
    Visibility = Visibility.Visible;
}

private void MainTxtBx_Loaded(object sender, RoutedEventArgs e)
{
  BindingExpression mainTxtBxBinding = BindingOperations.GetBindingExpression(MainTxtBx, TextBox.TextProperty);
  BindingExpression textBinding = BindingOperations.GetBindingExpression(this, TextProperty);

  if (textBinding != null && mainTxtBxBinding != null && textBinding.ParentBinding != null && textBinding.ParentBinding.ValidationRules.Count > 0 && mainTxtBxBinding.ParentBinding.ValidationRules.Count < 1)
  {
    foreach (ValidationRule vRule in textBinding.ParentBinding.ValidationRules)
      mainTxtBxBinding.ParentBinding.ValidationRules.Add(vRule);
  }
    }
  }
}

Usage:
<Controls:FormField_UC Header="First name" IsReadOnly="False" HorizontalAlignment="Left" VerticalAlignment="Top">
  <Controls:FormField_UC.Text>
    <Binding Path="Person.FirstName" Mode="TwoWay">
      <Binding.ValidationRules>
        <VDRules:NamesValidationRule InventoryPattern="{StaticResource NamesRegex}">
          <VDRules:NamesValidationRule.Attributes>
            <Validation:ValidationAttributes IsRequired="True" />
          </VDRules:NamesValidationRule.Attributes>
        </VDRules:NamesValidationRule>
      </Binding.ValidationRules>
    </Binding>
  </Controls:FormField_UC.Text>
</Controls:FormField_UC>

What i did was copy validation rules to nested text box after all bindings were created. You cannot modify binding after use, but you can add validation rules to it :)
It is very important to set certain properties inside custom control like:
<UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True>

cos you cannot set them afterwards. So setting them in usage line is not needed.


text:
Q: Large datatable always throwing System.outofmemory exception I have a large datatable which contains around 500 000 rows. I have to iterate through that data table and apply a business logic on each row.
The problem is that when after certain level of iteration over that huge datatable it throws System.OutofMemory exception.
dt is the datatable which contains 500 000 records.
I tried below approach:
int pageNum = 1;
int pageSize = 10000;
Datatable dtPage = null;
DataModel model = null;
//DataModel  is a class containing various properties
//i.e public class DataModel
//{
//  public string Name {get;set;}
 // public string Role {get;set;}
//etc....
//}

while(dt.Rows.Count  - (pageNum * pageSize ) > 0)
{
 dtPage = dt.Rows.Cast<System.Data.DataRow>().Skip((pageNum -1 ) *   pageSize).CopyToTable();
foreach(DataRow row in dtPage.Rows)
{
model = new DataModel();
PropertyInfo[] properties = typeof(DataModel).GetProperties();
foreach(PropertyInfo property in properties)
{
if(dtPage.Columns.Contains(property.Name))
 SetNewValue(model,property.Name,row[property.Name]);
}
if(model! = null) lst.Add(model);
}
pageNum ++;
}

What to use in this case? I have also tried batch approach of MoreLinq but still did not had any luck.

A: How about this line of code...
if(model! = null) lst.Add(model);

I would suspect that is your culprit due to the fact that you are continuing to add items to a variable that is outside the scope of your loop (which leads to question, why bother with all the complicated paging logic then if all you are doing is dumping everything into the same list).
You are iterating over a datatable with half a million rows, re-casting it as IEnumerable for every page, using reflection to iterate over your DataModel object, using reflection to set properties, and then storing the new objects in a collection.  Your memory usage will indeed continue to grow as you iterate over the table, because you are creating new objects on every single iteration.
This approach is impractical from both a performance and memory standpoint.  Consider doing the following:

*

*Cast your datatable to IEnumerable only once and store it in a variable so you aren't recasting every time

*Don't use reflection in a huge loop like this.  I am not anti-reflection, but performance will be abysmal.  Either explicitly write code to populate your object, or consider expression trees (although I believe in this case Expression Trees are overly complex)

*If this is coming from a database, implement paging in your stored procedure or select statement to only pull the data you need for a single page

*If you need to populate everything at once for some reason, then ditch the paging logic since you aren't using it in the code above

*Use a DataReader instead of a DataTable.  A DataReader is faster and has less overhead than a DataTable/DataSet

*Use column indexes, not column names, to retrieve data.  Using the column name vs. the index introduces additional performance penalties.  If you need to do it dynamically, then get the index of the column once using the name, store it, and use the stored value from there out


text:
Q: Assigning values in a sequence to a group of consecutive rows leaving some rows empty I'm trying to group several consecutives rows (and assigning them the same value) while leaving some of the rows empty (when a certain condition is not fulfilled).
My data are locations (xy coordinates), the date/time at which they were measured, and the time span between measures. Somehow simplified, they look like this:
ID   X     Y      Time    Span
1    3445  7671   0:00    -
2    3312  7677   4:00    4
3    3309  7680   12:00   8
4    3299  7681   16:00   4
5    3243  7655   20:00   4
6    3222  7612   4:00    8
7    3260  7633   0:00    4
8    3254  7641   8:00    8
9    3230  7612   0:00    16
10   3203  7656   4:00    4
11   3202  7678   8:00    4
12   3159  7609   20:00   12
...

I'd like to assign a value to every sequence of locations that are measured within a time span of 4 hours, and make my data look like this:
ID   X     Y      Time    Span  Sequence
1    3445  7671   0:00    -     -
2    3312  7677   4:00    4     1
3    3309  7680   12:00   8     NA
4    3299  7681   16:00   4     2
5    3243  7655   20:00   4     2
6    3222  7612   4:00    8     NA
7    3260  7633   0:00    4     3
8    3254  7641   8:00    8     NA
9    3230  7612   0:00    16    NA
10   3203  7656   4:00    4     4
11   3202  7678   8:00    4     4
12   3159  7609   20:00   12    NA

I've tried several algorithms with a loop "for" plus "ifelse" condition like:
Sequence <- for (i in 1:max(ID)) {
ifelse (Span <= 4, i+1, "NA")
}

without any luck. I know my attempt is incorrect, but my programming skills are really basic and I haven't found any similar problem in the web.
Any ideas would be very appreciated!

A: Here is a longish one liner:
ifelse(x <- DF$Span == 4, cumsum(c(head(x, 1), tail(x, -1) - head(x, -1) == 1)), NA)
# [1] NA  1 NA  2  2 NA  3 NA NA  4  4 NA

Explanation:

*

*x is a vector of TRUE/FALSE showing where Span is 4.

*tail(x, -1) is a safe way of writing x[2:length(x)]

*head(x, -1) is a safe way of writing x[1:(length(x)-1)]

*tail(x, -1) - head(x, -1) == 1 is a vector of TRUE/FALSE showing where we went from Span != 4 to Span == 4.

*since the vector above is one element shorter than x, I prepended head(x, 1) in front of it. head(x, 1) is a safe way of writing x[1].

*Then I take the cumsum so it converts the vector TRUE/FALSE into a vector of increasing integers: where Span jumps from !=4 to ==4 it increases by 1, otherwise stays constant.

*Everything is wrapped into an ifelse so you only see numbers where x is TRUE, i.e., where Span == 4.

A: Here's another alternative using rle and rep. We'll assume that your data.frame is named "test".
First, initialize your "Sequence" column, filling it with NA.
test$Sequence <- NA

Second, specify the condition that you are matching, in this case, test$Span == 4.
x <- test$Span == 4

Third, use the combination of rle's output (lengths and values) to get how many times each new run in the sequence occurs.
spanSeq <- rle(x)$lengths[rle(x)$values == TRUE]

Finally, use rep with the times argument set to the result obtained in step 3. Subset the required values of test$Sequence according to the index matched by test$Span == 4, and replace them with your new sequence.
test$Sequence[x] <- rep(seq_along(spanSeq), times = spanSeq)
test
#    ID    X    Y  Time Span Sequence
# 1   1 3445 7671  0:00    -       NA
# 2   2 3312 7677  4:00    4        1
# 3   3 3309 7680 12:00    8       NA
# 4   4 3299 7681 16:00    4        2
# 5   5 3243 7655 20:00    4        2
# 6   6 3222 7612  4:00    8       NA
# 7   7 3260 7633  0:00    4        3
# 8   8 3254 7641  8:00    8       NA
# 9   9 3230 7612  0:00   16       NA
# 10 10 3203 7656  4:00    4        4
# 11 11 3202 7678  8:00    4        4
# 12 12 3159 7609 20:00   12       NA

Once you understand the steps involved, you can also do this directly with within(). The following would give you the same result:
within(test, {
  Sequence <- NA
  spanSeq <- rle(Span == 4)$lengths[rle(Span == 4)$values == TRUE]
  Sequence[Span == 4] <- rep(seq_along(spanSeq), times = spanSeq)
  rm(spanSeq)
})

A: count = 0
for (i in 1:max(ID)) {
      Sequence[i] = ifelse(Span[i] <= 4, count <- count+1, NA)
}


text:
Q: Laravel 4 form post issue my problem is that when i submit my form it pass through the get method.
The workflow is form submit -> get -> post and it should be form submit -> post.
I need to have a condition in my get method to validate de array is not null
My code:
Routes
    Route::get('/pre-register-birth',array('as'=>'pre-register-birth', 'uses'=>'UserController@preRegisterBirthData'));
    Route::post('/pre-register-birth', 'UserController@preRegisterBirthDataPost');

View
    {{ Form::open(array('method' => 'POST', 'action' =>  'UserController@preRegisterBirthDataPost',
        'class'=>'form-horizontal', 'id'=>'regist-form')) }}

Controller
    public function preRegisterBirthData()
{
    $user = Session::get('user');

    if ($user)
        return View::make('user/pre-register-birth')->with('tempUser', $user);
    else
        return Redirect::Route('pre-register-get');
}

public function preRegisterBirthDataPost()
{
    $validator = Validator::make(Input::all(),
        array(
            'birthplace' => 'required|max:100',
            'birthdate' => 'required|max:100|date|date_format:Y-m-d'
        )
    );
    if ($validator->fails()) {
        return Redirect::Route('pre-register-birth')
            ->withErrors($validator)
            ->withInput();
    } else {
        $user = array(
            'email' => Input::get('email'),
            'pass' => Input::get('pass'),
            'name' => Input::get('name'),
            'surname' => Input::get('surname'),
            'birthplace' => Input::get('birthplace'),
            'birthdate' => Input::get('birthdate'),
            'hourKnow' => Input::get('hourKnow'),
            'dataCorrect' => Input::get('dataCorrect'),
            'news' => Input::get('news'),
        );
        return Redirect::Route('pre-register-terms')->with('user', $user);
    }
}

A: I think I've seen this issue before. Laravel for whatever odd reason doesn't like the action => ... So, change your form declaration from a to b:
// A
{{ Form::open(array('method' => 'POST', 'action' =>  'UserController@preRegisterBirthDataPost',
    'class'=>'form-horizontal', 'id'=>'regist-form')) }}

// B
{{ Form::open(array('method' => 'POST', 'url' =>  'pre-register-birth',
    'class'=>'form-horizontal', 'id'=>'regist-form')) }}

Notice I changed action => ... to url => ... It's a small change, but it might solve it. However, you may need to add in:
Route::post('/pre-register-birth', array('as'=> 'pre-register-birth', 'uses' => 'UserController@preRegisterBirthDataPost'));

So it recognizes the named route.
Hope this helps!


text:
Q: Determining a basis for a space of polynomials. Let $V = \mathbb R[x]_{\le 3}$
I have the space of polynomials $U_2 = \{ p = a_0 + a_1x + a_2x^2 + a_3x^3 \in V \mid a_1 - a_2 + a_3 = 0, a_0 = a_1   \}$
I am asked to find a basis, so I proceed by noticing that in $U_2$:
$$a_0 + a_1x + a_2x^2 + a_3x^3 = a_0 (1+x-x^3) + a_2 (x^2 +x^3)$$
So I figure that a basis is $(1+x-x^3,x^2 + x^3 )$ In $\mathbb R^4$ the vectors would be $(1 10 -1), (001 1)$  but the solution gives the vectors $(1110), (-1-1 0 1)$.
What am I doing wrong?
Edit: corrected an error pointed out in the comments.

A: $a_2=a_1+a_3$ $\therefore $ the space is spanned by $a_0(1+x+x^2)+a_3(x^2+x_3)$ So you get $(1,1,1,0)$ and $(0,0,1,1)$.
You can also write it as $a_0(1+x-x^3)+a_2(x^2+x^3)$ In this case you get your answer which is also absolutely correct. Remember their is no unique solution to this question.

A: These are both bases. Your basis is $\{1+x-x^3, x^2+x^3\}$; the solution gives the basis $\{1+x+x^2, -1-x+x^3\}$. But each of these is expressible in terms of the other:
\begin{gather*}
  1+x+x^2 = (1+x-x^3) + (x^2+x^3),\quad -1-x+x^3 = -(1+x-x^3) \\
  1+x-x^3 = -(-1-x+x^3),\quad x^2+x^3 = (1+x+x^2) + (-1-x+x^3).
\end{gather*}


text:
Q: Create a column populated by a continuous row of the same value which is taken from number in the filename in r After reading in csv file which features a number within its filename, I would like to create a column in the dataframe called 'station_no' and populate each row with the number that forms part of the filename. The typical file format name can be seen below.
For example:
air_temp_df <- read_csv('data/2015.AT[AirTemperature].csv.zip', skip = 15) %>%
   mutate(station_no = XXXXXX)
where xxxx is somewhere I would like the station_no column to be populated with multiple rows of 2015.
Thanks.

A: Solution using base R:
file_path <- 'data/2015.AT[AirTemperature].csv.zip'
air_temp_df <- read_csv(file_path, skip = 15)
air_temp_df$station_no <- gsub("^.*/([0-9]{4})\\..*", "\\1", file_path)

We can use regex to extract the four digits year from the file_path string.
The regex identifies :
start of line (^) followed by 'something or nothing' (.*) followed by a "/" (/) followed by a group of four numbers that we want to use later (marked by round parentheses)  ([0-9]{4}) followed by a dot (\\.) followed by something or nothing (.*).
Then we replace the whole string with only the first (an in this case only) group (\\1)
This solution should also work if there are other numbers in the file_path (Using "[^0-9]" would not work in these cases)


text:
Q: Push img resolution from loop to array I receive an array of images and want to get the resolution (width, height) and store them properly to the db. How can I push the resolution const resolution correctly into the array of the respective file?
const FilesStorage = require("../models/filesStorageModel");
const sizeOf = require('image-size');
const url = require('url')
const https = require('https')

exports.uploadFiles = async (req, res) => {
    const filesArray = req.files

    try {
        for (const file of filesArray) {

            const imgUrl = file.location
            const options = url.parse(imgUrl)

            https.get(options, (res) => {
                const chunks = []
                res.on('data', (chunk) => {
                    chunks.push(chunk)
                }).on('end', () => {
                    const buffer = Buffer.concat(chunks)
                    const resolution = sizeOf(buffer)

                    console.log(resolution)
                })
            })

            const uploadFiles = new FilesStorage({
                name: file.originalname,
                altTag: "alt",
                format: file.mimetype,
                filePath: file.location,
                sizeKB: (file.size / 1000),

                height: "resolution.height", // How?
                width: "resolution.width", // How?
            })

            await uploadFiles.save()
        }

        return res.status(200).json({
            success: true,
            message: 'Files successfully uploaded',
        })

    } catch(err) {
        return res.status(500).json({
            success: false,
            message: `Something wen't wrong`,
        })
    }
}

A: Here's the answer you're looking for:
First, we need to consider variable scopes. When we look at the resolution constant you have defined in your handler, we can see the scope makes it local to that handler and not the parent code block.
To make it accessible in other areas of the code block, we move it above the handler scope but keep it inside your for loop so it's file-specific. With this change, we can now insert the resolution into your database upload call.
Hope this helps!

const FilesStorage = require("../models/filesStorageModel");
const sizeOf = require('image-size');
const url = require('url')
const https = require('https')

exports.uploadFiles = async(req, res) => {
  const filesArray = req.files

  try {
    for (const file of filesArray) {

      const imgUrl = file.location
      const options = url.parse(imgUrl)

      //Added variable outside arrow function scope
      var resolution;

      https.get(options, (res) => {
        const chunks = []
        res.on('data', (chunk) => {
          chunks.push(chunk)
        }).on('end', () => {

          const buffer = Buffer.concat(chunks)

          //Set value to variable outside function scope
          resolution = sizeOf(buffer)

          console.log(resolution)
        })
      })

      const uploadFiles = new FilesStorage({
        name: file.originalname,
        altTag: "alt",
        format: file.mimetype,
        filePath: file.location,
        sizeKB: (file.size / 1000),

        //Get value by accessing variable above
        height: resolution.height,
        width: resolution.width,
      })

      await uploadFiles.save()
    }

    return res.status(200).json({
      success: true,
      message: 'Files successfully uploaded',
    })

  } catch (err) {
    return res.status(500).json({
      success: false,
      message: `Something wen't wrong`,
    })
  }
}


text:
Q: "Macaroni and cheese (is/are) on the lunch menu" Is the sentence ""Macaroni and cheese is on the lunch menu." correct?
I mean there 'is' is used as verb because two item means one unit. Or 'are' will be used?

A: Is is appropriate here, since "macaroni and cheese" refers to a single menu item, ordered as a unit.  A similar pair might be "spaghetti and meatballs."
Two completely separate items would use are.  For example, "Steak and chicken are on the menu."
Other options for a meal might use either verb, depending on how they are being discussed.
Lunch Menu
1. Hamburger and Fries
2. Fish and Chips

A hamburger and fries are on the menu.
  A hamburger and fries is one option from the menu.

In the second sentence, the message is set up to emphasize that "hamburger and fries" are a single item with multiple parts.
Fish and chips would be closer to macaroni and cheese in the US, as we don't refer to this style of fried potatoes as chips except in this context, when paired with fried, battered white fish.  Because these are grouped, you'd be more likely to hear someone say, "Fish and chips is on the menu" even though it would entirely appropriate to order them separately.  "Fish and chips are on the menu" would also be entirely acceptable.

A: That sentence sounds clumsy to my feeling. I would prefer There's (the dish) macaroni and cheese on the menu.


text:
Q: Show each row that is a duplicate I have a table with contains duplicate rows.For ex This is my table
 OriginalUrl                           NewUrl
/blog                                 /blog
es/blog                               es/blog
blog                                  blog

Now I would like to get the duplicates as follows
Output:
    OriginalUrl                           NewUrl
    /blog                                 /blog
    blog                                  blog

Thanks to "Zohar Peled" I have achieved most of it through this code http://sqlfiddle.com/#!6/c96cc/5.
But when I add blog without (/) I would even that as a duplicate as shown above.But this isn't happening with this code.So could anyone help me to achieve this

A: Final update
After yet another goal post shifting, I've updated my CTE again.
This is the final update since even if you are going to change your demands again I've had enough.
Please take my advice for future questions:

*

*Defind the problem as well as you can.

*Provide the most accurate table structure and sample data as ddl+dml.
Don't link to sqlfiddle as it suffers from a lot of downtime.

*Provide the most accurate expected output

*Show your efforts to solve the problem.

Here is the last updated CTE, everything else remains as it was in the last update. sqlfiddle here.
;WITH CTE AS (

SELECT OriginalUrl,
       NewUrl,
       RIGHT(OriginalUrl,
             LEN(OriginalUrl) -
                 CHARINDEX('/', OriginalUrl,
                     CASE WHEN PATINDEX('%://%/%', OriginalUrl) > 0 THEN
                         PATINDEX('%://%/%', OriginalUrl)+3
                     ELSE
                        0
                     END
                 )+1
             ) As Product
FROM MyTable
)

Update
Updated sample data (again....)
-- Create sample table and data.
-- DDL
create table MyTable (
  OriginalUrl varchar(50),
  NewUrl varchar(50)
)
-- DML
  insert into MyTable VALUES
('/blog', '/blog'),
('http://gaming.corsair.com/blog', 'http://gaming.corsair.com/blog'),
('http://www.corsair.com/blog', 'http://www.corsair.com/blog'),
('http://www.corsair.com/es/blog', 'http://www.corsair.com/es/blog')

I've updated the CTE to include in 'Product' everything from the last '/' char, so product for the first 3 rows is now /blog, and for the last one it's /es/blog. so everything after the protocol and domain parts of the URL is considered a product now. Note - this also should apply to https and any other protocol.
;WITH CTE AS (

SELECT OriginalUrl,
       NewUrl,
       RIGHT(OriginalUrl,
             LEN(OriginalUrl) -
                 CHARINDEX('/', OriginalUrl,
                     PATINDEX('%://%', OriginalUrl)+3 -- get the location right after '://'
                 )+1 -- get the location right after the first / after the patindex
             ) As Product
FROM MyTable
)

My query on the new CTE remain as it was in the last attempt:
SELECT T1.OriginalUrl, T1.NewUrl,T2.Product
FROM CTE T1
INNER JOIN (
    SELECT Product
    FROM CTE
    GROUP BY Product
    HAVING COUNT(1) > 1
) T2 ON(T1.Product = T2.Product)

Here is the output:
OriginalUrl                       NewUrl                            Product
---------------------------------------------------------------------------
/blog                             /blog                             /blog
http://gaming.corsair.com/blog    http://gaming.corsair.com/blog    /blog
http://www.corsair.com/blog       http://www.corsair.com/blog       /blog

You can play with it yourself on sqlFiddle.
Earlier versions
So, by duplicates you mean all rows that have the same string after the last / in OriginalUrl column?
If so, you might want to try this:
-- Create sample table and data.
-- DDL
create table MyTable (
  OriginalUrl varchar(50),
  NewUrl varchar(50)
)
-- DML
  insert into MyTable VALUES
('/blog', '/en-us/blog'),
('/blog', '/en-us/blog'),
('http://www.corsair.com/blog', 'http://www.corsair.com/blog'),
('http://gaming.corsair.com/blog', 'http://gaming.corsair.com/blog'),
('blablabla/blog', 'yadayada/blog'),
('I don''t see what is wrong with this/Answer', 'It seems to be working/Fine'),
('Unless my/Answer', 'assumes duplicates as something else then/you'),
('300r', '300r')

Note: You should use this way to provide sample data when asking questions about sql.
This way we can copy your DDL + DML to sqlfiddle or our own environments and actually test the answers we give.
I've Used a CTE to insulate the last word after the last / in your sample data,
so that I will only have to write the RIGHT expression once.
;WITH CTE AS (
SELECT OriginalUrl,
        NewUrl,
        RIGHT(OriginalUrl, CASE WHEN CHARINDEX('/', OriginalUrl) > 0 THEN
                               CHARINDEX('/', REVERSE(OriginalUrl))-1
                           ELSE
                               LEN(OriginalUrl)
                           END) As Product
FROM MyTable
)

SELECT DISTINCT T1.OriginalUrl, T1.NewUrl,T1.Product
FROM CTE T1
INNER JOIN CTE T2
ON(T1.Product = T2.Product)
WHERE T1.OriginalUrl <> T2.OriginalUrl

Update
Using the same CTE, try this:
SELECT T1.OriginalUrl, T1.NewUrl,T2.Product
FROM CTE T1
INNER JOIN (
    SELECT Product
    FROM CTE
    GROUP BY Product
    HAVING COUNT(1) > 1
) T2 ON(T1.Product = T2.Product)

Results:
    OriginalUrl                                        NewUrl                                             Product
    -------------------------------------------------- -------------------------------------------------- --------------------------------------------------
    I don't see what is wrong with this/Answer         It seems to be working/Fine                        Answer
    Unless my/Answer                                   assumes duplicates as something else then/you      Answer
    /blog                                              /en-us/blog                                        blog
    /blog                                              /en-us/blog                                        blog
    http://www.corsair.com/blog                        http://www.corsair.com/blog                        blog
    http://gaming.corsair.com/blog                     http://gaming.corsair.com/blog                     blog
    blablabla/blog                                     yadayada/blog                                      blog


text:
Q: Memory Usage of SQL Server SQL Server instance on my server is using almost full memory available in my Physical Server.
Say if i am having 8GB of RAM than SQL Server is using 7.8 GB of RAM from system.
I also have read articles and also read many similar questions regarding same on this forum and i understand that memory is reserved and it is using memory.
But i have 2 same servers and 2 SQL Servers, why this is happening on a single SQL Instance not on other. Also when i run DBCC MemoryStatus than it is showing up...
VM Reserved 8282008
VM Committed 537936

so from this we know that SQL reserved whole 8GB memory, but why this VM Committed keeps increasing. What i understand is VM Committed is:

VM Committed: This value shows the overall amount of VAS that SQL Server has committed. VAS that is committed has been associated with physical memory.

So this is the memory SQL Server has committed (from this i understand that physical memory actually SQL Server is using at instance).
So like to know the reason behind this ever increasing VM Committed memory on my server and not on another.
Thanks in Advance.

A: SQL Server is probably caching data in memory to speed queries in the future.
SQL Server and RAM
I would guess that your two servers are under different loads.

A: VM Reserved 8282008 = The larger of your physical memory footprint and the configured memory settings, or:
SELECT CAST(value_in_use AS INT) * 1024 FROM sys.configurations WHERE name = 'max server memory (MB)'
SELECT physical_memory_in_bytes / 1024 FROM sys.dm_os_sys_info

VM Committed 537936 = The actual memory used by SQL Server at this moment.


text:
Q: How can I bulk load CSV files into Snowflake with the filename added as a column? I can bulk load CSV files into Snowflake via an internal stage, or by directly loading the data into a table.
The problem I have is that the filename contains vital information and must be included in the table.
How I can bulk load CSV files into Snowflake, whilst adding the filename as an additional column?
For example:

A: You can use the meta column metadata$filename for this, as in:
select metadata$filename
  , metadata$file_row_number
  , t.$1, t.$2 from @mystage1 (file_format => myformat) t;

See https://docs.snowflake.com/en/user-guide/querying-metadata.html


text:
Q: Why isn't Heroku's Postgresql updating according to Django's models.py? Currently I'm running into issues with my models.py and Postgresql. The site is deployed on Heroku using Postgresql and the problem is models.py. Currently, I have models.py as a models.Charfield() and it works fine with sqlite, but when I deployed it to production, Postgresql still reports that it's a models.IntFied(). And because it's an integer field it won't allow for characters for some reason.
Originally, I had it as a integerfield but decided to change to charfield, yet it still won't change to charfield.
Solutions I've tried: resetting the database on heroku, deleting and recreating the database on heroku.
Any help is appreciated,
Thanks

A: To sync your models to your database relational schema, you have to run the command:
python manage.py makemigrations
python manage.py migrate

A: I normally follow the steps in this order:

*

*Ensure that your database changes have all been committed with git add and commit commands

*Reset the heroku database, Run
{heroku pg:reset DATABASE_URL}

*Push your current changes to heroku with
{git push heroku master}

*Launch the heroku terminal
{heroku run bash}

*On the heroku terminal run
{python manage.py migrate}


text:
Q: VS code intagrated terminal broken My integrated terminal doesn't work. I have no functional terminal. I can't create new one. When I click on the plus button, nothing append. And I don't have any terminal profile in the dropdown list.
dropdown list
I added some profiles in my settings file, but it seems they are not recognized.
 {
    "workbench.colorTheme": "Default Dark+",
    "terminal.integrated.profiles.windows": {
        "PowerShell": {
            "source": "PowerShell",
            "icon": "terminal-powershell"
        },
        "Command Prompt": {
            "path": [
                "${env:windir}\\Sysnative\\cmd.exe",
                "${env:windir}\\System32\\cmd.exe"
            ],
            "args": [],
            "icon": "terminal-cmd"
        },
        "Git Bash": {
            "source": "Git Bash"
        }
    },
    "terminal.integrated.defaultProfile.windows": "Command Prompt",
}

I tried to uninstall vs code, remove all folders and reinstall vs code but I have the same issue.

A: I have this same issue; for now, I installed version 1.59 which fixed my problem: https://code.visualstudio.com/updates/v1_59
I'd be interested in learning if there's a better fix, or if a bug report has been filed.

A: I added
"terminal.integrated.useWslProfiles": false
to my settings and it solved my problem.
There is an issue about that on Github. https://github.com/microsoft/vscode/issues/134418


text:
Q: Why can't generators be pickled? Python's pickle (I'm talking standard Python 2.5/2.6/2.7 here) cannot pickle locks, file objects etc.
It also cannot pickle generators and lambda expressions (or any other anonymous code), because the pickle really only stores name references.
In case of locks and OS-dependent features, the reason why you cannot pickle them is obvious and makes sense.
But why can't you pickle generators?

Note: just for clarity -- I'm interested in the fundamental reason (or assumptions and choices that went into that design decision) why, not in "because it gives you a Pickle error".
I realize the question's a bit wide-aimed, so here's a rule of thumb of whether your answered it: "If these assumptions were raised, or the type of allowed generator somehow more restricted, would pickling generators work again?"

A: There is lots of information about this available. For the "official word" on the issue, read the (closed) Python bugtracker issue.
The core reasoning, by one of the people who made the decision, is detailed on this blog:

Since a generator is essentially a souped-up function, we would need to save its bytecode, which is not guarantee to be backward-compatible between Python's versions, and its frame, which holds the state of the generator such as local variables, closures and the instruction pointer. And this latter is rather cumbersome to accomplish, since it basically requires to make the whole interpreter picklable. So, any support for pickling generators would require a large number of changes to CPython's core.
Now if an object unsupported by pickle (e.g., a file handle, a socket, a database connection, etc) occurs in the local variables of a generator, then that generator could not be pickled automatically, regardless of any pickle support for generators we might implement. So in that case, you would still need to provide custom __getstate__ and __setstate__ methods. This problem renders any pickling support for generators rather limited.

And two suggested workarounds are mentioned:

Anyway, if you need for a such feature, then look into Stackless Python which does all the above. And since Stackless's interpreter is picklable, you also get process migration for free. This means you can interrupt a tasklet (the name for Stackless's green threads), pickle it, send the pickle to a another machine, unpickle it, resume the tasklet, and voilà you've just migrated a process. This is freaking cool feature!
But in my humble opinion, the best solution to this problem to the rewrite the generators as simple iterators (i.e., one with a __next__ method). Iterators are easy and efficient space-wise to pickle because their state is explicit. You would still need to handle objects representing some external state explicitly however; you cannot get around this.

A: You actually can, depending on the implementation. PyPy and Stackless Python both allow this (to some degree anyway):
Python 2.7.1 (dcae7aed462b, Aug 17 2011, 09:46:15)
[PyPy 1.6.0 with GCC 4.0.1] on darwin
Type "help", "copyright", "credits" or "license" for more information.
And now for something completely different: ``Not your usual analyses.''
>>>> import pickle
>>>> gen = (x for x in range(100))
>>>> next(gen)
0
>>>> pickled = pickle.dumps(gen)
>>>> next(pickle.loads(pickled))
1

In CPython it's also possible to create an iterator object to simulate a pickable generator.


text:
Q: A sentence with listing items: How to remove the ambiguity? There is a store which trades oranges and 3 kinds of apples. And there is a person there to whom I'm giving directions. Which sentence will be the best in such a case?

*

*Put green apples in the first box. Put red and yellow apples and oranges in the second box.

*Put green apples in the first box. Put red and yellow apples, and oranges, in the second box.

*Put green apples in the first box. Put red and yellow apples, and also oranges, in the second box.

*Put green apples in the first box. Put red and yellow apples, as well as oranges, in the second box.

The 1st sentence looks wrong to me. We don't have red or yellow oranges.
The 2nd sentence looks OK to me, but I'm not sure that commas are enough to remove the ambiguity.
The 3rd and 4th sentences look somewhat wordy.
Edit: It is assumed that I cannot place oranges at the first place.

A: You have two good answers. I look at this question as probably one where clarity is at premium even at the cost of inelegant language. For instance, you are giving precise packing instructions and don't want any ambiguity. If this be the case, I would make boxes central to the communication, phrasing it as:

The first box is only for green apples. In the second box, put apples ( both red and yellow) and oranges

A: Another approach would be to put oranges first:

Put green apples in the first box. Put oranges and red and yellow apples in the second box.

Or if there are only green, red, and yellow apples, then:

Put green apples in the first box. Put oranges and the rest of the apples in the second box.

(or "the other apples")

A: One way to reduce the ambiguity is to include articles:

Put the green apples in the first box.  Put the red and yellow apples and the oranges in the second box.

With the definite articles in place, we can see that red and yellow applies only to apples and not to oranges.   This "red and yellow" is inside the phrase "the red and yellow apples", so it doesn't apply to the phrase "the oranges".
Using the definite article does imply that the apples and oranges in question are specified by something in the surrounding context.   That works in this context, since we're only talking about apples and oranges that are associated with the store.   In some other context, we might have reason to include unknown apples and oranges, or even hypothetical pieces of fruit.   If so, we might use a determiner like "any" or "all" to mark the same noun-phrase boundaries.
Using some determiner like the definite article could also resolve the ambiguity in the other direction:

... the red and yellow apples and oranges ...

In this example, we know that both colors apply to both kinds of fruit.

A: Put green apples in the first box. Put red apples, yellow apples, and oranges in the second box.
Note that there is no comma after "oranges".

A: Simply repeat the use of apples. Rather than using the shortcut of red and yellow apples, use the expanded form of red apples and yellow apples:

Put green apples in the first box. Put red apples, yellow apples, and oranges in the second box.

Alternatively, given that only 4 type of things are under consideration, there is an even simpler method of approaching a concise and clearly understood set of instructions:

Put green apples in the first box. Put everything else in the second box.

Once mention is made of green apples, there is no need to enumerate the remaining items at all.


text:
Q: Correct way to query for optional relationships using Cypher 2.0.0 I'm trying to figure out what the correct way is to query for additional optional relationships when returning a primary set of items (or if there is more idiomatic way to accomplish the same thing).
I've set up an example at http://console.neo4j.org/?id=747b3x.  I have three nodes, one of which HAS two tags and one IS_A thing.  I would like to query for all of the items and return the item itself as well as any related tags and things.
The result set I'm trying to create is the following:
Item     Tags        IS
-------  ----------  --------
1        ['A', 'B']  null
2        null        null
3        null        'foo'

This is what my query currently looks like:
MATCH (i:Item)
WHERE HAS(i.name)  // in reality, statements to narrow down i
WITH i
MATCH (i)-[?:HAS]->(t:Tag), (i)-[?:IS_A]->(s:Thing)
RETURN i.name AS item, COLLECT(t.name) AS tags, s.name AS is

In the console this gives a null pointer exception, but on my server it only seems to return items that have both tags and things associated with them. What's the best way to accomplish this?
Thanks!

A: MATCH (i:Item)
WITH i
MATCH (i)-[?:HAS|:IS_A]->(n)
RETURN i.name AS Item, COLLECT(n.tag_name) AS Tags, n.is_name AS IS

If it makes sense to differentiate the types of names on :HAS and :IS_A nodes (or perhaps just duplicate the name attribute into tag_name as well as is_name) then this is workable. However, if an Item has no tags, then instead of a NULL, you will get an empty list.
Edit:
Another method you might try, although it doesn't work on the console and I don't want to start up a new DB is:
MATCH (i:Item)
WITH i
MATCH (i)-[?:HAS]->(t:Tag)
RETURN i, t
MATCH (i)-[?:IS_A]->(s:Thing)
RETURN i.name as item, COLLECT(t.name) AS tags, s.name AS is


text:
Q: What deep learning methods should I explore for my panel data where one country is fixed? The data looks like the following image and is available from 1980 to 2019:

As you can see, nation 1 doesn't differ in any of the panels; only country 2 does and the country 2s for each panel remain same. What deep learning technique should I to explore to create a research report on it? I've seen a post on this site that recommended using LSTMs for panel data, but I'm not sure if that's the best strategy for my dataset. I did more research on LSTMs, and it appears to be suitable for my goal of prediction based on all values given its reliance on long term memory. Can someone guide me please?
Edits based on comments:

*

*I will have >70000 observations. In the worst case where I restrict the time series range, I will land up with 20k observations.  I understand that this might be less, so I am open to the possibility of allowing variation in country 1 and then using the model for prediction of my current country.

*I have around 6-10 variables (features) that determine the "Value" column in the table.

A: Extending comments into an answer:
You should start by not using deep learning. You have tabular data and for such data traditional statistical and machine learning models are successfully used both in the industry and in Kaggle competitions as noticed by Szilard Pafka. There are many empirical studies showing that traditional machine learning models outperform deep learning like this by Javier Rodriguez or the one by Ravid Shwartz-Ziv and Amitai Armon (2021) and many more.
You seem to be talking about time-series data and for such data traditional models also outperform neural networks. A great example is the M-competition that started in 1982 and already had five rounds (the last ended recently) where competitors use different models for thousands of time-series. In each competition, we saw simpler, traditional models outperform neural networks, where the only exception was the last competition where a hybrid model combining a traditional approach with a neural network won.
In the comment, you quoted this paper by Wohl and Kennedy (2018), as an example of a neural network giving better results than another model, but I am afraid it suffers from exactly the kind of biases we can see in much similar research: the authors use overtly simplistic model and compare it to the neural network. What this research shows is that a neural network beats a trivial benchmark, but it tells us nothing about its performance vs a more reasonable model.
This of course does not say that neural networks never work for such problems. It says that with other models you have a higher chance of getting better results. You should try neural networks for tabular data only after you proved that nothing else worked. Otherwise, you are throwing an overtly complicated model at the problem, that is likely to overfit.


text:
Q: Why does iTunes think my SIM card is unsupported? I recently bought an unlocked iPhone 4 from the US. I live in the UAE. I had a normal SIM card and I cut it and installed it into iphone and it started working.
But when I tried to upgrade to the most recent iOS version using iTunes, at the end of the installation it says Your SIM card does not appear to be supported.
When I went to my carrier office they gave me SIM card which works in their iPhone (UAE) but it does not work in my iPhone (US).
I am worried about what happened to it. I bought it just one week back. Now I am not able to even start it; it's not detecting my SIM (which is working in other iPhone).
Any idea what the problem is? What should I do? Shoud I format it?

A: If the handset was unlocked using UltraSn0w, then you have completely removed it by updating the firmware to the latest version (Ultrasn0w only supports iOS 4.3.3). Worse yet, this has updated your baseband and that cannot be reverted even if you manage to downgrade the OS (unless you used Pwnage Tools or Sn0wbreeze as they can preserve the baseband during update). If this is indeed the case, you have now a locked phone to whatever carrier it was purchased under (AT&T) and you will have to talk to that carrier for a "hard" unlock.
To my knowledge, a "true" unlocked iPhone has no geographic limitations. As long as the network supports GSM phones (read: SIM cards), then there should be no problem.

A: This means that your carrier is not supported with your version iPhone. I don't know anything about the United Arab Emirates, but I am guessing that your UAE SIM does not work with your US phone.
Thus, I think that you should get:
a: A UAE iPhone
or
b: A US SIM
You may want to consider checking your phone out at an Apple store or something similar before doing either of these, checking to make sure that your phone isn't to blame. (It shouldn't be, but you never know)

A: Are u sure your phone was originally unlocked by Apple when u bought it? Did you buy it from an Apple store or online unlocked? These are questions you need to answer to get to the root of the issue.
If theres a chance that it was bought attached to a network e.g AT&T but later unlocked then after restoring or updating the phone, it won't work with another sim.


text:
Q: Insert values of one table in a database to another table in another database I would like to take some data from a table from DB1 and insert some of that data to a table in DB2.
How would one proceed to do this?
This is what I've got so far:
CREATE VIEW old_study AS
SELECT *
FROM dblink('dbname=mydb', 'select name,begins,ends from study')
AS t1(name varchar(50), register_start date, register_end date);
/*old_study now contains the data I wanna transfer*/

INSERT INTO studies VALUES (nextval('studiesSequence'),name, '',3, 0, register_start, register_end)
SELECT name, register_start, register_end from old_study;

This is how my table in DB2 looks:
CREATE TABLE studies(
    id int8 PRIMARY KEY NOT NULL,
    name_string VARCHAR(255) NOT NULL,
    description VARCHAR(255),
    field int8 REFERENCES options_table(id) NOT NULL,
    is_active INTEGER NOT NULL,
    register_start DATE NOT NULL,
    register_end DATE NOT NULL
);

A: You should include the column names in both the insert and select:
insert into vip_employees(name, age, occupation)
    select name, age, occupation
    from employees;

However, your data structure is suspect.  Either you should use a flag in employees to identify the "VIP employees".  Or you should have a primary key in employees and use this primary key in vip_employees to refer to employees.  Copying over the data fields is rarely the right thing to do, especially for columns such as age which are going to change over time.  Speaking of that, you normally derive age from the date of birth, rather than storing it directly in a table.

A: Loop and cursor are weapons of last resort. Try to avoid them. You probably want INSERT INTO ... SELECT:
INSERT INTO x(x, y, z)
SELECT x, y, z
FROM t;

SqlFiddleDemo
EDIT:
INSERT INTO vip_employees(name, age, occupation) -- your column list may vary
SELECT name, age, occupation
FROM employees;

A: INSERT INTO studies
(
    id
    ,name_string
    ,description
    ,field
    ,is_active
    ,register_start
    ,register_end
    )

SELECT nextval('studiesSequence')
    ,NAME
    ,''
    ,3
    ,0
    ,register_start
    ,register_end
FROM dblink('dbname=mydb', 'select name,begins,ends from study')
     AS t1(NAME VARCHAR(50), register_start DATE, register_end DATE);

You can directly insert values that retured by dblink()(that means no need to create a view)

A: Your syntax is wrong. You cannot have both, a values clause for constant values and a select clause for a query in your INSERT statement.
You'd have to select constant values in your query:
insert into studies
(
  id,
  name_string,
  description,
  field,
  is_active,
  register_start,
  register_end
)
select
  studiesSequence.nextval,
  name,
  'Test',
  null,
  0,
  register_start,
  register_end
from old_study;


text:
Q: Why can't i use Click in Storyboard I am trying to implement a change of the Click Event when Snapped_detail happens but I cant seem to do it this way..? how else do i modify the click event of the back button?
Here is my code:
            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="backButton" Storyboard.TargetProperty="Click">
                <DiscreteObjectKeyFrame KeyTime="0" Value="snapped_back_click"/>
            </ObjectAnimationUsingKeyFrames>

And this is the rest of it.

                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="primaryColumn" Storyboard.TargetProperty="Width">
                    <DiscreteObjectKeyFrame KeyTime="0" Value="0"/>
                </ObjectAnimationUsingKeyFrames>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="itemListView" Storyboard.TargetProperty="Visibility">
                    <DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed"/>
                </ObjectAnimationUsingKeyFrames>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="itemDetail" Storyboard.TargetProperty="(Grid.Row)">
                    <DiscreteObjectKeyFrame KeyTime="0" Value="1"/>
                </ObjectAnimationUsingKeyFrames>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="itemDetail" Storyboard.TargetProperty="(Grid.RowSpan)">
                    <DiscreteObjectKeyFrame KeyTime="0" Value="1"/>
                </ObjectAnimationUsingKeyFrames>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="titlePanel" Storyboard.TargetProperty="(Grid.Column)">
                    <DiscreteObjectKeyFrame KeyTime="0" Value="1"/>
                </ObjectAnimationUsingKeyFrames>
                <!--<ObjectAnimationUsingKeyFrames Storyboard.TargetName="itemDetailTitlePanel" Storyboard.TargetProperty="(Grid.Row)">
                    <DiscreteObjectKeyFrame KeyTime="0" Value="0"/>
                </ObjectAnimationUsingKeyFrames>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="itemDetailTitlePanel" Storyboard.TargetProperty="(Grid.Column)">
                    <DiscreteObjectKeyFrame KeyTime="0" Value="0"/>
                </ObjectAnimationUsingKeyFrames>-->
                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="itemDetail" Storyboard.TargetProperty="Padding">
                    <DiscreteObjectKeyFrame KeyTime="0" Value="20,0,20,0"/>
                </ObjectAnimationUsingKeyFrames>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="itemDetailGrid" Storyboard.TargetProperty="Margin">
                    <DiscreteObjectKeyFrame KeyTime="0" Value="0,0,0,60"/>
                </ObjectAnimationUsingKeyFrames>

            </Storyboard>
        </VisualState>

A: You can register to Window.Current.SizeChanged event instead
Window.Current.SizeChanged += WindowSizeChanged;

and than in your WindowSizeChanged function assign the different function to button
    private void WindowSizeChanged(object sender, WindowSizeChangedEventArgs e)
    {
         if(ApplicationView.Value == ApplicationViewState.Snapped)
          {
               backButton.Click += snapped_back_click;
          }
          else
          {
               //something else
          }
    }


text:
Q: VS Code Break Points - Can I add breakpoint every x number of executions? I see that I can add a breakpoint condition to trigger after x executions, but I'm wondering if I can add a condition to trigger after ever x executions? I.e., I want to break every 10 times a certain function is triggered.
Is there a way to do that without manually editing the breakpoint each time it hits?
The closest thing I was able to find was this Issue on GH which didn't seem to provide an answer. Looks more like it's saying Xamarin has the functionality and VS Code doesn't. Am I reading this right?
https://github.com/Microsoft/vscode-debugadapter-node/issues/37

A: Doh, you just have to do %x, which will break every x times the line is executed.
So I did %10, which stopped on the 10th execution, and every 10 thereafter.


text:
Q: CDS LIKE filter from view parameter How to create a CDS that select all KUNNR from table KNA1 that Customer Number starts for example with A%.
I could use LIKE in the where clause but the RHS of the condition have to be static. It should depend on the input parameter from CDS.
Is it possible to do it with CDS?

A: I see two options.

*

*You get rid of your CDS input parameter handling and move the logic to ABAP. Write your OPEN SQL select on your CDS with like statement.

*Use CDS Table function and AMDP by pushing the like statement down to HANA native. Just follow my post here.
Hope it helps.


text:
Q: Cloud Run service gives 404 error when trying to access from hosted site I have set up a site using firebase hosting where I would like to send requests to an API to send emails. Locally, this works perfectly. However, after pushing the API using Google Cloud run, I had run into errors when trying to access the API online using the hosted site. I had used the following firebase tutorial to try and set this up.
https://firebase.google.com/docs/hosting/cloud-run#node.js_1
I was able to deploy it with no issues, however, when I try to access the API through POST requests, it returns a 404 error. The site itself was developed with React.JS and the backend API was developed using Golang.
firebase.json:
    {
"hosting": {
    "public": "build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "run": {
          "serviceId": "api",
          "region": "europe-west1"
        }
      }
    ]
  }
}

JavaScript where the call to the API is being made:
const response = await fetch(this.state.endpoint+"/sendEmail", {
                method: "POST",
                body: JSON.stringify(data),
                headers: {
                    'Content-Type': 'application/json'
                },
            });

Golang router where the routing is being handled:
router := mux.NewRouter().StrictSlash(true)
    router.HandleFunc("/sendEmail", SendEmail)

    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
    }
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))

Again, running this locally has no issues but running it on the cloud returns a 404 error.
Update
I have now fixed the issue that was pointed out by @guillaumeblaquiere, that was the issue to do with the code itself. I did not call the router and so the routing was not taking place. Below is the fixed version
log.Print("api: starting server")

router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/sendEmail", SendEmail)

port := os.Getenv("PORT")
fmt.Println(port)
if port == "" {
    port = "8080"
}

log.Printf("api: listening on port %s", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), router))

The only issue left is that I have to call the API using the URL directly, not using rewrites.