Q:

Neural network time series normalization

I am using LSTM as the hidden layer function in a time series prediction network. Is input normalization necessary? If it is, is data = data / sum(data) the correct normalization?
Should the output also be normalized with the inputs?

A:

Is input normalization necessary?
No, but it might make your network converge faster. Use this calculation to scale your values to [0,1]:
.
Should the output also be normalized with the inputs?
No, I can't think of a reason why you would ever want to do that.


Q:

Проблема с select запросом по значениям из подзапроса

Уважаемые программисты, прошу помочь. Запрос:
select Task_name from tasks_table
  where task_status=3
  and task_creator=all(select id from personnel_table where chief=5)

в подзапросе all(select id from personnel_table where chief=5) несколько значений. Необходимо вывести из таблицы tasks_table все Task_name у которых task_creator= значениям  из select id from personnel_table where chief=5

A:

Вам нужен оператор IN
SELECT * FROM tbl WHERE clmn IN (1,2,3)
SELECT * FROM tbl WHERE clmn IN (SELECT id FROM personnel_table WHERE chief = 5)

Или джойны
SELECT * FROM tbl
INNER JOIN personnel_table AS pt ON pt.id = tbl.clmn
WHERE pt.chief = 5

Что лучше с точки зрения производительности - лично я не скажу, но ходят слухи, что джойны


Q:

Suggestions for speeding up a dynamic programming solution to the Traveling Salesman Problem?

I'm following an online course in which one of the assignments is to implement a dynamic programming algorithm to solve the Traveling Salesman Problem (TSP). My Python implementation works for small cases (~5 cities), but for the 'real' application of 25 cities it seems to be very slow. I'm looking for suggestions to speed up the algorithm.
The algorithm is described in the following excerpts:

The dynamic programming solution is also described at http://www.geeksforgeeks.org/travelling-salesman-problem-set-1/, where additional references are given.
The problem statement of the assignment is:

I've implemented the pseudocode using a pandas DataFrame object for the array A. Since sets are not hashable and can't be used as indices, I've instead used tuples, taking care to sort them in order to make them unique representations of sets. Here is the code along with several test cases of increasing size:
import functools
from itertools import combinations
import numpy as np
import pandas as pd
from cached_property import cached_property
import pytest

def powerset_list(s):
    '''Return a list of tuples representing all subsets of s'''
    return functools.reduce(lambda x, y: x + y, [list(combinations(s, r)) for r in range(len(s)+1)])

class Graph(object):
    def __init__(self, edges):
        self.edges = edges

    @cached_property
    def nodes(self):
        _nodes = set()
        for edge in self.edges:
            u, v, weight = edge
            _nodes.add(u)
            _nodes.add(v)
        return list(_nodes)

    @cached_property
    def W(self):
        '''Matrix of edge weights'''
        n = len(self.nodes)
        w = np.full((n, n), np.inf)
        np.fill_diagonal(w, 0)
        w = pd.DataFrame(w, index=range(1, n+1), columns=range(1, n+1))
        for edge in self.edges:
            u, v, weight = edge
            w.set_value(u, v, weight)
            w.set_value(v, u, weight)
        return w

    def tsp(self):
        '''Solve the traveling salesman problem using a dynamic programming method'''
        n = len(self.nodes)
        sets = [(1,) + x for x in powerset_list(range(2, n+1))]
        A = pd.DataFrame(np.full((len(sets), n), np.inf), index=sets, columns=range(1, n+1))
        A.set_value((1,), 1, 0)
        for m in range(2, n+1):
            for S in [(1,) + perm for perm in combinations(range(2, n+1), m-1)]:
                for j in set(S) - set([1]):
                    S_min_j = tuple(sorted(set(S) - set([j])))
                    A.set_value(S, j, min(A.get_value(S_min_j, k) + self.W.get_value(k, j) for k in S_min_j))
        return min(A.get_value(tuple(range(1, n+1)), j) + self.W.get_value(j, 1) for j in range(2, n+1))

@pytest.fixture
def edges_geeksforgeeks():
    '''Edges from the example graph on http://www.geeksforgeeks.org/travelling-salesman-problem-set-1/'''
    return [(1, 2, 10), (1, 3, 15), (1, 4, 20), (2, 3, 35), (2, 4, 25), (3, 4, 30)]

def test_tsp(edges_geeksforgeeks):
    graph = Graph(edges_geeksforgeeks)
    min_cost = graph.tsp()
    assert min_cost == 80

def dist(coord1, coord2):
    return np.linalg.norm(np.array(coord1) - np.array(coord2))

def edges_from_coords(filename):
    with open(filename) as f:
        coords = [tuple(map(float, line.split())) for line in f.read().splitlines()[1:]]
    nodes = list(range(1, len(coords) + 1))
    coords = dict(zip(nodes, coords))
    return [(comb[0], comb[1], dist(coords[comb[0]], coords[comb[1]])) for comb in combinations(nodes, 2)]

@pytest.mark.parametrize("test_input, expected", [("Hulburd_1.txt", 10.24), ("Hulburd_2.txt", 12.36), ("Hulburd_3.txt", 14.00)])
def test_Hulburd(test_input, expected):
    '''Test data supplied by Eric Hulburd on the course forum'''
    edges = edges_from_coords(test_input)
    graph = Graph(edges)
    min_cost = graph.tsp()
    assert np.around(min_cost, decimals=2) == expected

@pytest.fixture
def edges_cities():
    return edges_from_coords('tsp.txt')

@pytest.mark.skip(reason="This takes too long to run")
def test_tsp_cities(edges_cities):
    graph = Graph(edges_cities)
    min_cost = graph.tsp()
    print("The minimum cost rounded down to the nearest integer is {}".format(int(np.floor(min_cost))))

if __name__ == "__main__":
    pytest.main([__file__, "-s"])

The files used in the tests are Hulburd_1.txt, Hulburd_2.txt, Hulburd_3.txt, and the main file for the actual assignment, tsp.txt. The problem is that the last (skipped) test involving tsp.txt takes too long to run.
How might I speed up the algorithm? On the course forum there are some saying they got it to run in ~3 minutes using bitmasks and parallelization; another suggestion was to simplify the indices of the array rather than using tuples.

A:

Some ideas how to improve performance:

instead of tuples use 32 bit ints to represent your subsets - this should be enough if you have no more than 32 cities
on each step you need previously calculated values for subsets of size m - 1 only (you don't have to store any values for subsets of size m-2, m-3 etc.) - this may vastly reduce your memory usage


Q:

maintaining div position between images

I have 3
s like this:
-----------------------------------------
|         |        div2        |        |
|  div1   |--------------------|  div3  |
|         |////////new div/////|        |
-----------////////////////////----------

CSS
.parentdiv{
position:relative;
}
div1,div2,div3{
position:relative
float:left}

I've tried to make the new
 with position:relative and float
but couldn't make it .
I don't want to use position:absolute.

A:

place three divs, float:left or display:inline to each other,
and then divide the middle one into two.

and CSS like
    .A,.B, .C
    {
       float:left;
       width:30%;
       height:200px;
       border:1px Solid #CCC;
    }
    .B .upper
   {
      width:100%;
      height:50%;
      background-color:Yellow;
   }
   .B .lower
   {
    width:100%;
    height:50%;
    background-color:Green;
   }

see this fiddle


Q:

Prove a set $I=[0,\infty)$ is not an open interval.

$(\exists y \in I)$ $(\forall x \in \mathbb{R})$ $x<y\Rightarrow x\notin I$.
I am trying to prove that the set $I=[0,\infty)$ is not an open interval.
So I know there exists a $y$ such that the statement is valid for all $x$. I think I need to set $y=0$ (a value in the set) then say that $x<0$. I'm not sure where to go from here.

A:

I'm assuming that $$(\exists y \in I)(\forall x \in \mathbb{R})x<y\Rightarrow x\notin I$$ is your definition of not open? If so, it looks to me like you are already done. If you set $y=0$ and let $x<y$ then clearly $x \notin [0,\infty)$ so $I$ is not open. You don't need to consider the case of $x \geq 0$ as that isn't relevant to your definition of not open.


Q:

Invariant Violation: Text strings must be rendered within a Text component

I am trying to add my CardsSection component into my Card component however I keep getting this error about a Text Violation but I'm not even using any Text within my Tournament, Card, or CardSection .js files. I don't see why I'm getting this error. Can someone tell me what to do and why?
Tournament.js
import React from "react";
import { View, Text, Image, ScrollView } from "react-native";
import { Card, Button, Spinner, CardSection } from "../common";

class Tournaments extends React.Component {
  static navigationOptions = {
    tabBarLabel: "Tournaments"
  };
  render() {
    return (
      <View style={styles.containerStyle}>
        <Card>
          <View style={styles.logoContainer}>
            <Image
              style={styles.logo}
              source={require("../../Images/ShoeJackCityLogo.png")}
            />
          </View>
          <View style={styles.formContainer} />
        </Card>
        <ScrollView horizontal>
          <Card>
            <View style={{ flex: 1, flexDirection: "row" }}>
              <CardSection>
                <Image
                  style={styles.product}
                  source={require("../../Images/aj_4_toro.png")}
                />
              </CardSection>
              <CardSection>
                <Image
                  style={styles.product}
                  source={require("../../Images/aj_4_toro.png")}
                />
              </CardSection>
              <CardSection>
                <Image
                  style={styles.product}
                  source={require("../../Images/aj_4_toro.png")}
                />
              </CardSection>
            </View>
          </Card>
        </ScrollView>
      </View>
    );
  }
}
const styles = {
  containerStyle: {
    flex: 1,
    backgroundColor: "#F13C20",
    paddingBottom: 20
  },
  logoContainer: {
    alignItems: "center",
    flexGrow: 1,
    justifyContent: "flex-start",
    paddingBottom: 15
  },
  logo: {
    paddingTop: 15,
    width: 50,
    height: 50
  },
  product: {
    width: 100,
    height: 100,
    paddingBottom: 15,
    marginRight: 50
  }
};
export default Tournaments;

CardSection.js
import React from 'react';
import { View } from 'react-native';

const CardSection = (props) => (
    <View style={styles.containerStyle}>
    {props.children};
    </View>
  );

const styles = {
  containerStyle: {
    borderBottomWidth: 1,
    padding: 5,
    backgroundColor: 'white',
    justifyContent: 'flex-start',
    flexDirection: 'row',
    borderColor: '#ddd',
    position: 'relative'
  }
};

export { CardSection };

Card.js
import React from 'react';
import { View } from 'react-native';

const Card = (props) => (
    <View style={styles.containerStyle}>
      {props.children}
    </View>
  );

const styles = {
  containerStyle: {
    borderBottomWidth: 0,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 1,
    marginLeft: 5,
    marginRight: 5,
    marginTop: 30,
}
};

export { Card };

A:

You have a semicolon concatenated right after your children in CardSection component. This semicolon is interpreted as text and since every text must be within a <Text> component, the error is thrown.
To fix the issue, simply change
const CardSection = (props) => (
  <View style={styles.containerStyle}>
    {props.children};
  </View>
);

to
const CardSection = (props) => (
  <View style={styles.containerStyle}>
    {props.children}
  </View>
);


Q:

How to read a file from assets folder in android?

Successfully i wrote program to read single file in asset folder and assign it to text view.
Now i want to read all files and assign it to the text view, will any one of you help me how to do? all the files are text files, thankful to you in advance.

A:

****In Android we can't read file from assets folder u have to copy file from asseset to sdcard than perform reading**
EDIT: this statement is wrong. See comments.
use following code for perform copy from assets folder
private void copyAssets() {
    AssetManager assetManager = getAssets();
    String[] files = null;
    try {
        files = assetManager.list("");
    } catch (IOException e) {
        Log.e("tag", "Failed to get asset file list.", e);
    }
    for(String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
          in = assetManager.open(filename);
          out = new FileOutputStream("/sdcard/" + filename);
          copyFile(in, out);
          in.close();
          in = null;
          out.flush();
          out.close();
          out = null;
        } catch(IOException e) {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
        }
    }
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}


