text:
Q: My menu and heading move when I resize page, what am i doing wrong? I am trying to finish off my menu and headings, however, when I resize the browser window my menu and my headings move to the right and will not center or stay where I want it too. Any help would be much appreciated. HTML and CSS below.

var slideIndex = 0;
carousel();

function carousel() {
  var i;
  var x = document.getElementsByClassName("mySlides");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > x.length) {
    slideIndex = 1
  }
  x[slideIndex - 1].style.display = "block";
  setTimeout(carousel, 2000);
}
@charset "UTF-8";

/* CSS Document */

body {
  width: 100%;
  margin: 0, auto;
}

body {
  min-width: 100px;
}

body {
  background-color: rgba(255, 255, 255, 1.00)
}

body,
h1,
h2,
h3,
p {
  font-family: "Verdana", sans-serif;
}

h1 {
  font-size: 3em;
  text-align: center;
  font-weight: lighter;
  position: relative;
  margin-top: 0px;
  margin-bottom: 0px;
}

h2,
h3 {
  font-weight: normal;
}

h2 {
  font-size: 1.3em;
  text-align: fixed;
  margin-right: 600px;
  margin-bottom: 0px;
  margin-top: 0px;
  margin-left: 339px;
  font-family: "Verdana", sans-serif;
}

h3,
p {
  font-size: 1em;
  font-family: 100% "Verdana", sans-serif;
  margin-left: 339px
}

ul {
  font-size: 1.2em;
}

ul {
  list-style-type: none;
  text-align: center;
}

a,
li,
h2,
h3,
p {
  text-decoration: none;
  color: rgba(128, 128, 128, 1.00)
}

img {
  margin-top: 0px;
}

li {
  margin-top: 0px;
}

header {
  margin-top: 0px;
}

menu {
  margin-top: 0px;
  margin-bottom: 0px;
}

img {
  width: inherit;
  max-height: 500px;
  position: inherit;
  object-fit: contain;
}

div {
  width: 100%;
  margin-bottom: 0px;
  margin-top: 0px;
  border: 0px solid #FFFFFF;
  position: relative;
}

.menu-wrap {
  position: relative;
  width: 1000px;
  margin-top: 0px;
  margin-bottom: 0px;
}

/* drop down menu */

.clearfix:after {
  display: inherit;
  clear: both;
  margin-bottom: 0px;
}

.menu {
  width: 720px;
  min-width: 720px;
  margin-left: 259px;
}

.menu li {
  margin: 0px;
  list-style: none;
  font-family: "Verdana", sans-serif;
}

.menu a {
  transition: all linear 0.15s;
  color: rgba(135, 135, 135, 1.00);
}

.menu li:hover>a,
.menu .current-item>a {
  text-decoration: none;
  color: rgba(135, 135, 135, 1.00);
}

.menu .arrow {
  font-size: .5em;
  line-height: 0%;
}

.menu>ul>li {
  float: left;
  display: inline-block;
  position: relative;
  font-size: 19px;
}

.menu>ul>li>a {
  padding: 10px 40px;
  display: inline-block;
}

.menu>ul>li:hover>a,
.menu>ul>.current-item>a {
  background: #DCDADA;
}

.menu li:hover .sub-menu {
  z-index: 6;
  opacity: 2;
}

.sub-menu {
  width: 171px;
  padding: 0px 0px;
  position: absolute;
  top: 44px;
  left: 1px;
  z-index: -1;
  opacity: 0;
  transition: opacity linear 0.15s;
  box-shadow: 0px 2px 3px rgba(0, 0, 0, 0.2);
  background-color: rgba(255, 255, 255, 1.00);
  height: 349px;
}

.sub-menu li {
  display: block;
  font-size: .7em;
  color: rgba(135, 135, 135, 1.00);
}

.sub-menu li a {
  padding: 10px 30px;
  display: block;
}

.sub-menu li a:hover,
.sub-menu .current-item a {
  background-color: rgba(231, 231, 231, 1.00);
}
<!doctype html>

        <meta charset="UTF-8">
        <meta name="description" content="Earth, Wind, Fire & Water Project">
            <title>Earth, Wind, Fire & Water</title>
            <link rel="stylesheet" href="../../Xavier website styles.css">

Xavier King

Portfolio

                Projects ▼

Are We Free?

Ben Hart

Daisy Bertenshaw

Decay

Earth, Wind, Fire & Water

Frozen In Time

The CCTV's Eye

    CV

 Contact

Earth, Wind, Fire, Water

A: Try:
.menu {
  width: 720px;
  min-width: 720px;
  margin: 0 auto;
}

This way, it centers the .menu in a similar way such as text-align: center.

var slideIndex = 0;
carousel();

function carousel() {
  var i;
  var x = document.getElementsByClassName("mySlides");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > x.length) {
    slideIndex = 1
  }
  x[slideIndex - 1].style.display = "block";
  setTimeout(carousel, 2000);
}
@charset "UTF-8";

/* CSS Document */

body {
  width: 100%;
  margin: 0, auto;
}

body {
  min-width: 100px;
}

body {
  background-color: rgba(255, 255, 255, 1.00)
}

body,
h1,
h2,
h3,
p {
  font-family: "Verdana", sans-serif;
}

h1 {
  font-size: 3em;
  text-align: center;
  font-weight: lighter;
  position: relative;
  margin-top: 0px;
  margin-bottom: 0px;
}

h2,
h3 {
  font-weight: normal;
}

h2 {
  font-size: 1.3em;
  text-align: fixed;
  margin-right: 600px;
  margin-bottom: 0px;
  margin-top: 0px;
  margin-left: 339px;
  font-family: "Verdana", sans-serif;
}

h3,
p {
  font-size: 1em;
  font-family: 100% "Verdana", sans-serif;
  margin-left: 339px
}

ul {
  font-size: 1.2em;
}

ul {
  list-style-type: none;
  text-align: center;
}

a,
li,
h2,
h3,
p {
  text-decoration: none;
  color: rgba(128, 128, 128, 1.00)
}

img {
  margin-top: 0px;
}

li {
  margin-top: 0px;
}

header {
  margin-top: 0px;
}

menu {
  margin-top: 0px;
  margin-bottom: 0px;
}

img {
  width: inherit;
  max-height: 500px;
  position: inherit;
  object-fit: contain;
}

div {
  width: 100%;
  margin-bottom: 0px;
  margin-top: 0px;
  border: 0px solid #FFFFFF;
  position: relative;
}

.menu-wrap {
  position: relative;
  width: 1000px;
  margin-top: 0px;
  margin-bottom: 0px;
}

/* drop down menu */

.clearfix:after {
  display: inherit;
  clear: both;
  margin-bottom: 0px;
}

.menu {
  width: 720px;
  min-width: 720px;
  margin: 0 auto; /*-------------- This code ------------*/
}

.menu li {
  margin: 0px;
  list-style: none;
  font-family: "Verdana", sans-serif;
}

.menu a {
  transition: all linear 0.15s;
  color: rgba(135, 135, 135, 1.00);
}

.menu li:hover>a,
.menu .current-item>a {
  text-decoration: none;
  color: rgba(135, 135, 135, 1.00);
}

.menu .arrow {
  font-size: .5em;
  line-height: 0%;
}

.menu>ul>li {
  float: left;
  display: inline-block;
  position: relative;
  font-size: 19px;
}

.menu>ul>li>a {
  padding: 10px 40px;
  display: inline-block;
}

.menu>ul>li:hover>a,
.menu>ul>.current-item>a {
  background: #DCDADA;
}

.menu li:hover .sub-menu {
  z-index: 6;
  opacity: 2;
}

.sub-menu {
  width: 171px;
  padding: 0px 0px;
  position: absolute;
  top: 44px;
  left: 1px;
  z-index: -1;
  opacity: 0;
  transition: opacity linear 0.15s;
  box-shadow: 0px 2px 3px rgba(0, 0, 0, 0.2);
  background-color: rgba(255, 255, 255, 1.00);
  height: 349px;
}

.sub-menu li {
  display: block;
  font-size: .7em;
  color: rgba(135, 135, 135, 1.00);
}

.sub-menu li a {
  padding: 10px 30px;
  display: block;
}

.sub-menu li a:hover,
.sub-menu .current-item a {
  background-color: rgba(231, 231, 231, 1.00);
}
<!doctype html>

        <meta charset="UTF-8">
        <meta name="description" content="Earth, Wind, Fire & Water Project">
            <title>Earth, Wind, Fire & Water</title>
            <link rel="stylesheet" href="../../Xavier website styles.css">

Xavier King

Portfolio

                Projects ▼

Are We Free?

Ben Hart

Daisy Bertenshaw

Decay

Earth, Wind, Fire & Water

Frozen In Time

The CCTV's Eye

    CV

 Contact

Earth, Wind, Fire, Water


text:
Q: Drag and zoom text with Kineticjs I am trying to zoom and pan a text which is draggable already. All the examples are on images or shapes and it seems I cannot adapt it to a text object. My questions are:

*

*Do I have to use the anchors or is any simpler way zoom a text with Kineticjs?

*I found an example regarding zooming a shape and the code crashes here:
  var layer = new Kinetic.Layer({
     drawFunc : drawTriangle  //drawTriangle is a function defined already
  });

Can we call a function while we are creating a layer?
I usually create a layer and then add the outcome of the function in it.
Any idea would be great, thanks.

