Q: comparing extended objects private List<Fruit> myFruit = new Vector<Fruit>();

ok so if I have a list of different types of fruit objects how could I go through the list and compare the different objects.
public class Fruit{
 String type;
 String color;

 }

 public class Grape extends Fruit{
  int seedCount;

   public Grape(Attributes attributes){
    this.type = attributes.getValue("type");
    this.color=attributes.getValue("color");
    this.seedCount=attributes.getValue("seedCount");

 }

 public class Banana extends Fruit{
    String color;

   public Banana(Attributes attributes){
    this.type = attributes.getValue("type");
    this.color=attributes.getValue("color");

 }

public load(localName name, Attributes attributes){
if (name.equalsIgnoreCase("grape"){
 Grape grape = new Grape(attributes);
 myFruit.add(grape);
  }
if (name.equalsIgnoreCase("banana"){
   Banana banana = new Banana(attributes);
   myFruit.add(banana);
  }
 }

So how would I go about sorting through the list of Fruit and displaying specific properties of these objects based on what type of object they are. Ie. if type=Grape display seedCount.

A: *

*If you want to sort Fruit, you need to implement the Comparable interface for the Fruit class.

*If you want to display attributes, have an abstract method in Fruit class and provide the implementations in the subclass.
This way depending on the instance of the Fruit , it will show the corresponding properties.
public abstract class Fruit implements Comparable{
    public abstract void displayProperties();

    @Override
    public int compareTo(Fruit otherFruit){
        return 0;
    }

}

public class Banana extends Fruit {
    private int seedCount;
    @Override
    public void displayProperties() {
        // TODO Auto-generated method stub
        System.out.println(seedCount);
    }

}

public class Grape extends Fruit{
    private String color;
    @Override
    public void displayProperties() {
        // TODO Auto-generated method stub
        System.out.println(color);
    }

}

A: You could add an abstract method to Fruit displayProperties()
You would then be forced to impliment the method for all types  of fruit, then in your for loop you would just call displayProperties()

A: This isn't recommended, but you could use
if(object instanceof Class) {
    Class temp = (Class) object
    //operate on object
}

But what you should do is create a Fruit interface that gives access to the important info related to all fruit, in general you shouldn't cast down to get extra information.
While downcasting isn't evil, it could mean you aren't taking full advantage of polymorphism. To take advantage of polymorphism one should ensure that the supertype the subtypes share has methods to get as much info or behavior as necessary.
For example, lets say you have a list of HousePets, and the HousePets consist of the subtypes Dog and Cat. You loop over this list and want to wag all of the tails of the HousePets that can wag their tails. For simplicity there are two ways to do this, either only the Dog has the method 'wagTail()' (since Cats don't wag tails), or HousePets has a method called 'wagTail()' that is inherited by Cats and Dogs (but the Cat's version does nothing). If we choose the first example the code would look something like this:
 for(HousePet pet : petList)
     if(pet instanceof Dog) {
         ((Dog)pet).wagTail();
     }

And for the second example it would look like this:
 for(HousePet pet : petList)
     pet.wagTail();

The second example takes a little less code and is a little more streamlined. In the worst case scenario, if we go with the first option, we will need an if-block for each new subtype of HousePet, which will make the code bulkier/uglier/etc. Better yet we could have a HousePet method called "showHappiness", and the Dog would wag its tail while the cat purred.

A: I think you need an instanceof operator. It allows you to check object type.
if (list.get(0) instanceof Grape) {
    // list.get(0) is Grape
}


Q: Redux dispatch inside Meteor.call or get Meteor.call value My project works with Meteor and react-redux
For redux to work, one must be able to access the dispatch function in the this.props of the component.
However when I use Meteor.call the callback's this property does not contain the redux function dispatch as is expected.
So this is my Meteor.call:
var testing;

Meteor.call('seed', mergedobj, function(err, seed){
      if(err){
        console.log('ERROR ERROR ERROR: when calling seed err', err);

        if(err.error === 'SWE_RISE_TRANS_NEGATIVE'){
        }
      }else{
        console.log('return of seed', seed)
        console.log('this', this)
        //this.props.dispatch(seedAction(seed))
        testing = seed

      }
    })
console.log('testing', testing) //'INITIAL' and not seed!!

I either need to change the this of the callback so I can call this.props.dispatch inside of the callback or I need to get the value of seed outside of the callback.....
How do I achieve this?
How do I get the value of seed inside variable that is outside of the callback's scope?

A: How about using this syntax:
const dispatch = this.props.dispatch;
Meteor.call('seed', mergedobj, function(err, seed){
      if(err){
        // error handling here.
      }else{
        dispatch(seedAction(seed));
      }
})

So you don't have to deal with this keyword.


Q: Tabulator getElement is not a function I currently have a tabulator table of 100 elements in the array. When I call the function to grab the specific cell, it manages to grab the first 25 rows and change the color of the specific cell that I want.
The problem is that the ones after isn't changing color when everything else is the same. How do I get around it?
Here is the code that I am using to generate the background color. It works for the first 25 rows but it wasn't able to grab the next 75 rows
var allRowData = table.getRows();

    // loops the entire row
    allRowData.forEach(x => {

        // using the row data, grab the columns and compare with a condition
        scope.columns.forEach(y => {

            if (y.priority == 3) { // checks for the priority number to add a color to it
                var rowCell = x.getCell(`${y.fieldName}`);
                rowCell.getElement().style.backgroundColor = "#F00";
            }
        });
    });

A: You should not be trying to directly manipulate the layout of the table from outside of Tabulator.
Tabulator uses a virtual DOM which means that it will create and destroy elements of the table as needed, which means that you can only style elements that are currently visible, when these elements are updated any previous formatting can be lost without notice.
If you wish to style cell elements you must use the formatter function in the column definition or the rowFormatter function on the table which are called when the rows/cells are redrawn.
Full details of these can be found in the Formatter Documentation
If you are wanting to change the state of rows based on something outside of the table, then your formatters should reference this external variable and when you update the external state you should trigger the redraw function on the table to retrigger the formatters


Q: No equivalent of Yes yes command in linux prints y infinitely on the console. This is helpful to respond to few interactive commands with y. For e.g. yes | cp A/*.txt B automatically overwrites all files in destination directory.
Is there an equivalent command in linux that prints n infinitely?

A: yes accepts an argument, y is just the default value.
You can use:
yes n | command

How cool is that?

Pro tip:
# Use this and see what happens
yes maybe | command

Note: Not every command implements maybe.


Q: cmd type without printing filenames I have a makefile that concatenates two files to create a small kernel.
I am using the following command:
type boot_sect.bin kernel.bin > os-image

Unfortunately, type still shows something on the cmd:
boot_sect.bin

kernel.bin

Is there a way to not show the filenames with type?

A: You can try the following command:
copy /y /b boot_sect.bin+kernel.bin os-image > nul

The /y switch is to automatically overwrite the destination file in case it already exists and /b is for binary copy.


Q: :dependent => :destroy isn't calling the destroy method before the deletion? I have a note model, with the following association
note.rb
has_many :note_categories, :dependent => :destroy
has_many :categories, :through => :note_categories

The NoteCategory model was created to function as a join table between notes and categories. Initially it was just a model/table, but I've created a controller to do some custom stuff when someone is removing a category from a note.
note_categories_controller.rb
def destroy
    p "in notes_categories_controller destroy"
    note_category_to_delete = NoteCategory.find(params[:id])
    #some custom stuff
    note_category_to_delete.destroy
    respond_to do |format|
        format.html { redirect_to(notes_url }
        format.xml  { head :ok }
    end
end

This works fine, because I can use this link to create a button which will remove a category from a note:
<%= button_to 'Remove', note_category, :confirm => 'Are you sure?', :controller => :note_categories, :method => :delete %>

and it works fine.
The problem is, when I delete a note, the note_category rows the belonged to the note are getting deleted, but the destroy method isn't being run. I know this because the custom code isn't being run, and the terminal output in the first line doesn't show up in the terminal. Here is the terminal output:
Note Load (0.7ms)   SELECT * FROM "notes" WHERE ("notes"."id" = 245)
NoteCategory Load (0.5ms)   SELECT * FROM "note_categories" WHERE ("note_categories".note_id = 245)
NoteCategory Destroy (0.3ms)   DELETE FROM "note_categories" WHERE "id" = 146
Note Destroy (0.2ms)   DELETE FROM "notes" WHERE "id" = 245

I thought that by using :dependent => :destroy, the destroy method in the NoteCategories Controller should run before it's deleted. What am I doing wrong?

A: :dependent => :destroy will call the destroy method on the model not the controller.
From the documentation:

If set to :destroy all the associated objects are destroyed alongside this object by calling their destroy method.

That is, if you want something custom to your note_categories before being destroyed, you'll have to either override the destroy method in your NoteCategory model, or use an after_destroy/before_destroy callback.
Either way, using :dependent => :destroy will never execute code contained within your controller, which is why you're not seeing the output of the puts statement in the terminal.


Q: Navbar contents, icons, and card body? (HTML, bootstrap) So I have 3 issues:

*

*The contents of my navbar after the navbar-brand area will not show up for some reason. I am trying to add a home button, about section with a drop-down menu containing: 'Our mission', 'our team', 'faq;' a contact button, etc. (see picture for reference)

*The icon in my card footers will not appear

*How do I make the gray part of the cards a transparent gray color that also shows the body background?

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
  <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@700&display=swap" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="app3.css">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

  <title>Quarantine Blog</title>

      Quarantine Pal

            Home (current)

            Link

Home

                About

                Our Mission

                Our Team

                FAQ

Contact

Our Founder

Press

Sign Up

Login

Quarantine State of Mind

Exploring the 'New Normal'

    Sign Up
    Login

Self-Care and Burn Out

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

        Download

Help Fight Coronavirus

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

        Download

Pandemic Socializing

This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.

Last updated 3 mins ago

        Download

CSS:
#header {
    background-color: transparent;
    background-position: center bottom;
}

h1 {
    color: white;
    text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4),
                0px 8px 13px rgba(0, 0, 0, 0.1),
                0px 18px 23px rgba(0, 0, 0, 0.2);
    font-family: 'Source Sans Pro', sans-serif;
}

.navbar-brand {
    color: white;
    text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4),
                0px 8px 13px rgba(0, 0, 0, 0.1),
                0px 18px 23px rgba(0, 0, 0, 0.2);
    font-family: 'Source Sans Pro', sans-serif;
}

.navbar.bg-dark.navbar-dark {
    background-color: transparent !important;
}

body {
    background-image: url('https://images.unsplash.com/photo-1588774210246-a1dc467758df?ixlib=rb-1.2.1&auto=format&fit=crop&w=1934&q=80')

}

.card-body {
    font-family: 'Source Sans Pro',
}

.lead {
    color: white;
    text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4),
                0px 8px 13px rgba(0, 0, 0, 0.1),
                0px 18px 23px rgba(0, 0, 0, 0.2);
    font-family: 'Source Sans Pro', sans-serif;
}

.card-body {
    background-color: gray;
    opacity: 80%;
}

.card-title {
    color: white;
    font-family: 'Source Sans Pro', sans-serif;
}

.card-text {
    color: white;
    font-family: 'Source Sans Pro', sans-serif;
}

A: *

*I have fixed your navigation issue. You may need to change the style of the navigation items.

*I also fix your icon display issue, you need to use Font Awesome 4 style. fa fa-heart-o

*Finally, I also add in CSS code to make the background of the card body becomes 80% transparent. Class .card background-color need to set to transparent and class card-footer background-color need to set to white.

.card {
  background-color: transparent !important;
}
.card-body {
    background-color: gray;
    opacity: 80%;
}
.card-footer {
  background-color: #fff !important;
}

#header {
    background-color: transparent;
    background-position: center bottom;
}

h1 {
    color: white;
    text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4),
                0px 8px 13px rgba(0, 0, 0, 0.1),
                0px 18px 23px rgba(0, 0, 0, 0.2);
    font-family: 'Source Sans Pro', sans-serif;
}

.navbar-brand {
    color: white;
    text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4),
                0px 8px 13px rgba(0, 0, 0, 0.1),
                0px 18px 23px rgba(0, 0, 0, 0.2);
    font-family: 'Source Sans Pro', sans-serif;
}

.navbar.bg-dark.navbar-dark {
    background-color: transparent !important;
}

body {
    background-image: url('https://images.unsplash.com/photo-1588774210246-a1dc467758df?ixlib=rb-1.2.1&auto=format&fit=crop&w=1934&q=80')

}

.card-body {
    font-family: 'Source Sans Pro',
}

.lead {
    color: white;
    text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4),
                0px 8px 13px rgba(0, 0, 0, 0.1),
                0px 18px 23px rgba(0, 0, 0, 0.2);
    font-family: 'Source Sans Pro', sans-serif;
}
.card {
  background-color: transparent !important;
}
.card-body {
    background-color: gray;
    opacity: 80%;
}
.card-footer {
  background-color: #fff !important;
}
.card-title {
    color: white;
    font-family: 'Source Sans Pro', sans-serif;
}

.card-text {
    color: white;
    font-family: 'Source Sans Pro', sans-serif;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

  Quarantine Pal

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

Home

                About

          Our Mission

          Our Team

          FAQ

Contact

Our Founder

Press

Sign Up

Login

Quarantine State of Mind

Exploring the 'New Normal'

  Sign Up
  Login

Self-Care and Burn Out

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

        Download

Help Fight Coronavirus

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

        Download

Pandemic Socializing

This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.

Last updated 3 mins ago

        Download


Q: connect to Apple Watch through node.js I am looking to try to connect a workout from my Apple Watch to my node.js application. I am not using react or anything, I just specifically want to connect to the Apple Watch through node.js and grab the data.
Is it possible through an Api, without using swift?

A: You can use any API provided by apple to use it in your React app. You can find the documentation here.


Q: Can't add compiler options for nvcc in nsight eclipse How do I add options to my nvcc using nsight eclipse. I tried to modify the command option Under Project->Properties->Build->Settings->Tool Settings-> NVCC Compiler. I changed it from "nvcc" to "nvcc --someoption". However when it compiles I see this output "/usr/local/cuda-7.0/bin/nvcc -O3 -ccbin gcc-4.9 -std=c++11 -gencode arch=compute_35,code=sm_35 -gencode arch=compute_52,code=sm_52 -odir "." -M -o "binomial.d" "../binomial.cu"
Notice that --someoption in not in it. How can I add an option in eclipse?  I also noticed that I can change the command from nvcc to some gibberish and it still compiles so I think that option does not affect anything.  If so how can I add compiler options which eclipse does not include in its gui.

A: I would recommend using the -optf switch that is selectable under Project Settings... Build ... Settings...Tool Settings...Miscellaneous and add your own file to the project that contains whatever compiler switches you want to add.
I think most compiler switches are already covered in the GUI, however.


Q: runtime error : return value gets lost I'm working on this project : https://github.com/zsteve/zebra-zmachine-interpreter
which is supposed to be an interpreter for z-machine story files, but I'm still working on it.
Anyway, the error I'm having is within ztext.cpp and ZDictionary's unit test main.cpp.
zChartoDictionaryZCharString() is supposed to return a pointer to a string/array of zwords.
It is creating/calculating that array properly, but is strangely failing to return it properly...
the error occurs at line 499 of ztext.cpp :
[code]  return (outWord);[/code]
Right at this point, outWord points to an array of zwords : {15 25, 28 ab} allocated by new[]
Once it returns to line 42 in https://github.com/zsteve/zebra-zmachine-interpreter/blob/master/zdictionary/zdictionary/main.cpp ,
the returned zword* now points to {50 00, 00 00}, which shouldn't happen.
I spent an hour debugging the entire thing until I figured out that this was where it went wrong.
So my question is : what causes this problem in my program?
I suspect it's either unmatched new[]/delete[] (could this cause it?) or the std::vector objects in zChartoDictionaryZCharString().
Here is the code :
in main.cpp (/zdictionary/zdictionary/main.cpp) from line 40:
// error occurs here :
// at this point : tmp == {15 25 28 ab}
zword* tmp=zChartoDictionaryZCharString(tmp_);

in ztext.cpp (/ztext/ztext/ztext.cpp) from line 502:
zword* zChartoDictionaryZCharString(zword* zstring)
{
// converts a normal zchar string to a dictionary zchar string
// returns a zword* to either a 2 or 3 zword array.
    std::vector<zchar> vector1=expandZChars(zstring);
    std::vector<zchar> vector2(0);
    if(zVersion<=3){
        // for versions 1 to 3, dictionary word length is 4 bytes (6 zchars)
        int done=0;
        for(int i=0; i<vector1.size() && i<6; i++, done++)
        {
            vector2.push_back(vector1[i]);
        }
        if(done<6)
        {
            for(int i=done; i<6; i++)
            {
                vector2.push_back(5);
            }
        }
        // now we need to pack them to 2x zwords.
        zword* outData=new zword[2];
        zchar* zcharArray=new zchar[vector2.size()];
        for(int i=0; i<vector2.size(); i++) zcharArray[i]=vector2[i];
        outData[0]=endianize(packZChars(zcharArray));
        outData[1]=endianize(packZChars(zcharArray+3)|128);
        delete[] zcharArray;
        vector1.clear();
        vector2.clear();
        return outData;
    }else if(zVersion>3){
        // for versions 4 and up, dictionary word length is 6 bytes (9 zchars)
        int done=0;
        for(int i=0; i<vector1.size() && i<9; i++, done++)
        {
            vector2.push_back(vector1[i]);
        }
        if(done<9)
        {
            for(int i=done; i<9; i++)
            {
                vector2.push_back(5);
            }
        }
        // now we need to pack them to 3x zwords.
        zword* outData=new zword[3];
        zchar* zcharArray=new zchar[vector2.size()];
        for(int i=0; i<vector2.size(); i++) zcharArray[i]=vector2[i];
        outData[0]=packZChars(zcharArray);
        outData[1]=packZChars(zcharArray+3);
        outData[2]=packZChars(zcharArray+6);
        outData[2]|=128;
        for(int i=0; i<3; i++) outData[i]=endianize(outData[i]);
        delete[] zcharArray;
        return outData;
    }
}

Any help on fixing this would be greatly appreciated.
Thanks!


Q: java array casting? How can it be that i get a class cast exception when i try to do:
PrioritetArraySorteret<String> p = new PrioritetArraySorteret<String>();

the error is in the constructor?
public class PrioritetArraySorteret<E> implements PrioritetADT<E> {
private int capacity = 5;
private Entry S[];
private int size;

public PrioritetArraySorteret() {
    S = (Entry[]) new Object[capacity];
    size = 0;
}

private class Entry implements Comparable<Entry> {
    private int key;
    private E value;

    public Entry(int key, E value) {
        this.key = key;
        this.value = value;
    }

    public int getKey() {
        return key;
    }

    public E getValue() {
        return value;
    }

}

A: You really are declaring an array of type Object and trying to cast it, which doesn't work. Instead, in your constructor, do:
S = new Entry[capacity];

A: Why do you do a cast in
S = (Entry[]) new Object[capacity];

and not just
S = new Entry[capacity];

That would probably solve the problem.

A: Your error appears to be attempting to mix generics with something that can't handle this use of generics - namely, arrays.
Changing the definition of S to List<Entry<E>>, and the instantiation to new ArrayList<Entry<E>>(capacity) allows your program to run (given the limited sample).
Some other random notes, given your sample:

*

*You've named your array-to-sort S.  Please follow the standard naming conventions (other people will expect you to), and give it a meaningful name.  It doesn't help that it may look similar to 5 (depends on font, I'll admit).

*capacity is an instance variable used for initialization for every instance of the class (and nowhere else).  Change this to a final static variable and/or change the name of the variable to reference why this is the case

*You define size - Likely, you should be returning S.size() regardless, unless you have some (unstated) specific need.

*Your use of the terms key and value suggests you are attempting to use (or maybe implement) a HashMap.


Q: How do I make it so my code displays a cerrtain amount of lines (like it does) but backwards So when I enter 4, instead of say 4 bottles of beer etc, It will start with 100 and go to 96 and then stop (ending with the final line)
import java.util.Scanner;

public class ThreeDotNine {
  public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.print("How many Verses would you like to print:  ");
      String num = sc.nextLine();
      int num2 = Integer.parseInt(num);
      String s = " ";

      for (int x = num2; x > 0; x--) {
          System.out.println(x + " bottles of beer on the wall " + x + " bottles of beer");
          System.out.println("Take one down, pass it around, " + (x - 1) + " bottles of beer on the wall.\n");
      }
      System.out.print("Go to the store, buy some more, ");
      System.out.println("99 bottles of beer on the wall.\n");

  }
}

A: there is nothing wrong with the program. It works fine, Just check it again
How many Verses would you like to print:  4
4 bottles of beer on the wall 4 bottles of beer
Take one down, pass it around, 3 bottles of beer on the wall.

3 bottles of beer on the wall 3 bottles of beer
Take one down, pass it around, 2 bottles of beer on the wall.

2 bottles of beer on the wall 2 bottles of beer
Take one down, pass it around, 1 bottles of beer on the wall.

1 bottles of beer on the wall 1 bottles of beer
Take one down, pass it around, 0 bottles of beer on the wall.

Go to the store, buy some more, 99 bottles of beer on the wall.

A: I would try it like that:
for ( int x = 0; x <= num2; x++ ) {
  int y = 100 - x;

  System.out.println(y + " bottles of beer on the wall " + y + " bottles of beer");
  System.out.println("Take one down, pass it around, " + (y - 1) + " bottles of beer on the wall.\n");
}

It's easier to understand if you define a second variable.
Now you have your output with
100
99
98
97
96


Q: How to deserialize derived class with other derived class as property I have 2 projects. One is a WPF application and second is my "toolkit" with predefined WPF control, XML deserialization and some base configuration classes.
In my toolkit I have a ConfigurationBase class:
public class ConfigurationBase : XmlDeserializeConfigSectionHandler
{
      public GuiConfigurationBase GuiConfiguration { get; set; }
}

This is GuiConfigurationBase
public class GuiConfigurationBase
{
    public int LogLineCount { get; set; }
}

My toolkit contains predefined View for in app log messages. So my LogViewModel constructor requires a ConfigurationBase which should contain GuiConfiguration with LogLineCount property.
This is because I don't want to implement in app log for every application.
Then I have a WPF project. It contains a class Config which is derived from ConfigurationBase. It's extended with some other props which are not important.
I also needed to extend GuiConfigurationBase so I have class called GuiConfiguration which derives from GuiConfigurationBase.
public class Config : ConfigurationBase
{
    public string AppName { get; set; }
}

public class GuiConfiguration : GuiConfigurationBase
{
    public int TextSize { get; set; }
}

I am also using XmlSerializer for deseserializing my XML file. I need to fill both of my derived classes.
How I can achieve this please?
I tried some abstraction for base classes but with no success.
Thank you for any suggestion.

A: I found a solution.
It's necessary to use XmlAttributeOverrides.
Because I have two projects I had to use reflection to retrieve classes which derive from GuiConfigurationBase. (I don't know anything about project where is my toolkit project referenced)
Then add new XmlElementAttribute for each class (in my case it should be enough to use Linq First() method) - This should be same as XmlIncludeAttribute(Type)
And finaly add XmlAttributeOverrides for ConfigurationBase class's property GuiConfiguration
Here is my deserialize method:
 public T Deserialize<T>(string input) where T : class
    {
        //Init attrbibutee overrides
        XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
        XmlAttributes attrs = new XmlAttributes();

        //Load all types which derive from GuiConfiguration base
        var guiConfTypes = (from lAssembly in AppDomain.CurrentDomain.GetAssemblies()
                            from lType in lAssembly.GetTypes()
                            where typeof(GuiConfigurationBase).IsAssignableFrom(lType) && lType != typeof(GuiConfigurationBase)
                            select lType).ToArray();

        //All classes which derive from GuiConfigurationBase
        foreach (var guiConf in guiConfTypes)
        {
            XmlElementAttribute attr = new XmlElementAttribute
            {
                ElementName = guiConf.Name,
                Type = guiConf
            };

            attrs.XmlElements.Add(attr);
        }

        //Add Attribute overrides for ConfigurationBase class's property GuiConfiguration
        attrOverrides.Add(typeof(ConfigurationBase), nameof(ConfigurationBase.GuiConfiguration), attrs);

        XmlSerializer ser = new XmlSerializer(typeof(T), attrOverrides);

        using (StringReader sr = new StringReader(input))
        {
            return (T)ser.Deserialize(sr);
        }
    }

I hope it will help someone else :-)


Q: Capture time difference between values of two regular expression reference names in Jmeter I defined regular expressions in my JMeter test plan and I'm able to capture the values in simple variables in user.variables. But I'm trying to calculate the time difference between two variables as follows in Beanshell post processor and I'm not getting any result in my report.
import javax.xml.bind.DatatypeConverter;

vars.put("old_date_submitted", "submittedDate"); // submittedDate, succeeddedDate and runningDates are regular expr. reference names
vars.put("old_date_succeeded", "succeededDate");
vars.put("old_date_running", "runningDate");

Calendar cal_s =       DatatypeConverter.parseDateTime(vars.get("old_date_submitted"));
Calendar cal_c = DatatypeConverter.parseDateTime(vars.get("old_date_succeeded"));
Calendar cal_r = DatatypeConverter.parseDateTime(vars.get("old_date_running"));

Date new_date1 = cal_s.getTime(); // submitted Time
Date new_date2 = cal_c.getTime(); // succeeded Time
Date new_date3 = cal_r.getTime(); // running Time

long new_date1_ms = new_date1.getTime(); // submitted Time
long new_date2_ms = new_date2.getTime();
long new_date3_ms = new_date3.getTime();

log.info("Date in milliseconds: " + new_date1_ms);

long delta1 = new_date2_ms - new_date1_ms; //calculate the difference (succeededDate - submittedDate)
long delta2 = new_date3_ms - new_date1_ms; //calculate the difference (runningDate - submittedDate)
vars.put("delta1", String.valueOf("delta1")); // store the result into a JMeter Variable
vars.put("delta2", String.valueOf("delta2")); // store the result into a JMeter Variable

A: This bit:
vars.put("old_date_submitted", "submittedDate"); // submittedDate, succeeddedDate and runningDates are regular expr. reference names
vars.put("old_date_succeeded", "succeededDate");
vars.put("old_date_running", "runningDate");

seems odd to me. Given:

submittedDate, succeeddedDate and runningDates are regular expr. reference names

My expectation is that you should be using JMeter Variables instead of hardcoded strings there, so you should change your code to look like:
vars.put("old_date_submitted", vars.get("submittedDate")); // submittedDate, succeeddedDate and runningDates are regular expr. reference names
vars.put("old_date_succeeded", vars.get("succeededDate"));
vars.put("old_date_running", vars.get("runningDate"));

So most likely your code is failing at DatatypeConverter.parseDateTime.
Next time you face any problem with your Beanshell scripts consider the following troubleshooting techniques:

*

*Check jmeter.log file - in case of Beanshell script failure the error will be printed there

*Add debug(); directive to the very beginning of your Beanshell script - it will trigger debugging output to stdout

*Put your Beanshell code in try/catch block like:
try {
    //your code here
}
catch (Throwable ex) {
    log.error("Something went wrong", ex);
    throw ex;
}

This way you get more "human-friendly" stacktrace printed to jmeter.log file.
See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information on using Beanshell in JMeter tests.


Q: Generic response in retrofit I have 2 calls using retrofit, because the API is poorly design I get difference structure of JSON so I have two different model objects.
what I want to achieve is smaller fetch method and to avoid the duplicate code. I'm trying to use generic class for the pojo but without success.
Thanks,
my models:
   public class GenreResponse {
      @SerializedName("genre") @Expose private Genre genre;
      @SerializedName("sort") @Expose private String sort;
      @SerializedName("page") @Expose private Integer page;
      @SerializedName("limit") @Expose private Integer limit;
      @SerializedName("events") @Expose private List<Movie> events;
      @SerializedName("subGenres") @Expose private List<SubGenre> subGenres = new ArrayList<>();

      public List<SubGenre> getSubGenres() {
        return subGenres;
      }

      public Genre getGenre() {
        return genre;
      }

      public String getSort() {
        return sort;
      }

      public Integer getPage() {
        return page;
      }

      public Integer getLimit() {
        return limit;
      }

      public List<Movie> getEvents() {
        return events;
      }

    }

    public class GeneralSearchResponse {
      @SerializedName("query")   @Expose private String query;
      @SerializedName("sort")    @Expose private String sort;
      @SerializedName("page")    @Expose private String page;
      @SerializedName("limit")   @Expose private Integer limit;
      @SerializedName("amount")  @Expose private Integer amount;
      @SerializedName("events")  @Expose private List<Movie> events;
      @SerializedName("sideNav") @Expose private List<SideNav> sideNavList = new ArrayList<>();

      public List<Movie> getEvents() {
        return events;
      }

      private class SideNav {
        @SerializedName("id")           @Expose private Integer id;
        @SerializedName("name")         @Expose private String name;
        @SerializedName("englishName")  @Expose private String englishName;
        @SerializedName("amount")       @Expose private Integer amount;
        @SerializedName("isKidsEvents") @Expose private Boolean isKidsEvent;
      }
    }

my method:
 private void fetchGenresData(String genreId, int page, final boolean addMore, String sortType) {
    switch (fragmentMode) {
      case MODE_GENRE:
        Observable<GenreResponse> observableGenre = RxUtils.wrapRetrofitCall(
            VODApplication.getInstance()
                .getApi()
                .getGenres(genreType, genreId, page, DEFAULT_PAGE_LIMIT, sortType));

        RxUtils.wrapAsync(observableGenre).subscribe(new Action1<GenreResponse>() {
          @Override public void call(GenreResponse response) {

            if (addMore) {
              mAdapter.remove(mAdapter.getItemCount() - 1);
              mAdapter.addAll(response.getEvents());
            } else {
              // called for the first time.
              mAdapter.setGenres(response.getEvents());
              mSpinnerView.setListener(GenreFragment.this);
              mSpinnerView.initSpinners(response);
            }

            isLoading = false;
          }
        }, new Action1<Throwable>() {
          @Override public void call(Throwable t) {
            ((GenreScreen) getActivity()).getDialog().dismiss();
          }
        });
        break;

      case MODE_SEARCH:
        AppUtils.hideKeyboard(getActivity());

            .enqueue(new Callback<GeneralSearchResponse>() {
              @Override public void onResponse(Call<GeneralSearchResponse> call,
                  Response<GeneralSearchResponse> response) {

                if (addMore) {
                  mAdapter.remove(mAdapter.getItemCount() - 1);
                  mAdapter.addAll(response.body().getEvents());
                } else {
                  // called for the first time.
                  mAdapter.setGenres(response.body().getEvents());
                  mSpinnerView.setListener(GenreFragment.this);
                }

                isLoading = false;
              }

              @Override public void onFailure(Call<GeneralSearchResponse> call, Throwable t) {
                Log.d(TAG, "call: " + t.getMessage());
              }
            });
        break;
    }
  }


Q: Positioning 2 elements (countdown timer and button) in row, side by side - they are not centered I have a problem with one of sections in my HTML code.
My idea is simply: one section made by 1 row, who is divided on 2 columns.
In left column i tried to put countodwn timer, and "submit" button in right column. They have to be side by side, and on equal distance in regards to each other; but there are some problems - they are on unequal distance and i am wondering how to fix it...
Also, when i test how draft of my site looks on mobile, parts of the clock do not stay together - they just move under each other.
Here is a jsfiddle.
What i am doing wrong?

Deadline:

Days

Hours

Minutes

Seconds

<button class="button button1" style="width: 300px; height: 100px;">Submit</button>

And CSS:
  #clockdiv{
    font-family: Open Sans;
    color: #ffffff;
    display: inline-block;
    font-weight: 100;
    text-align: center;
    font-size: 30px;
  }

  #clockdiv > div{
    padding: 0px;
    border-radius: 3px;
    background: #fffff;
    display: inline-block;
  }

  #clockdiv div > span{
    padding: 15px;
    border-radius: 3px;
    background: #000;
    display: inline-block;
    position: relative;

  }

  .smalltext{
    padding-top: 5px;
    font-size: 16px;
    color: #000;
    position: relative;

  }

  .button {
    background-color: #fff;
    border: none;
    color: white;
    text-align: center;
    text-decoration: none;
    font-size: 16px;
    font-family: 'Open Sans';
    margin: 4px 2px;
    -webkit-transition-duration: 0.4s;
    transition-duration: 0.4s;
    cursor: pointer;
  }

  .button1 {
    background-color: white;
    color: #000;
    border: 2px solid #000;

  }

  .button1:hover {
    background-color: #fff;
    color: white;


Q: regex to filter php array by conditional existence of value I have have a php array
    $arr[0] = "something/somethingelse/anotherval";
    $arr[1] = "something/!somevar/anotherval";
    $arr[3] = "something/!notcorrect/anotherval";
    $arr[4] = "something/somethingelse/_MyVal";
    $arr[5] = "something/_MyVal/anotherval";
    $arr[6] = "something/_AnotherNotCorrect/anotherval";

I'm using array_filter to filter the array by certain criteria...
    $f = array_filter(array_keys($arr), function ($k){
    return ( strpos($k, 'something/') !== false ); });

This returns all my vals where the term something/ is matched... I'd like to be able to say IF we encounter a ![something here] or a _[something here] then we need to make sure that the [something here] matches either $afterExcl or $afterUnderscore. If we didn't encounter a ! or _ then just check the strpos($k, 'something/') !== false check...
(notice that the ! and _ portions may or may not be at the end of val string)
I'm assuming this is regex, but I've always struggled to build them.
CLARIFICATION
Thanks. Clarification though, the ! or _ sequence may not be the next directory after something/, it may three or four more steps in. AND, I'll be providing a $afterExcl or $afterUnderscore value which will designate approved values. Basically the client is using ! and _ to denote "regions" ie.
something/images/!Canada
something/videos/tutorials/!Canada or
something/images/!USA or
something/images/!Mexico OR last
something/images/All
then I'd specify
$afterExcl=Canada
My filter would return
something/images/!Canada
something/videos/tutorials/!Canada
something/images/All

A: You can use something like this:
$f = array_filter(array_keys($arr), function ($k){
    return preg_match('~something/(?![_!])~', $k); });

The negative lookahead (?!...) checks if the slash isn't followed by a ! or a _.
Note that preg_match returns 1 if found or 0 if not. If you want to return true or false you can do it with the ternary operator:
return preg_match('~something/(?![_!])~', $k) ? true : false;

an other way:
If you use strpos, I assume that the string you describe as 'something/' is a fixed string $str, in other words you know the length of this strings. Since strpos returns the position $pos in the string of the occurence, you can easily check if at the position $pos + strlen($str) there is either an exclamation mark or an underscore. (you could, for example, extract this next character and check if it is in the array array('!', '_'))


Q: ssis 2008, delete contents from excel im using SSIS for SQL Server 2008.
My SSIS package grabs data from sql and exports it to an excel file. But everytime it does this I want new data on the excel.
The problem right now is, If i execute the package more than one time I will have the old data plus the new one on the excel file. I only want the new data displayed.
On the SSIS, on the Control Flow tab I have an Data Flow task. On the Data Flow tab I have an OLEDB source and an Excel Destination in order to put the data on the excel.
So im thinking on deleting the contents from the excel on the SSIS every time before the data gets inserted on the excel.
The excel file has an image, a title and the column names. I want these data to stay.
But I want the data from the rows deleted.
How can I do this?
Thanks...

A: Ok. What I did was to make a copy of the file and load the data on the new file, and everytime the ssis loads it overwrites the file, so I always have new data..........Thanks!!


Q: google script detect empty cell after edit -- Take 2 This is related to onEdit functionality and a question with the same title found here .
I am not getting the responses they are indicating I might or should when cells go from having values to empty, and those work around solutions did not work as a result. It's as if something has changed since those answers were given or there is different underlying behavior.
Here is a link to spreadsheet with a simple example.
In this example, I have a cell with data validation on it. In context, this cell allows me to pick sales ticket IDs from a list to recall data. After I have recalled the data, if I remove the value from the selection cell with backspace or delete, the onEdit function should be called, a falsy value should exist for "e.value" and I should be able to clear the data it retrieved.  Pretty simple.
== Full Testing Protocal ==
1) When the cell is blank and I pick a value from the list,  I test the e.value property for truthy, i get truthy response, and it completes a function to get data.
2) When the cell is NOT blank and I pick a value from the list,  I test the e.value property for truthy, i get truthy response, and it completes a function to get data.
3) When the cell is NOT blank, and I click into the cell and select backspace or delete to empty the cell. I test the e.value property for truthy and instead of getting a falsy response, I get an object back?!   {old_value=xxxx}.
So, not only do I not get a falsy value, I get an object returned instead that is missing the value item in it??
From looking at the other post, it seems when there is no "value", google has decided to leave the "value" item out of the e object instead of leaving "value" item in the e object  and setting it to null or blank.
I don't know why that was chosen, but that's the way I interpret that.  That said, it seems to me that decision should not have mattered.
If I'm testing for an item in an object and the item doesn't exist, I should get a falsy of some sort, but instead, I'm getting an object returned to me?!
The only way that I know of that might to work around this is to check for variable type to see if an object was returned which is really terribly confusing for those new to programming and shouldn't be required. I will try that shortly, but wanted to get this out first.
I do recall running into this several years ago and not taking the time to try to get a sound answer.
function onEdit(e){
  Logger.log("onEdit running")
  var ss =        SpreadsheetApp.getActiveSpreadsheet();

  if (ss.getRangeByName("sTkt_uniqueID_recall").getA1Notation() == e.range.getA1Notation() ){
    Logger.log("onEdit - sTkt_uniqueID_recall")

    if(e.value){
      Logger.log("recall ID cell has value - get Data")
      Logger.log(e.value)
      //sTkt_getRecallData()

    }else{
      //oE.value should be blank, null or something falsy..
      //instead an object is returned?! {old_value: xxxxxx}
      // and thus is not null and thus it never gets here..
      Logger.log("recall ID cell now empty - clear Data")
      Logger.log(e.value)
      //sTkt_clearForm()
    }
    Logger.log("onEdit fxnComplete")
  }
}

Thanks for the help with this.
EDIT:  Added logs.
Logs when item is in cell...
[19-10-20 15:17:18:071 PDT] onEdit running
[19-10-20 15:17:18:159 PDT] onEdit - sTkt_uniqueID_recall
[19-10-20 15:17:18:160 PDT] recall ID cell has value - get Data
[19-10-20 15:17:18:160 PDT] 1002
[19-10-20 15:17:18:161 PDT] onEdit fxnComplete

Logs when item has been deleted -- it takes wrong path b/c of the object with oldValue in it...
[19-10-20 15:15:25:411 PDT] onEdit running
[19-10-20 15:15:25:509 PDT] onEdit - sTkt_uniqueID_recall
[19-10-20 15:15:25:510 PDT] recall ID cell has value - get Data
[19-10-20 15:15:25:511 PDT] {oldValue=1001.0}
[19-10-20 15:15:25:511 PDT] onEdit fxnComplete

EDIT: Providing the full event object shows this clearly. Should have just done that earlier.  As you can see old value is in there, but there is an object being returned for "value" instead of a falsy (blank or something else)...
[19-10-20 15:54:19:750 PDT] {authMode=LIMITED, range=Range, source=Spreadsheet, oldValue=10/3/2019--6939, user=xxx@xxxxacupuncture.com, value={oldValue=10/3/2019--6939}}

EDIT: I've tested a work around and this is the one I will likely use as it remind me of exactly what is going on AND Im thinking if the issue gets cleaned up or fixed, this work around should still work and I wouldn't need to make any changes in places it may go in.
if(e.value && typeof e.value !== 'object')

A: *

*In your situation, using your shared Spreadsheet, when you delete the value from the cell "C4" of the data validation with the delete button, the event object of e of onEdit(e) has "value":{"oldValue":"deleted value"}.

*

*You want to know about this situation.

If my understanding is correct, how about this answer?
When I had tested this, in your situation, I noticed that the border of cell under the simple trigger is related to this situation.
Preparation 1:
For the explanation, it supposes as follows.

*

*Create new Spreadsheet.

*Put a text of sample to the cell "A1".

*Set a simple trigger of the OnEdit event trigger as the script of function onEdit(e) {Logger.log(JSON.stringify(e))}.

*

*At the explanation, e of the event object is used, when the OnEdit event trigger was fired.

Sample situations 1:

Situation 1A:

When the value of sample of the cell "A1" is deleted by the delete button, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"user":{"nickname":"","email":""}}

Situation 1B:

When the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","user":{"nickname":"","email":""},"value":{"oldValue":"sample"}}

Sample situations 2:
Here, in order to replicate your situation, please set the border to the cell "A1".

Situation 2A:

When the value of sample of the cell "A1", which was surrounded by the border, is deleted by the delete button, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","user":{"nickname":"","email":""},"value":{"oldValue":"sample"}}

Situation 2B:

When the text of sample in the cell "A1", which was surrounded by the border, is deleted by deleting each character using the backspace key, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","user":{"nickname":"","email":""},"value":{"oldValue":"sample"}}

Preparation 2:
For the explanation, it supposes as follows.

*

*Create new Spreadsheet.

*Put a text of sample to the cell "A1".

*Copy and paste the script of function InstallOnEdit(e) {Logger.log(JSON.stringify(e))}.

*

*At the explanation, e of the event object is used, when the OnEdit event trigger was fired.

*Set the installable OnEdit event trigger to the function of InstallOnEdit.
Sample situations 1:

Situation 1A:

When the value of sample of the cell "A1" is deleted by the delete button, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"triggerUid":"###","user":{"nickname":"###","email":"###@gmail.com"}}

Situation 1B:

When the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","triggerUid":"###","user":{"nickname":"###","email":"###@gmail.com"}}

Sample situations 2:
Here, in order to replicate your situation, please set the border to the cell "A1".

Situation 2A:

When the value of sample of the cell "A1", which was surrounded by the border, is deleted by the delete button, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","triggerUid":"###","user":{"nickname":"###","email":"###@gmail.com"}}

Situation 2B:

When the text of sample in the cell "A1", which was surrounded by the border, is deleted by deleting each character using the backspace key, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","triggerUid":"###","user":{"nickname":"###","email":"###@gmail.com"}}

Results and discussions:
From above experiment, the following results could be obtained.

*

*Values of the event object depend on the situation with and without the border of cell.

*

*Also above situation can be seen at not only the border, but also the cases that the background color of the cell, the format (font color, size, bold and so on) except for the default font format.

*It seems that when the cell and font are changed from the default settings, the event object returns the values of "Sample situations 2".

*Values of the event object also depend on with and without using the installable event trigger.

*In the case of the cell with the default cell and font under the simple trigger,

*

*When the value of sample of the cell "A1" is deleted by the delete button, e of the event object has no both oldValue and value.

*When the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object has both oldValue and value. And value is {"oldValue":"deleted value"}.

*In the case of the cell with the border under the simple trigger,

*

*When the value of sample of the cell "A1" is deleted by the delete button and also the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object has both oldValue and value. And value is {"oldValue":"deleted value"}.

*In the case of the cell with the default cell and font under the installable trigger,

*

*When the value of sample of the cell "A1" is deleted by the delete button, e of the event object has no both oldValue and value.

*When the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object has oldValue and no value. And oldValue is the deleted value which is not the object.

*In the case of the cell with the border under the installable trigger,

*

*When the value of sample of the cell "A1" is deleted by the delete button and also the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object has oldValue and no value. And oldValue is the deleted value which is not the object.

From above results, I thought that the values (no both oldValue and value) of event object from the default condition of the cell and font might be a bug or the specification. But I had looked for the official document about this. Unfortunately, I couldn't still find it.
About your situation:
Using above results, when your shared Spreadsheet was tested, the cell "C4" is surrounded by the border. And the simple trigger is used. So the situation is the same with above "Sample situations 2" of "Preparation 1". By this, when the value of cell "C4" is deleted by the delete button, "value":{"oldValue":"deleted value"} is returned.
In this case, how about the following method?

*

*When you want to use the simple trigger, I think that the script of the bottom of your question can be used.

*When you can use the installable OnEdit event trigger, you can know whether the value was deleted by checking with and without value in the event object e.

References:

*

*Event Objects

*Simple Triggers

*Installable Triggers


Q: Qt font renders weird on OS X I just started using Qt (using Qt 5 beta 1), and I found that the fonts rendered in OS X 10.6.8 are messed up. I've tried using different fonts, but they all look like the image I've posted below (very thin, pixelated). How can I get the fonts to render correctly?
The code I'm using is simply:
#include <QApplication>
#include <QLabel>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QLabel label("The quick brown fox jumps over the lazy dog...");
    label.show();
    return a.exec();
}


Q: MATLAB Fit a line to a histogram I am just wondering, how would I go about fitting a line to histogram, using the z-counts as weights? An example of this is shown below (although this post just discusses overlaying multiple plots), taken from Scatter plot with density in Matlab).
My initial thought is to make an array consisting of each pixel from the density plot, repeated n times to make a scatter plot (n == the number of counts), then do a linear polyfit. This seems awfully redundant though.

A: The other approach is to do a weighted least squares solution.  You need the (x,y) location of each pixel and the number of counts n within each pixel.  Then, I think that you'd do the weighted least-squares this way:
%gather your known data...have x,y, and n all in the same order as each other
A = [x(:) ones(length(x),1)];  %here are the x values from your histogram
b = y(:);  %here are the y-values from your histogram
C = diag(n(:));  %counts from each pixel in your 2D histogram

%Define polynomial coefficients as p = [slope; y_offset];

%usual least-squares solution...written here for reference
% b = A*p;               %remember, p = [slope; y_offset];
% p = inv(A'*A)*(A'*b);  %remember, p = [slope; y_offset];

%We want to apply a weighting matrix, so incorporate the weighting matrix
% A' * b = A' * C * A * p;
p = inv(A' * C * A)*(A' * b);  %remember, p = [slope; y_offset];

The biggest uncertainty for me with this solution is whether the C matrix should be made up of n or n.^2, I can never remember.  Hopefully, someone can correct me in the comments, if needed.

A: If you have the original data, which is a collection of (x,y) points, you simply do a polyfit on the original data:
p = polyfit(x(:),y(:),1);  %linear fit

That will give you a best fit (in the least-squares sense) to the original data, which is what you want.
If you do not have the original data, and you only have the 2D histogram, the approach that you defined (which basically recreates a facsimile of the original data) will give a similar answer as if you did the polyfit on the original data.


Q: Custom image shuffler not working? Basically, what I'm trying to do is shuffle through images using some JavaScript code. All it does is change the display style of the current image to block, and at the same time change the previous one to none.
The HTML code:

The JavaScript code:
var id = ["image1", "image2", "image3"]; //Array with the id's in the document you want
to shuffle through
var i = 0; //Set inital array element
initiateTimer(); //Get the loop going

function initiateTimer() {
if (i > id.length) {
    i = 0;
    initiateTimer();
}
setTimeout(function() { changeElement(); }, 2000); //2000 = 2 seconds
}

function changeElement() {
if (id === 0) {
    document.getElementById(id[2]).style.display = 'none';
    document.getElementById(id[i]).style.display = 'block';
} else {
    document.getElementById(id[i - 1]).style.display = 'none';
    document.getElementById(id[i]).style.display = 'block';
}
i += 1;
initiateTimer();
}

A: when i === 3 you will have problems
if (i > id.length) {

should become
if (i >= id.length) {

UPDATE: http://jsfiddle.net/HgNuc/


Q: Cant open a doc file from the browser I have a link using  tag and it is linked to a .doc file in the server. When I click on the link, instead of giving the open, save box, it opens the file in the browser in the binary format. Has anyone encountered this problem? I am using a Weblogic server.

A: As Russ said, sometimes you have to add the Content-Type header to explicitly set the mime type; and sometimes, you also have to add a Content-Disposition header, perhaps to a value like

"attachment; filename=doc1.doc"

If Russ' fix doesn't work for you, try adding this additional header.

A: try setting the MIME Type, possibly to application/msword or application/doc
EDIT:
If the server doesn't know the mime type of the file then it defaults to text/plain and displays the bytes.


Q: Why is Microsoft.PythonTools.Attacher.exe blocking Visual Studio 2010? At least two or three times a day Visual Studio gets stuck (in a deadlock I suspect) and displays the spinning-toilet-bowl-of-death cursor and pops up the dreaded "Microsoft Visual Studio is Busy" notification in the notification area:

It used to be that when this happened Visual Studio would stay like that for hours (and possibly until the end of time itself or a power cut) unless I kicked it to the kerb with an "End Process" in task manager.
More recently I noticed another process always seemed to be lurking about whenever this problem arises - Microsoft.PythonTools.Attacher.exe - which is part of the Python Tools for Visual Studio project:

If I kill that process then Visual Studio manages to free itself from whatever deadly embrace it's got itself into and can continue on its way, and this is what I look out for every time VS does this.
Whilst I do have Python Tools for Visual Studio 1.0 installed, the projects I am working on are plain old ASP.NET MVC3 apps written in C#. I'm not using any Python code or libraries and often I only have one instance of Visual Studio running.
What I also observe is that this process doesn't always start/appear for whole development sessions, and when it does, it seems to start up an random times (i.e. it's not there for the first hour or two and then it magically appears in the process list in task manager), but when it does I know I'm going be in trouble at some point.
Does anyone know why this process seems to randomly start and why it's interfering with Visual Studio in such a dramatic fashion?
I'm running Visual Studio 2010 Premium SP1 on Windows 7 Ultimate x64 SP1.

A: When you do Debug->Attach to Process you'll see that VS displays a list of processes and along with them it displays the types of code that you can debug which are running in those processes.  To get this information VS queries the various installed debug engines.  So when we get queried we go and inspect a bunch of processes to see what's going on.  If it's a 32 bit process life is easy - we can use various APIs to enumerate the modules and try and figure out if there's a Python interpreter in the process.  If it's a 64-bit process life is a little tougher because we're running inside of VS and it's a 32-bit process.  We can't use the APIs from a 32-bit to a 64-bit process so instead we spawn a helper process to do the work.
It sounds like this helper process is somehow becoming a zombie on your system.  It'd be great if you could attach VS to it and send any stack traces back in a bug.  But we should also provide some defense in depth and timeout if the helper process isn't responding.
Finally killing it should generally be safe, it's not doing anything stateful, and we'll start a new one when we need it.
If you never use Debug->Attach to Process for Python debugging there's probably a trivial file update to our .pkgdef file which I could track down and post which would make this problem go away entirely.


Q: How to trigger fresh install instead of update? I'm an android developer and I'll be releasing a new update of my application in the coming days. But the new update is a complete redesign of the app's entire architecture, so I'd like the user to uninstall the previous version of the app before he installs the new version so that all the cached data/already logged in user gets cleared and the user makes a fresh start. I was wondering how I could make this happen? What are my best options? Thanks!

A: If you use sqflite or shared_preferences simply remove all data in the main() function with clear all keys or clear the database. Then you need to write a function that will execute this part of the code once. So basically that's all.
import 'package:shared_preferences/shared_preferences.dart';

void main(List<String> arguments) async {
  bool isDataCleared = false;
  if (isDataCleared == false) {
    final prefs = await SharedPreferences.getInstance();
    prefs.clear();
    isDataCleared = true;
    prefs.setBool('isDataCleared', isDataCleared);
  } else {
    // Do something or continue
  }
}

I hope it will help!

A: You must have made the changes in your code previously for it to trigger an update whenever there is a new release automatically. There is a workaround I can think of though:
You can embed some data in this new release which should be passed to the backend. If this new data is not passed, you should log them out with an error message to update the application.
This approach is because the backend is the only common link between the old and new applications.


Q: Tutorial to create phone book contact in Android SDK Although there are sites out there to help me create a contact, I am still not able to understand how to do it, Can someone give me a pointer/link/suggestion, that teaches me from scratch how to create a phone contact that will eventually show up in phone contacts list. Thank you.

A: While I don't know of any tutorials to show step by step. These links may help:

*

*Using the Contacts API

*ContactManager - Contact Manager


Q: Mongoose Connection I read the quick start from the Mongoose website and I almost copy the code, but I cannot connect the MongoDB using Node.js.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

exports.test = function(req, res) {
  var db = mongoose.connection;
  db.on('error', console.error.bind(console, 'connection error:'));
  console.log("h1");
  db.once('open', function callback () {
    console.log("h");
  });
  res.render('test');
};

This is my code. The console only prints h1, not h. Where am I wrong?

A: Mongoose connection using Singleton Pattern
Mongoose Connection File - db.js
//Import the mongoose module
const mongoose = require('mongoose');

class Database { // Singleton
  connection = mongoose.connection;

  constructor() {
    try {
      this.connection
      .on('open', console.info.bind(console, 'Database connection: open'))
      .on('close', console.info.bind(console, 'Database connection: close'))
      .on('disconnected', console.info.bind(console, 'Database connection: disconnecting'))
      .on('disconnected', console.info.bind(console, 'Database connection: disconnected'))
      .on('reconnected', console.info.bind(console, 'Database connection: reconnected'))
      .on('fullsetup', console.info.bind(console, 'Database connection: fullsetup'))
      .on('all', console.info.bind(console, 'Database connection: all'))
      .on('error', console.error.bind(console, 'MongoDB connection: error:'));
    } catch (error) {
      console.error(error);
    }
  }

  async connect(username, password, dbname) {
    try {
      await mongoose.connect(
        `mongodb+srv://${username}:${password}@cluster0.2a7nn.mongodb.net/${dbname}?retryWrites=true&w=majority`,
        {
          useNewUrlParser: true,
          useUnifiedTopology: true
        }
      );
    } catch (error) {
      console.error(error);
    }
  }

  async close() {
    try {
      await this.connection.close();
    } catch (error) {
      console.error(error);
    }
  }
}

module.exports = new Database();

call the connection from app.js
const express = require("express"); // Express Server Framework

const Database = require("./utils/db");

const app = express();

Database.connect("username", "password", "dbname");

module.exports = app;

A: When you call mongoose.connect, it will set up a connection with the database.
However, you attach the event listener for open at a much later point in time (when a request is being handled), meaning that the connection is probably already active and the open event has already been called (you just weren't yet listening for it).
You should rearrange your code so that the event handler is as close (in time) to the connect call as possible:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log("h");
});

exports.test = function(req,res) {
  res.render('test');
};

A: I had the same error popping up. Then I found out that I didn't have a mongod running and listening for connections. To do that you just need to open another command prompt (cmd) and run mongod

A:
The safest way to do this, it to "listen for the connect event". This way you don't care how long it takes for the DB to give you a connection.
Once that is done - you should start the server. Also.. config.MONGOOSE is exposed across your app, so you only have one DB connection.
If you want to use mongoose's connection, simply require config in your module, and call config.Mongoose.  Hope this helps out someone!
Here's the code.

var mongoURI;

mongoose.connection.on("open", function(ref) {
  console.log("Connected to mongo server.");
  return start_up();
});

mongoose.connection.on("error", function(err) {
  console.log("Could not connect to mongo server!");
  return console.log(err);
});

mongoURI = "mongodb://localhost/dbanme";

config.MONGOOSE = mongoose.connect(mongoURI);

A: Mongoose's default connection logic is deprecated as of 4.11.0. It is recommended to use the new connection logic:

*

*useMongoClient option

*native promise library

Here is the example from npm module: mongoose-connect-db
// Connection options
const defaultOptions = {
  // Use native promises (in driver)
  promiseLibrary: global.Promise,
  useMongoClient: true,
  // Write concern (Journal Acknowledged)
  w: 1,
  j: true
};

function connect (mongoose, dbURI, options = {}) {
  // Merge options with defaults
  const driverOptions = Object.assign(defaultOptions, options);

  // Use Promise from options (mongoose)
  mongoose.Promise = driverOptions.promiseLibrary;

  // Connect
  mongoose.connect(dbURI, driverOptions);

  // If the Node process ends, close the Mongoose connection
  process.on('SIGINT', () => {
    mongoose.connection.close(() => {
      process.exit(0);
    });
  });

  return mongoose.connection;
}

A: A simple way i make a connection:
const mongoose = require('mongoose')
mongoose.connect(<connection string>);
mongoose.Promise = global.Promise;
mongoose.connection.on("error", error => {
    console.log('Problem connection to the database'+error);
});


Q: Android TV :Show Row Title always How do I get the title of the individual rows to always appear instead of only when it is selected? Like the example here in Youtube app, "Uploads" and "Popular Uploads" should always be seen.

A: I just answered this question here, but the general gist is:

I was able to achieve this affect by calling setExpand(true) as the first line of my onCreateView() in my RowsFragment.
If you want to lock this effect forever, you can override setExpand(...) in your RowsFragment and just call super.setExpand(true). I believe you'll still need the initial call in onCreateView() though.


Q: What is the best data structure to store playing cards held in a player's hand? I'm beginner in java and I'm currently creating a card game like gin rummy for Android.  I want to know what's the best implementation for creating Hand class?  What's the best way where to store the card returned by Deck.dealt()?

*

*Array

*ArrayList

*Vector

*HashSet

*LinkedList

Also, I would appreciate if anyone could provide a gin rummy open source links.

A: I think a good idea would be to use an interface (List if element are ordered, or Set if elements are not ordered. You can use the implementation you prefer, for example:
List<Card> deck = new ArrayList<Card>();

or
Set<Card> deck = new HashSet<Card>();

A: If you really want to understand the nuances between the collection types, here goes.
List isn't technically appropriate except when the game is Bohnanza (which, ahem, is one of the greatest card games of all time, but I'mma let me finish).
List says, among other things, that one hand containing the Ace and King of Clubs, and another hand containing the King and Ace of Clubs, are fundamentally not the same hand. This is a much stronger dependence on order than simply "well, I want to remember the order that the user wants to see their cards in", which is a property that tons of non-List collections have, like LinkedHashSet and Guava's ImmutableSet.
List also implies that there is some particular significance attached to the card that sits in index N.  This is true of no card game I know.
Set isn't generally appropriate for card games -- only the ones that use a single deck of completely unique cards.
To allow duplicates but still have order-independent equality, the type to use is Guava's Multiset.  For example HashMultiset or ImmutableMultiset. Note that most multiset implementations represent multiple "equal" cards by storing just the card and a count, so when iterating over them, duplicates of a card you have in your hand must always appear together. If it's important to let the user freely control the order of cards in her hand, you would need LinkedListMultiset.
Now that lesson time is over.... well, let's be honest. Calling myHand.equals(yourHand), or using an entire hand as a key in a Map is not actually something you're ever going to do... so go ahead and use the ArrayList, you'll be fine. :-)

A: Store them in an ArrayList.
Cards in a hand are in a certain order, not in an unordered pile.  This ordering is preserved in a List over a Set.
ArrayList also gives you the opportunity to select a specific card by index, which will be helpful as you implement the game.
Keep in mind that as long as you design your Hand class properly, you can always change this data structure easily at any point in the future.  As long as you keep this in mind with any class you design, you can always change it if you realize you need something different.

A: Well, a HashSet is faster(as far as I know), but if you want to make a card game, then maybe you will wish to sort the cards. That is why I would suggest using a List. If you are a beginner, then maybe the best thing would be to use an ArrayList. It's easy to use and understand. At least this is what I would do. If you want to learn more, I suggest reading about each one's unique properties so that you can decide for yourself. And yes, like greuze said before, you should use an interface for more flexibility.

A: Firstly, use of Vector is discouraged in the latest versions of Java, so you can probably ignore that one.
Secondly, as you'll know if you're read the Javadoc on those remaining classes, they all have advantages or disadvantages. Some have an order, some can take duplicate values, some cannot and so on. Therefore I think the best approach is to write some pseudo-code for your application which is not based on a specific class (just write things like 'add Card to Hand', 'remove card from Hand'). Once you have some of this pseudo code you will be able to see your requirements more clearly; will you want to keep the cards in the hand in a specific order? will you want to be able to retrieve cards from the hand by a key?
Then, your choice will be clearer.

A: Keeping the deck in a List makes sense as it does maintain order. I tend to default to using Lists.newArrayList() to create a List. Lists is part of Guava. I strongly recommend using and getting to know Guava since it has many useful offerings.
It would make sense to be able to keep the hand in some data structure that could be sorted easily in order to make it easier to compare hands. OTOH, IIRC, gin rummy hands aren't all that large.


Q: Using nonce or hash values in content-security-policy for inline styles I am adding content-security-policy settings for my web app and would like to be strict about inline scripts and inline styles.  I have inline scripts working properly but am having trouble with inline styles.  For background, my web app uses Elixir/Phoenix on the back end and includes React components on the front end.
Nonce for Inline Scripts - Works
I have just a smattering of inline scripts to get the React components bootstrapped.  Per CSP guidelines, I'm using nonce values to handle these inline scripts.  Specifically, I generate a new nonce value server side on each page load and include it in the content-security-policy header and also inject it into a nonce attribute in the script tags using server side rendering.  This works fine.
Nonce for Inline Styles - Doesn't Work
Inlines styles are another story.  Inlines styles are pretty common in React.  My hope was that I could use a similar nonce approach for this, but so far I have not been able to get it to work.  Nonce values are listed in the style-src page at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src so it seems like this should work, though that section of the doc references scripts so maybe not.  I have tried injecting a nonce attribute into the generated HTML, but this does not work.  I continue to receive the normal error messages.

Refused to apply inline style because it violates the following Content Security Policy directive: "default-src 'self' 'nonce-my-long-ugly-random-nonce-value'". Either the 'unsafe-inline' keyword, a hash ('sha256-specific-hash'), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'style-src' was not explicitly set, so 'default-src' is used as a fallback.

I've been searching for a while and have yet to find any hint that nonce values work for inline styles, other than what I mention above.  Can anyone confirm that nonce values work for inline styles?
If they don't work, it seems like using hashes is my next best bet.  I can get hashes to work, by looking at each error message like the one above and adding the hash to the content-security-policy header.  That is not a very scalable solution though, and if I have to go that route I'd like to know if anyone has come up with a way to automate generating the hashes without having to manually navigate everywhere in the app and look at the error message to get the hash.
Any help you can provide is appreciated.
Thanks.
Justin

A: After looking at Content Security Policy allow inline style without unsafe-inline it appears this isn't supported, perhaps because the spec seems to imply that it is referring only to inline styles in a <style> tag, similar how the spec refers to inline scripts in a <script> tag.
Assuming that is correct, it looks like I'll have to go the hash route or add 'unsafe-inline' just for style-src.


Q: SELECT UPDATE SQL Not Working I have 2 forms
First Form has
Public Class frmMain

Friend strBillIDNumber As String
Friend strBillPassword As String
Friend ds As New DataSet
Friend cnn As OleDbConnection
Friend sql As String
Friend adptr As OleDbDataAdapter
Dim attempt As Integer = 1

Private Sub btnSign_Click(sender As Object, e As EventArgs) Handles btnSign.Click

    Dim connectionString As String
    connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Renz\Documents\Visual Studio 2012\FINAL\Database\UsersDB.accdb;"
    sql = "Select ID, LASTNAME, FIRSTNAME, LOGINSTATUS from TblUser"
    cnn = New OleDbConnection(connectionString)
    Try
        cnn.Open()
        adptr = New OleDbDataAdapter(sql, cnn)
        adptr.Fill(ds)

        For i = 0 To ds.Tables(0).Rows.Count - 1

            If ds.Tables(0).Rows(i).Item(0) = txtID.Text Then
                MessageBox.Show("UserName Matched")
                If ds.Tables(0).Rows(i).Item(1) = txtPassword.Text Then
                    MessageBox.Show("Password Matched")

                    If txtPassword.Text = "admin" Then
                        MessageBox.Show("You are now Logged In as Admin.")
                        frmFaculty.Show()
                        Me.Hide()
                    Else
                        frmStudent.lblSI.Text = ds.Tables(0).Rows(i).Item(0)
                        frmStudent.lblLN.Text = ds.Tables(0).Rows(i).Item(1)
                        frmStudent.lblFN.Text = ds.Tables(0).Rows(i).Item(2)
                        frmStudent.lblLS.Text = ds.Tables(0).Rows(i).Item(3)
                        MessageBox.Show("You are now Logged In.")
                        frmStudent.Show()
                        Me.Hide()
                    End If
                Else
                    MessageBox.Show("Invalid Password.")
                    MessageBox.Show("Please Try Again." & vbNewLine & "ATTEMPT: " & attempt & " out of 3")
                    attempt = attempt + 1
                End If
            End If

        Next

        adptr.Dispose()
        cnn.Close()
    Catch ex As Exception
        MessageBox.Show("Please Try Again!")
    End Try

    'log-in attempt 3x fail'
    If attempt > 3 Then
        MessageBox.Show("You have exceeded the number of login attempt." & vbNewLine & "Please Contact the Administrator.")
    End If
End Sub

And my Second Form Has
Imports System.Data.OleDb

Public Class frmStudent
Dim TimeInHold As String
Private Sub loginBTN_Click(sender As Object, e As EventArgs) Handles loginBTN.Click

    Dim cnn2 As New OleDbConnection
    Dim Command As OleDbCommand
    Dim i As Integer
    Dim sql2 As String
    Dim status As String

    Try
        cnn2 = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Renz\Documents\Visual Studio 2012\FINAL\Database\AuditDB.mdb;")
        cnn2.Open()

        sql2 = "INSERT INTO Audit ([ID],[TIMEIN]) VALUES('" & frmMain.txtID.Text & "','" & DateTime.Now & "')"

        Command = New OleDbCommand(sql2, cnn2)
        i = Command.ExecuteNonQuery

    Catch ex As Exception
        cnn2.Close()

    End Try

    MessageBox.Show("You have successfully Signed in." & vbNewLine & " Please Don't Forget to Logout.")
    frmMain.cnn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Renz\Documents\Visual Studio 2012\FINAL\Database\UsersDB.accdb;")
    frmMain.cnn.Open()
    frmMain.adptr = New OleDbDataAdapter(frmMain.sql, frmMain.cnn)
    frmMain.adptr.Fill(frmMain.ds)
    If frmMain.ds.Tables(0).Rows(i).Item(0) = lblSI.Text Then
        frmMain.sql = "UPDATE TblUser SET LOGINSTATUS = 'SignedIn'"

        frmMain.cnn.Close()
    End If
    Me.Close()
    frmMain.Show()
    frmMain.txtID.Text = String.Empty
    frmMain.txtPassword.Text = String.Empty
End Sub

I can't get my SELECT and UPDATE sql statement to work that will get the data set from form 1.  And when the button is clicked, it will update the field "LoginStatus" to a value of "Signed In".
P.S. I'm creating a time-in, time-out monitoring system that will determine if the user is an admin or a student and will redirect them to their corresponding forms.  Student form will have sign in and sign out buttons, and will record their time in and time out.  When sign in is clicked, it will be grayed out.
Please Help..

A: If frmMain.ds.Tables(0).Rows(i).Item(0) = lblSI.Text Then
    frmMain.sql = "UPDATE TblUser SET LOGINSTATUS = 'SignedIn'"

    frmMain.cnn.Close()
End If

It seems that the UPDATE statement doesn't get executed.
I don't see ExecuteNonQuery for it.
ps: The UPDATE statement is to update all records in the table. Look out!
ps2: I'm not familiar with the VB(.net) :)

A: I think you are missing executeNonQuery in second form and is there only one user then query is fine if more than one consider using " Where Clause" eg.
sql= "UPDATE TblUser SET LOGINSTATUS = 'SignedIn' where ID =" <provide id>

if that doesn't solve your problem then feel free to ask more.
Regards.


Q: Gatsby Dynamic Image I have a problem: this is my Heroes component
const Hero = styled.div`
display: flex;
flex-direction: column;
justify-content: flex-end;
background: linear-gradient(to top, #1f1f21 1%, #1f1f21 1%,rgba(25, 26, 27, 0) 100%) , url(${props => props.bgdesktop}) no-repeat top center;
height: 100vh;
background-size: cover;
@media (max-width:1024px) {
background: linear-gradient(to top, #1f1f21 1%, #1f1f21 1%,rgba(25, 26,
27, 0) 100%) , url(${props => props.bgtablet}) no-repeat center top;
}
@media (max-width:480px) {
background:linear-gradient(to top, rgba(31, 31, 33, 1) 2%, rgba(31, 31,33, 1) 5%,rgba(25, 26, 27, 0) 100%)  , url(${props => props.bgmobile}) no-repeat center top;
    }
`
class Heroes extends React.Component {
constructor(props) {
    super(props);
...
render() {
    return (
<Hero
bgdesktop={this.props.bgdesktop}
bgtablet={this.props.bgtablet}
bgmobile={this.props.bgmobile}/>
)}}

Then I added this component to 'pages/Hero.js':
export default props => {
const hero = props.location.href
? heroCards.find(h => h.name === props.location.href.substring(28))
: heroCards[0]
return (
<Layout>
<Heroes
        bgdesktop={require(`./../images/BG/${hero.name}_Desktop.jpg`)}
        bgtablet={require(`./../images/BG/${hero.name}_Tablet.jpg`)}
        bgmobile={require(`./../images/BG/${hero.name}_Mobile.jpg`)}
      />
</Layout>
)
}

Now, clicking on different buttons on the Home page, I'm redirected different pages that take different bg depending on 'name' included in heroes.js (located in costants folder). It works on local but not on production and the problem is gatsby that doesn't allow that '{require(./../images/BG/${hero.name}_Desktop.jpg)}'. How can I solve this problem?

A: I don't think you need require for this.
Why not use the prop you pass and bake that into a string literal that you insert into the component (without require and outside of the return)?
const mobilePath = `./../images/BG/${props.bgmobile}_Mobile.jpg`;
const desktopPath = `./../images/BG/${props.bgdesktop}_Desktop.jpg`;

return(
  <Heroes mobile={mobilePath} desktop={desktopPath} />
)

EDIT: the substring part could be added in either <Heroes> before passing  the prop. Or by filtering the prop in <Hero> and passing that variable instead of the prop


Q: Recursion time complexity I am looking for help in understanding what the Time/Space complexity of my solution, for finding permutations of an array, is. I know that because I am using an Array.forEach method that my time complexity includes O(n), however since I am also using recursion I do not know how the time complexity changes. The recursion seems to me to be in O(n) time complexity as well. Does that make the overall time complexity of the algorithm O(n^2)? And for space complexity is that 0(n) as well? since each recursion call returns a bigger memory array? Thanks in advance.
  function getPermutations(array) {
      if (array.length <= 1){
        return array.length === 0 ? array : [array];
      }

      let lastNum = array[array.length - 1]
      let arrayWithoutLastNum = array.slice(0, array.length - 1);
      let permutations = getPermutations(arrayWithoutLastNum);

      let memory = []
      permutations.forEach(element => {
        for(let i = 0; i <= element.length; i++){
          let elementCopy = element.slice(0);
          elementCopy.splice(i, 0, lastNum)
          memory.push(elementCopy)
        }
      })

      return memory
    }


Q: I need to delete an element in an array everytime a user press , but when is being output after deletion I got long number like ; 124352919 int main ()
{
    int a[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75};

    char ans;
    int i = 0;
    int pos = 0;

    cout<<"Press y to generate number"<<"\n";
    cin >> ans;

    while(ans=='y'||ans=='Y')
    {
        cout<<"\n\nEnter position to Delete number :: ";
        cin>>pos;

        --pos;

        for(i=pos;i<=size-1;i++)
        {
            a[i]=a[i+1];
            cout<<" "<<a[i]<<" ";
        }
        cout<<"\nNew Array is :: \n\n";

        for(i=0;i<size-1;i++)
        {

        }

        cout<<"Press y to generate number"<<"\n";
        cin >> ans;

    }

    cout << "\n\n";

//I need to delete an element in the array ,for example ; if I input position 67 ,it deletes position 67 but when the array is being after deletion , I got 1312123131 at the end

A: You can't delete an element from an array, but you can delete a vector element like this:
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> nums = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75 };

    char ans;
    int pos = 0;

    cout << "Press y to generate number: ";
    cin >> ans;

    while (ans == 'y' || ans == 'Y')
    {
        cout << "\n\nEnter position to Delete number: ";
        cin >> pos;

        --pos;

        nums.erase(nums.begin() + pos);
        cout << "\nNew Array is:\n\n";

        for (const auto& element : nums)
        {
            std::cout << element << '\n';
        }

        cout << "Press y to generate number" << "\n";
        cin >> ans;
    }
}


Q: Python MultiProcessing I'm using Python Python Multiprocessing for a RabbitMQ Consumers.
On Application Start I create 4 WorkerProcesses.
def start_workers(num=4):
    for i in xrange(num):
        process = WorkerProcess()
        process.start()

Below you find my WorkerClass.
The Logic works so far, I create 4 parallel Consumer Processes.
But the Problem is after a Process got killed. I want to create a new Process. The Problem  in the Logic below is that the new Process is created as child process from the old one and after a while the memory runs out of space.
Is there any possibility with Python Multiprocessing to start a new process and kill the old one correctly?
class WorkerProcess(multiprocessing.Process):

def ___init__(self):
    app.logger.info('%s: Starting new Thread!', self.name)
    super(multiprocessing.Process, self).__init__()

def shutdown(self):
    process = WorkerProcess()
    process.start()
    return True

def kill(self):
    start_workers(1)
    self.terminate()

def run(self):
    try:
        # Connect to RabbitMQ
        credentials = pika.PlainCredentials(app.config.get('RABBIT_USER'), app.config.get('RABBIT_PASS'))
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(host=app.config.get('RABBITMQ_SERVER'), port=5672, credentials=credentials))
        channel = connection.channel()

        # Declare the Queue
        channel.queue_declare(queue='screenshotlayer',
                              auto_delete=False,
                              durable=True)

        app.logger.info('%s: Start to consume from RabbitMQ.', self.name)
        channel.basic_qos(prefetch_count=1)
        channel.basic_consume(callback, queue='screenshotlayer')
        channel.start_consuming()
        app.logger.info('%s: Thread is going to sleep!', self.name)

        # do what channel.start_consuming() does but with stoppping signal
        #while self.stop_working.is_set():
        #    channel.transport.connection.process_data_events()

        channel.stop_consuming()
        connection.close()
    except Exception as e:
               self.shutdown()
    return 0

Thank You

A: In the main process, keep track of your subprocesses (in a list) and loop over them with .join(timeout=50) (https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.join).
Then check is he is alive (https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.is_alive).
If he is not, replace him with a fresh one.
def start_workers(n):
    wks = []
    for _ in range(n):
        wks.append(WorkerProcess())
        wks[-1].start()
    while True:
        #Remove all terminated process
        wks = [p for p in wks if p.is_alive()]

        #Start new process
        for i in range(n-len(wks)):
            wks.append(WorkerProcess())
            wks[-1].start()

A: I would not handle the process pool management myself. Instead, I would use the ProcessPoolExecutor from the concurrent.future module.
No need to inherit the WorkerProcess to inherit the Process class. Just write your actual code in the class and then submit it to a process pool executor. The executor would have a pool of processes always ready to execute your tasks.
This way you can keep things simple and less headache for you.
You can read more about in my blog post here: http://masnun.com/2016/03/29/python-a-quick-introduction-to-the-concurrent-futures-module.html
Example Code:
from concurrent.futures import ProcessPoolExecutor
from time import sleep

def return_after_5_secs(message):
    sleep(5)
    return message

pool = ProcessPoolExecutor(3)

future = pool.submit(return_after_5_secs, ("hello"))
print(future.done())
sleep(5)
print(future.done())
print("Result: " + future.result())


Q: OutputDebugString error I use:
OutputDebugString(L"My error");

in Visual Studio 2010, but instead of displaying "My error", I get just an "ERROR" in the window.

How do I fix this issue?

A: Since you're explicitly passing an UNICODE string, I'd suggest you also explicitly call OutputDebugStringW().
Otherwise, if the UNICODE preprocessor symbol is not defined in your compilation unit, the ANSI version of the function (OutputDebugStringA()) would end up being called with an UNICODE string, which it does not support, and it should result in a compilation error.
EDIT: You cannot use OutputDebugString() to write a string in your application's status bar. OutputDebugString() only sends the string you pass to the debugger.
You have to use the appropriate API to write text to the status bar instead. In your case, wxStatusBar::SetStatusText() should do the trick.


Q: Why does FPS go down if canvas is larger than 255x220? I've found a wierd phenomenon with HTML5 canvas. I was getting a lower than expected framerate, but only in Firefox, and only on one computer (but not on another I tested). The wierd thing is, if I reduce the canvas size to be 255x250 or less, Firefox performs similar to other browsers. If I add one more pixel in width, the FPS falls rapidly to a third.
I've made a jsPerf to demonstrate the problem: http://jsperf.com/critical-canvas-size
(Make sure that the grey rectangle is on screen. I let the tests fail if not, because I found it changes the results if you scroll away accidentally.)
All four test cases are pretty similar with most browsers on most systems, but on this one PC with Firefox 17, I see the following:

The PC in question is running an older Red Hat Linux, and I guess it probably doesn't have hardware accelleration support (from the OS side).
So, what could be the cause for this? Is there anything I can do in my code to circumvent the issue? (I've been thinking about using several small canvasses instead of one large one, for example.)

Edit:
Here is a standalone html file that exibits the problem, and one that doesn't. The only difference is the width of the canvas, 251 vs. 250. (You can comment out the spinner animation, it is just to make the problem visible. Also please excuse the accuracy of the FPS timer, its implementation is very simple.)
The 250px version gets about 60 FPS, in fact it seems to be capped. You can increase the numIterations variable to make the frame function draw a multiple amount of tiles. I can get up to numIterations = 100, or 120000 tiles/sec, while still having a decent framerate. However, the 251px version gives me even for numIterations = 1 a framerate below 20, or less than 1000 tiles/sec.

A: This makes sense because drawing to the canvas and clearing the canvas are expensive methods; if you have a smaller canvas and call clearRect on it every animation step then it will perform better than a larger canvas running the exact same code. The best thing to do is optimise your draw method to only clear what changed each frame. Once you do that you will notice a performance boost; this article will help with other areas in which you can increase performance.
I'm developing with canvas too and have found that WebKit based browsers, in general, handle canvas operations quicker than Gecko in most cases.

A: I actually see similar behavior.  I believe it is when you cross the 65776 pixel barrier -> not 65536 as you would expect.
I don't yet know why this is the case, but it is likely some kind of internal data structure or data type issue (possibly its using a hash and needs to grow the table at that point) inside your browser.  Your test is actually invalid on my chrome browser - it does not exhibit the same performance drop.
I wrote some test cases
http://jsperf.com/pixel-count-matters/2
and
http://jsperf.com/magic-canvas/2
Hope this helps!