Q:

Wordpress plugin to display new content from other websites

It there such a plugin in wordpress that can take a list of links to arbitrary websites and return/display the newest content, like for example newest published article?

A:

You're going to want an RSS plugin for this, the best one available seems to be http://www.wprssaggregator.com/
This will let you import RSS feeds from external websites into posts and such.


Q:

One More Ordinary Differential Equation

While working on some variations of a physics problem (how does the normal force vary in a circular loop with a constant attrition coefficient with regards to the angle )   , I arrived at the following equation for it :
$f(x) = a(\int_0^x f(x) dx) + b (3 cos(x) - 2) + c$
(Where $a = 2\frac{μ_k}{R}$, $b=mg$, and $c=\frac{v_i^2}{R}m$)
I am not familiar with ODEs, so I don't know how to solve this for f(x).  What do you recomend as a method to approach these types of equations?

A:

To be more puristic, write $$f(x) = a\int_0^x f(t) dt + b (3 \cos(x) - 2) + c$$ Differentiate both sides using the fundamental theorem of calculus; this gives
$$f'(x)=a f(x)-3b \sin(x)$$
Now, for the homogeneous part
$$f'(x)=a f(x) \implies f(x)=C(x) e^{ax}$$ Now, variation of parameters leads to
$$C'(x)=-3b \sin(x)e^{-ax}$$ which does not seem to be very difficult.


Q:

Binary tree pruning with BFS

Below the text of the exercise:

We are given the head node root of a binary tree, where additionally
  every node's value is either a 0 or a 1.
Return the same tree where every subtree (of the given tree) not
  containing a 1 has been removed.
(Recall that the subtree of a node X is X, plus every node that is a
  descendant of X.)
Note:

The binary tree will have at most 100 nodes.
The value of each node will only be 0 or 1.

I have the following code and it does not look nice to me as too many if statements strolling around. How can I make this shorter and nice looking (more readable). Tree has nodes that contain 0 or 1 as value. I make the node null if it does not contain any node having 1 as value.
public TreeNode pruneTree(TreeNode root) {
    if (root == null || (root.left == null && root.right == null && root.val == 0)) return null;

    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);

    while(!queue.isEmpty()) {
        TreeNode node = queue.poll();

        if (node.left != null && !containsOne(node.left)) {
            node.left = null;
        }

        if (node.right != null && !containsOne(node.right)) {
            node.right = null;
        }

        if (node.left != null) {
            queue.offer(node.left);
        }

        if (node.right != null) {
            queue.offer(node.right);
        }
    }

    return root;
}

private boolean containsOne(TreeNode node) {
    if (node == null) return false;
    if (node.val == 1) return true;
    return containsOne(node.left) || containsOne(node.right);
}

A:

Note: I checked binary tree pruning and the structure of class TreeNode is not modifiable as I expected:
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

It's possible to shorten your code with constraints of the class, your method containsOne is the following:

private boolean containsOne(TreeNode node) {
    if (node == null) return false;
    if (node.val == 1) return true;
    return containsOne(node.left) || containsOne(node.right);
}

Because the third line will be executed when the condition node.val == 1 is false put directly this condition in the or expression in the third line:
private static boolean containsOne(TreeNode node) {
    if (node == null) return false;
    return node.val == 1 || containsOne(node.left) || containsOne(node.right);
}

About your method PruneTree you can shorten the following lines inside the method:

if (node.left != null && !containsOne(node.left)) {
    node.left = null;
}
if (node.right != null && !containsOne(node.right)) {
    node.right = null;
}
if (node.left != null) {
    queue.offer(node.left);
}
if (node.right != null) {
    queue.offer(node.right);
}

The code can be rewritten like below, two equal blocks and not so elegant to see but the original structure in the site cannot be modified, so I haven't thought about other alternatives:
if (node.left != null) {
    if (!containsOne(node.left)) { node.left = null; }
    else { queue.offer(node.left); }
}

if (node.right != null) {
    if (!containsOne(node.right)) { node.right = null; }
    else { queue.offer(node.right); }
}

I checked the code on the site passing all tests.


Q:

Failure to run db:migrate in Rails

I'm trying to run db:migrate after installing image attachment via paperclip gem and it won't allow me to do migration. Could someone help please? Thanks a lot This is what it said on my terminal
This is my config file config/database.yml
This is my create item table:
class CreateTodoItems < ActiveRecord::Migration[5.0]
  def change
    create_table :todo_items do |t|
      t.column :content
      t.column :deadline

      t.references :todo_list, foreign_key: true

      t.timestamps
    end
  end
end

Item model
class TodoItem < ActiveRecord::Base

  belongs_to :todo_list

  has_attached_file :image, styles: { medium: "500x500>", thumb: "100x100#"}

  validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/

  def completed?

    !completed_at.blank?

  end

end

A:

You're adding a column to database that doesn't exist. You don't happen to have items table you have todo_items table your migration should look something like:
$ bin/rails generate migration AddAttachmentImageToTodoItems attachment_image:string


Q:

Alamofire complaining about argument types