A: I thought of many ways you could do this but this is the one I ended up implementing: jsfiddle
Basically, you have an anchor (which doesn't always have to be there, you can hide and show it if you would like. Let me know if you need help with that) and if you drag the anchor down it increases the fontSize, and if you drag the anchor up it decreases the fontSize.
I followed the exact same anchor tutorial but instead I added a dragBoundFunc to limit dragging to the Y-axis:
var anchor = new Kinetic.Circle({
    x: x,
    y: y,
    stroke: '#666',
    fill: '#ddd',
    strokeWidth: 2,
    radius: 8,
    name: name,
    draggable: true,
    dragOnTop: false,
    dragBoundFunc: function (pos) {
        return {
            x: this.getAbsolutePosition().x,
            y: pos.y
        };
    }
});

And then I updated the updateAnchor() function to only detect the single anchor I added to the group named sizeAnchor:
var mY = 0;

function update(activeAnchor, event) {
  var group = activeAnchor.getParent();
  var sizeAnchor = group.get('.sizeAnchor')[0];
  var text = group.get('.text')[0];

  if (event.pageY < mY) {
    text.setFontSize(text.getFontSize()-1);
  } else {
    text.setFontSize(text.getFontSize()+1);
  }

  sizeAnchor.setPosition(-10, 0);

  mY = event.pageY;
}

Basically mY is used compared to the e.PageY to see if the mouse is moving up or down. Once we can determine the mouse direction, then we can decide if we should increase or decrease the fontSize!
Alternatively, you can use the mousewheel to do the exact same thing! I didn't implement it myself but it's definitely doable. Something like:

*

*Mousewheel down and the fontSize decreases

*Mousewheel up and the fontSize increases

Hopefully this emulates "Zooming" a text for you. And I guess being able to drag the text acts as "panning" right?
UPDATE (based on comment below)
This is how you would limit dragging to the Y-Axis using dragBoundFunc:
var textGroup = new Kinetic.Group({
    x: 100,
    y: 100,
    draggable: true,
    dragBoundFunc: function (pos) {
        return {
            x: this.getAbsolutePosition().x,
            y: pos.y
        };
    }
});

See the updated jsfiddle (same jsfiddle as above)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java Key Bindings are firing very inconsistently I am working on a game that has a player of which I would like to move using WASD. I have decided to use Key Bindings in order to try and fix a problem I had with Key Listeners which is still happening now even after switching to Key Bindings. The problem is that even though pressing these keys is moving the player, after moving the player a few times, the input begins to stop working almost completely. This happens to the point of only maybe 1/10 key presses moving the player. What could I be doing wrong? Any help would be much appreciated.
Here is my game's main class with the Key Bindings:
(Let me know if I should post the rest of my code)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import java.lang.Math;
import java.util.LinkedList;
import java.awt.event.KeyEvent;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.KeyStroke;

public class ZombieMain extends JPanel implements ActionListener{

   private static int WIDTH = 1600;
   private static int HEIGHT = 900;

   private Action a,s,w,d,ra,rs,rw,rd;

   private LinkedList<Zombie> zombies = new LinkedList();
   Zombie z = new Zombie(100,100,50,30,50);
   static ZombiePlayer player = new ZombiePlayer(950,572,2,30);

   public ZombieMain(){
      this.setFocusable(true);
      this.requestFocus();

      Timer t = new Timer(10,this);
      t.start();

      Action w = new AbstractAction() {
         public void actionPerformed(ActionEvent e) {
            player.vY = -player.speed;
         }
      };
      Action s = new AbstractAction() {
         public void actionPerformed(ActionEvent e) {
            player.vY = player.speed;
         }
      };
      Action d = new AbstractAction() {
         public void actionPerformed(ActionEvent e) {
            player.vX = player.speed;
         }
      };
      Action a = new AbstractAction() {
         public void actionPerformed(ActionEvent e) {
            player.vX = -player.speed;
         }
      };
      Action rw = new AbstractAction() {
         public void actionPerformed(ActionEvent e) {
            player.vY = 0;
         }
      };
      Action rs = new AbstractAction() {
         public void actionPerformed(ActionEvent e) {
            player.vY = 0;
         }
      };
      Action rd = new AbstractAction() {
         public void actionPerformed(ActionEvent e) {
            player.vX = 0;
         }
      };
      Action ra = new AbstractAction() {
         public void actionPerformed(ActionEvent e) {
            player.vX = 0;
         }
      };

     getInputMap().put(KeyStroke.getKeyStroke("W"),"w");
     getInputMap().put(KeyStroke.getKeyStroke("S"),"s");
     getInputMap().put(KeyStroke.getKeyStroke("D"),"d");
     getInputMap().put(KeyStroke.getKeyStroke("A"),"a");
     getInputMap().put(KeyStroke.getKeyStroke("released W"),"rw");
     getInputMap().put(KeyStroke.getKeyStroke("released S"),"rs");
     getInputMap().put(KeyStroke.getKeyStroke("released D"),"rd");
     getInputMap().put(KeyStroke.getKeyStroke("released A"),"ra");

     getActionMap().put("w",w);
     getActionMap().put("s",s);
     getActionMap().put("d",d);
     getActionMap().put("a",a);
     getActionMap().put("rw",rw);
     getActionMap().put("rs",rs);
     getActionMap().put("rd",rd);
     getActionMap().put("ra",ra);
   }

   public void actionPerformed(ActionEvent e){
      repaint();
   }

   public void paint(Graphics g){
      g.setColor(new Color(40,40,40));
      g.fillRect(0,0,WIDTH,HEIGHT);
      z.draw((Graphics)g);
      player.draw((Graphics)g);
   }

   public int getWidth(){
      return WIDTH;
   }
   public int getHeight(){
      return HEIGHT;
   }
   public static void main(String[] args){
        JFrame frame = new JFrame();
        frame.add(new ZombieMain());
        frame.setSize(WIDTH,HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setResizable(false);
   }
}

A: As to "why" you're having issues, I can only guess at, as we've only got an out of context snippet to deal with, however, there are a number of things which could be improved which might help resolve the issue.

*

*User WHEN_IN_FOCUSED_WINDOW when calling getInputMap
This applies context to when key events will actually be triggered, in the above case, key events will be triggered when ever the window has focus, regardless of which component currently has keyboard focus.

*

*Prefer overriding paintComponent over paint
Painting in Swing is some what complex, as general recommendation, it is best to override paintComponent when you want to perform custom painting.  A nice side effect of this is, it will paint the components background color for your, one less thing you have to do ;)

*

*Prefer overriding getPreferredSize when you need to provide sizing hints

Overriding getWidth and getHeight will cause no end of possible issues and is just best avoided.  Instead, override getPreferredSize, this way, you are participating within the layout API and get all its advantages, such as been able to call pack on the JFrame and have it take care of all the oddities revolving around frame decorations.

*

*Seperate the change of the state from the mechanisms used to affect that state

Nice wordy for "decouple your code".  In your code, the state of the player is changed directly by the key actions.  This is not only a bad idea, it can produce unexpected side effects and becomes increasingly difficult to manage as the requirements become more complex.  It also makes it difficult to change the way that input is done.  For example, you could include different input methods, such as joysticks, but you'd have to write the same code for it.
Instead, you should simply have a "state manager" which carries the current state of the input, when your "main loop" is ready, it will apply that state to the model, as a seperate step.
The "main loop" doesn't care how the state is updated, only that it can obtain the information it needs to make decisions about how to apply it.
Below is a rough example of everything I've discussed above and in my testing I had no issues with the bindings "stalling"
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;

public class ZombieMain extends JPanel implements ActionListener {

    enum VerticalDirection {
        UP, DOWN, NONE
    }

    enum HorizontalDirection {
        LEFT, RIGHT, NONE
    }

    public class VerticalStateController {

        private VerticalDirection state = VerticalDirection.NONE;

        public void setState(VerticalDirection state) {
            this.state = state;
        }

        public VerticalDirection getState() {
            return state;
        }

    }

    public class HorizontalStateController {

        private HorizontalDirection state = HorizontalDirection.NONE;

        public void setState(HorizontalDirection state) {
            this.state = state;
        }

        public HorizontalDirection getState() {
            return state;
        }

    }

    public class VerticalAction extends AbstractAction {

        private VerticalStateController controller;
        private VerticalDirection state;

        public VerticalAction(VerticalStateController controller, VerticalDirection state) {
            this.controller = controller;
            this.state = state;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            controller.setState(state);
        }

    }

    public class HorizontalAction extends AbstractAction {

        private HorizontalStateController controller;
        private HorizontalDirection state;

        public HorizontalAction(HorizontalStateController controller, HorizontalDirection state) {
            this.controller = controller;
            this.state = state;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            controller.setState(state);
        }

    }

    private static int WIDTH = 400;
    private static int HEIGHT = 400;

    private Rectangle player = new Rectangle(0, 0, 20, 20);
    private VerticalStateController verticalStateController = new VerticalStateController();
    private HorizontalStateController horizontalStateController = new HorizontalStateController();

    public ZombieMain() {
        setBackground(new Color(40, 40, 40));

        Timer t = new Timer(10, this);
        t.start();

        InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
        ActionMap am = getActionMap();

        // Pressed
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), "Pressed.up");
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), "Pressed.down");
        // Released
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, true), "Released.up");
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, true), "Released.down");

        // Pressed
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false), "Pressed.left");
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), "Pressed.right");
        // Released
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, true), "Released.left");
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, true), "Released.right");

        am.put("Pressed.up", new VerticalAction(verticalStateController, VerticalDirection.UP));
        am.put("Pressed.down", new VerticalAction(verticalStateController, VerticalDirection.DOWN));
        am.put("Released.up", new VerticalAction(verticalStateController, VerticalDirection.NONE));
        am.put("Released.down", new VerticalAction(verticalStateController, VerticalDirection.NONE));

        am.put("Pressed.left", new HorizontalAction(horizontalStateController, HorizontalDirection.LEFT));
        am.put("Pressed.right", new HorizontalAction(horizontalStateController, HorizontalDirection.RIGHT));
        am.put("Released.left", new HorizontalAction(horizontalStateController, HorizontalDirection.NONE));
        am.put("Released.right", new HorizontalAction(horizontalStateController, HorizontalDirection.NONE));
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(WIDTH, HEIGHT);
    }

    public void actionPerformed(ActionEvent e) {
        switch (verticalStateController.getState()) {
            case UP:
                player.y -= 4;
                break;
            case DOWN:
                player.y += 4;
                break;
        }
        switch (horizontalStateController.getState()) {
            case LEFT:
                player.x -= 4;
                break;
            case RIGHT:
                player.x += 4;
                break;
        }
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setColor(Color.RED);
        g2d.fill(player);
        g2d.dispose();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new ZombieMain());
                frame.pack();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

I should point out that this is just one approach.  Could also put a bunch of "flags" in a Set of some kind


text:
Q: Entering data with WebSQL I'm having some trouble using WebSQL for my Chrome Extension. (This is my first time using it)
I found this tutorial and am trying to adapt it to my needs: http://www.html5rocks.com/en/tutorials/webdatabase/todo/
Heres my code:
var favourites = {};
favourites.webdb = {};

favourites.webdb.db = null;

favourites.webdb.open = function () {
  var dbSize = 5 * 1024 * 1024; // 5MB
  favourites.webdb.db = openDatabase("favourites", "1", "Favourites Database", dbSize);
};

favourites.webdb.onError = function(tx, e) {
  alert("There has been an error: " + e.message);
};

favourites.webdb.onSuccess = function(tx, r) {
  // re-render the data.
  // loadTodoItems is defined in Step 4a
  favourites.webdb.getAllTiles(loadTiles);
};

favourites.webdb.createTable = function() {
  var db = favourites.webdb.db;
  db.transaction(function(tx) {
    tx.executeSql("CREATE TABLE IF NOT EXISTS " +
                  "tiles(ID INTEGER PRIMARY KEY ASC, name, colour, width, linkURL, imgURL)", []);
  });
};

favourites.webdb.addTile = function(tileName, tileColour, tileWidth, tileLinkURL, tileImgURL) {
  var db = favourites.webdb.db;
  db.transaction(function(tx){
    tx.executeSql("INSERT INTO tiles(name, colour, width, linkURL, imgURL) VALUES (?,?,?,?,?)",
        [tileName, tileColour, tileWidth, tileLinkURL, tileImgURL],
        favourites.webdb.onSuccess,
        favourites.webdb.onError);
   });
};

function loadTiles(tx, rs) {
  var rowOutput = "";
  var todoItems = document.getElementById("tiles");
  for (var i=0; i < rs.rows.length; i++) {
    rowOutput += renderTile(rs.rows.item(i));
  }

  tiles.innerHTML = rowOutput;
}
function renderTile(row) {
  return "" +
      "
" +
      "" +
      "
" +
      "";
};

favourites.webdb.deleteTile = function(id) {
  var db = favourites.webdb.db;
  db.transaction(function(tx){
    tx.executeSql("DELETE FROM tiles WHERE ID=?", [id],
        favourites.webdb.onSuccess,
        favourites.webdb.onError);
    });
};

function init() {
  favourites.webdb.open();
  favourites.webdb.createTable();
  //favourites.webdb.getAllTiles(loadTiles);
};

I am getting an error when I try to add data to the database:
http://i.imgur.com/AGoBP9X.png
Could somebody explain what's going wrong with my code?