In the code below, Alamofire is complaining that it "Cannot invoke 'responseJSON' with an argument list of type ((_, _, _, _) -> _)." The same issue occurs when using 'response.'
    func request(parameters: [String : AnyObject?], completionHandler: ((NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void)) -> Void {
      Alamofire.request(.POST, "localhost:8080/reserve", parameters:
            ["refreshToken": refreshToken,
             "accessToken": accessToken,
             "deviceToken": deviceToken],
            encoding: .JSON)
      .responseJSON { (request, response, data, error) in
            completionHandler(request, response, data, error)
      }
   }

Why is this occuring?

A:

Your parameters argument is bad typed. It should be [String: AnyObject]? instead of [String : AnyObject?].
Fixing this error, you should be able to compile again.
Otherwise, ensure your token variables exist. If not, the compiler is confused, and the error is not actually due to Alamofire.


Q:

MySQL Connection Error in PHP

I have set the password for root and grant all privileges for root.  Why does it say it is denied?
****mysql_query() [function.mysql-query]: Access denied for user 'SYSTEM'@'localhost' (using password: NO) in C:\wamp\www\photo_gallery\includes\database.php  on line 56

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in C:\wamp\www\photo_gallery\includes\database.php on line 56

The Query has problemAccess denied for user 'SYSTEM'@'localhost' (using password: NO)

Code as follows:
<?php
include("DB_Info.php");

class MySQLDatabase
{
    public $connection;
    function _construct()
    {
        $this->open_connection();
    }
    public function open_connection()
    {
        $this->connection = mysql_connect($DB_SERVER,$DB_USER,$DB_PASS);
        if(!$this->connection)
        {
            die("Database Connection Failed" . mysql_error());
        }
        else
        {
            $db_select = mysql_select_db($DB_NAME,$this->connection);
            if(!$db_select)
            {
                die("Database Selection Failed" . mysql_error());
            }
        }
    }
    function mysql_prep($value)
    {
        if (get_magic_quotes_gpc())
        {
             $value = stripslashes($value);
        }
        // Quote if not a number
        if (!is_numeric($value))
        {
            $value = "'" . mysql_real_escape_string($value) . "'";
        }
        return $value;

    }
    public function close_connection()
    {
        if(isset($this->connection))
        {
            mysql_close($this->connection);
            unset($this->connection);
        }
    }
    public function query($sql)
    {

        $result = mysql_query($sql);
        $this->confirm_query($result);
        return $found_user;
    }
    private function confirm_query($result)
    {
        if(!$result)
        {
            die("The Query has problem" . mysql_error());
        }
    }

}

$database = new MySQLDatabase();

?>

A:

You have not defined any of $DBSERVER,$DBUSER,$DBPASS within the current variable scope.
If those variables are in the global scope you must add the following to the functions that uses them:
global $DBSERVER,$DBUSER,$DBPASS;

If you intended to use the variables defined and then commented in the open_connection function you must first uncomment them and then alter the arguments passed to the mysql_connect function.

A:

The missing second underscore for __construct() in
class MySQLDatabase
{
    public $connection;
    function _construct()
    {

explains all the symptoms (mysql_query raising the warning, no undefined variable notices, no matter what you do to make the parameters available to function open_connection() it doesn't work simply because it's never called, access denied for system@localhost because your webserver runs as localsystem and therefore system is the default username for the default mysql connection, ...)
When you create a new object via $database = new MySQLDatabase(); the method _construct() isn't invoked and therefore neither is $this->open_connection() and therefore  no value is assigned to the property $connection which remains NULL and no connection to the mysql server is established.
Now when you call $database->query('something'); and there is no database connection mysql_query() tries to establish the default connection as explained at http://docs.php.net/mysql_query:
resource mysql_query  ( string $query  [, resource $link_identifier  ] )
[...]
If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Fix the typo in _construct()
pass $this->connection to mysql_real_escape_string(), mysql_query() and mysql_error()
make sure open_connection() has all the parameters it needs, e.g. isset($DB_SERVER,$DB_USER,$DB_PASS,$DB_NAME) or die('missing parameters');
add some debug output to see whether it has been called at all, e.g. echo "Debug: this->connection = mysql_connect($DB_SERVER,$DB_USER,$DB_PASS);\n";
don't roll your own MySQL class, use one of the gazillion existing classes, preferably one with broader acceptance.


Q:

Concatenate a custom field and a text string in a trigger

I am attempting to use a trigger for Case to input defined text as well as a custom case field value into an autogenerated Case Comment. The custom field value is Issue_Number__c. The code snippet is below:
casecomment comment = new casecomment(parentid=record.id,commentbody='Ticket '+ Case.Issue_Number__c+ ' has been created for your issue.' ,ispublished=true);

The Case Comment successfully generates, but with the following:
"Ticket Issue_Number__c has been created for your issue."

A:

You are concatenating in the field token (SObjectField), rather than the field value (String). Here is some code to illustrate:
String fieldValue = record.Issue_Number__c; // this value is what you want
String fieldToken = Case.Issue_Number__c; // this value is what you are using

So simply change Case.Issue_Number__c to record.Issue_Number__c.


Q:

I have a question and an error. C# CS8180

I'm just trying to make a basic program and here is part of my instructions:

Create a class "Course".

create a constructor with two string parameters "courseId" and "courseName".
create two string data members "CID" with property "ID"(set, get),  and "CName" with property "Name"(set, get).

For one, I don't understand how to have a string property "ID", when the data member already has a name, and the property is get and set.
Also, my code gives me an error code CS8180 ( { or ; or => expected ). When I click on the error, it leads me to the space after my set. Take a look:
using System;

class Course
{
    public string CID { get; set }

    public void CourseInfo(string courseId, string courseName)
    {
    }

}

A:

You are missing a ; after set :
using System;

class Course
{
   public string CID { get; set; }

   public void CourseInfo(string courseId, string courseName)
   {
   }
}


Q:

Android Build job on Jenkins fails with Error cloning remote repo 'origin'

I'm setting up an Android Build job in Jenkins(1.589).
For the moment I have decided to use http authentication .
My code repo is on Git and I have successfully installed Git Plugin for Jenkins.
This seems a common error however in most instances ssh authentication is used and either an exception or an error code is available.
My Build job fails with following error.
>Started by user anonymous
>Building in workspace C:\Users\hkarunasekara\.jenkins\jobs\Test_Android\workspace\androiddev
> Wiping out workspace first. Cloning the remote Git repository
> Cloning repository http://username:password@domain.com/scm/mob/androiddev.git
> C:\Program Files (x86)\Git\bin\git.exe init C:\Users\hkarunasekara\.jenkins\jobs\Test_Android\workspace\androiddev # timeout=10
Fetching upstream changes from http://username@domain.com/scm/mob/androiddev.git
> C:\Program Files (x86)\Git\bin\git.exe --version # timeout=10
> C:\Program Files (x86)\Git\bin\git.exe fetch --tags --progress http://username@domain.com/scm/mob/androiddev.git +refs/heads/*:refs/remotes/origin/*
ERROR: Error cloning remote repo 'origin'
ERROR: Error cloning remote repo 'origin'
Sending e-mails to: <email address>
Finished: FAILURE

Thanks for your input
Addition
I tried executing the above 3 git commands as is via git bash

git init C:\Users\hkarunasekara.jenkins\jobs\Test_Android\workspace\androiddev # timeout=10
git --version # timeout=10
git fetch --tags --progress http://username@domain.com/scm/mob/androiddev.git +refs/heads/:refs/remotes/origin/

At the 3rd command (fetch) i was prompted for the password.Wondering if the same happens when jenkins is trying to connect as I dont see a git command executing with the password.

A:

I've just had a similar problem with a private repository on GitHub, building on a Windows slave.
My solution was to use the Credentials plugin to provide the username/password (How to do that with GitHub), and then specify the credentials in the drop-down below the repository URL box.


Q:

is this ENUM method thread safe?

is this ENUM code thread safe?
enum One{
    IONE;
    public mone(){
        // some code
    }
}

when above code is not thrad safe?

A:

An enum value is guaranteed to only be initialized once, ever, by a single thread, before it is used.However, methods that you add to an enum class do not carry any thread safety guarantee. If you have an enum so that the methods don't change its state, then they are by definition thread safe


Q:

What Trainer level is necessary to complete the last tournament?

In Magikarp Jump, you can get higher max level when you level up.
What Magikarp level is needed to beat the last tournament, and so what trainer level do you need to beat that tournament?

A:

Original - for version 1.02:
Per Serebii, the highest JP you will encounter in an opponent is 58.1M JP (final karp in Expert League 3).  This is achievable with a level 60 Magikarp (see list of MagiKarp JP/Level) to win without a support boost.
A level 59 Magikarp (max JP 52k) could win with a 25% support boost, but not with a 5%.
Edit for 1.1.0 Update (adding Heal League):
The new maximum for the Heal League is  135,188,472, which is apparently nearly identical to the Level 66 maximum of 135,188,474, according to Serebii.  I'm not sure how accurate the numbers are at the bottom (you can only see "135M") so it's unclear how they know the precise values, and it's possible you'll need to actually be level 67.  It could be beaten at +25% at the level 65 maximum.
The new maximum for Expert League 3 is 430,524,767, slightly lower than the Level 73 maximum (which is the new overall maximum).  It could be beaten at +25% at the level 72 maximum.


Q:

out of memory error when use the VisualVm to analysis heap dump

when use the heap dump of visualVm, there is an option to see all the instances of a specific class, but when the instances is to much, i got this error:
out of memory in heap walker：
To avoid this error，increase the -Xmx value in the etc/netbeans.conf file in NetBeans IDE installation directory.
But the error should have nothing to do with the netbeans.conf, it should be something like a visualVM.conf file.  And I also did not find the configuration file in my jdk. So how can i solve this error?

A:

There are two solutions for this :

1.using command line to start the JvisualVM, e.g: jvisualvm -J-Xms1024m -J-Xmx2048m
2.update the properties in %JDK_HOME%\lib\visualvm\etc\visualvm.conf

Option 1 is more convenient and recommended


Q:

Goursat's theorem and residue theorem understanding

It seems to me that Goursat's theorem doesn't align with the residue formula, because with the residue formula we end up with a number different than zero.
Could you help me find what I understood the wrong way?
Goursat's Theorem: Let $D \subset \mathbb{C} $ an open set and $p$ a point inside D. Let $f$ be continuous on $D$, and holomorphic on $D-\{p\}$. Then for every triangle $T \subset D$ with the interior of $T$ also contained in $D,$ $\int_{T} f(z)=0$.
Residue Theorem: Let $D$ a convex open set and $a_i \in D$. Then for every holomorpic function in $D-\{a_1,a_2,...,a_N\}$ and for every closed curve in $D-\{a_1,a_2,...,a_N\}$ $\int_{T} f(z)=2 \pi i\sum_{j=1}^{N} Res(f,a_j) d_{\gamma}(a_j)$,  where $d_{\gamma}(a_j)$ is $1$ if $a_j$ lies in the interior of $\gamma$ and zero otherwise.

A:

Because $f$ is continuous on $D$, $f$ is bounded near $p$ and hence $p$ is a removeable singularity (see here for instance: http://en.wikipedia.org/wiki/Removable_singularity). Because of this, Goursat's theorem and the Residue Theorem give the same result.


Q:

php fluentpdo -> Undefined variable: fpdo

I am confused with the include stuff i think, I don't know where exactly its wrong.
The Connection file with fluentpdo
    <?php
error_reporting(E_ALL | E_STRICT);
include($_SERVER['DOCUMENT_ROOT'].'/Mark20/libs/FluentPDO/FluentPDO.php');

$pdo = new PDO("mysql:dbname=ummah", "pluto","admin");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$pdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$fpdo = new FluentPDO($pdo);
//~ $software->debug = true;
?>

if i am using to insert data like this as below:
Insert.php
<?php
include '../connect.inc.php';

function inReg(){
    try{
        $values = array('name' 'xyz', 'pwd' => '1234');
        $query = $fpdo->insertInto('users')->values($values)->execute();
        echo 'success';
        return;
    }catch (Exception $e) {
        die ('File did not upload: ' . $e->getMessage());
    }
}
?>

Not a problem with above stuff, its just in a php file. What I am trying to do is use a class as i did below:
Connection file is same.
DBInsert.php
<?php

include($_SERVER['DOCUMENT_ROOT'].'/Mark20/bin/connect.inc.php');

class DBInsert {
    function Insert($table, $values){
        try{
            $query = $fpdo->insertInto($table)->values($values)->execute();
            return 'success';
        }catch (Exception $e) {
            die ('File did not upload: ' . $e->getMessage());
        }
    }
}

?>

now i am creating object of above class and trying to call the Insert function like this:
Test.php
include($_SERVER['DOCUMENT_ROOT'].'/Mark20/bin/dao/DBInsert.php');

function Signup(){
    $values = array('name' => 'xyz', 'pwd' => '1234');
    $db = new DBInsert();
    echo $db->Insert('users',$values);
}
Signup();
?>

So when i am accessing Test.php i am getting the following error:

Notice: Undefined variable: fpdo in E:\Program Files\Apache Software
  Foundation\Apache2.2\htdocs\Mark20\bin\dao\DBInsert.php on line 15
Fatal error: Call to a member function insertInto() on a non-object in
  E:\Program Files\Apache Software
  Foundation\Apache2.2\htdocs\Mark20\bin\dao\DBInsert.php on line 15

I am new to php, not totally new also :). So a little help is greatly appreciated.
Thanks and Regards
Adeeb

A:

Global variables are not in scope in functions by default. You need to do:
function inReg(){
    global $fpdo;
    try{
        $values = array('name' 'xyz', 'pwd' => '1234');
        $query = $fpdo->insertInto('users')->values($values)->execute();
        echo 'success';
        return;
    }catch (Exception $e) {
        die ('File did not upload: ' . $e->getMessage());
    }
}

or pass $fpdo as a parameter to the function.


Q:

Arduino Snakes and Ladders

Here is a snakes and ladders game I made using an Arduino using a serial terminal, a set of addressable LED's to create a physical game board, a 7 segment display, and a piezoelectric to create sound.
I'd love to get some feed back on this regarding what I did right, what I did wrong, and any improvements that can be made to this game.
#include "FastLED.h"

#define NUM_LEDS 100

#define DATA_PIN 9

CRGB leds[NUM_LEDS];

//Assign correct pin values to corresponding variables
int piezoPin = 10;
int segmentOne = 7;
int segmentTwo = 2;
int segmentThree = 8;
int segmentFour = 4;
int segmentFive = 6;
int segmentSix = 3;
int segmentSeven = 5;

int boardArray[101]; // array of numbers   index = value, depending on the value of the index determains what is in that square of the board

int snakeArray[7][1]; // array of 8 snakes, with a start and end value  --- index starts from 0, 7 == 8
int ladderArray[7][1];  // array of 8 ladders, with a start and end value --- index starts from 0, 7 == 8

//Player Start Positions, the board array start from 0, we want to start from one, so set to 1.
int playerOnePosition = 1;
int playerTwoPosition = 1;

//variables needed to figure out which snake or ladder the player landed on, 10 is out of range and can be used as a null value
int ladderLandedOn = 10;
int snakeLandedOn = 10;

int turn = 1; // curren't player
boolean gamefinish; //boolean to setmode gam
int winner = 0; // game winner
int userInput;  // int variable to store the users input
int gameMode;   //variable to store the selected game mode

boolean gameStarted = false; // variable to store the game status, if false the game needs to wait for a game selection

void setup() {
  randomSeed(analogRead(0)); // each loop randomise the seed, stops repetative number generation between games when the arduino isn't being reset

  Serial.begin(38400); //Start the Serial Monitor
  //Set the pin modes.
  pinMode(piezoPin, OUTPUT);
  pinMode(segmentOne, OUTPUT);
  pinMode(segmentTwo, OUTPUT);
  pinMode(segmentThree, OUTPUT);
  pinMode(segmentFour, OUTPUT);
  pinMode(segmentFive, OUTPUT);
  pinMode(segmentSix, OUTPUT);
  pinMode(segmentSeven, OUTPUT);

  //For each index of array assign value of index, index 0 = (int)0 index 54 = (int)56 . . .
  for (int i = 0; i < 101; i++) {
    boardArray[i] = i;
  }

  //create 8 random snakes and ladders positions, starting from 0, so while n is less than 8, where n is 7 we have looped 8 times

  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);

  for(int i = 0; i < NUM_LEDS ;i++){
    leds[i] = CRGB::Black;
  }
  FastLED.show();
}

void loop() {
  randomSeed(analogRead(0)); // each loop randomise the seed, stops repetative number generation between games when the arduino isn't being reset
  (gameStarted == false ? gameInit() : voidFunction());  // if the game has not started run function game init(), else game has started, just do something random as i cant have a null value here
  (gameMode == 1 ? modeComputerVsComputer() : (gameMode == 2 ? modeSinglePlayer() : (gameMode == 3 ? modeMultiplayer() : loop())));  // ternary if statment, becuase ternary if statments are sexy. run the function that corresponds to the game mode, if there isnt one run the loop again
}

void voidFunction(){
}

void boardGen(){
  for (int i = 0; i < 101; i++) {
    boardArray[i] = i;
  }

  for (int n = 0; n < 8; n++) {
    int snakeStart = random(11, 100); // pick a random value to place the start of the snake above the first row on the board.
    int snakeFinish = random(3, snakeStart);  // pick a location to place the tail of the snake, this can be on the bottom row, but can not be above the snake head
    int ladderStart = random(3, 90); // pick a random value to place the start of the ladder between 3 and 98
    int ladderFinish = random(ladderStart + 5, 99); // pick the ladded finish position, between the ladder start + 5, this stops the creation of pointless 1 square ladders, and 98

    snakeArray[n][0] = snakeStart;    //Each loop store the start and end positions
    snakeArray[n][1] = snakeFinish;   //Each loop store the start and end positions
    boardArray[snakeStart] = 103;     //within the array of positions 1-100, place a snake there, snakes are represnted by an int of value 103

    ladderArray[n][0] = ladderStart;  //Each loop store the start and end positions
    ladderArray[n][1] = ladderFinish; //Each loop store the start and end positions
    boardArray[ladderStart] = 104;    //within the array of positions 1-100, place a ladder there, ladders are represnted by an int of value 104
  }
}

//The gameInit function displays the menu options and waits for a users input

void blinkRandomFade(){
  int hue = 0;
  int brightness = 0;
  for(int b = 0; b < 255; b++ ){
    for(int i = 0; i < NUM_LEDS;i++){
      leds[i] = CHSV(random(0,255),255,brightness);
    }
    FastLED.show();
    hue++;
    brightness++;
  }
  brightness = 255;
  for(int b = 0; b < 255; b++ ){
    for(int i = 0; i < NUM_LEDS;i++){
      leds[i] = CHSV(random(0,255),255,brightness);
    }
    FastLED.show();
    brightness--;
  }
}

void resetLights(){
  for(int i = 0; i < NUM_LEDS ;i++){
    leds[i] = CRGB::Black;
  }
  FastLED.show();
}

void gameInit() {
  showMainMenu(); //Show the menu
  boardGen();
  gameMode = getUserInput();  //set GameMode to the output of getUserInput which is an int, so entering a 1 will set game mode to 1
  if (gameMode > 0 && gameMode < 4) gameStarted = true; // if the gameMode is between 1-3 then set gameStarted to true, if not then it wont change and next loop gameInit will be ran again

}

//The getUserInput function waits for user input and then outputs the int value
int getUserInput() {
  int userInput;  //init the int userInput
  Serial.flush(); //flush all previous received and transmitted data
  while (!Serial.available()){
    if(gameStarted == false){
      blinkRandomFade();
    }
  };  // while there is nothing in the buffer, hold the program.
  userInput = Serial.parseInt(); // once there is something in the buffer the while will close and userInput will be assinged to the int entered
  return userInput; //Return the int value
}

//The showMainMenu function displays the main menu.
void showMainMenu() {
  Serial.println("----------------------");
  Serial.println(" | Main Menu! | ");
  Serial.println("----------------------");
  Serial.println();
  Serial.println("Please Select a Game mode!");
  Serial.println();
  Serial.println("Enter 1 for - Demo Mode - Computer Vs Computer");
  Serial.println("Enter 2 for - Single Player Vs Computer");
  Serial.println("Enter 3 for - Multiplayer");
}

//ShowEndGameMenu function displays the menu after a winner has been declared
void showEndGameMenu() {
  Serial.println("Enter 1 to Replay");
  Serial.println("Enter 2 to go to the main menu");
}

void modeSinglePlayer() {
  // run the check to see if any player has won the game.
  winnerCheck();
  // if player one has won.
  if (winner == 1) {
    //re run the random blink/fade function
    blinkRandomFade();
    //display who won in the console
    Serial.println("The winner is Player 1");
    //Show the end game menu
    showEndGameMenu();
    //Wait for user input 1 for restarting 2 for going back to the
    userInput = getUserInput();
    // if the user inputs 1 restart the game
    if (userInput == 1) {
      //Regenerate the board layout
      boardGen();
      //blank all the lights
      resetLights();
      //Set game started to true
      gameStarted = true;
    }
    //if the player entered 2
    else {
      //set game starte to false
      gameStarted = false;
    }

    //reset the winners/ positions/ and turns
    winner = 0;
    playerOnePosition = 1;
    playerTwoPosition = 1;
    turn = 1;
  }
  else if ( winner == 2) {
    blinkRandomFade();
    Serial.println("The winner is Player 2");
    showEndGameMenu();
    userInput = getUserInput();
    if (userInput == 1) {
      boardGen();
      resetLights();
      gameStarted = true;
    }
    else {
      gameStarted = false;
    }
    winner = 0;
    playerOnePosition = 1;
    playerTwoPosition = 1;
    turn = 1;
  }
  else {
    //draw the player turn display
    Serial.println("----------------------");
    Serial.print(" | Player ");
    Serial.print(turn);
    Serial.println("'s turn! |");
    Serial.println("----------------------");

    Serial.println("Please Select a number of rolls between 1-3");
    int numOfRolls;

    if (turn == 1) {
      //wait for the user to enter how many rolls they want
      numOfRolls = getUserInput();
      if (numOfRolls > 3) {
        //if they enter a value greater than 3 set it to 3
        numOfRolls = 3;
      }
      else if (numOfRolls < 1) {
        //if they enter a value less than 1 set it to 1
        numOfRolls = 1;
      }
    }
    else {
      numOfRolls = random(1, 4);
    }

    Serial.print("You selected ");
    Serial.println(numOfRolls);
    Serial.println();
    boolean reroll = false;
    int diceRoll = rollDice(numOfRolls);

    Serial.println("rolling Dice");
    //    delay(1000);
    Serial.print("player ");
    Serial.print(turn);
    Serial.print(" rolled a ");
    Serial.println(diceRoll);
    delay(500);

    //if the dice was a 6 then reroll
    if (diceRoll == 6) {
      Serial.println("You landed on a 6 and get to reroll!");
      playSound(3,1);
      reroll = true;
    }

  //move the player based on whos turn it is and the dice roll
    movePlayer(turn, diceRoll);
  //display player status
    displayPlayerStatus();

  //display the boards
    printBoard();

  //if player player got a 6 do nothing.
    if (reroll != true) {
      //if the player was 1 change to 2
      if (turn == 1) {
        turn = 2;
      }
      // the player was 2 change to 1
      else {
        turn = 1;
      }
    }
  }
}

void modeMultiplayer() {
  winnerCheck();
  if (winner == 1) {
    blinkRandomFade();
    Serial.println("The winner is Player 1");
    showEndGameMenu();
    userInput = getUserInput();
    if (userInput == 1) {
      boardGen();
      resetLights();
      gameStarted = true;
    }
    else {
      gameStarted = false;
    }
    winner = 0;
    playerOnePosition = 1;
    playerTwoPosition = 1;
    turn = 1;
  }
  else if ( winner == 2) {
    blinkRandomFade();
    Serial.println("The winner is Player 2");
    showEndGameMenu();
    userInput = getUserInput();
    if (userInput == 1) {
      boardGen();
      resetLights();
      gameStarted = true;
    }
    else {
      gameStarted = false;
    }
    winner = 0;
    playerOnePosition = 1;
    playerTwoPosition = 1;
    turn = 1;
  }
  else {

    Serial.println("----------------------");
    Serial.print(" | Player ");
    Serial.print(turn);
    Serial.println("'s turn! |");
    Serial.println("----------------------");

    Serial.println("Please Select a number of rolls between 1-3");
    int numOfRolls;

    numOfRolls = getUserInput();
    if (numOfRolls > 3) {
      numOfRolls = 3;
    }
    else if (numOfRolls < 1) {
      numOfRolls = 1;
    }

    Serial.print("You selected ");
    Serial.println(numOfRolls);
    Serial.println();
    boolean reroll = false;
    int diceRoll = rollDice(numOfRolls);

    Serial.println("rolling Dice");
    Serial.print("player ");
    Serial.print(turn);
    Serial.print(" rolled a ");
    Serial.println(diceRoll);
    delay(500);

    if (diceRoll == 6) {
      Serial.println("You landed on a 6 and get to reroll!");
      playSound(3,1);
      reroll = true;
    }

    movePlayer(turn, diceRoll);

    displayPlayerStatus();

    printBoard();

    if (reroll != true) {
      if (turn == 1) {
        turn = 2;
      }
      else {
        turn = 1;
      }
    }
  }
}

void modeComputerVsComputer() {
  winnerCheck();
  if (winner == 1) {
    Serial.println("The winner is Player 1");
    showEndGameMenu();
    userInput = getUserInput();
    if (userInput == 1) {
      resetLights();
      boardGen();
      gameStarted = true;
    }
    else {
      gameStarted = false;
    }
    winner = 0;
    playerOnePosition = 1;
    playerTwoPosition = 1;
    turn = 1;
  }
  else if ( winner == 2) {
    Serial.println("The winner is Player 2");
    showEndGameMenu();
    userInput = getUserInput();
    if (userInput == 1) {
      boardGen();
      resetLights();
      gameStarted = true;
    }
    else {
      gameStarted = false;
    }
    winner = 0;
    playerOnePosition = 1;
    playerTwoPosition = 1;
    turn = 1;
  }
  else {
    Serial.println("----------------------");
    Serial.print(" | Player ");
    Serial.print(turn);
    Serial.println("'s turn! |");
    Serial.println("----------------------");

    Serial.println("Please Select a number of rolls between 1-3");
    int numOfRolls = random(1, 4);

    Serial.print("You selected ");
    Serial.println(numOfRolls);
    Serial.println();
    boolean reroll = false;
    int diceRoll = rollDice(numOfRolls);

    Serial.println("rolling Dice");
    Serial.print("player ");
    Serial.print(turn);
    Serial.print(" rolled a ");
    Serial.println(diceRoll);
    delay(500);

    if (diceRoll == 6) {
      playSound(3,1);
      Serial.println("You landed on a 6 and get to reroll!");
      reroll = true;
    }

    movePlayer(turn, diceRoll);

    displayPlayerStatus();

    printBoard();

    if (reroll != true) {
      if (turn == 1) {
        turn = 2;
      }
      else {
        turn = 1;
      }
    }
    delay(2000);
  }
}

//The printboard function displays the snakes and ladders game boad with all the snakes, ladders, players and square numbers
void printBoard() {
  int rowStartValue = 101; // the value at the start of each row, the first row would be 91, going up to 100
  Serial.println(); // create a 1 line gap between what ever else has been printed
  Serial.println("----------------------------------------------------"); // make the top of the board pretty
  for (int r = 0; r < 10; r++) { //for each row, we have 10
    for (int x = rowStartValue - 10; x < rowStartValue; x++ ) {  //for each row , get the start value - 10  for the first row(91), then each iteration add 1,
      Serial.print(" | "); // place a pipe at the start of each square
      if (boardArray[x] == 101) { // if boardArray[x] == 101, where 101 is player 1 and boardArray[x] is the position, print an X, X represents Player 1
        Serial.print(" X");
        leds[x-1] = CRGB::Green;
      }
      else if (boardArray[x] == 102) { // if boardArray[x] == 102, where 101 is player 1 and boardArray[x] is the position, print an O, O represents Player 2
        Serial.print(" O");
        leds[x-1] = CRGB::Blue;
      }
      else if (boardArray[x] == 103) { // if boardArray[x] == 103, where 101 is player 1 and boardArray[x] is the position, print an S, S represents a Snake
        Serial.print(" S");
        leds[x-1] = CRGB::Red;
      }
      else if (boardArray[x] == 104) { // if boardArray[x] == 104, where 101 is player 1 and boardArray[x] is the position, print an H, H represents a ladder
        Serial.print(" H");
        leds[x-1] = CRGB::LightBlue;
      }
      else {
        if (x < 10) {
          Serial.print(" ");   // position below 10, so 1-9 are only one character, we need to add a space before the number to keep the format of the board
        }
        Serial.print(boardArray[x]);  //if the current possition on the board is not P1, P2, snake or a ladder, print the square value
        leds[x-1] = CRGB::Black;

      }
      if (x != rowStartValue - 1) {
      }
      else {
        Serial.print(" | ");
      }
    }

    Serial.println(); //Moves to the next line after printing the number 10 at the bottom of the board
    rowStartValue = rowStartValue - 10; // after each row, remove another 10 from start value, for the next row
    Serial.println("----------------------------------------------------"); // make the bottom of the board look pretty
  }
  Serial.println(); // drop another line in afte rthe board has all been rendered
  FastLED.show();
}

//The winnderCheck function checks if a player has won.
void winnerCheck() {
  if (playerOnePosition == 100) { //if player one has reached square 100 then set winner to 1.
    winner = 1;
  }
  else if (playerTwoPosition == 100) { //if player twp  has reached square 100 then set winner to 2.
    winner = 2;
  }
}

//The movePlayer function, moves the player to a new location, movePlayer takes two arguments (int turn, int Moves), turn is the value of which player, ie 1 for player 1, 2 for player 2, and moves is the number of moves to move.
void movePlayer(int turn, int moves) {

  int player; // init a player variable, so we can more easily use it instead of calling specific player variables
  if (turn == 1) {
    player = playerOnePosition;  //if the player is player 1 then set player to the player position variable
  }
  else {
    player = playerTwoPosition;  //else it's player two so set it to player twos position
  }
  if (player + moves <= 100) {  // if the current position plus moves is less than or equal too 100, they are allowed to move. else they have over shot and have to wait again
    for (int i = 0; i < 8; i++) { // for each of the snakes in the game
      if (snakeArray[i][0] == player + moves) { // check to see if there start position is equal to where the player would be if they move.
        snakeLandedOn = i; // if the player would land on a snake, put the index of the snake in to snakeLandedOn, this way we can get the tail position later
      }
    }
    for (int i = 0; i < 8; i++) { // for each ladder in the game
      if (ladderArray[i][0] == player + moves) { //check to see if the start position of the ladder is where the player would be if they move
        ladderLandedOn = i; // if the player would land on the ladder put the index of the ladder in to ladderLandedOn so we can get the ladder data later on
      }
    }
    if (snakeLandedOn != 10) { // if snake landed on != 10, then the player has landed on snake ,10 is the default and mean the player has not landed on a snake
      playSound(1,1);
      Serial.println("You have landed on a snake!"); // Tell the player
      boardArray[player] = player; //set the index in the boardArray of where they player was, to there old position, this resets the value back to it's number,  example if the player was on square 1, and is moving to 10, square 1 will show X but when the player moves we need to set the square 1 back to 1 and remove X
      if (turn == 1) { // check if we are moving player one of player two
        boardArray[snakeArray[snakeLandedOn][1]] = 101; //change the value of the square number to show where the player now is after they slide down the snake
        playerOnePosition = snakeArray[snakeLandedOn][1]; // set the position of the player to there new position
      }
      else {
        boardArray[snakeArray[snakeLandedOn][1]] = 102; //change the value of the square number to show where the player now is after they slide down the snake
        playerTwoPosition = snakeArray[snakeLandedOn][1]; // set the position of the player to there new position
      }
    }
    else if (ladderLandedOn != 10) {
      playSound(2,1);
      Serial.println("You have landed on a ladder!");
      boardArray[player] = player;
      if (turn == 1) {
        boardArray[ladderArray[ladderLandedOn][1]] = 101; //change the value of the square number to show where the player now is after they climb up the ladder
        playerOnePosition = ladderArray[ladderLandedOn][1]; // set the position of the player to there new position
      }
      else {
        boardArray[ladderArray[ladderLandedOn][1]] = 102; //change the value of the square number to show where the player now is after they climb up the ladder
        playerTwoPosition = ladderArray[ladderLandedOn][1]; // set the position of the player to there new position
      }
    }
    else { // if we did not land on a snake or a ladder then we need to move normally
      boardArray[player] = player;  // set the old position back to it's value
      if (turn == 1) { // if player 1
        boardArray[player + moves] = 101; //set the new position to value 101
        playerOnePosition = player + moves; // set the playerTwoPosition to the new position
      }
      else {
        boardArray[player + moves] = 102; //set the new position to value 102
        playerTwoPosition = player + moves; // set the playerTwoPosition to the new position
      }
    }
    snakeLandedOn = 10; //set the sanke landed on back to 10;
    ladderLandedOn = 10; //set the sanke landed on back to 10;
  }
}

//The displayPlayerstatus function displays where both players currently are on the board
void displayPlayerStatus() {
  Serial.println(); // move to the next line down
  Serial.print("Player 1 is currently at "); // print the player and there location
  Serial.println(playerOnePosition);

  Serial.print("Player 2 is currently at "); // print the player and there location
  Serial.println(playerTwoPosition);
}

// The rollDice fucnction generates a random number between 1-6, rollDice accepts one argument int(numOfRolls), which is the amount of times to roll the dice
int rollDice(int numOfRolls) {

  for (int i = 0; i < numOfRolls; i++) {  // for the number of rolls choosen by the player, since we are starting from 0, we need the finish one before the selection, 0 = 1 roll 1 = 2 rolls
    int randomNumber = random(1, 7); // Generate a number between 1-6
    drawRoll(); // draw the random roll to the 7 seg display

    //draw the correct digit for the number landed on
    if (randomNumber == 1) {
      drawOne();
    }
    else if (randomNumber == 2) {
      drawTwo();
    }
    else if (randomNumber == 3) {
      drawThree();
    }
    else if (randomNumber == 4) {
      drawFour();
    }
    else if (randomNumber == 5) {
      drawFive();
    }
    else if (randomNumber == 6) {
      drawSix();
    }
    // if we are on the last roll then return the value of randomNumber
    if (i == numOfRolls - 1) {
      return randomNumber;
    }
  }
}

void blankDisplay() {
  digitalWrite(segmentOne, LOW);
  digitalWrite(segmentTwo, LOW);
  digitalWrite(segmentThree, LOW);
  digitalWrite(segmentFour, LOW);
  digitalWrite(segmentFive, LOW);
  digitalWrite(segmentSix, LOW);
  digitalWrite(segmentSeven, LOW);
}

/*
 5 more functions like this to draw various numbers on the 7 segment cut them out to reduse the size
*/

void drawOne() {
  blankDisplay();
  digitalWrite(segmentTwo, HIGH);
  digitalWrite(segmentFour, HIGH);
}

void drawRoll() {
  for (int i = 0; i < 4; i++) {
    blankDisplay();
    digitalWrite(segmentOne, (random(0, 2)  == 1  ?   HIGH : LOW ));
    digitalWrite(segmentTwo, (random(0, 2)  == 1  ?   HIGH : LOW ));
    digitalWrite(segmentThree, (random(0, 2)  == 1  ?   HIGH : LOW ));
    digitalWrite(segmentFour, (random(0, 2)  == 1  ?   HIGH : LOW ));
    digitalWrite(segmentFive, (random(0, 2)  == 1  ?   HIGH : LOW ));
    digitalWrite(segmentSix, (random(0, 2)  == 1  ?   HIGH : LOW ));
    digitalWrite(segmentSeven, (random(0, 2)  == 1  ?   HIGH : LOW ));
    delay(100);
  }
}

void playSound(int sound, int repeatTimes) {

  for (int i = 1; i <= repeatTimes; i ++) {
    if (sound == 1) {
      tone(piezoPin, 523, 250);
      delay(500);
    }
    else if (sound == 2) {
      tone(piezoPin, 261, 250);
      delay(500);
    }
    else if (sound == 3) {
      tone(piezoPin, 523, 150);
      delay(100);

    }
  }
}

A:

Arduino specifics
Disclaimer: I've got very little experience with Arduino programming.  That said, my understanding is that the code you write essentially sits inside a function like this:
setup();     // User provided function, executed once on startup
while(true) {
    loop();  // User provided function, executed over and over again
}

Assuming I'm correct, then it looks like you have a potential bug in your loop code.  At the end of it you have a line that checks the current gameMode and if it's not 1,2 or 3 it calls loop.
(gameMode == 1 ? modeComputerVsComputer() :
                (gameMode == 2 ? modeSinglePlayer()
                               : (gameMode == 3 ? modeMultiplayer()
                                                : loop())));

You don't need to do this, it's handled automatically for you.  By calling loop yourself you're recursing, if you do it enough times, you're going to end up with a stack overflow.  My guess is that the Arduino would just reset in this situation and then call setup again. Since you're not playing, you might not even notice it happen.
Your setup contains randomSeed(analogRead(0)).  This is also the first line of your loop method.  Setup doesn't seem to actually be using the randomiser, so I suspect you don't need to call it from setup, simply call it from loop.
Ternary Operator
I've got nothing against the ternary operator, however some of your choices do nothing but make your code harder to follow.  Nested ?s should be avoided.  Creating a null function so that you can use the ternary operator is unnecessarily complex.
The method would be easier to follow if you used constants and spread out the logic a bit.
randomSeed(analogRead(0));
if (!gameStarted) gameInit();
switch(gameMode)
{
    case GAME_MODE_COMPUTER_VS_COMPUTER:
        modeComputerVsComputer();
        break;
    case GAME_MODE_SINGLE_PLAYER:
        modeSinglePlayer();
        break;
    case GAME_MODE_MULTIPLAYER:
        modeMultiplayer();
        break;
}

Alternately you could setup an array of function pointers and index into it based on the gamemode to get the method to execute.
Repeated Code
There seems to be some repeated code between the different game modes.  For example the following is repeated twice in each game mode (once for player 1 win, once for player 2).  There is a slight variation in computerVsComputer, where the blinkRandomFade is omitted, it's unclear if this is intentional or not.
blinkRandomFade();
Serial.println("The winner is Player 1");
showEndGameMenu();
userInput = getUserInput();

This could be refactored into a method that takes the winning player number.  There are other repeated blocks that again could be refactored into functions to reduce the overall amount of code and make it easier to follow the logic.  For example, startGame?:
boardGen();
resetLights();
gameStarted = true;

The Interface
You've done some good centralisation of the interface with some of the board elements drawRoll, playSound centralise the interaction so that you could replace these methods and maintain the core logic of the game.  However, your interaction with the Serial interface permeates your entire code.  If you centralised this interaction, then it would be easier to remove the dependency (for example to run it on a computer, or if you wanted to use different components in the future).
Consider using function pointers
There are various points in your code where you are calling different methods based on an index like this:
if (randomNumber == 1)
{
    drawOne();
}
else if (randomNumber == 2)
{
    drawTwo();
}
else if (randomNumber == 3)
{
    drawThree();
}
else if (randomNumber == 4)
{
    drawFour();
}
else if (randomNumber == 5)
{
    drawFive();
}
else if (randomNumber == 6)
{
    drawSix();
}

Consider replacing this with function lookup table, that way the invocation is a lot simpler (bounds checking may be required, although not for this case because of the source of the number):
void (*drawNumberMethods[6])() = {drawOne,drawTwo,drawThree,drawFour,drawFive,drawSix};

drawNumberMethods[randomNumber-1]();

Magic Numbers
For the most part, I don't mind having actual numbers in code where they make sense in context.  In the die drawing code above, it is easy to follow that the 1 and drawOne are connected as the value of the die.  However some of your numbers are less clear, like ladderLandedOn = 10 representing not on a ladder.  Where the meaning isn't obvious, avoid using the numbers and consider replacing them with a meaningful constant / #define.


Q:

How to get the bluetooth name/id of Samsung Gear S3 smartwatch web application

I am trying to get the bluetooth name/id in a tizen web-application running on Gear S3.
On the watch, this information can be found -
Settings -> Connections -> Bluetooth -> Bluetooth Gear S3(AAA1).
I want the AAA1 value programmatically. Is there any method or API to get the value in a tizen web-application ?

A:

Invoke the discoverDevices function, You will find the BluetoothDevice interface on the succesCallback parameter.
BluetoothDevice interface represents a remote Bluetooth device having the propertoes:
DOMString name;
BluetoothAddress address;
BluetoothClass deviceClass;
boolean isBonded;
boolean isTrusted;
boolean isConnected;
BluetoothUUID[] uuids;
name is the property you are looking for.
In your case the name is: 'Gear S3(AAA1)'
var adapter = tizen.bluetooth.getDefaultAdapter();

var discoverDevicesSuccessCallback = {
        ondevicefound: function(device) {
            alert('Found device - name: ' + device.name);
        }
    };

adapter.discoverDevices(discoverDevicesSuccessCallback, null);

Add 'bluetooth.gap' privilege (for Tizen 2.3.2 and below) or 'bluetooth' privilege (for Tizen 3.0 and above) in your config.xml:
<tizen:privilege name="http://tizen.org/privilege/bluetooth.gap"/>  // <=2.3.2
<tizen:privilege name="http://tizen.org/privilege/bluetooth"/>     // >=3.0

Additionally, If you need only 'AAA1' instead of 'Gear S3 (AAA1)', May try a little Regular Expression and split.
var deviceName = "Gear S3 (AAA1)";                  // Gear S3 (AAA1)
var removePrts = deviceName.replace(/[()]/g,'');    // Gear S3 AAA1
var shortName = removePrts.split(' ');              // Gear,S3,AAA1
alert(shortName[2]);                                // AAA1


Q:

Improving performance on large select lists

in my asp.net (c#) web-forms application i have to use very large jquery-dropdown lists (inside a table).
For that i am using the jquery plugin "select2" which has an included search field so i can search for a specific entry ...
On the backend of my ddl i have a sqldatasource which returns >1000 entries.
In Firefox the rendering of this  tag takes like 2 seconds, but in IE it takes like 6 seconds.
I am already using caching on my datasource but that didnt help much, because i think the bottleneck is the rendering in my case.
Do you have any suggestions on how to improve the performance?

A:

See if you can change your dropdownlist to a Auto Complete box and try to load the result based on the key strokes by the user.
If you are already using Cache then try to cache it in the form of a JSON string and use that to send to the client and use the auto complete at the client.


Q:

How to execute the Durandal JS optimizer.exe as part of VS2012 build/publish process?

I was getting 404 Not found for the main-built.js file when I was running my DurandalJS SPA application published in release mode on a web server.

So I figured out I needed to run the optimizer.exe to generete the missing file main-built.js
Is it possible to include the execution of optimizer.exe as part of Visual Studio 2012 build/publish process?
If yes, how do I do that?
Thanks

A:

I added the optimizer step as a Pre Build step.
So in the Pre Build Events box in the project properties of your web project I added this:
cd $(ProjectDir)App\durandal\amd

optimizer.exe

main-built.js is then generated as part of the build process.
Note you will probably have to add the main-built.js file to your project for it to be deployed automatically if you are using msdeploy. I had to do this because we are using TFS hosted build service with automatic Azure publishing. Without this step the file was not being deployed.


Q:

Reliable write to Java SocketChannel

I'd have a question regarding java SocketChannel.
Say I have a socket channel opened in blocking mode; after calling the the write(ByteBuffer) method, I get an integer describing how many bytes were written. The javadoc says:
"Returns: The number of bytes written, possibly zero"
But what exactly does this mean? does this mean that the number of bytes really has been delivered to the client (so that sender received tcp ack making evident how many bytes have been received by server), or does this mean that the number of bytes has been written to the tcp stack? (so that some bytes still might be waiting e.g. in the network card buffer).

A:

does this mean that the number of bytes really has been delivered to the client

No.  It simply means the number of bytes delivered to the local network stack.
The only way to be sure that data has been delivered to the remote application is if you receive an application level acknowledgment for the data.


Q:

Characterising functions $f$ that can be written as $f = g \circ g$?

I'd like to characterise the functions that ‘have square roots’ in the function composition sense. That is, can a given function $f$ be written as $f = g \circ g$ (where $\circ$ is function composition)?
For instance, the function $f(x) = x+10$ has a square root $g(x) = x+5$.
Similarly, the function $f(x) = 9x$ has a square root $g(x) = 3x$.
I don't know if the function $f(x) = x^2 + 1$ has a square root, but I couldn't think of any.
Is there a way to determine which functions have square roots? To keep things simpler, I'd be happy just to consider functions $f: \mathbb R \to \mathbb R$.

A:

I showed you the link to the MO question mostly to convince you that this is a hard question.  I will "answer" it in the special case that $f$ is a bijection.
Recall that given a bijection $f : S \to S$, where $S$ is a set, a cycle of $f$ length $n$ is a set of distinct points $x, f(x), ... f^{n-1}(x)$ such that $f^n(x) = x$.  A cycle of infinite length is a set of distinct points $x, f(x), f^2(x), ...$.  It is not hard to see that $S$ is a disjoint union of cycles of $f$.
Claim:  A bijection $f : S \to S$ has a square root if and only if there are an even number of cycles of $f$ of any given even length.  (For the purposes of this result, infinity is an even number; so there can be an infinite number of cycles, and you need to consider cycles of infinite length.)
Proof.  First we show that any bijection with a square root has this property.  Let $g : S \to S$ be a bijection such that $g(g(x)) = f(x)$.  Then each cycle of $g$ corresponds to either one or two cycles of $f$, as follows.  If the cycle has odd length, it corresponds to one cycle of $f$.  For example, the cycle $1 \to 2 \to 3 \to 1$ of $g$ would correspond to the cycle $1 \to 3 \to 2 \to 1$ of $f$.  If the cycle has even length, it corresponds to two cycles of $f$.  For example, the cycle $1 \to 2 \to 1$ of $g$ would correspond to the pair of cycles $1 \to 1$ and $2 \to 2$, and the cycle $1 \to 2 \to 3 \to ... $ would correspond to the pair of cycles $1 \to 3 \to ... $ and $2 \to 4 \to ...$.  In particular, cycles of $f$ of odd length can come from cycles of $g$ one at a time or two at a time, but cycles of $f$ of even length can only come from cycles of $g$ two at a time.
Now we show the reverse implication.  Given a cycle of $f$ of odd length $2k+1$, consider the corresponding cycle of $f^{k+1}$ of odd length.  Since $f^{2k+2} = f$ when restricted to this cycle, make this a cycle of $g$.  Given a pair of cycles of $f$ of the same even length, just weave them together to get a cycle of $g$.
I say "answer" instead of answer because it's not obvious if you can always find the cycle decomposition of some complicated bijection on an infinite set.  In any case, if $f$ isn't assumed to be a bijection this question becomes much harder; the analogue of cycle decomposition is much more difficult to work with.  I suggest you look at some examples where $S$ is finite if you really want to get a grip on this case; best of luck.


Q:

Android SDK API/Feature Breakdown?

Is there anyway I can look at "what's new"/release notes in any of the releases for the Android SDK?
Specifically new API's that have been added per version. For example DreamService is only available in API 17 and up.

A:

Each API level has a changes page, which is like a summary, as well as a full changes report.
For example, the Android 4.2 "changes page" can be found here: Android 4.2 APIs (Note: You can navigate all versions by using the menu on the left.)
And the full changes report can be found here: Android API Differences Report (Note: Not as easy to navigate; changing the "17" in the URL is the easiest way to explore previous API versions.)

A:

You can see official site. Go to http://developer.android.com/about/versions/android-4.2.html . You can choose specific API on the left panel


Q:

How to map custom directive to my html page in Angular Js

I am very new in angularJs please guide me ,i have created custom directive called testDirective in separate file and my controller and config files are in separate files i want to use my custom directive in my html page but while loading the application that custom element is loading but not able to fetch content of directive i guess m missing some sort of mapping .kindly help me
//this is testDirective.js

var app=angular.module('mytodoApp');
app.directive('testDirective',function(){

return {
    restrict:'E',
    template:'
This is comes from directive
'

};

});

 var app=angular.module('mytodoApp');
 app.controller('MainCtrl', function ($scope) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];
  });

  < test-directive>
  < /test-directive>

A:

You have to bootstrap the Angular app, otherwise the HTML page does not know that you are using AngularJS and what you app has.
Bootstrapping is done by using ng-app="moduleName".

  <test-directive></test-directive>


Q:

La clase "tabla" de una table creada no toma todas las propiedades de igual forma. JavaScript

cree una tabla con document.createElement("table") y le aplique la class tabla. Cuando voy al ordenador veo que no me toma algunas propiedades como el color y el border-collapse. Alguien entiende porque sucede esto?
Cuando voy al ordenador el "border-color" y el "border-collapse" aparecen tachados, pero otras propiedades no, y no entiendo porque pasa esto.
Gracias

Calendario

A:

Propiedades CSS en la tabla

Importante: se desarrollarán algunos ejemplos para dar un poco de contexto al problema planteado con el código.

La razón por la que no se "aplica" la regla CSS a la tabla es porque no tiene celdas. Por ejemplo, partiendo de los fragmento que siguen más abajo.
Tabla sin celdas
HTML:
...

Y JavaScript:
window.onload = function () {
  ...
  var tabla = document.createElement("table");
  div1.appendChild(tabla);
  tabla.className = "tabla";
};

Producirá el siguiente resultado (en el código HTML):

#divCentral {
  width: 400px;
  height: 400px;
  border: solid 1px gray;
  border-radius: 7px;
  margin: 100px auto;
}

.tabla {
  width: 300px;
  height: 200px;
  margin: 50px auto;
  border-style: solid;
  border-color: gray;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  border-collapse: collapse;
}

Por lo tango, no se observan resultados de la regla .tabla { ... } sobre la tabla que se creó cuando se insertó en el elemento

 porque la tabla no tiene celdas.
Tabla con celdas
Si se modifica el código anterior, es decir, se agregan celdas a la tabla observaremos la aplicación de las propiedades CSS de la regla .tabla{ ... } sobre la tabla:

#divCentral {
  width: 400px;
  height: 400px;
  border: solid 1px gray;
  border-radius: 7px;
  margin: 100px auto;
}

.tabla {
  width: 300px;
  height: 200px;
  margin: 50px auto;
  border-style: solid;
  border-color: gray;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  border-collapse: collapse;
}

Se observan los resultados de la regla CSS .tabla{ ... } sobre la tabla.
Tabla con celdas usando JavaScript

Por favor, lea los comentarios que se ubican dentro del código. En ellos se explican detalles específicos para entender un poco el contexto del problema resuelto.

En esta oportunidad, reproduciremos la solución del problema incorporando JavaScript:

onload = () => {
  // A parte de crearse la tabla, se crean los
  // elementos que formarán la celda de la tabla:
  let
    tabla = document.createElement( "table" ),
    fila = document.createElement( "tr" ),
    celda = document.createElement( "td" );

  // Se inserta el elemento «tr» en la tabla:
  tabla.append( fila );

  // Y se coloca el elemento «td» en la fila:
  fila.append( celda );

  // Se inserta la tabla en el elemento «#divCentral»
  divCentral.appendChild(tabla);

  // Y finalmente, le agregamos la clase
  // «.tabla» al elemento «table»:
  tabla.classList.add( "tabla" );
};
/*
   Los estilos no se modificaron,
   excepto en la eliminación del comentario
   que empezaba con » // en la regla «.tabla{ ... }» y
   la propiedad «margin-top: 200px;» de la regla h1 { ... }
*/