A: My first guess would be, that favourites.webdb.db === null and therefore does not have a method transaction.
For that reason, I would check if init is actually invoked. (If so, then check if the verison parameter of openDatabase is correct. In the docs I find, it should rather be "1.0" than just "1".


text:
Q: Почему build:gradle:1.5.0 показывает ошибку? Я имплементировал библиотеку в свой проект и столкнулся с такой ситуацией, для того, чтоб она работала и не вылетало никаких ошибок нужно было поменять версию android.tools на пониженную. У меня по дефолту была вот такая
classpath 'com.android.tools.build:gradle:1.5.0'

и пока я ее не поменял на вот такую (пониженную)
classpath 'com.android.tools.build:gradle:1.2.3'

у меня вываливалась вот такая ошибка
Error:Cannot access first() element from an empty List

если версия старая 1.2.3 то все работает, а когда ставлю 1.5.0 , то не работает...
Почему так получается? Что делать если я хочу использовать новые версии?

A: Решение из разряда очевидного, вам необходимо юзать более новую версию, а не старую.
"чтоб она работала и не вылетало никаких ошибок нужно было поменять версию android.tools на пониженную." Сильно сомневаюсь, что это правильное решение проблемы


text:
Q: Finding files with both of two specified terms via git grep I'm attempting to find files in my git repository using git grep and I have no easy way of doing so without manual searching. I have found one workaround like this:
git grep -l 'term1' | xargs -i grep -l term2 {}

But I'm wondering if there is a way similar to this which doesn't require xargs:
git grep -l -E 'term1|term2'

This essentially means show me the files containing either term1 or terms2... is there a "show me files with BOTH these terms."
I'm trying to use the git grep command in a way that is not practical for piping commands into other commands. I really hate working with python's subprocess module and its use of piping...

A: Two ways to achieve the goal:
1) combining multiple patterns specified by -e option with --and flag

--and
--or
--not
( … )
  Specify how multiple patterns are combined using Boolean expressions.

git grep -l -e 'term1' --and -e 'term2'

2) using --all-match flag

When giving multiple pattern expressions combined with --or, this flag
  is specified to limit the match to files that have lines to match all
  of them.

git grep -l --all-match -e 'term1' -e 'term2'

https://git-scm.com/docs/git-grep#git-grep--e

A: You can combine it with another grep command:
git grep -l -E 'term1' | grep term2


text:
Q: how Multidimensional array javascript and filter perempuan then show that name ? (need example and show) var mahasiswa = new Array();
mahasiswa[0]=new Array("100000001","Alda","Perempuan","1 Mei 1994","DKV");
mahasiswa[1]=new Array("100000002","Aldi","Laki-Laki","2 Mei 1994","Seni");
mahasiswa[2]=new Array("100000003","Aldo","Laki-Laki","3 Mei 1994","Seni");
mahasiswa[3]=new Array("100000004","Alfi","Laki-Laki","4 Mei 1994","Akutansi");
mahasiswa[4]=new Array("100000005","Andi","Laki-Laki","5 Mei 1994","Seni");
mahasiswa[5]=new Array("10000006","Bandri","Laki-Laki","6 Mei 1994","DKV");
mahasiswa[6]=new Array("100000007","Basri","Laki-Laki","7 Mei 1994","Sistem Informasi");
mahasiswa[7]=new Array("100000008","Bagas","Laki-Laki","8 Mei 1994","DKV");
mahasiswa[8]=new Array("100000009","Bagus","Laki-Laki","9 Mei 1994","Sistem Informasi");
mahasiswa[9]=new Array("1000000010","Citra","Perempuan","10 Mei 1994","Teknik Informatika");
mahasiswa[10]=new Array("1000000011","Danu","Laki-Laki","11 Mei 1994","Teknik Informatika");
mahasiswa[11]=new Array("1000000012","Dani","Laki-Laki","12 Mei 1994","Broadcast");
mahasiswa[12]=new Array("1000000013","Gina","Perempuan","13 Mei 1994","DKV");
mahasiswa[13]=new Array("1000000014","Fahmi","Laki-Laki","14 Mei 1994","Broadcast");
mahasiswa[14]=new Array("1000000015","Farah","Perempuan","1 Mei 1994","Seni");
mahasiswa[15]=new Array("1000000016","Handini","Perempuan","1 Mei 1994","Akutansi");
mahasiswa[16]=new Array("1000000017","Handita","Laki-laki","1 Mei 1994","Akutansi");
mahasiswa[17]=new Array("1000000018","Robi","Laki-laki","1 Mei 1994","Sistem Informasi");
mahasiswa[18]=new Array("1000000019","Riska","Perempuan","1 Mei 1994","Teknik Informatika");
mahasiswa[19]=new Array("1000000020","Riski","Perempuan","1 Mei 1994","Sistem Informasi");
mahasiswa[20]=new Array("1000000021","Rizky","Laki-laki","1 Mei 1994","Teknik Informatika");
mahasiswa[21]=new Array("1000000022","Marlina","Perempuan","1 Mei 1994","DKV");
mahasiswa[22]=new Array("1000000023","Nani","Perempuan","1 Mei 1994","Broadcast");
mahasiswa[23]=new Array("1000000024","Nana","Perempuan","1 Mei 1994","Broadcast");
mahasiswa[24]=new Array("1000000025","Oki","Perempuan","1 Mei 1994","DKV");
mahasiswa[25]=new Array("1000000026","Sayid","Laki-laki","1 Mei 1994","DKV");
mahasiswa[26]=new Array("1000000027","Tika","Perempuan","1 Mei 1994","Seni");
mahasiswa[27]=new Array("1000000028","Wirya","Laki-laki","1 Mei 1994","Sistem Informasi");
mahasiswa[28]=new Array("1000000029","Wisnu","Laki-laki","1 Mei 1994","DKV");
mahasiswa[29]=new Array("1000000030","Zaraki","Laki-laki","1 Mei 1994","Shinigami");

mahasiswa.filter(function (el) {
  return el[2] === 'perampuan';
}).forEach(function (el) {`enter code here`
  console.log(el[1])
});


text:
Q: Number of combinations of a ternary sequence with restrictions. If you are given a ternary sequence (a sequence of numbers which only contain $0$, $1$, and $2$'s) which is composed of 15 numbers.  Let's say you must have $6$, $0's$, $5$, $1's$, and $4$, $2's$, then you can arrange this sequence in $\binom{15}{6}$ ways for the $0$'s, then we have $15-6=9$ places left to arrange the $1$'s.  So we can arrange the $1$'s in $\binom{9}{5}$ ways, and finally for the $2$'s we can arrange them in $\binom{4}{4}$ ways.  So in total we can have: $\binom{15}{6}\binom{9}{5}\binom{4}{4}$ ways of arranging this 15 ternary sequence.
However, what if we put a restriction on this sequence.  For example, the first $1$ must be preceded by a $0$ (ex: $2200100101011$).  Or the first $0$ precedes the first $1$ and the first $1$ precedes the first $2$ (ex: 000010201211212).  How would you go about counting the total number of ways now, with these type of restrictions?

A: To simplify your initial thoughts on ternary arrangements, you have a multiset with three distinct elements and a number of repetitions - in your example, $\{(0,6),(1,5),(2,4)\}$ and the arrangements of the elements are simply the trinomial coefficient
$${15 \choose 6,5,4}=\frac{15!}{6!\,5!\,4!}$$
Then subsequent constraints can often be represented by breaking the possible strong into parts as @lulu mentions. However the examples you describe I would attack in step-by-step insertion method using stars-and-bars assuming that the multiset specification remains the same.
Thus the first problem starts with $6$ zeroes and $6$ places to allocate the $1$s:
$$ 0\,\,\_\,\,0\,\,\_\,\,0\,\,\_\,\,0\,\,\_\,\,0\,\,\_\,\,0\,\,\_ $$
giving ${10 \choose 5}$ options, then ${15 \choose 4}$ further options to place the $2$s by a similar process (or by "masking" $0$s and $1$s together, same answer).
$$ {10 \choose 5}{15 \choose 4} = \frac{10!}{5!\,5!}\frac{15!}{11!\,4!} = \frac{15!}{11\cdot 5!\,5!\,4!}$$
Similarly the second problem restricts placement of the $2$s into the $1$s, then restricts placing the $1/2$ string into the $0$s.
$${8 \choose 4}{14 \choose 9}$$


text:
Q: Typeahead Bloodhound autocomplete cant work with json objects Desperately trying to figure out why autocomplete not working with json objects
(function($){

    let $country = $('#country');

    let countries = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.whitespace,
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: '../../data/countries.json'
    });

    $country.typeahead({
        name: 'countries',
        hint: true,
        highlight: true,
        minLength: 1
    },{
        source: countries,
        templates: {
            empty: ['No data'].join('\n'),
            suggestion: {
                function (data) {
                    return '

'+data.name+'

';
                }
            }
        }
    });

}(jQuery));

Everything working with json like ["item1","item2","Item3"]
But not with [{"name":"item1"},{"name":"item2"},{"name":"item3"}]
My json is correct, I even tried to use this one: http://twitter.github.io/typeahead.js/data/nba.json
When using associative array always getting "No data".
Also tried this one:
prefetch: {
            url: '../../data/countries.json',
            filter: function(list) {
                return $.map(list, function(item) {
                    return {
                        name: item.name,
                        code: item.code
                    };
                });
            }
        }

Data is prefetching, but still no suggestion.
Of course after every edit I cleaning my local storage.
Also tried using Handlebars
name: 'countries',
        source: countries,
        display: 'name',
        templates: {
            empty: ['No data'].join('\n'),
            suggestion: Handlebars.compile('
{{name}}
')
        }

A: Ok so I figureout it, still not sure why...
datumTokenizer: function (d) { return Bloodhound.tokenizers.whitespace(d.name); }

Instead of
datumTokenizer: Bloodhound.tokenizers.whitespace

So full working code is
(function($){

    let $country = $('#country');

    let countries = new Bloodhound({
        datumTokenizer: function (d) { return Bloodhound.tokenizers.whitespace(d.name); },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: {
            url: '../../data/countries.json',
            filter: function(list) {
                return $.map(list, function(item) {
                    return {
                        name: item.name,
                        code: item.code
                    };
                });
            },
            cache: true
        }
    });

    $country.typeahead({
        name: 'countries',
        hint: true,
        highlight: true,
        minLength: 1
    },{
        source: countries,
        display: function(data) { return data.name },
        templates: {
            empty: ['No data'].join('\n'),
            suggestion: function (data) {
                return '

'+data.name+'

';
            }
        }
    });

}(jQuery));


text:
Q: Quick Edit View Substitute in Modern? I have been attempting to have a section on a Sharepoint main page where anyone with modify access to that document library can easily modify the document metadata. Specifically there is a Status column that directs which stage of a review process a document is in and where it is displayed on the site.
I'm trying to make this as painless as possible for the end users. Right now the proposed process is to click the Quick Edit button, modify the column via a dropdown, and then click Exit quick edit to save the changes. Ideally, this document library web part would have a view set up that allowed access to the dropdown without having to go into quick edit, but it appears that the modern view of Sharepoint Online does not allow for the datasheet view to work correctly when used within the web part.
Is there another option to make this editing simpler?
Thanks!


text:
Q: translating php sha1 to c# What is self::prefix? How this line will looks like in C#?
Thanks in advance.

A: Just find static member called prefix in your class and replace it in C# with that value. It's a simple variable.


text:
Q: ERROR SQL-client exception I have query in my c# file and I have error.
            conn.Open();
            string sql = "INSERT INTO bk (a,b,c, d, guest) VALUES ('" + a+ "','" + b+ "','" + c+ "', d," + guest + " )";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.ExecuteNonQuery();
            conn.Close();

ERROR System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'juwita'. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, ........

but when I delete guest on my sql. it fine.
What does it mean and what should I do ?

A: You forgot to add single quote around 'guest' variable in your query
string sql = "INSERT INTO booking (noSeat,start,[end], statusBooked, guest) VALUES ('" + noSeat + "','" + now + "','" + bookDate + "', 1,'" + guest + "' )";

This should fix your problem.


text:
Q: Discord.py, send a message to a channel I just created I've been trying to run a loop that creates a text channel and directly after that, sends multiple messages to it. I've come up with this code:
@client.event
async def on_message(message):
    msg = message.content
    guild = message.guild

    if msg.startswith("test") and message.author.id == admin:
        await message.reply("valid", mention_author=True)

        for i in range (10):
            await guild.create_text_channel('test channel')
            for j in range (5):
                await i.send("ah")

Unfortunately, it gives me this error:
    Ignoring exception in on_message
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 29, in on_message
    await i.send("ah")
AttributeError: 'int' object has no attribute 'send'

Could someone help me with this?

A: You're not using the result of the channel creation, instead you're using i which is your index in the iteration. As described in the documentation, create_text_channel returns a TextChannel object, try using that instead:
for i in range (10):
    channel = await guild.create_text_channel('test channel')
    for j in range (5):
        await channel.send("ah")

A: i, in this case, is an integer, so that is why you can't do:
await i.send(<message>)

What you are supposed to do is:
await channel.send(<message>)


text:
Q: Update CSS variable in Angular I want to use in my Angular app Bennett Feely "Image-effects".
For exemple this is the 'photo-border-effect':

.photo-border-effect {
  background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/Point_Reyes_Lighthouse_%28April_2012%29.jpg/593px-Point_Reyes_Lighthouse_%28April_2012%29.jpg), url(https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/Point_Reyes_Lighthouse_%28April_2012%29.jpg/593px-Point_Reyes_Lighthouse_%28April_2012%29.jpg);
  background-position: center;
  background-size: 60%, 20%;
  background-repeat: no-repeat, repeat;
}