h1 {
  text-align: center;
  color: mediumturquoise;
}

#divCentral {
  width: 400px;
  height: 400px;
  border: solid 1px gray;
  border-radius: 7px;
  margin: 100px auto;
}

/* En esta regla CSS se ubicaba un comentario que
   empezaba con //. Fue eliminado */
.tabla {
  width: 300px;
  height: 200px;
  margin: 50px auto;
  border-style: solid;
  border-color: gray;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  border-collapse: collapse;
}

Calendario

Nota: en esta publicación no se explica cómo escribir código correctamente. El objetivo principal es explicar el problema planteado en la pregunta.

Dato adicional
Tomando en cuenta la inquietud de tu pregunta que cito a continación:

Cuando voy al ordenador el "border-color" y el "border-collapse" aparecen tachados, pero otras propiedades no, y no entiendo porque pasa esto.

Las propiedades que suelen estar tachadas, si están escritas correctamente, porque hay otra regla CSS con el mismo selector de clase (.tablaen tu caso) que están usando las mismas propiedades que mencionas. Es decir, las sobreescriben.


Q:

Store data between controllers as uique

I have a controller which, I have expected, will contain unique data, gather as follow:
        setInterval(function() {

            dataStorage.setData('maxTime',maxTime);
            dataStorage.setData('currentTime',currentTime);
            dataStorage.setData('previousTime',previousTime);

            var dMaxTime = dataStorage.getData('maxTime');
            var dCurrentTime = dataStorage.getData('currentTime');
            var dPreviousTime = dataStorage.getData('previousTime');

            $log.debug("Max time  " + dMaxTime);
            $log.debug("Current time " + dCurrentTime);
            $log.debug("Previous time " + dPreviousTime)

        }, 2000);

which uses simple factory to capture data between controllers
myApp.factory('dataStorage', [function() {

    var dataInfo = [];

    return {

        setData: function (key, data) {
            dataInfo[key] = data;
        },
        getData: function (key) {
            return dataInfo[key];
        }

    };
}]);

but when I go back and forth to the view which has first code above it stores the same variables again but with different (updated values) and then displays them in the log as how many times that view with controller was hit.
Is there any way to prevent that and to have stored only most recent captured data?

A:

When the controller is destroyed, you need to clear your interval, otherwise it continues to run.
app.controller('SomeCtrl', ['$scope', function($scope) {

  var interval = setInterval(function() {
    console.log('whatever')
  }, 2000);

  $scope.$on('$destroy', function() {
    clearInterval(interval);
  });

}]);


Q:

How to fetch from server on Redux Rehydrate?

I'm using React/Redux and redux-persist to maintain local storage persistence. I'm looking to load an 'appSettings.json' from the server when redux-persist has finished Rehydrating the store from local storage.
In the persistStore method there is a callback function that is guaranteed to come after the store has been rehydrated, but I then need to make a server call to fetch the appSettings.json.
Is there a way in which I can await the fetch until the server responds?
I require the API URL from the appSettings.json in order to make API calls, but the calls from within the components are occurring before the appSettings fetch has returned.
const persistor = persistStore(store, persistConfig, async () => {

return await fetch('settings.json')
    .then(response => {
        return response.json();
    })
    .then(data => {
        console.log(data);
        store.dispatch({ type: "API_BASE_RESPONSE",  base_api_url: data.baseApiUrl });
    })

});