[class$=-effect] img {
    vertical-align: top !important;
    margin: 0 !important;
    opacity: 0 !important;
}

/* CodePen Styles */
body {
    display: flex;
    height: 100vh;
}
div {
    margin: auto;
}

But I have to change the urls in the CSS manually, not very convenient for my app. I know I can use CSS variables but I can't find a way to update it from my .ts directly.
What is the proper way to update CSS variable in Angular?
Mihir Dave response could work but I have cases with different background-image in the same class:
.flannel-effect {
  background-image: url(photo.jpg);
  background-size: cover;
  background-position: center;
}

@supports (background-blend-mode: overlay) {
  .flannel-effect {
    background-image: url(photo.jpg), url(photo.jpg), url(photo.jpg);
    background-position: center;
    background-size: 100%, 100000% 100%, 100% 100000%;
    background-blend-mode: overlay;
  }
}

A: I found a quick and easy way to do it.
I use CSS variables and set the value from my .ts using DomSanitizer.
Here is a Stackblitz with this solution implemented.

A: You can remove the background image from the CSS and pass it from a template using angular like this.

you can also create a method in the ts file with your business logic to return a string

TS
getHeroes(): string {
    // add cases here based on which you can return different strings to background urls
    return 'url('+YourUrlFromVariable+'), url(photo.jpg);';
}


text:
Q: validating attribute presence with condition I am trying to introduce a functionality in my application in which the users can suggest an event to the organizers.To suggest an event the user will have to fill a form. I want to validate the presence of few fields(the attribute of the events) with a condition to be true, i.e. the fields should not be left blank if the user(the submitter of the form) is not an admin.However if the submitter of the form is an admin, the fields can be left blank.
validates :attribute_name, presence: { :if => :user.is_admin? }

undefined method `is_admin?' for :user:Symbol Did you mean? is_haml?
I have also tried :user.is_admin()==True , It also throws error:
undefined method `is_admin' for :user:Symbol Did you mean? is_a?
I have this attribute in the users table:
t.boolean  "is_admin",               default: false

I have the following associations defined in my events model:
has_many :event_users, dependent: :destroy
  has_many :users, through: :event_users

  has_one :submitter_event_user, -> { where(event_role: 'submitter') }, class_name: 'EventUser'
  has_one  :submitter, through: :submitter_event_user, source: :user

In the controllers I have this code:
@event.submitter = current_user

A: The issue is you are trying to call is_admin? on the Symbol :user as the error suggests.
If I understand correctly this attribute should be present unless user.is_admin? returns true
This can be done in multiple ways:
validates :attribute_name, presence: true, unless: -> {|u| u.is_admin?}
#Or
validates :attribute_name, presence: true, unless: :is_admin?
# or using presence directly as you tried to originally
validates :attribute_name, presence: {unless: -> {|u| u.is_admin?} }
# or
validates :attribute_name, presence: {unless: :is_admin? }