I've tried a few different variations of awaiting but with no luck. Is there perhaps an even better method of doing what I'm trying to achieve?

A:

Managed to resolve (for now) this by adding a method to the PersistGate of redux-persist.
const onBeforeLift = async () => {

    // take some action before the gate lifts
    return await fetch('settings.json')
        .then(response => {
            return response.json();
        })
        .then(data => {
            console.log(data);
            store.dispatch({ type: "API_BASE_RESPONSE",  base_api_url: data.baseApiUrl });
        })
}

ReactDOM.render((
    // specify basename below if running in a subdirectory or set as "/" if app runs in root
    <Provider store={store}>
        <PersistGate
            onBeforeLift={onBeforeLift}
            persistor={persistor}>
            <BrowserRouter basename={WP_BASE_HREF}>
                <Routes />
            </BrowserRouter>
        </PersistGate>
    </Provider>

), document.getElementById('app'))


Q:

Ruby Retrieve a Set of String within a String

I have the following issue.
phrase = "I love Chrome and firefox, but I don't like ie."

browsers = ["chrome", "firefox", "ie", "opera"]

def little_parser ( str )

  # what's the best way to retrieve all the browsers within phrase?

end

If we use the method little_parser( phrase ), it should return
["chrome", "firefox", "ie"]

If the phrase was:
 phrase_2 = "I don't use Opera"

If we run little_parser( phrase_2 ), it should return only:
["opera"]

How do I do that in the simplest way?

A:

You could iterate through the browsers and use str.include? to single out the items which are in the string:
def little_parser(str)
  browsers = ["chrome", "firefox", "ie", "opera"]
  browsers.select { |browser| str.include?(browser) }
end


Q:

qtscript engine - make system calls

I use qtscript in an application to provide automation capabilities for various functions within the application.
To allow greater flexibility i need the possibility to execute other tools (commandline commands/applications) from the script and get their output (the application itself is not security relevant - so calling random code may be ok).
Is their a way to do this with the basic qtscript module or some 3rd party class that encapsulate this or do i have to do this on my own?

A:

A process can be spawned via QProcess class. It also provides console I/O capabilities to fetch executed process output (standard and error).
You will need to have a wrapper class however, since QProcess cannot be exposed directly to script environment (e.g. it defines no public slots accessible to a script).
See Related discussion on qtcentre forum.


Q:

OpenVr: alternatives and compatibility

I am trying to figure out the OpenVR APIs capabilities and its exact role in VR contents development.
So far i understood that games can be developed using OpenVR in order to be flexible on the kind of hardware used.
At this point I have a couple of questions that come to my mind:

if one doesn't use OpenVR to develop a game in (let's say) unity, what else can he/she use? does the Steam plugin for unity use OpenVR?
also, if I develop an OpenVR driver for a new kind of controller for VR games, what kind of games would be compatible with my new controller?

Thanks a lot

A:

SteamVR is at this point synonymous with OpenVR. It is the only known server that implements the API. So yes, the SteamVR plugin will use OpenVR.
If you want to develop a VR controller, then I guess it would work in most games as long as you map it with the same axis. For example, here is the mapping that Unity3d uses. You can make a vastly different controller, but don't count on it working with software that was not designed with it in mind.
Remember, that the controller API has not only tracking and axis, but also it's 3d model that can be shown in VR. Quite a few (most?) apps don't use the API provided model, but have their own built in. This means people will most likely still see your controller in VR as the standard Vive wand. Try to model the grip at the same shape so at least that doesn't break immersion.


Q:

Jquery trying to get src using html()

I am trying to get the src from this jquery html().
So using jquery html() my alert shows this output

what I want is the src. See code below:
 var $boxes = $(".slideWrap"),
                var hdnImg = $boxes.first().show();
                var p = hdnImg.html(); //OUTPUTS
                alert(p.attr("src")); // DOES NOT WORK??

Why is p.attr("src") does not work? I am trying to get the html and then getting the src from the html.
Any one please help?

A:

According to the documentation .html() returns a string. Strings don't have an .attr() method.
If you want the attribute from the element, the use .attr() on the element that has the attribute you want.

Here's another part of the problem...
var p = hdnImg.html(); //OUTPUTS

Because the output shows the HTML of the , and the .html() method returns the HTML content, then that means the image is nested.
To get the image, you need to traverse down to it. Do this instead...
var p = hdnImg.children('img').html();