I generally prefer the first option as, IMO, it is the least ambiguous and the most readable but all of them should result in the same function so choose the one you prefer as long as you remain consistent.
In the block form the instance is yielded to the block and the block's return value is used to determine whether or not the validation should run.
When using the symbol the symbol is sent to the instance via the send message transmission e.g. self.send(:is_admin? and again the return value is used to determine if the validation should be applied
ActiveModel::Validations::ClassMethods#validates
Update based on revised question:
Since the Event is related to the User via submitter and this is already being set to the instance of a User you can validate in a very similar fashion via
validates :attribute_name, presence: true,
    unless: ->(event) { event.submitter&.is_admin?}

Or make a separate method such as
def admin_submitter?
  self.submitter&.is_admin?
end
validates :attribute_name, presence: {unless: :admin_submitter?}


text:
Q: How to use Queryable.Where when type is set at runtime? I'm implementing the back end of a search/filter UI for an app using EF6. I have code that builds an Expression to use with Queryable.Where for a given DbSet, where the type of the DbSet is determined at runtime (the DBContext has a lot of them, and they may change). The call to Where works fine if I cheat by casting the Expression to a specific type first. Otherwise, I get this error:
'The best overloaded method match for 'System.Linq.Queryable.Where(System.Linq.IQueryable, System.Linq.Expressions.Expression>)' has some invalid arguments'
I'm struggling to find a way to filter the DbSet like this where the underlying 'table' type is provided at runtime. Here's a greatly simplified version of the code to illustrate:
    void ProcessFilter(AppDbContext context, NameValueCollection filters, Type tableType)
    {
        // If tableType == typeof(Organisation), expression is a Expression<Func<Organisation, bool>>
        var expression = GetFilterExpression(filters);
        var dbset = Set(context, tableType);

        dynamic dynamicSet = dbset;

        // This fails
        var results = Queryable.Where(dynamicSet, expression);
        // see https://stackoverflow.com/questions/4285598/iqueryable-non-generic-missing-count-and-skip-it-works-with-iqueryablet

        // Suppose tableType == typeof(Organisation)
        // This works
        var typedExpression = expression as Expression<Func<Organisation, bool>>;
        var typedResults = Queryable.Where(dynamicSet, typedExpression);

    }

    public static IQueryable Set(DbContext context, Type T)
    {
        // Similar to code in
        // https://stackoverflow.com/questions/21533506/find-a-specified-generic-dbset-in-a-dbcontext-dynamically-when-i-have-an-entity
        var method = typeof(DbContext).GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(x => x.Name == "Set" && x.IsGenericMethod).First();

        // Build a method with the specific type argument
        method = method.MakeGenericMethod(T);

        return method.Invoke(context, null) as IQueryable;
    }

A: Answering you concrete question. Given
IQueryable source
LambdaExpression predicate

how to call the static generic method
Queryable.Where<T>(IQueryable<T> source, Expression<Func<T, bool>> predicate)

It can be done using (A) reflection, (B) DLR dynamic dispatch and (C) Expression.Call.
What you are trying to do is option (B). However
var result = Queryable.Where((dynamic)source, predicate);

does dynamic search for method having second argument of type LambdaExpression, which of course fails.
In order to be able to dynamically match the target method, you need to make the second argument dynamic as well:
var result = Queryable.Where((dynamic)source, (dynamic)predicate);

The equivalent option (C) implementation of the above is:
var result = source.Provider.CreateQuery(Expression.Call(
    typeof(Queryable), nameof(Queryable.Where), new[] { source.ElementType },
    source.Expression, predicate));

A: congrats on your first question.
Let's begin by looking at an approach for filtering a collection of data based on some custom filters. I will assume that the NameValueCollection Type you prefer to pass in your filters, holds PropertyNames as Keys and PropertyValues as Value.
Before we go forth filtering an entire collection, let's first figure out how to determine whether one object has properties that match our filters. And since we do not know the Type of our object till runtime, we will need to use Generics in C# to accomplish this.
Step 1
- Get All Class Properties
We will need to get all properties of our generic class, e.g <TClass>. Doing this using Reflection is deemed as slow and Matt Warren explains Why Reflection is slow in .NET and how to work around it. We shall therefore implement caching of class component model to get its PropertyDescriptorCollection which exists in the namespace System.ComponentModel.PropertyDescriptorCollection.
Components Cache
private static IDictionary<string, PropertyDescriptorCollection> _componentsCache
        = new Dictionary<string, PropertyDescriptorCollection>();

The key of our Dictionary represents the name of the generic class and the value holds the PropertyDescriptorCollection of that given class.
internal static bool InnerFilter<T>(T obj, NameValueCollection filters)
        where T : class
{
        Type type = typeof(T);
        PropertyDescriptorCollection typeDescriptor = null;

        if (_componentsCache.ContainsKey(type.Name))
            typeDescriptor = _componentsCache[type.Name];
        else
        {
            typeDescriptor = TypeDescriptor.GetProperties(type);
            _componentsCache.Add(type.Name, typeDescriptor);
        }
}

Step 2
- Loop through filters
After we have gotten the PropertyDescriptorCollection for the generic class T in the variable typeDescriptor as shown above, now let's loop through our filters and see if any of its property names match any of our filter keys. If T has a property name that matches any of our filter keys, now we inspect if the actual value of the property matches our filter value. To improve the quality of our search/filter function, we are going to use Regular Expressions in C# to determine whether a comparison is a hit or a miss.
for (int i = 0; i < filters.Count; i++)
{
    string filterName = filters.GetKey(i);
    string filterValue = filters[i];

    PropertyDescriptor propDescriptor = typeDescriptor[filterName];
    if (propDescriptor == null)
        continue;
    else
    {
        string propValue = propDescriptor.GetValue(obj).ToString();
        bool isMatch = Regex.IsMatch(propValue, $"({filterValue})");
        if (isMatch)
            return true;
        else
            continue;
    }
}

Step 3
- Implement Extension Methods.
To make the code that we've written easy to use and re-use, we are going to implement Extension Methods in C# so that we can better re-use our functions anywhere within our project.
- Generic Collection Filter Function that Uses the above Function.
Since an IQueryable<T> can be converted to an IEnumerable<T> by the .Where() function in System.Linq, we are going to utilize that in our function call as shown below.
public static IEnumerable<T> Filter<T>(this IEnumerable<T> collection, NameValueCollection filters)
        where T : class
{
    if (filters.Count < 1)
        return collection;

    return collection.Where(x => x.InnerFilter(filters));
}

Step 4
Put everything together.
Now that we have everything we need, let's look at how the final/full code looks as one block of code in a single static class.
public static class Question54484908
{
    private static IDictionary<string, PropertyDescriptorCollection> _componentsCache = new Dictionary<string, PropertyDescriptorCollection> ();

    public static IEnumerable<T> Filter<T> (this IEnumerable<T> collection, NameValueCollection filters)
        where T : class
    {
        if (filters.Count < 1)
            return collection;

        return collection.Where (x => x.InnerFilter (filters));
    }

    internal static bool InnerFilter<T> (this T obj, NameValueCollection filters)
        where T : class
    {
        Type type = typeof (T);
        PropertyDescriptorCollection typeDescriptor = null;

        if (_componentsCache.ContainsKey (type.Name))
            typeDescriptor = _componentsCache[type.Name];
        else {
            typeDescriptor = TypeDescriptor.GetProperties (type);
            _componentsCache.Add (type.Name, typeDescriptor);
        }

        for (int i = 0; i < filters.Count; i++) {
            string filterName = filters.GetKey (i);
            string filterValue = filters[i];

            PropertyDescriptor propDescriptor = typeDescriptor[filterName];
            if (propDescriptor == null)
                continue;
            else {
                string propValue = propDescriptor.GetValue (obj).ToString ();
                bool isMatch = Regex.IsMatch (propValue, $"({filterValue})");
                if (isMatch)
                    return true;
                else
                    continue;
            }
        }

        return false;
    }
}

FINALLY
Filtering IEnumerable<T>, List<T>, Arrays
This is how you are going to use the above code anywhere in your project.
private IEnumerable<Question> _questions;
_questions = new List<Question>()
{
    new Question("Question 1","How do i work with tuples"),
    new Question("Question 2","How to use Queryable.Where when type is set at runtime?")
};
var filters = new NameValueCollection
{
   { "Description", "work" }
};
var results = _questions.Filter(filters);

Filtering DbSet<T>
Every DbContext has a function .Set<T> that returns a DbSet<T> that can be used as  an IQueryable<T> and thus our function can be used as well as shown below.
Example
_dbContext.Set<Question>().Filter(filters);

Hope this answers your question or rather points you in the right direction.


text:
Q: Reshaping and calculation of data in R I am new to R and I would like to use it to write a simple code to visualize the Defect removal efficiency for software defect (Fixed defects / Unresolved defects) * 100 based on the priority of the bugs
I have exported some data sample from Jira:
Priority    Resolution  Created     Resolved
P3          Unresolved  28.02.2017  28.02.2017
P3          Unresolved  28.02.2017  28.02.2017
P1             Fixed    27.02.2017  06.03.2017
P2             Fixed    27.02.2017  14.03.2017
P1          Unresolved  24.02.2017  13.03.2017
P1          duplicate   21.02.2017  02.03.2017
P1             Fixed    24.02.2017  07.03.2017

I would like to reshape this table and at the same time do some calculations.
This is very easy using excel pivot tables but I would like to script it with R
Expected output:
Resolution  P1  P2  P3  Grand Total
duplicate   2               2
Fixed       4   4   1       9
Unresolved  2   2   4       8
Grand Total 8   6   5       19

Also, I would like to see the trend of the resolution (Something like the following)
Dates   P1 unresolved   P1 fixed    P1 DRE, %          P2 unresolved    P2 fixed    P2 DRE, %
date1          5           0             0%                   20          3           15%
date1 + 7      6           2            33%                   37          4           11%
date1 + 14     9           3            33%                   40          4           10%

How this could be achieved by R programming?

A: These functions from the janitor package mimic Excel's PivotTable:
library(janitor)
dat %>%
  tabyl(Resolution, Priority) %>%
  adorn_totals(c("row", "col"))

 Resolution P1 P2 P3 Total
  duplicate  1  0  0     1
      Fixed  2  1  0     3
 Unresolved  1  0  2     3
      Total  4  1  2     7

Data used:
dat <- read.table(text = "Priority    Resolution  Created     Resolved
P3          Unresolved  28.02.2017  28.02.2017
                  P3          Unresolved  28.02.2017  28.02.2017
                  P1             Fixed    27.02.2017  06.03.2017
                  P2             Fixed    27.02.2017  14.03.2017
                  P1          Unresolved  24.02.2017  13.03.2017
                  P1          duplicate   21.02.2017  02.03.2017
                  P1             Fixed    24.02.2017  07.03.2017", header = TRUE)

A: Here is an answer for the first part using just table.  I saved your data into a file in the same directory, comma-separating the values.
data = read.csv('jira_data.csv')
new_data = table(data$Resolution, data$Priority)
new_data = addmargins(new_data)


text:
Q: How can I get a response without a backslash and double quotes?(Android, Kotlin) Implementing profile modification. The function has the ability to request values for image change and nickname change to the server, and the server hands over the modified nickname value and the value of the base64 decoded image to the response value. There is a problem implementing the feature, where the value of the image is answered correctly, but the value of the modified nickname is not a pure string value, but contains odd double quotation and backslash values. What is wrong with that?
This is all code i coded

This is result from Log:
resultCode : CNAPResponse(nickname="abcdefg", image=/9j/4QJcRXhpZgAATU0AKgAAAAgACAEQAAIAAAAUAAAAbgEAAAQAAAABAAAFcAEBAAQAAAABAAAHQAEyAAIAAAAUAAAAggESAAMAAAABAAEAAIdpAAQAAAABAAAAnYglAAQAAAABAAABswEPAAIAAAAHAAAAlgAAAABzZGtfZ3Bob25lNjRfeDg2XzY0ADIwMjM6MDI6MDYgMTI6Mzk6NDcAR29vZ2xlAAAQgp0ABQAAAAEAAAFjgpoABQAAAAEAAAFrkpIAAgAAAAQ3OTAAkpEAAgAAAAQ3OTAAkpAAAgAAAAQ3OTAAkgoABQAAAAEAAAFzkgkAAwAAAAEAAAAAiCcAAwAAAAEAZAAAkAQAAgAAABQAAAF7kAMAAgAAABQAAAGPoAMABAAAAAEAAAdApAMAAwAAAAEAAAAAoAIABAAAAAEAAAVwkgIABQAAAAEAAAGjkgEACgAAAAEAAAGrkAAABwAAAAQwMjIwAAAAAAAAARgAAABkAEVkODuaygAAAAzkAAAD6DIwMjM6MDI6MDYgMTI6Mzk6NDcAMjAyMzowMjowNiAxMjozOTo0NwAAAAEpAAAAZAAAHmQAAAPoAAYAAQACAAAAAk4AAAAAAgAKAAAAAwAAAgEAAwACAAAAAlcAAAAABAAKAAAAAwAAAhkABwAFAAAAAwAAAjEAHQACAAAACwAAAkkAAAAAAAAAJQAAAAEAAAAZAAAAAQAACHEAAABkAAAAegAAAAEAAAAFAAAAAQAAAlMAAABkAAAADAAAAAEAAAAnAAAAAQAAACwAAAABMjAyMzowMjowNgD/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEUAAQEAAAIYAAAAAAQwAABtbnRyUkdCIFhZWiAAAAAAAAAAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAAHRyWFlaAAABZAAAABRnWFlaAAABeAAAABRiWFlaAAABjAAAABRyVFJDAAABoAAAAChnVFJDAAABoAAAAChiVFJDAAABoAAAACh3dHB0AAAByAAAABRjcHJ0AAAB3AAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAFgAAAAcAHMAUgBHAEIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFhZWiAAAAAAAABvogAAOPUAAAOQWFlaIAAAAAAAAGKZAAC3hQAAGNpYWVogAAAAAAAAJKAAAA+EAAC2z3BhcmEAAAAAAAQAAAACZmYAAPKnAAANWQAAE9AAAApbAAAAAAAAAABYWVogAAAAAAAA9tYAAQAAAADTLW1sdWMAAAAAAAAAAQAAAAxlblVTAAAAIAAAABwARwBvAG8AZwBsAGUAIABJAG4AYwAuACAAMgAwADEANv/bAEMAAwICAwICAwMDAwQDAwQFCAUFBAQFCgcHBggMCgwMCwoLCw0OEhANDhEOCwsQFhARExQVFRUMDxcYFhQYEhQVFP/bAEMBAwQEBQQFCQUFCRQNCw0UFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFP/AABEIB0AFcAMBIgACEQEDEQH/xAAdAAEAAgIDAQEAAAAAAAAAAAAABggFBwECCQME/8QAWRABAAABBQQTCgsHBQEAAQUAAAIBAwQFBgcWU9ERFRcYITE2N1RVVnWSlKKys9LTCBIUMjRRcXSTpBMzNUVScnODhLHCCUFhgqGjxGaRpbTjIiRCQ0Zjgf/EABwBAQABBQEBAAAAAAAAAAAAAAAFAQIGBwgEA//EAEMRAQAAAgMKDAUDBAIDAAMAAAABAgMEBRUWMTJRU3KRobEGERITFDM0NVJi0eEXY3GB0iFhwUFkkqIiQkSC8AcjJP/aAAwDAQACEQMRAD8A9SAH1egAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

This is also result but from Postman:

In the sharedPreference file, values seem to be stored properly in the form of a string, but when the response values are checked with log and postman, the nickname values among the response values differ from each other, especially postman, and the nickname values include double quotes and backslashes.
How can I fix it?


text:
Q: Xpath - How to select subnode where sibling-node contains certain text I want to use XPath to select the sub tree containing the <name>-tag with "ABC" and not the other one from the following xml. Is this possible? And as a minor question, which keywords would I use to find something like that over Google (e.g. for selecting the sub tree by an attribute I would have the terminology for)?
<root>
  <operation>
    <name>ABC</name>
    <description>Description 1</description>
  </operation>
  <operation>
    <name>DEF</name>
    <description>Description 2</description>
  </operation>
</root>

A: Use:
/*/operation[name='ABC']

For your second question: I strongly recommend not to rely on online sources (there are some that aren't so good) but to read a good book on XPath.
See some resources listed here:
https://stackoverflow.com/questions/339930/any-good-xslt-tutorial-book-blog-site-online/341589#341589

A: For your first question, I think a more accurate way to do it would be://operation[./name[text()='ABC']].And according to this , we can also make it://operation[./name[text()[.='ABC']]]


text:
Q: How can I manually interpolate string escapes in a Perl string? In perl suppose I have a string like 'hello\tworld\n', and what I want is:
'hello  world
'

That is, "hello", then a literal tab character, then "world", then a literal newline. Or equivalently, "hello\tworld\n" (note the double quotes).
In other words, is there a function for taking a string with escape sequences and returning an equivalent string with all the escape sequences interpolated? I don't want to interpolate variables or anything else, just escape sequences like \x, where x is a letter.

A: Sounds like a problem that someone else would have solved already. I've never used the module, but it looks useful:
use String::Escape qw(unbackslash);
my $s = unbackslash('hello\tworld\n');

A: You can do it with 'eval':
my $string = 'hello\tworld\n';
my $decoded_string = eval "\"$string\"";

Note that there are security issues tied to that approach if you don't have 100% control of the input string.
Edit: If you want to ONLY interpolate \x substitutions (and not the general case of 'anything Perl would interpolate in a quoted string') you could do this:
my $string = 'hello\tworld\n';
$string =~ s#([^\\A-Za-z_0-9])#\\$1#gs;
my $decoded_string = eval "\"$string\"";

That does almost the same thing as quotemeta - but exempts '\' characters from being escaped.
Edit2: This still isn't 100% safe because if the last character is a '\' - it will 'leak' past the end of the string though...
Personally, if I wanted to be 100% safe I would make a hash with the subs I specifically wanted and use a regex substitution instead of an eval:
my %sub_strings = (
    '\n' => "\n",
    '\t' => "\t",
    '\r' => "\r",
);

$string =~ s/(\\n|\\t|\\n)/$sub_strings{$1}/gs;


text:
Q: How to plot area between a predefined upper and lower bounds in ggplot2? Data:
Morocco_ObsClim
Morocco_ProjClim
Code:
Morocco_ObservedClim <- read.csv(file = "Morocco_ObservedClim.csv", header=TRUE, sep=",", na.string="NA", dec=".", strip.white=TRUE)
Morocco_ProjectedClim <- read.csv(file = "Morocco_ProjectedClim.csv", header=TRUE, sep=",", na.string="NA", dec=".", strip.white=TRUE)

# Select the data

obs_annualanom.df <- subset(Morocco_ObservedClim, DataSource %in% c("avg") & DataFormat %in% c("anom") & Timeframe %in% c("annual"))
obs_annualanom.df <- obs_annualanom.df[1:41,]
proj_annualanom.df <- subset(Morocco_ProjectedClim, gcm %in% c("avg","min","max") & DataFormat %in% c("anom") & Timeframe %in% c("annual"))

# Melting the data

obs_annualanom.df <- melt(obs_annualanom.df, id.vars=c("Year","DataSource","DataFormat","Timeframe"))
proj_annualanom.df <- melt(proj_annualanom.df, id.vars=c("Year","sres","gcm","DataFormat","Timeframe"))

# Plots

precip <- ggplot(data=obs_annualanom.df) + geom_line(aes(Year,value),subset=.(variable %in% c("Precip")),size=1.1)
precip <- precip + geom_line(data=proj_annualanom.df, aes(Year,value),colour="brown",size=1.1,subset=.(variable %in% c("Precip") & gcm %in% c("avg") & sres %in% c("20thC")))
precip <- precip + geom_area(data=proj_annualanom.df, aes(Year,value),fill="tan1",alpha=0.5,subset=.(variable %in% c("Precip") & gcm %in% c("max") & sres %in% c("20thC")))
precip <- precip + geom_area(data=proj_annualanom.df, aes(Year,value),fill="tan1",alpha=0.5,subset=.(variable %in% c("Precip") & gcm %in% c("min") & sres %in% c("20thC")))
precip <- precip + geom_line(data=proj_annualanom.df, aes(Year,value),colour="red",size=1.1,subset=.(variable %in% c("Precip") & gcm %in% c("avg") & sres %in% c("A2")))
precip <- precip + geom_area(data=proj_annualanom.df, aes(Year,value),fill="red3",alpha=0.3,subset=.(variable %in% c("Precip") & gcm %in% c("max") & sres %in% c("A2")))
precip <- precip + geom_area(data=proj_annualanom.df, aes(Year,value),fill="red3",alpha=0.3,subset=.(variable %in% c("Precip") & gcm %in% c("min") & sres %in% c("A2")))
precip <- precip + geom_line(data=proj_annualanom.df, aes(Year,value),colour="blue",size=1.1,subset=.(variable %in% c("Precip") & gcm %in% c("avg") & sres %in% c("A1B")))
precip <- precip + geom_area(data=proj_annualanom.df, aes(Year,value),fill="royalblue3",alpha=0.3,subset=.(variable %in% c("Precip") & gcm %in% c("max") & sres %in% c("A1B")))
precip <- precip + geom_area(data=proj_annualanom.df, aes(Year,value),fill="royalblue3",alpha=0.3,subset=.(variable %in% c("Precip") & gcm %in% c("min") & sres %in% c("A1B")))
precip <- precip + geom_line(data=proj_annualanom.df, aes(Year,value),colour="green4",size=1.1,subset=.(variable %in% c("Precip") & gcm %in% c("avg") & sres %in% c("B1")))
precip <- precip + geom_area(data=proj_annualanom.df, aes(Year,value),fill="palegreen3",alpha=0.3,subset=.(variable %in% c("Precip") & gcm %in% c("max") & sres %in% c("B1")))
precip <- precip + geom_area(data=proj_annualanom.df, aes(Year,value),fill="palegreen3",alpha=0.3,subset=.(variable %in% c("Precip") & gcm %in% c("min") & sres %in% c("B1")))
precip <- precip + labs(title="Precipitation",y="Anomalies (mm/year)", x="") + theme_bw()
#precip <- precip + scale_x_discrete(breaks=seq(by=20)) #+ scale_y_continuous(breaks = seq(-50, 80, by=25))
precip <- precip + theme(plot.title=element_text(face="bold", size=rel(2), hjust=0.5, vjust=1.5),
                     axis.text.x=element_text(color="black", size=rel(2.5), hjust=0.5, vjust=0.5),
                     axis.text.y=element_text(color="black", size=rel(2.5), hjust=1),
                     axis.title=element_text(face="bold", color="black", size=rel(1.7), hjust=0.5, vjust=0.2))

temp <- ggplot(data=obs_annualanom.df) + geom_line(aes(Year,value),subset=.(variable %in% c("Temp")),size=1.1)
temp <- temp + geom_line(data=proj_annualanom.df, aes(Year,value),colour="brown",size=1.1,subset=.(variable %in% c("Temp") & gcm %in% c("avg") & sres %in% c("20thC")))
temp <- temp + geom_area(data=proj_annualanom.df, aes(Year,value),fill="tan1",alpha=0.5,subset=.(variable %in% c("Temp") & gcm %in% c("max") & sres %in% c("20thC")))
temp <- temp + geom_area(data=proj_annualanom.df, aes(Year,value),fill="tan1",alpha=0.5,subset=.(variable %in% c("Temp") & gcm %in% c("min") & sres %in% c("20thC")))
temp <- temp + geom_line(data=proj_annualanom.df, aes(Year,value),colour="red",size=1.1,subset=.(variable %in% c("Temp") & gcm %in% c("avg") & sres %in% c("A2")))
temp <- temp + geom_area(data=proj_annualanom.df, aes(Year,value),fill="red3",alpha=0.3,subset=.(variable %in% c("Temp") & gcm %in% c("max") & sres %in% c("A2")))
temp <- temp + geom_area(data=proj_annualanom.df, aes(Year,value),fill="red3",alpha=0.3,subset=.(variable %in% c("Temp") & gcm %in% c("min") & sres %in% c("A2")))
temp <- temp + geom_line(data=proj_annualanom.df, aes(Year,value),colour="blue",size=1.1,subset=.(variable %in% c("Temp") & gcm %in% c("avg") & sres %in% c("A1B")))
temp <- temp + geom_area(data=proj_annualanom.df, aes(Year,value),fill="royalblue3",alpha=0.3,subset=.(variable %in% c("Temp") & gcm %in% c("max") & sres %in% c("A1B")))
temp <- temp + geom_area(data=proj_annualanom.df, aes(Year,value),fill="royalblue3",alpha=0.3,subset=.(variable %in% c("Temp") & gcm %in% c("min") & sres %in% c("A1B")))
temp <- temp + geom_line(data=proj_annualanom.df, aes(Year,value),colour="green4",size=1.1,subset=.(variable %in% c("Temp") & gcm %in% c("avg") & sres %in% c("B1")))
temp <- temp + geom_area(data=proj_annualanom.df, aes(Year,value),fill="palegreen3",alpha=0.3,subset=.(variable %in% c("Temp") & gcm %in% c("max") & sres %in% c("B1")))
temp <- temp + geom_area(data=proj_annualanom.df, aes(Year,value),fill="palegreen3",alpha=0.3,subset=.(variable %in% c("Temp") & gcm %in% c("min") & sres %in% c("B1")))
temp <- temp + labs(title="Temperature",y="Anomalies (degree C)", x="") + theme_bw()
#temp <- temp + scale_x_discrete(breaks=seq(by=20)) #+ scale_y_continuous(breaks = seq(-50, 80, by=25))
temp <- temp + theme(plot.title=element_text(face="bold", size=rel(2), hjust=0.5, vjust=1.5),
                 axis.text.x=element_text(color="black", size=rel(2.5), hjust=0.5, vjust=0.5),
                 axis.text.y=element_text(color="black", size=rel(2.5), hjust=1),
                 axis.title=element_text(face="bold", color="black", size=rel(1.7), hjust=0.5, vjust=0.2))

My Results:

My objective: Reproduce this graph

Graphs nomenclature:
Solid lines represent the average.
The filled area is supposed to represent the max and min, which is available in the data.
The problem I have is that I want to achieve the following:
First, plot the averages which is accomplished successfully as per my resulting graphs.
Second, be able to set the fill between the min and max values in the data, which is where I fail.
Any help would be appreciated.
Thanks

A: I think you are overcomplicating things.  Consider:
df <- subset(
  Morocco_ProjectedClim,
  DataFormat=="anom" & gcm %in% c("avg", "min", "max") & Timeframe=="annual",
  select=c("sres", "Year", "gcm", "Temp")
)
df.cast <- dcast(df, sres + Year ~ gcm)
library(ggplot2)
ggplot(df.cast, aes(x=Year, y=avg)) +
  geom_ribbon(aes(ymin=min, ymax=max, fill=sres), alpha=0.4) +
  geom_line(aes(color=sres)) +
  scale_fill_manual(values=c("tan1", "red3", "royalblue3", "palegreen3")) +
  scale_color_manual(values=c("brown", "red", "blue", "green4"))

This does just the temperatures from the projected data set, but should give you a good idea on how to tackle the problem.

EDIT: this adds actuals:
ggplot(df.cast, aes(x=Year, y=avg)) +
  geom_ribbon(aes(ymin=min, ymax=max, fill=sres), alpha=0.4) +
  geom_line(aes(color=sres)) +
  geom_line(
    data=subset(Morocco_ObservedClim, DataSource == "avg" & DataFormat == "anom" & Timeframe == "annual"),
    aes(x=Year, y=Temp, color="Actual")
  ) +
  scale_fill_manual(values=c("tan1", "red3", "royalblue3", "palegreen3")) +
  scale_color_manual(values=c(`20thC`="brown", A1B="red", A2="blue", B1="green4", Actual="black"))

Though note I didn't update the plot.


text:
Q: Non-repeatable affinity for pthreads I am trying to measure the time it takes for a thread from creation to actually start.
Using POSIX thread on a Debian 6.0 machine with 32-cores (no hyper-threading) and calling pthread_attr_setaffinity_np function to set the affinity.
In a loop, I am creating the threads, waiting for them to finish, repeatedly.
So, my code looks like the following (thread 0 is running this).
for (ni=0; ni<n; ni++)
   {
      pthread_t *thrds;
      pthread_attr_t attr;
      cpu_set_t cpuset;
      ths = 1; // thread starts from 1

      thrds = malloc(sizeof(pthread_t)*nt); // thrds[0] not used
      assert(!pthread_attr_init(&attr));
      for (i=ths; i<nt; i++)
      {
         pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
         CPU_ZERO(&cpuset);
         CPU_SET(i, &cpuset); // setting i as the affinity for thread i
         assert(!pthread_attr_setaffinity_np(&attr,
                  sizeof(cpu_set_t), &cpuset));
         assert(!pthread_create(thrds+i, &attr, DoWork, i));
      }
      pthread_attr_destroy(&attr);

      DoWork(0);

      for (i=ths; i<nt; i++)
      {
         pthread_join(thrds[i], NULL);
      }
      if (thrds) free(thrds);
   }

Inside the thread function, I am calling sched_getcpu() to verify that the affinity is working. The problem is, this verification only passes the first iteration of i-loop. For the second iteration, thrd[1] gets the affinity of nt-1 (instead of 1) and so on.
Can anyone please explain why? And/or how to fix it?
NOTE: I found a workaround that if I put the master thread to sleep for 1 second after the join finishes at each iteration, the affinity works correctly. But this sleep duration could different on other machines. So still need a real fix for the issue.


text:
Q: Blur que está atrapalhando o navbar Já tentei usar o "z-index=1", mas não funcionou.
Tentei tirar a navbar da div first blur, só que quando eu clico no botão ela não fica com "blur", mas se eu deixo dentro fica com bordas pretas do lado, como se fosse uma sombra, já tentei várias coisas enfim... queria que a navbar ficasse com "blur" quando eu clicasse no botão "entrar", mas que não ficasse com essa borda preta.
Obs: Os códigos tanto da nav.css e do JANE1estilo.css são da mesma página, só que em arquivos css diferentes... por isso da erro ao executar.

.firstBlur {
  margin:20px 20px 0;
  padding:20px;
  position:relative;
  z-index: 1;
}
/* coloque blur em todos os elementos menos no elemento com a class .modal */
.firstBlur.modalBlur > *:not(.modal) {
  -webkit-filter: blur(8px);
  filter: blur(8px);
}
/* remove a cor escurecida do fundo, se quiser que fique escurecido ajuste a opacidade para 0.5*/

.log{
  margin-top: -400px;
}
body {font-family: Arial, Helvetica, sans-serif;
  margin:0;
  background-color: black;
}

/* Full-width input fields */
input[type=text], input[type=password] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}

.imgcontainer + div{
   position: relative;
   z-index: 1;
}
/* Extra styles for the cancel button */
.cancelbtn {
  width: auto;
  padding: 10px 18px;
  background-color: #f44336;
}

/* Center the image and position the close button */
.imgcontainer {
  text-align: center;
  margin: 24px 0 12px 0;
  position: relative;

}

/* Imagem do logotipo, caso queira alterar a posição dela ou aplicar efeitos, etc... */

.logo {
  height: 500px;
  width: 500px;
  margin: 24px 0 12px 0;
  margin-left: -14px;
  margin-top: 130px;
  position: relative;

}

img.avatar {
  width: 40%;
  border-radius: 50%;
}

.container {
  padding: 16px;
  color: black;
}

span.psw {

  margin-left: : -5px;

}

/* The Modal (background) */

.container1-blur{
  filter: blur(8px);
  -webkit-filter: blur(8px);
}
/* The Close Button (x) */

/* Add Zoom Animation */
.animate {
  -webkit-animation: animatezoom 0.6s;
  animation: animatezoom 0.6s

}

@-webkit-keyframes animatezoom {
  from {-webkit-transform: scale(0)}
  to {-webkit-transform: scale(1)}
}

@keyframes animatezoom {
  from {transform: scale(0)}
  to {transform: scale(1)}
}

/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
  span.psw {
     display: block;
     float: none;

  }
  .cancelbtn {
     width: 100%;
  }
<!DOCTYPE html>

        <Meta charset="UTF-8">
    <Meta name="description" content="Site educaciona para deficientes auditivos">
    <Meta name="keywords" content="deficientes, deficientes auditivos, educação, surdos, educação para surdos, educação para deficientes, site educacional, projeto aval, aval, auxilio para surdos, ajuda com surdos, escola surdos, escola deficientes, surdos e mudos">
    <Meta name="author" content="Vitor Hugo Minhaco Junior e João Vitor Galhardo">
  <Meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="css/JANE1estilo.css">
    <link rel="stylesheet" type="text/css" href="css/nav.css">
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />

      Home

      About Us

      Testimonials

      Entrar

Faça o login!

                        <form class="log">

      Nome
      <input type="text" placeholder="Digite seu nome" name="uname" required>

      Senha
      <input type="password" placeholder="Digite sua senha" name="psw" required>

      <button type="submit" class="shadow-pop-tr"style="background-color:#008080">Entrar</button>

        <input type="checkbox" checked="checked" name="remember"> Lembrar de mim

      Esqueceu a senha?
      </form>

</script>

$('.nav-link').on('click', function() {
 $('.active-link').removeClass('active-link');
 $(this).addClass('active-link');
});
a {
 outline: none;
}

.navbar-container{
 text-align: center;
 background-color: #009688;
 box-shadow: 0px -20px 5px 20px #333333;
 padding: 10px;
 font-size: 0;
  z-index: 2;
}

.navbar-container ul {
 margin: 0;
 padding: 0;
 text-align: right;
 display: inline-block;
 vertical-align: middle;
  z-index: 2;
}

.navbar-container ul li {
 display: inline-block;
 font-size: 16px;
  z-index: 2;
}

.navbar-container ul li a {
 color: #ffffff;
 text-decoration: none;
 display: inline-block;
 padding: 10px;
 transition: color 0.5s;
  z-index: 2;
}

.navbar-container ul li .underline {
 height: 3px;
 background-color: transparent;
 width: 0%;
 transition: width 0.2s, background-color 0.5s;
 margin: 0 auto;
  z-index: 2;
}

.navbar-container ul li.active-link .underline {
 width: 100%;
 background-color: white;
  z-index: 2;
}

.navbar-container ul li:hover .underline {
 background-color: white;
 width: 100%;
  z-index: 2;
}

.navbar-container ul li:hover a {

}

.navbar-container ul li:active a {
 transition: none;
 color: rgba(255,255,255,0.76);
}

.navbar-container ul li:active .underline {
 transition: none;
 background-color: rgba(255,255,255,0.76);
}

A: Seu principal problema é com o box-shadow mesmo e não com o blur(), repare que na classe .navbar-container vc colocou um box-shadow: 0px -20px 5px 20px #333333; veja que ele tem no terceiro valor 5px, esse 5px representa esse "esfumaçado" tipo um blur mesmo que vc está vendo e não consegue tirar pq ele não está no filter blur() e sim no box-shadow, assim como o último valor que é  de 20px e representa o quando o box-shadow deve ter de largura antes de começas a "esfumaça", isso que está criando a borda preta que vc não quer.
Leia mais sobre box-shadow aqui:box-shadow pegar os quatro cantos da imagem
Veja que ajustando isso ele funciona perfeitamente.

Segue o código corrigido. Recomendo que vc faça uma revisão no seu HTML pois vc deixou algumas divs abertas, mas vou deixar isso pra vc resolver.

<!DOCTYPE html>

<Meta charset="UTF-8">
<Meta name="description" content="Site educaciona para deficientes auditivos">
<Meta name="keywords" content="deficientes, deficientes auditivos, educação, surdos, educação para surdos, educação para deficientes, site educacional, projeto aval, aval, auxilio para surdos, ajuda com surdos, escola surdos, escola deficientes, surdos e mudos">
<Meta name="author" content="Vitor Hugo Minhaco Junior e João Vitor Galhardo">
<Meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/JANE1estilo.css">
<link rel="stylesheet" type="text/css" href="css/nav.css">

                    Home

                    About Us

                    Testimonials

                    Entrar

Faça o login!

                        <form class="log">

                                Nome
                                <input type="text" placeholder="Digite seu nome" name="uname" required>

                                Senha
                                <input type="password" placeholder="Digite sua senha" name="psw" required>

                                <button type="submit" class="shadow-pop-tr" style="background-color:#008080">Entrar</button>

                                    <input type="checkbox" checked="checked" name="remember"> Lembrar de mim

                                Esqueceu a senha?
                        </form>


text:
Q: Profiling tool for Clojure? does anyone know of a good profiling tool or library for Clojure?
I would prefer something that could be used from the REPL, along the lines of (with-profiling ...) in Allegro Common Lisp back in the day.
Is there anything along those lines?
Or do you have any experience with (non-commercial) Java profilers that work well with Clojure?

A: I found VisualVM (see here and here) to be very convenient. Its use with Clojure has been described about a year ago in this blog post; as far as I can see, it's not outdated in any way.
Note that the GUI from which one starts the VisualVM profiler has a prominent text area where one can enter classes / packages to be excluded from profiling -- I find the results rather more useful when clojure.* is on that list.

A: There's a newish Clojure library which offers profiling: https://github.com/ptaoussanis/timbre

A: Just found profile in Clojure contrib.
It doesn't work for large amounts of code (it blew up with OutOfMemoryError on a Project Euler solution which VisualVM handled just fine) and it requires you to insert profiling calls in the functions you want to profile.
Still, it's a better alternative to VisualVM in the cases where you just want to profile a couple of functions.

A: Quick heads-up that I've deprecated Timbre's profiling for a new dedicated Clojure + ClojureScript profiling lib at https://github.com/ptaoussanis/tufte.
That's basically a refinement of the stuff from Timbre, plus dedicated docs.
The README includes a comparison with JVM tools like VisualVM, YourKit, etc.


text:
Q: Why does $\dim M > \dim N \implies$ there are no regular points $x \in M$, where $M,N$ are smooth manifolds? Let $f:M \rightarrow N$ be a smooth function between smooth manifolds $M,N$. A regular point is a point $x \in M$ s.t. $d_xf$ is surjective. Why does $\dim M> \dim N$ mean that there are no regular points in $M$?
I attempted to show this by contradiction: assume $x$ is regular,so $d_xf:T_xM \rightarrow T_{f(x)}N$ is a surjection. Thus $\forall y \in T_{f(x)}N,$ $ \exists$ $ v \in T_xM$ s.t. $d_xf(v) = y$. But dim $T_{f(x)}N=\dim N < \dim M = \dim T_xM$. But this is not a contradiction since we can still have a surjection from a higher dimension to one of lower dimension. This seems to show that actually $\dim M< \dim N$ means there are no regular points in $M$.
Where is this argument flawed, and what am I misunderstanding?

A: Maybe you wanted to say $\dim N>\dim M$.
Intuitively the idea is that there is not enough space. But concretely, for a regular point the differential of $f$ must be surjective. Since the dimension of $N$ is bigger that the dimension of $M$ there is no way for a linear map to be surjective between the tangent spaces.


text:
Q: CSS text-overflow on label For my website I have a checkbox with a label next to it, but if the text in the label is longer than for example 60px, I want to cut off the text.
I know about the text-overflow: clip, this does exactly what I want, but for some reason it doesn't work on a label. And using a div instead isn't a really good solution, since you can't click on the text to select the checkbox then.
How can I do this?

A: vertical-align: middle serves as a great solution here to align the label with the check-box and text-overflow: ellipsis for snipping the text with the three dots ... at the end.
The following snippet shows an example:
HTML:
<input type="checkbox"/>
    <label>Pretty awesome label to describe the uber cool checkbox. </label>

CSS:
    label {
      text-overflow: ellipsis;
      display: inline-block;
      overflow: hidden;
      width: 300px;
      white-space: nowrap;
      vertical-align: middle;
    }

Here is a fiddle for you - link

A: A utility class ellipsis could be used here:
.ellipsis {
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

A: label or span are inline by default. You cannot set width on inline elements.
So make label inline-block
/// markup
<input type="checkbox"/> <label style="display: inline-block; width: 60px; overflow: hidden">Sample text sample text</label>


text:
Q: tool to find the routing distance between two latitude/longitude points using OSM data I need a tool to find the distance between two points whose longitude and latitude are given. I am making an application so it will require bulk queries, so i cannot use google maps distance matrix API that could tell me the distance via road, airways or any other.
So I turned up to OSM data, i downloaded the OSM data and then pgrouting tool. But I am unable to find the distance via road between two points from this data stored in postgres table.
Any help regarding how to fetch this data from the postgresql db or any other resource you know that can accomplish my goal will be greatly appreciated.

A: OSM has a page dedicated to routing, which is worth going over:
http://wiki.openstreetmap.org/wiki/Routing
There is a special tool for importing OSM data into a PGRouting system and generating the required structure:
https://github.com/pgRouting/osm2pgrouting
Lastly, there is a workshop tutorial on getting routing working with OSM data here:
http://workshop.pgrouting.org/index.html

A: You can use GraphHopper for this task. Have a look into the documentation for more information.


text:
Q: Prove or disprove statement about convergence of random variables
Prove or disprove the following statement:
\begin{align*}
\text { If } X_{N} \stackrel{d}{\rightarrow} X \text { then } \frac{X_{N}}{\sqrt{N}} \stackrel{P}{\rightarrow} 0
\end{align*}
where $\stackrel{d}{\rightarrow}$ is convergence in distribution and $\stackrel{P}{\rightarrow}$ is convergence in probability.

Intuitively, if the sequence $X_1, \ldots, X_n$ is converging to a fixed distribution as $n \to \infty$, then dividing that random variable by larger and larger values of $\sqrt{n}$ should converge to zero. So I think that statement is true.
However, I feel like I don't have the mathematical language in probability theory to express this precisely.
Could someone help me with this problem?

A: $\newcommand{\pr}{\mathbb P}$Let's formalize your intuition step by step. Consider this more an exercise in formalization of intuition, rather than the formation of the intuition itself (which seems to be sound). I'm going to first present a wrong way of doing things, and then the correct way of doing things, because I know students who, way too often, use the wrong way, get stuck and/or make wrong conclusions and don't get credit.

Your idea is the following (copied verbatim) :

Intuitively, if the sequence $X_1\ldots X_n$ is converging to a fixed distribution as $n\to\infty$, then dividing that random variable by larger and larger values of $n$ should converge to zero. So I think that statement is true.

Think about this in terms of resemblance. $\frac{X_n}{\sqrt n}$ looks like $\frac{X}{\sqrt n}$ for large $n$, which looks like $0$ for large $n$. So we expect $\frac{X_n}{\sqrt n}$ to look like $0$ for large $n$.
Now, the problem with this logic (and yes, there is!) is that one could be tempted to write down the following very natural looking equality (I'm mentioning this because I cannot tell you HOW many people have made this mistake from thinking merely intuitively, and I want to address the elephant in the room) :
$$
\frac{X_n}{\sqrt n} = \frac{X_n -X}{\sqrt n} + \frac{X}{\sqrt n}
$$
and then say something of the form : "both terms on RHS are usually small, so we can use the triangle inequality".
But there's trouble in this paradise : indeed, even if $X_n \to X$ in distribution, it is not true that $X_n -X \to 0$ in probability, or in fact even in distribution. That's basically because subtraction of potentially dependent random variables can have a devastating effect on the distribution functions.
In some sense, this explains the "intuition-mathematics" gap well, since the notion of what it means for two things to be close, actually fails in one particular kind of argument. Ideally speaking, in arguments regarding distribution it's extremely rare that you can add and subtract random variables from one another and have any structure remaining(unless random variables are degenerate , see Slutsky's theorem for example).
The basic reason is that when I look at, say $X_n-X$, I'm looking at it as the function $X_n(\omega) - X(\omega)$ for $\omega$ an element of the sample space. However, unlike convergence a.s. or convergence in probability, I don't actually get an almost sure $\omega$-by-$\omega$ statement anywhere in the definition of convergence in distribution. That's why I need to stop adding and subtracting random variables, and focus on mere probability comparison.
Example : Let $X_i$ be iid any standard random variable, like the Poisson r.v. or the uniform random variable (suggested by E-A below, and the idea of the example was from Bryden so I thank them as well) and $X$ be independent of the $X_i$ and have the same distribution. Now, $X_i$ converges to $X$ in distribution : this is obvious, because *the probabilities that $X_i,X$ lie in certain regions are close enough (I mean, they're literally the same) for all $i$, let alone just large enough $i$. However, because $X_i,X$ are independent, they are created in such a way that $X_n(\omega),X(\omega)$ will really look quite different. For example, if $X,Y$ are iid $N(0,1)$ then $X-Y$ is iid $N(0,2)$! The basic reason is that although we've linked $X_i$ and $X$ via a distribution, we haven't linked them in an $\omega$-to-$\omega$ way, or a way that allows one to depend upon the other w.r.t. the sample space elements themselves. So of course $X_i-X$ won't go in distribution to $0$, although $X_i$ has the same distribution as $X$.
Which means, that I'm going to have to say intuitively : "It's not $X_n$ and $X$ which are close, but rather the probabilities of $X_n$ and $X$ lying in certain regions, which are close". Note the subtlety and beauty of the statement, and how it applies to this particular situation.
So next time, when you say : "things are converging to a fixed distribution" and stuff like that, make sure you have additional intuition to make the argument the way it has to be made.

Now, $X_n \to X$ in distribution, means that for any $k$ (at which $F_X$ is continuous) we have $\pr(X_n \leq k) \to \pr(X \leq k)$. That is the kind of closeness we want to exploit.
Let's now look at the bad event, $\pr\left\{|X_n|>\epsilon\sqrt n\right\}$. Without having to look at $X_n -X$ , we can comfortably say this : This guy resembles $\pr\left\{|X| > \epsilon \sqrt n\right\}$ and that resembles $0$ for large enough $n$.
The point is, the resemblance is between the probabilities : thanks to convergence in distribution, we know this is the case, but because $\epsilon\sqrt n$ could be a point of discontinuity, we need to be slightly careful with our argument.
Well, we can prove the following statement fairly easily :

There exist sequences $x_i \to \infty$ and $y_i \to -\infty$ with $x_i ,y_i \in C(F_X)$ for all $i$.

What that means, is that I can go as far up and down the number line I want and still find continuity points of $F_X$. To prove this, if for the sake of contradiction there wasn't a continuity point beyond some $N$, then every point beyond $N$ is a point of discontinuity, which is a contradiction since that creates an uncountable set of discontinuities for a monotone function (which $F_X$ is), which can have only countably many discontinuities. (Do the same with $-N$ for the other side).
In particular, we know that $F_X(x_i) \to 1$ as $i \to \infty$ and $F_X(y_i) \to 0$ as $i \to \infty$. Furthermore, $F_{X_N}(x_i) \to F_{X}(x_i)$ for all $i$ (and similarly for $y_i$).
The advantage of this , is that even if I don't know about $F_X$ at a point, I can use monotonicity to ensure that it lies above/below some threshold by using these $x_i,y_i$ as reference points.
With that in mind, we are going to do the obvious , and write :
$$
\pr\{|X_n| > \epsilon \sqrt n\} = \pr\{X_n > \epsilon \sqrt n\} + \pr\{X_n < - \epsilon \sqrt n\} \leq 1 - F_{X_n}(\epsilon \sqrt n) + F_{X_n}(-\epsilon \sqrt n)
$$
(Note that $\pr\{X_n < - \epsilon \sqrt n\} \leq F_{X_n}(-\epsilon \sqrt n)$ but doesn't equal it necessarily) Let's mathematically argue our way out of this now. There's an order, a way of choosing things so that the mathematics is made easier. We know we have to bring in the following :

*

*$x_i,y_i$ to replace the $\epsilon\sqrt n$ terms somewhere.

*$X_n$ to be replaced by $X$ somewhere.
The point is , which to do first? Let's think about it this way : we can't replace $X_n$ by $X$ unless we know the points at which the replacements are to be made! So the order is clear : choose the points first, then do the replacement.
Now let's choose the $x_i,y_i$. Fix a $\delta > 0$ which we will use for deciding the $x_i,y_i$ carefully.
Find $N$ such that $1-F_X(x_N) > \delta , F_X(y_N)<\delta$. This can be done using the limit conditions and the property of distribution functions at $\pm \infty$.
With that, where were we? Oh yes, we were here :
$$
\pr\{|X_n| > \epsilon \sqrt n\} = \pr\{X_n > \epsilon \sqrt n\} + \pr\{X_n < - \epsilon \sqrt n\} \leq 1 - F_{X_n}(\epsilon \sqrt n) + F_{X_n}(-\epsilon \sqrt n)
$$
Since $\epsilon \sqrt n\to \infty$ as $n \to \infty$, let's consider $n>N_0$ large enough , such that $\epsilon \sqrt n  > x_N$ and $-\epsilon \sqrt n < y_N$ for $n>N_0$. We chose this to ensure that:
$$
1 - F_{X_n}(\epsilon \sqrt n) + F_{X_n}(-\epsilon \sqrt n) \leq 1 - F_{X_n}(x_N) + F_{X_n}(y_N)
$$
Now, because $N$ doesn't depend upon $n$ (whereas the earlier term inside the brackets very much did), we are in pole position to drag $n$ to infinity, in the inequality:
$$
0 \leq \pr\{|X_n| > \epsilon \sqrt n\} \leq 1 - F_{X_n}(x_N) + F_{X_n}(y_N)
$$
except there's a small problem : the RHS has a limit, but the LHS does not! So one cannot use monotonicity of limits directly. Instead, one uses the monotonicity of the limit superior and limit inferior, which are stronger notions than that of a limit which coincides with it for convergent sequences. Using the first notion , which is also monotonic, gives :
$$
0 \leq \limsup_n \pr\{|X_n| > \epsilon \sqrt n\} \leq \limsup_n 1 - F_{X_n}(x_N) + F_{X_n}(y_N) = 1 - F_X(x_n) + F_{X}(y_n) < 2\delta
$$
for all $\delta>0$. In particular, we must have $\limsup_n \pr\{|X_n| > \epsilon \sqrt n\}  = 0$. It is easy to see from monotonicity for the $\liminf$ that $\liminf 0 \leq \liminf \pr\{|X_n| > \epsilon \sqrt n\}$. In particular, the $\limsup$ and $\liminf$ for the given sequence coincide and equal $0$ : it's easy to prove that the limit is , in fact, zero, from this.
This, of course, concludes $\frac{X_n}{\sqrt n} \to 0$ in probability.

So the key idea while formalizing intuition into argument is to go further into your investigation and see what key object needs approximations, what subapproximations have to be made, and what order they are to be made in. Thinking linearly and in an orderly fashion can be greatly beneficial while tackling simple problems.

A: $\def\abs#1{\left|#1\right|}\def\paren#1{\left(#1\right)}$Consider a fixed $ε_0 > 0$. For any $ε > 0$, since $X_n \stackrel{\mathrm{d}}{→} X$, there exist $A_1$ and $A_2$ such that$$
P(X_n \leqslant A_k) → P(X \leqslant A_k) \quad (n → ∞,\ k = 1, 2)
$$
and $P(X \leqslant A_1) < ε$, $P(X \leqslant A_2) > 1 - ε$. Note that for $n \geqslant \dfrac{1}{ε_0^2} \max(A_1^2, A_2^2)$,\begin{align*}
P\paren{ \abs{ \frac{X_n}{\sqrt{n}} } > ε_0 } &\leqslant P(X_n > ε_0\sqrt{n}) + P(X_n < -ε_0\sqrt{n})\\
&\leqslant P(X_n > A_2) + P(X_n < A_1) < 2ε.
\end{align*}
Thus $\varlimsup\limits_{n → ∞} P\paren{ \abs{ \dfrac{X_n}{\sqrt{n}} } > ε_0 } \leqslant 2ε$, and making $ε → 0+$ yields $\lim\limits_{n → ∞} P\paren{ \abs{ \dfrac{X_n}{\sqrt{n}} } > ε_0 } = 0$. Therefore, $\dfrac{X_n}{\sqrt{n}} \stackrel{P}{→} 0$.

A: I would like to repeat two standard lemmas which are apparently learnt by heart by most of probabilists. These two will help you to translate better your intuition into probabilistic language.
Lemma 1 If $X_n \xrightarrow[]{(d)}X$ and $ Y_n  \xrightarrow[]{(d)}c $ for some constant $c$ then $(X_n,Y_n) \xrightarrow[]{(d)} (X,c)$.
Lemma 2 If $X_n \xrightarrow[]{(d)} c $  for some constant $c$ then $ X_n  \xrightarrow[]{P}c $
Back to your question, applying lemma 1 above, you can see that:
$$g(X_N,\frac{1}{\sqrt{N}}) \xrightarrow[]{(d)} g(X,0)$$
For any continuous function $g \in \mathcal{C}( \mathbb{R}^2,\mathbb{R})$.
Choosing $g(x,y)= \frac{x}{\max(y,1)}$, we obtain
$$\frac{X_N}{\sqrt{N}} \xrightarrow[]{(d)} 0$$
Using lemma 2, we imply the desired result.


text:
Q: Coil Gun Schematic I have a question. I have been looking at making a Coil gun lately and i had an idea for a simple one. Just need to know if it would work. Basically:
Battery-->Switch-->Diode-->Transformer-->Coil
For my Coil I am using a coil from a Pinball Machine Flipper. Just An Idea for makers of a coil gun.

A: In principle that will work, but probably not well. Efficient coil gun drive requires the coil to maintain current while the projectile is accelerating, and only cut the current when the projectile is in the coil. If the current persists after the projectile exits the coil it will act to decellerate the projectile, which does defeat the purpose of the whole thing. Your circuit (and it needs resistances to model coil resistance and the transformer - as it stands if you try to run a simulation it will produce infinite current in both the transformer and the coil) will produce a fixed pulse width. Is this too short, too long, or just right? No way to tell.