Q:

Programatically execute another touch event when one touch event occures in android

I am making ImageView Drag and drop with creating duplicate instance by touching original one.
I am having one horizontal-layout containg many small images.
when I touch on it it creates duplicate instance of it and puts at that position on screen slight different.
Now, I want to continue the touch event but want to finish up the first one touch event done on the original ImageView and want to start-up the touch event of duplicate instance of it. but with-out removing  fingure up.
I have done following :
img22.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        ImageView img2 = null;

        switch (event.getActionMasked()) {
        case MotionEvent.ACTION_DOWN :
...   ...
...   ...
            Bitmap bmp2 = BitmapFactory.decodeResource(ImageListActivity.this.getResources(),
                R.drawable.img2);
            //ImageView
            img2 = new ImageView(ImageListActivity.this);
            img2.setImageBitmap(bmp2);
            img2Param.setMargins( (rx-10-x), (ry-10-y-50), 0, 0);
            img2.setLayoutParams(img2Param);

            img2.setOnTouchListener(new OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {

                    System.out.println("   ---   img2 On Touch Called   ---");

                    RelativeLayout.LayoutParams img2Param =
                    (RelativeLayout.LayoutParams) v.getLayoutParams();
                    img2Param.setMargins((int)event.getRawX()-10, (int)event.getRawY()-60, 0, 0);
                    v.setLayoutParams(img2Param);
                    v.invalidate();
                        return true;
                    }
                });
            long downTime2 = SystemClock.currentThreadTimeMillis(),
                    eventTime2 = SystemClock.currentThreadTimeMillis() + 10;
            float x2 = 0.0f, y2 = 0.0f;
            int metaState2 = 0;
            MotionEvent motionEvent2 = MotionEvent.obtain(
                    downTime2, eventTime2, MotionEvent.ACTION_POINTER_1_UP, x2, y2, 1);
            v.dispatchTouchEvent(motionEvent2);

            long downTime = SystemClock.currentThreadTimeMillis(),
                    eventTime = SystemClock.currentThreadTimeMillis();// + 5000;
            float x1 = 0.0f, y1 = 0.0f;
                int metaState = 0;
            MotionEvent motionEvent = MotionEvent.obtain(
                    downTime, eventTime, MotionEvent.ACTION_MOVE, x1, y1, 1);
            img2.onTouchEvent(motionEvent);
...    ...
...    ...

Can any one give me Idea about continuing touch event and changing the instance of ImageView.

A:

It sounds like what you want to do is click "Image1", have this action create an "Image2" and continue the touch gesture as if it was clicked on "Image2"?
Instead of doing this it might be a better idea to have a Touch Surface - An invisible view layered above these view's which captures the touch event and then performs the actions as needed - this will mean you can continue your gesture "off" the image without creating a new gesture.


Q:

Are there any limitations to what can be done in an inline onclick handler?

When adding code to an onclick handler, are there any limitations to what can be done?
Can I have unlimited statements separated by ; ?
Can I declare variables that will live in the global scope?
Can I declare an anonymous function right in there and call it? (function(){})();?
Is there any limitation?
The reason I'm asking is that i'm putting a lot of code in an onclick handler, and only in IE, one variable that I'm declaring and should go to the global scope is not being found afterwards.
However, that same code does work in other browsers, and it does work in IE when I use the same code as a bookmarklet.
EDIT:  The code in question is here
EDIT 2: The reason I'm making such a horrible and bulky onclick handler is that I'm making code that other people can put on their websites (think: Digg button), that will inject a script of mine. I'm trying to keep it simple for them, without cluttering their namespace too much, which is why giving them simply an <img> with an onclick handler is ideal.
If I absolutely can't make this work, then I'll have to  give them code that declares a <script>, with a named function inside, and then the <img> with the onclick handler that calls that function.
Any ideas?
Thanks!

A:

Try prepending window. to AppD.


Q:

What's the fastest way to get 50 reputation on Stack Overflow?

I need to comment on some questions/answers, but can't, because I don't have enough reputation. I want to help, but the site doesn't let me.

A:

If you "need to comment on some questions/answers" then you likely have an answer or a good understanding of why another answer is flawed.
I'd therefore recommend that you write the answer you have.  e.g. "The @SomeGuyOrGal gave will work but only in Java 8.  To make this work in all versions of Java you'll need to use something like this:
...(code detailing the complete solution)...
If your answer is truly the correct answer (or at least worth noting) you should gain some reputation from your answer.  In time this rep will grow where by you can post comments as needed when you need clarification.

A:

I feel with gnat, since I also was told "use the comment function instead" by other users and I simply can't. I think using a high reputation level as spam protection is the wrong way to go. This is really frustrating for people like me who just want to help.


Q:

How to return fully resolved promise?

I am trying to play around with $q, write some tests, try to stub promises etc. and I wondered if there is a way to return fully resolved promise like one can do it with whenjs, when("stuff to return), something that would be equal to this
  function fullyResolvedPromise(expectedResponse) {

        var dfd = $q.defer();
        dfd.resolve(expectedResponse);
        $rootScope.$apply();

        return dfd.promise;
    }

Clarification: I know this code works, but I want to do it without writing this function. I want to do something like this  $q(expectedresponse) and get equivalent to above code. That is what I am after. Just like with whenjs you can write when(stuffToResolve) and it would return you a fully resolved promise.

A:

After posting a clarification I re-read the documentation and there it is - when() method.
So I can use $q.when(stuffToResolve) and it would be equal to calling the above function.


Q:

I need to write a code that takes input(sentences) from user and stops at @

As i said i need to write this code as my hw however i need to write this in while loop because we dont know how big will user write their sentences or how many sentences they will write. It is going to be a paragraph
string word;
string parag;
while (cin >> word)
{
    parag += word;
    for ( unsigned int k = 0; k < parag.length(); k++ )
    {
        if (parag.at(k) == '@')
        break;
    }
}

I know there are problems here but it wont stop even if i wrote "@". I dont know what to do i am just a beginner.

A:

do

{
    parag = "";

cin >> word;

while (word != "@")
{
    parag += word + " ";
    cin >> word;

}
parag = parag.substr (0, parag.length()-1); //Takes all characters but "@" at the end

ToLower(parag); //This code is in header file that our teacher gave us. Makes all characters lower case in order to make our code "case insensitive".

}while ( ( CheckInput(parag) ) ); // This checks inputs(obviously) if inputs are correctly entered.

This is what i wrote after going to class and learning about do-while loop if anyone interested. Program will take infinite "cin" to create a paragraph. About why getline(cin, parag) wouldn't work user could write something like this
"Roses are red
Violets are blue. @"
As you see sentence is not in the same line and getline takes only one line as inputs. And best part is (pls dont judge i am a beginner) with "do" i can say something like this if the input is wrong. "Please enter your input again" and i can take inputs without closing my program till all inputs are right.
Rest my homework is about taking paragraph from user. Dividing paragraph to sentences as user inputs (with finding dots). Reversing all the sentences, asking user to write reverse sentences and compare those inputs with programs to see if user give reverse sentences all correctly and if not say how many mistakes did user do.


Q:

Geometry: Prove the evolute does not contain a line segment

Given a regular curve $\alpha:\mathbb{R}\to\mathbb{E}^2$ with an oriented curvature $\kappa(t) \ne 0$. Prove the evolute does not contain an open subset of a straight line.
I'm a bit stumped as to how I'm supposed to tackle this question. I mean, intuitively it feels easier to work the contraposition: assume the evolute contains a line, and then somehow end up proving the curvature vanishes.
Note: I eventually managed to construct an answer which has been confirmed to be more or less accurate by an external source.

A:

Since $a(s)$ is regular, a Frenet-apparatus can be constructed:
$$
\begin{align}
T'(s) &=\quad ||\alpha'(s)|| \cdot \kappa(s) \cdot N(s) \\
N'(s) &=     -||\alpha'(s)|| \cdot \kappa(s) \cdot T(s) \\
\end{align}
$$
with $R(s)=\kappa^{-1}(s)$.
The velocity of the evolute is given by
$$
\begin{align}
E'(s) &= \alpha'(s) + R'(s) \cdot N(s) + R(s) \cdot N'(s) \\[1ex]
      &= ||\alpha'(s)|| \cdot T(s) + R'(s) \cdot N(s) - R(s) \cdot ||\alpha'(s)|| \cdot \kappa(s) \cdot T(s) \\[1ex]
      &= R'(s) \cdot N(s) \\[3ex]
||E'(s)|| &= ||R'(s) \cdot N(s)|| \\[1ex]
          &= R'(s)
\end{align}
$$
$a)$ Assume $R'(s) = 0$ for $s \in ] s_0, s_1 [$. Then R(s) = R is constant, which means $\alpha$ is a circle segment over $] s_0, s_1 [$. Consequently, $E(s)$ is a singleton: the center of the circle. Since a singleton is a closed set, this concludes the proof.
$b)$ Assume $R'(s) \ne 0$. This means $E(s)$ is also regular, and a Frenet-apparatus can be constructed for the evolute:
$$
\begin{align}
T_E(s)  &= \frac{E'(s)}{||E'(s)||} = N(s) \\[1ex]
T_E'(s) &= N'(s) \\[3ex]
N_E(s)  &= J \cdot T_E(s) = -T(s) \\[1ex]
N_E'(s) &= -T'(s) \\
\end{align}
$$
Consequently, the curvature of the evolute equals
$$
\begin{align}
\kappa_E(s) &= \frac{T'_E(s) \cdot N_E(s)}{||E'(s)||} = -\frac{N'(s) \cdot T(s)}{R'(s)} \\[1ex]
            &= \frac{||\alpha'(s)|| \cdot \kappa(s)}{R'(s)} \cdot (T(s) \cdot T(s)) \\[1ex]
            &= \frac{||\alpha'(s)||}{R'(s) \cdot R(s)} \ne 0\\[1ex]
\end{align}
$$
Since the curvature of the evolute is not zero, the evolute itself cannot be a straight line, thus concluding the proof.


Q:

Cannot disable localParticipant.audioTracks with Twilio Video

I'm adapting Twilio's JS Quickstart and trying to provide a button that will mute a user's audio. From looking around online, my code looks like this:
function toggleAudio(){
  room.localParticipant.audioTracks.forEach(function(track) {
    console.log(track);
    track.disable();
  })
}

The console.log() spits out a LocalAudioTrackPublication, yet I get the following error:
Uncaught TypeError: track.disable is not a function
So I'm stumped. The docs imply that the .disable() method will do what I expect, yet apparently, it's not defined?

A:

It was such a ridiculously simple solution, as is always the case.
function toggleAudio(){
  room.localParticipant.audioTracks.forEach(function(track) {
    track.track.disable();
  })
}

The actual track is inside of the track property.


Q:

"Occasionally, I receive requests that does not meet our requirements"

"Occasionally, I receive requests that does not meet our requirements" - "does not" or "do not" should be used in this context?

A:

"do not" is correct.  It must agree with "requests."  You can test it by saying "the requests do not meet our requirements."