Q:

How to make a value interact with lines within its range on a table column?

I have a datatable, like this.

At some point people will be required to provide their own measurement, which can be -5 -4 -3 -2 -1 etc... all up till 35.
I need to make an interpolation between the resulting values of the measurement.
I could do something like this
double usermeasurement;
//user inserts the measurement in a textbox

if(usermeasurement <5)
{ //interpolation between line 1 and line 2 of the table
}

else if (usermeasurement <15)
{ //interpolation between line 2 and 3 of the table..
}
// and so on...

My programming question is, is there a simpler, advanced way to make the usermeasurement variable fit itself on the column measurement?
I can make my own interpolation method, but is there a simpler math operation that does it?

A:

If you are fetching this from a DataTable in code
int userInput = 7;

DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("Measurement", typeof(int)));
dataTable.Columns.Add(new DataColumn("Value", typeof(string)));

dataTable.Rows.Add(-5, "-0,1");
dataTable.Rows.Add(5, "0,2");
dataTable.Rows.Add(15, "0,5");
dataTable.Rows.Add(25, "0,7");
dataTable.Rows.Add(35, "0,9");

int min = Convert.ToInt32(dataTable.Compute("MIN(Measurement)", "Measurement > " + userInput.ToString()));
int max = Convert.ToInt32(dataTable.Compute("MAX(Measurement)", "Measurement < " + userInput.ToString()));
DataRow[] rows = dataTable.Select("Measurement = " + min.ToString() + " OR " + "Measurement = " + max.ToString());

If you are querying your database then use the below query
SELECT * FROM Measurements WHERE Measurement = (select MIN(Measurement) from Measurements WHERE Measurement > 16) OR Measurement = (select MAX(Measurement) from Measurements WHERE Measurement < 16)


Q:

How to calculate active load on a swingset?

Related to this question from DIY StackExchange.
Given a beam (a swingset) with three swings suspended from it.  Each swing holds 450 lbs of stationary load for a total of 1,350 lbs of stationary weight suspended from the beam.
All three swings begin swinging in synch so that the load hits the bottom of the arc simultaneously.
How does one calculate the effective weight of the moving mass on the three swings combined?
To clarify - the need is to determine the maximum load that will be put on the beam, so that the proper sized beam can be selected to ensure it can be used without breaking.  The charts that indicate maximum active load are here.  I think we're looking for total uniformly distributed load (w from the tables) that will be applied.

A:

Let $m$ be the mass of the load. I will make the assumption that the swing will never pass $90^\circ$ from the vertical. Letting $\ell$ be the length of the swing, the height difference will never pass $\ell$. From conservation of energy, we have
$$\frac{1}{2}mv^2 = mgh \implies v^2 = 2gh$$
At the bottom of the swing, we will have $h = \ell$. From the centripetal force, we have
$$F_c = \frac{mv^2}{\ell} = 2mg$$
This is totaled with the actual weight of the masses to give an effective force of $3mg$.

A:

By "effective weight", presumably you mean the force exerted by the swings and the beam on each other? The swings experience a gravitational force $mg$ (where $m$ is the mass of the swings and $g\approx9.81\text{ms}^{-2}$ is the gravitational acceleration), which they pass on to the beam. The beam also exerts a centripetal force on the swings, which is $m\omega^2r=mv^2/r$, where $\omega$ is the swings' angular frequency and $v$ is their veocity. The two forces add constructively, so the total force exerted by the swings and the beam on each other is their sum.


Q:

Finding the limits for integration.

How do we get 0.5 <= u <= 1 and -u <= v <= u over here?

A:

We have a trapezoid $(x,y)\in\Box(1,0)(2,0)(2,0)(1,0)$, and choose to rotate and rescale using $u=(x+y)/2, v=(y-x)/2$.
After this transformation we have: $(u,v) \in\Box(\tfrac 12, -\tfrac 12)(1,-1)(1,1)(\tfrac 1 2, \tfrac 12)$
Hence this transformed region is: $\tfrac 12 \leq u\leq 1$ and $-u\leq v\leq u$
Sketching a diagram of that trapezoid might help you see why.


Q:

GitHub & Eclipse - Issue in cloning

We have recently started using GitHub for saving our automation package and we were able to commit, push, pull, and other operations properly.
But recently we had to enable 2FA in Git, after which we couldn't perform any operation like commit/push/pull... so we tried to clone the project again and try perform these actions, but surprisingly we couldn't even clone the project now. Please help in understanding this - how can we clone the project and perform other regular actions of Git in Eclipse after enabling 2FA?

A:

I have never used git with 2FA but I had come across this when I was looking into. hope they help
https://help.github.com/articles/providing-your-2fa-authentication-code/
and this
https://developer.github.com/v3/auth/


Q:

Prestashop INVALID SECURITY TOKEN I understand the risks and I really want to display this page

Have created module which can create tab while installing it to prestashop v1.6 admin panel : to create tab and install code is as follow. please help to resolve.
 class Greeting extends Module {
   protected $tabs = [
    [
        'name' => 'Personalised Greetings',
        'className' => 'AdminMkonGreetinList',
        'active' => 1,
        'childs' => [
            [
                'active' => 0,
                'name' => 'List Greetings',
                'className' => 'AdminMkonGreetinList',
            ],
        ],
    ];

   //Adding Tab on Admin Section
    public function addTab($tabs, $id_parent = 0) {
    foreach ($tabs as $tab) {
        $tabModel = new Tab();
        $tabModel->module = $this->name;
        $tabModel->active = $tab['active'];
        $tabModel->class_name = $tab['className'];
        $tabModel->id_parent = $id_parent;

        //tab text in each language
        foreach (Language::getLanguages(true) as $lang) {
            $tabModel->name[$lang['id_lang']] = $tab['name'];
        }

        $tabModel->add();

        //submenus of the tab
        if (isset($tab['childs']) && is_array($tab['childs'])) {
            $this->addTab($tab['childs'],
            Tab::getIdFromClassName($tab['className']));
        }
    }
    return true;
  }
  public function __construct() {
     - - - - - -
  }
  public function install() {
    if (Shop::isFeatureActive()) {
        Shop::setContext(Shop::CONTEXT_ALL);
    }
     //add Tabs
    $this->addTab($this->tabs);
      if (!parent::install() || !$this->registerHook('leftColumn') ||
    !$this->registerHook('header')) {
        return false;
    }
    $this->frontMenu();
    return true;
   }
  }

Dashboard Personalize Greetings Tab :

Error Screen while clicking on Tab :

Dashboard Personalize Greetings Tab :
Error Screen while clicking on Tab :

A:

This error is usually due to file(name) and class(name) case sensitive differences. also "controller" suffix is required
AdminMkonGreetinListController.php  :
Class AdminMkonGreetinListController extends ModuleAdminController


Q:

Migrate map Issue

This is a weird issue with the Migrate module 2.6
I'm migrating a users table "mysql" database to a test node and I'm getting a error with the migration map
here is the error :
Migration failed with source plugin exception: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.migrate_map_usersmigration map ON u.user_id = map.sourceid1 WHERE ( (map.source' at line 1

and here is my code:
class UsersMigration extends myBaseMigrationClass {

  public function __construct($arguments) {
    parent::__construct($arguments);

    $this->description = t('Just for testing');

    $query = Database::getConnection('default', 'mydb')
      ->select('users', 'u')
      ->fields('u', array('user_id', 'full_name', 'birthday'));

    $this->source = new MigrateSourceSQL($query);

    $this->destination = new MigrateDestinationNode('test');

    $this->map = new MigrateSQLMap(
    $this->machineName,
      array(
        'user_id' => array(
            'type' => 'int',
            'not null' => TRUE,
            'alias' => 'u',
        ),
      ),
      MigrateDestinationNode::getKeySchema()
    );

    $this->addFieldMapping('title', 'full_name');
  }
}

Do I'm doing something wrong here?

Also to clarify, the source query is working fine and I'm getting the correct data out when I print it out.

A:

Finally I was able to find a solution for this weird issue, according to the Migration examples (beer, Wine) modules. the code I have posted above should work fine, However it's throwing that weird error. it turns out that I needed to pass the database name again like this:
$this->map = new MigrateSQLMap(
$this->machineName,
  array(
    'user_id' => array(
        'type' => 'int',
        'not null' => TRUE,
        'alias' => 'u',
    ),
  ),
  MigrateDestinationNode::getKeySchema(),
 'mydbName'
);

even the example modules that using SqlSource class wont work with migrate "7.x-2.6-rc1+57-dev". I will try to report that issue to the developer


Q:

How to refer to the style which contains text styling items

I've two themes,
AppTheme - for entire application and
AppTheme.NoActionBar - for navigation activity
In both the themes I've text styling.
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:textColor">@color/black_shade</item>
    <item name="android:textSize">@dimen/text_size</item>
    <item name="android:windowFullscreen">true</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:textColor">@color/black_shade</item>
    <item name="android:textSize">@dimen/text_size</item>
    <item name="android:windowFullscreen">true</item>
</style>

How do I group text-style-items and refer them in these two themes?
I've tried:
<style name="TextAppearance" >
    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:textColor">@color/black_shade</item>
    <item name="android:textSize">@dimen/text_size</item>
    <item name="android:windowFullscreen">true</item>
</style>

And referred it by
    <item name="textAppearance">@style/TextAppearance</item>

It's not working.
How do I achieve this?

A:

See: https://stackoverflow.com/a/3166865/5018798
My example (based on above):
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="android:textViewStyle">@style/TextAppearance</item>

    </style>

    <style name="AppTheme.NoActionBar" parent="AppTheme">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="android:windowFullscreen">true</item>

        <item name="android:textViewStyle">@style/TextAppearance</item>
    </style>

    <style name="TextAppearance" parent="android:Widget.TextView">
        <item name="android:textColor">#F00</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textSize">55sp</item>
    </style>

</resources>


Q:

How to find out if your webcam and LED have been hardwired or not

In these days webcam and LED in some laptops are interlocked either on a firmware base or a hardware base. Is there any possibility to determine whether or not the LED connection to the webcam is hardware based or firmware based? If it's hardware based then malware can't disable it.
I want to find out for Dell Inspiron 15 3521.

A:

if you are running linux
uvcdynctrl -c

May show LED
if so
LED_STATE: 0=Always-off, 1=Always-on, 2=Always-blink, 3=Auto on

then
 uvcdynctrl -d CAMERA_NAME -s 'LED1 Mode' 1

Should turn it on


Q:

Print new  on id iteration change inside php while loop from MySQL result

I have this MySQL table:
+------------+-------------+
| contact_id | _company_id |
+------------+-------------+
|          1 |           1 |
|          2 |           1 |
|          3 |           1 |
|          4 |           2 |
|          5 |           2 |
+------------+-------------+

Im trying to print a new
 containing all rows with the same _company_id
So far I have this code:
$previous = '';

while ($result = $stmt->fetch()) {

    $current = $_company_id;

    //This should be executed every first iteration and every time $_company_id changes
    if ($current != $previous) { $html .= '
'; }

    //Iterate all contact_id here with the same _company_id

    if ($current != $previous) { $html .= '
'; }

    $previous = $current;

}

My desired output is:

123

45

Right now the output is:

1

23

4

5

What should I change?

A:

$previous = null;

while ($result = $stmt->fetch()) {

    $current = $_company_id;

    //This should be executed every first iteration and every time $_company_id changes
    if ($current !== $previous) {
      if($previous !== null)
        $html.='
';
      $html .= '
';
    }

    //Iterate all contact_id here with the same _company_id

    $previous = $current;

}

if($previous!==null)
  $html.='
';


Q:

useRef() error: cannot set property disabled of null when trying to focus on a textarea

I am trying to get the textarea to be focused on so the user doesn't have to click start then click on the textarea, but keep getting an error when i click start, using codesandbox IDE.
Bit stuck now so not sure what i can do to fix it, the code runs fine when inputRef.current.focus and inputRef.current.disabled aren't included in the startGame() function.
import React, { useState, useEffect, useRef } from "react";
import "./styles.css";

export default function App() {
  const STARTING_TIME = 5;

  const [text, updateText] = useState("");
  const [time, setTime] = useState(STARTING_TIME);
  const [isTimeRunning, setIsTimeRunning] = useState(false);
  const [wordCount, setWordCount] = useState(0);
  const inputRef = useRef(null)

  function handleChange(event) {
    const { value } = event.target;
    updateText(value);
  }

  function startGame() {
    setIsTimeRunning(true);
    setTime(STARTING_TIME);
    updateText("");
    setWordCount(0);
    inputRef.current.disabled = false;
    inputRef.current.focus();
  }

  function endGame() {
    setIsTimeRunning(false);
    const numWords = countWords(text);
    setWordCount(numWords);
  }

  function countWords(text) {
    const wordsArr = text.trim().split(" ");
    const filteredWords = wordsArr.filter(word => word !== "");
    return filteredWords.length;
  }

  useEffect(() => {
    if (isTimeRunning && time > 0) {
      setTimeout(() => {
        setTime(time => time - 1);
      }, 1000);
    } else if (time === 0) {
      endGame();
    }
  }, [time, isTimeRunning]);

  return (

Speed Typing Game

      <textarea
        onChange={handleChange}
        value={text}
        disabled={!isTimeRunning}
      />

Time remaning: {time}

      <button type="button" onClick={startGame} disabled={isTimeRunning}>
        Start Game
      </button>

Word Count: {wordCount}

  );
}

Errors shown in the IDE console log below:

A:

You have to attach the inputRef to your textArea.
<textarea
  onChange={handleChange}
  value={text}
  disabled={!isTimeRunning}
  ref={inputRef}
/>

Find out more about React Refs here


Q:

"Center-of-Mass" of lattice polygons (generalization of Pick's theorem)

Call a polygon with integer coordinates (in the Euclidean plane) a 'lattice polygon'. Pick's Theorem allows you to efficiently compute the number of lattice points inside this polygon given just its set of vertices.
Is there a similar method to efficiently compute the sum
$$\sum_{(x,y)\in \mathcal{P}} x$$
where $\mathcal{P}$ is some lattice polygon? In other words, are there any methods to compute the "center-of-mass" of the set of lattice points belonging to the interior/boundary of a given lattice polygon?
(By efficiently, I mean something on the order of the number of vertices of the polygon. Also, by triangulation it's clear that it suffices to answer this question for lattice triangles)
EDIT: In case it was unclear, I am not trying to find the actual center of mass of the triangle - I want to find the center of mass of the set of lattice points inside the triangle (hence the above sum).
EDIT 2: After working on this problem a bit more, I think I've arrived at a fairly simple method which seems to work and avoids the messy machinery of 3D-Ehrhart polynomials.
The idea is (just as in Pick's theorem), since we can inscribe any triangle inside a rectangle, it suffices to compute the sum for rectangles and right triangles. Computing the sum for rectangles is easy; it's just something like $(y_2-y_1)(x_1+(x_1+1)+...+x_2)$.
Because of symmetry, it's almost as simple for right triangles. Namely, the sum of x-coordinates in/on the boundary of any right triangle is just equal to ((sum of x-coordinates in the corresponding rectangle) + (sum of x-coordinates along the diagonal))/2.
Hopefully this helps anyone who later has the same problem.

A:

It depends on what you mean by efficient.  Computing $$\sum_{(x,y)\in P}x$$ is equivalent to computing the number of lattice points in a 3d polyhedron (basically $P$ with a slanted roof.)  This is a job for Ehrhart polynomials. If you decompose $P$ into triangles you can decompose the triangle's corresponding polyhedron into a triangular prism (for which computing the lattice points therein is just an application of Picks Theorem) and two tetrahedra, which are straightforward to deal with, but fiddly (see the mathworld page referenced above.)  All of this is explained clearly in great detail in Computing the Continuous Discretely.


Q:

How do I use mutate_at with multiple functions where each function has parameters?

I want to take multiple lagged values of multiple columns in R.
How do I use mutate_at to get the same results as below? Lets say the real example has 30 columns, so it doesn't make sense to write out the lag formula 30x for each time period.
df <- data_frame(time_col = 1:26, col_1 = letters, col_2 = rev(letters))

df %>% mutate(col_1_lag_1 = lag(col_1, n = 1, by = time_col),
              col_2_lag_1 = lag(col_2, n = 1, by = time_col),
              col_1_lag_2 = lag(col_1, n = 2, by = time_col),
              col_2_lag_2 = lag(col_2, n = 2, by = time_col))

I think it should be something like this, but I don't know how to specify both sets of parameters:
df <- data_frame(time_col = 1:26, col_1 = letters, col_2 = rev(letters))

df %>% mutate_at(vars(col_1, col_2), funs(lag, lag), n = 1, n = 2, by = time_col)

A:

A solution with the help from purrr.
library(dplyr)
library(purrr)

df <- data_frame(time_col = 1:26, col_1 = letters, col_2 = rev(letters))

map_dfc(1:2, function(x){
  df2 <- df %>% transmute_at(vars(starts_with("col")),
                             funs(lag(., n = x, by = time_col)))
  return(df2)
}) %>%
  bind_cols(df, .) %>%
  set_names(c(names(df), paste0("col_", 1:2, "_lag_", rep(1:2, each = 2))))
# # A tibble: 26 x 7
#    time_col col_1 col_2 col_1_lag_1 col_2_lag_1 col_1_lag_2 col_2_lag_2
#       <int> <chr> <chr> <chr>       <chr>       <chr>       <chr>
#  1        1 a     z     NA          NA          NA          NA
#  2        2 b     y     a           z           NA          NA
#  3        3 c     x     b           y           a           z
#  4        4 d     w     c           x           b           y
#  5        5 e     v     d           w           c           x
#  6        6 f     u     e           v           d           w
#  7        7 g     t     f           u           e           v
#  8        8 h     s     g           t           f           u
#  9        9 i     r     h           s           g           t
# 10       10 j     q     i           r           h           s
# # ... with 16 more rows


Q:

What nuances does the term "тугрик" have?

When not referring to the actual Mongolian currency, what nuances does the term "тугрик" have, if any?
For example, does it imply that the currency is weak?

A:

It usually metaphorically means "some obscure local currency", hardly known and hardly usable outside the country of origin; "some kind of monetary surrogate of limited use and circulation" (such as chits, company store vouchers, in-game currency in online games etc.).
It's close in meaning to English "monopoly money" or "funny money".

В портах, куда мы заходили, нам выдавали ― донги или еще какие тугрики.
Я не стал говорить Владимиру, что местные тугрики тоже называются долларами
Тут надо заметить, что в Мексике местные тугрики обозначают таким же значком, как доллары

A:

The term as a reference to exotic currency was widepread during times of Soviet international contracts. Since nineties, the meaning became broader.
Phonosemantically and similar to cockney rhyming slang, the term implies a joking attitude (towards the topic, the situation, the currency, goods, etc.).
In this context it can refer not just to an exotic monetary unit, but to Russian roubles or more usual currency as well:
Есть тугрики?
Давай тугрики!

A:

As a native speaker I understand it as just a slang term for "money", similar to "капуста", not sure that teenagers are using it, probably adult audience is more inclined to use it ;-)


Q:

Using variables in a vim shell command

How would I go about using a variable in a vim shell command (one done with !) in a vimscript? For instance, something kind of like this: (just an example, not what I'm really trying to do)
function Ls(dir)
    !ls a:dir
endfunction

A:

Use the execute command. Everything after it is an expression that evaluates to a string, which it then executes like a command you had typed in yourself.
function Ls(dir)
    execute '!ls ' . a:dir
endfunction

This says, "Evaluate the expression '!ls ' . a:dir and then execute it." The variable a:dir is expanded, the dot concatenates the two strings into '!ls whatever' and then that is executed as if you had typed it.


Q:

Dealing with missing values in SQL Server with Binary Column

I'm building a file, using SSMS, that will be an input to a machine learning program.  The output file will be the result of a query of several tables in a SQL Server 2008 R2 Express DB.
The query results in NULL values for some of the cells.  Currently I'm using the ISNULL() function to insert '0.00' when there is a NULL value but this is just a temporary measure as some values are actually '0.00' and this skews the calculation.
What raw data would look like:
  id        surveyResponseRate      personResponseRate
 001            .068                      .15
 002            0.00                     NULL
 003            .014                      .03
 004            NULL                      .20
 005            .068                     0.00
 ...             ...                      ...

What current process creates:
 id        surveyResponseRate      personResponseRate
 001            .068                      .15
 002            0.00                     0.00
 003            .014                      .03
 004            0.00                      .20
 005            .068                     0.00
 ...             ...                      ...

I'm curious if there's a way to create a binary column that is 0 if the value is actually 0.00 and 1 if it's actually 0.00 due a NULL value.
What I'd like to see:
 id        surveyResponseRate      personResponseRate  survRRNA      perRRNA
 001            .068                      .15              0            0
 002            0.00                     0.00              0            1
 003            .014                      .03              0            0
 004            0.00                      .20              1            0
 005            .068                     0.00              0            0
 ...             ...                      ...             ...          ...

Any suggestions for how to do this?

A:

Just add expressions for the new columns to the SELECT clause like this:
SELECT
  id,
  ISNULL(surveyResponseRate, 0) AS surveyResponseRate,
  ISNULL(personResponseRate, 0) AS personResponseRate,
  CASE WHEN surveyResponseRate IS NULL THEN 1 ELSE 0 END AS survRRNA,
  CASE WHEN personResponseRate IS NULL THEN 1 ELSE 0 END AS perRRNA
FROM ...


Q:

Is mathematical induction is about proving the expression or its validity over set of value assuming expression is correct.

Is mathematical induction is about proving the expression or is it about proving that expression is valid over a set of value(natural number), assuming expression is correct?

A:

Can you explain what you mean a little more? Induction can be described by a sort of domino effect. We prove that if we can knock over the first domino, and if one domino knocks over the succeeding domino, then we have knocked over all the dominoes. This can be used to prove a range of things that require the natural numbers. It can be something from a closed form expression of a recursive sequence, to facts about generators and relations of some algebra. Its use is very diverse.


Q:

Best strategy for a combinatorial game

Consider the following scenario. We have 20 balls and 100 boxes. We put all 20 balls into the boxes, and each box can contain at most one ball.
Now suppose we are given 5 chances to pick 20 out of 100 boxes. Let's say that each time we choose 20 boxes, they form a group of boxes. So in the end, we get to pick 5 groups (each consists of 20 boxes).
Each group of course, can contain 0 to 20 balls. In the end, we get a score, which is the maximum number of balls in any of the groups we chose.
Our goal is to maximize our score.
A bad strategy is to just randomly choose the groups, in which case we will likely get a score of 0. A smarter way is to utilize the pigeonhole principle and choose 5 disjoint groups, in which case the pigeonhole principle tells us that at least one of the groups contain 20/5 = 4 balls. Thus our minimum score becomes 4.
In the general case, where we have $N$ boxes and $k$ balls, and are given $N/k$ chances to pick groups of size $k$, the strategy I described above seems to be optimal, which guarantees a score of $k^2/N$. On the other hand, if we are given $O(2^N)$ chances to pick groups, we can guarantee a max score of $k$. My question is, what is the optimal strategy to maximize our score when we are only given a polynomial number of groups. Can we do better than a guaranteed score of $k^2/N$?
Edit: for simplicity, I am assuming that $N/k$ is a constant. So all the asymptotics are with respect to $N$.

A:

Let me address the case $k=N/2$. Consider a hypergraph whose edges are your groups. Then, basically, you are interested in the discrepancy of your hypergraph. The first estimate at the linked Wikipedia page, $\textrm{disc}\leq \lambda=\sqrt{2N\ln 2m}$, where $m$ is the nunber of edges, shows that you cannot guess more than $N/4+O(\sqrt{N\ln N})$ by a polynomial number of choices.
Surely, a similar argument may be applied for any case when the ratio $k/N$ is fixed, and even wider.

A:

The question is a little ambiguous as to what it is asking. But the idea is clear and it is a nice question. As I interpret it, I think the answer might be no and that designs and finite geometries might provide examples.
Since you want the guaranteed score ,not the expected one, I interpret your problem as this: We select some number $c$ of $k$ element subsets from an $N$ set, say $G_1,\cdots,G_c$. Call these guesses or groups.  Then someone else, knowing our choices, gets to pick $t \geq 1$ $k$-element subsets  $T_1,\cdots,T_t,$ the target(s). Our score is the maximum of $T_j \cap G_i$. With $c=\frac{N}k$ (if that is an integer) we can be sure of a score of $\lceil\frac{k}c\rceil.$ Then the question is to bound our best score if $c$ is a polynomial in the size of $M=\frac{N}k$.
A design theory question is "How large a collection of $k$-element blocks can be chosen from a set of size $N$ so that each pair has intersection no larger than $\mu?$" Given a highly optimal example we might consider taking some, most, or all but one, as guesses and then one (or all) of the rest as targets.
One ambiguity is how $k$ and $N$ grow relative to each other. In your example $k=20$ and $N=100.$ The question might be different for large $N$ and $k=\frac{N}5$ compared to $k=2\sqrt{N}.$ Another is if you are concerned with polynomial size with respect to $N$ or $M=\frac{N}k.$
Here is the base set for some examples I was thinking of:
There is a field $\mathbb{F}=\mathbb{F}_q$ with $q$ elements for $q$ a prime power. This is integers $\bmod q$ for $q$ a prime. The Affine geometry $AG(q,d)$ consists of the $N=q^d$ points $(x_1,\cdots,x_d)$ with $x_i \in \mathbb{F}$ with lines, planes and higher dimensional subspaces defined in the obvious way. In $AG(q,3)$ there are $q^3$ points, $q^4+q^3+q^2$ lines of size $q$ and $q^3+q^2+q$ planes with $q^2$ points.
An ovoid in $AG(q,3)$ is a subset of $q^2$ points, no three collinear. It turns out that these exist (for example the points $(s,t,s^2+st+at^2)$ where the polynomial $x^2+x+a$ does not factor in $\mathbb{F}$.) It turns out that exactly $q^2$ of the planes intersect the ovoid in a single point and the other $q^3+q$ intersect it in exactly $q^2$ points. (Note, ovoids are generally defined in a projective space, but I think I translated correctly)

I don't know that the $c=q^3+q^2+q$ planes are the optimal choice for that $c$ and $N=q^3, k=q^2.$ But it feels like they should be. Here $M=\frac{N}k=q$ so $c=O(M^3)$ and $\frac{k^2}N=q.$ If the target is an ovoid we have no improvement over the case $c=q$ of an arbitrary partition into $q$ groups.

I think there are $O(q^6)$ ovoids so we could take that many targets.
I suspect that we could take the guesses to be all the ovoids and the target to be a plane to have $c=O(M^6).$ Actually we could also throw all other planes into the guess collection. This would be nicer in a projective setting. I justify this by analogy below.

For  $N=q^{d},k=q$ and $c=q^{d-1}\frac{q^d-1}{q-1}=O(M^2)$ , I don't know that the lines of $AG(q,d)$ are an optimal choice of guesses, but again it seems as if it should be. Then having the target be the set of points $(1,t,t^2,\cdots,t^{d-1})$ for $t \in \mathbb{F}$ does allow a score of $2$ while  $\lceil \frac{k^2}N \rceil=\lceil \frac1{q^{2d-2}} \rceil=1.$

There might be other examples of this flavor.
An analogy for the first example with $\mathbb{R}^3$ is if the guesses are the planes and the target is a sphere. Then these are $2$ dimensional in a $3$ dimensional setting and the intersections are one dimensional (so $q^2,q^3$ and $q$ in some sense.) In that setting the collection of all ovoids $a(x-u)^2+b(y-v)^2+c(z-w)^2=1$ is $6$-dimensional. Then if the target is a plane the intersections will be one dimensional. I suspect this translates into an example over finite fields though I didn't check very carefully. If so, $N=q^3,k=q^2,c=O(M^6)$ and the score $q$ is no better than for $c=M.$


Q:

openURL from App Extension

On iOS 8 beta 2 it should be possible to use openUrl from app extension as written into the release notes:

however when I try to use this API (on Xcode 6 beta 2) I get the following error:

Beta 2 really fixed this issue or not?

A:

you may use this code:
[self.extensionContext openURL:url completionHandler:^(BOOL success) {
        NSLog(@"fun=%s after completion. success=%d", __func__, success);
    }];

the API document:
openURL:completionHandler:
you could also refer to this question:
openURL not work in Action Extension

A:

Accepted solution only works in Today extensions, a working solution in Swift 3.1 (tested in iOS10) for other extension-types:
You need to create your own URL Scheme, then add this function to your ViewController and call it with openURL("myScheme://myIdentifier")
//  Function must be named exactly like this so a selector can be found by the compiler!
//  Anyway - it's another selector in another instance that would be "performed" instead.
func openURL(_ url: URL) -> Bool {
    var responder: UIResponder? = self
    while responder != nil {
        if let application = responder as? UIApplication {
            return application.perform(#selector(openURL(_:)), with: url) != nil
        }
        responder = responder?.next
    }
    return false
}


Q:

How to stop Ember CLI's http-mock server throwing an error when there are websockets in one of the server files?

I have a websocket in one of my http-mock server files initialised as follows:
var WebSocketServer = require('ws').Server;
var socketServer = new WebSocketServer({port: 13434, path: "/update"});

and later in the file I have the following happen on connection:
socketServer.on('connection', function(ws) {
    ws.on('close', function(message) {
        clearInterval(sendResults);
    });

    ws.on('message', function(message) {
        handleClientMessage(ws, message);
    });

    sendResults = setInterval(function() {
        ws.send(JSON.stringify(getResultsFromEntries()));
    }, resultInterval);
});

However, whenever I edit any of the server files I get the following error:
File changed: "mocks/entry.js"

Just getting started with Ember? Please visit http://localhost:4200/ember-getting-started to get going

events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE 0.0.0.0:13434
    at Object.exports._errnoException (util.js:907:11)
    at exports._exceptionWithHostPort (util.js:930:20)
    at Server._listen2 (net.js:1250:14)
    at listen (net.js:1286:10)
    at net.js:1395:9
    at nextTickCallbackWith3Args (node.js:453:9)
    at process._tickCallback (node.js:359:17)

I'm guessing I need to detect when the file change happens and close the current websocket connection. On process exit doesn't seem to get called until the server dies, and then process.on('exit', function() {}) is called the number of times the server has refreshed. It doesn't bother me too much as I have a script that restarts ember server if it goes down, but other developers don't like the ember server going down when they edit a server file.  Any ideas?

A:

I ended up setting a new WebSocketServer as a property of process (which persists over the server getting restarted) then at the top of the file I close the previous WebSocketServer (if there was one):
if (process["updateSocketServer"]) {
    process["updateSocketServer"].close();
    process["updateSocketServer"] = undefined;
}

Then setup a new WebSocketServer:
process["updateSocketServer"] = new WebSocketServer({port: 13434, path: "/update"});

Then I did the following on connection:
process["updateSocketServer"].on('connection', function(ws) {
    // Connection code.
});


Q:

How to call a dll file from c#

I am trying to call a dll file from c#
The dll file is made from a java application using ikvm and for now all the code does is print hello world.
How do i call the dll file in my c# code and is it possible to create an application in java that will return a boolean value to my c# code?
Thanks for your time.

A:

I'm not sure I understand what you're trying to do, so apologies if I'm misreading. IKVM should translate your java code to a .NET dll or executable. After the "translation" you should be able to use the .dll more or less in the same way as you would with a "native" .NET code.
If your java application has a main method that prints "hello world" on the console, you should have converted it to a .NET executable (.exe) and not to a dll.
After converting it to a .exe (and assuming you're running it on Microsoft .NET on a windows system) you should just execute it.
As for the second part of your question, you can also create a dll (converted from java) that returns a boolean and consume it from a C# application.
See this tutorial for two examples of (pretty much exactly) what you're doing.


Q:

Repaired Records : Cell information from worksheet created from scratch

I'm receiving an error when opening my OpenXML created spreadsheet.  The error is as follows.
Repaired Records: Cell information from /xl/worksheets/sheet.xml part
Repaired Records: Cell information from /xl/worksheets/sheet2.xml part
Repaired Records: Cell information from /xl/worksheets/sheet3.xml part

The only thing I could find online that was helpful was this issue was the discussion of an algorithm which alters an individual cell multiple times causing the issue. Having said that, I'm going to link my Constructor for the SpreadsheetDocument as well as the three functions for updating a cell (which I do once).
I can supply any additional functions as needed, but I believe the problem is somewhere in the two listed below.
By the way,
 GetWorksheetPartByName
 InsertCellInWorksheet
 GetCell

should all working as intended.
The Actual Program
static void Main(string[] args)
    {
        //Full path for File
        const string newFile = "@C:\test.xlsx";

        //Constructor creates default worksheet called "mySheet"
        var spreadsheet = new XLSXHelper(newFile);

        //updating some cells.
        spreadsheet.UpdateCell("mySheet", "D2", "R", 2);
    }

Constructor
    public XLSXHelper(string filepath)
    {
        newFile = filepath;
        spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);
        this.workbookPart = spreadsheetDocument.AddWorkbookPart();
        workbookPart.Workbook = new Workbook();
        this.worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
        worksheetPart.Worksheet = new Worksheet(new SheetData());
        Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
        AppendChild<Sheets>(new Sheets());
        Sheet sheet = new Sheet()
        {
            Id = spreadsheetDocument.WorkbookPart.
                GetIdOfPart(worksheetPart),
            SheetId = 1,
            Name = "mySheet"
        };
        sheets.Append(sheet);
        workbookPart.Workbook.Save();
        spreadsheetDocument.Close();
    }

Update Cell
    public void UpdateCell(string worksheetName, string textToInsert, string columnName, uint rowIndex)
    {
        using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(newFile, true))
        {
            WorksheetPart worksheetPart = GetWorksheetPartByName(spreadSheet, worksheetName);
            if (worksheetPart != null)
            {
                InsertCellInWorksheet(columnName, rowIndex, worksheetPart);
                Cell cell = GetCell(worksheetPart.Worksheet,columnName, rowIndex);
                cell.CellValue = new CellValue(textToInsert);
                worksheetPart.Worksheet.Save();
            }
        }
    }

A:

If you are adding a string to a cell rather than a number (or a string that can be converted to a number) then you should use an inline string or a shared string instead of the CellValue.  You can only use CellValue if the value is numeric.
The XML generated when using CellValue looks something like:
<x:row>
  <x:c>
    <x:v>12345</x:v>
  </x:c>
</x:row>

when you use an inline string it looks like:
<x:row>
  <x:c t="inlineStr">
    <x:is>
      <x:t>Foo</x:t>
    </x:is>
  </x:c>
</x:row>

note the "is" node for inline string and that the cell type attribute is set to "inlineStr".
Here is C# code to generate correct XML for a cell containing text:
cell.DataType = CellValues.InlineString;
cell.InlineString = new InlineString() { Text = new Text(textToInsert) };

From what I have read using shared strings is preferable but using inline strings avoids the error and looks just fine when you open the file in Excel.

A:

I realize this is an old thread, but I just had the same error message pop up for a programmatically generated Excel sheet also.  My issue was that I had been setting the name of the worksheet with a name that had a forward slash in it.
Hopefully this helps someone else who stumbles on this thread as it's the most popular thread on the topic.


Q:

Is parameterisation needed in this instance?

Im designing a UWP app that uses an SQLite database to store its information. From previous research I have blearnt that using the SQLite function SQLiteConnection.Update() and SQLiteConnetion.Insert() functions are safe to use as the inputs are sanitised before entering in the database.
The next step I need to do is sync that data with an online database - in this case SQL Server - using a service layer as my go between. Given that the data was previously sanitised by the SQLite database insert, do I still need to parameterise the object values using the service layer before they are passed to my SQL Server database?
The simple assumption says yes because, despite them being sanitised by the SQLite input, they are technically still raw strings that could have an effect on the main database if not parameterised when sending them there.
Should I just simply employ the idea of "If in doubt, parameterise" ?

A:

I would say that you should always use SQL parameters. There are a few reasons why you should do so:

Security.
Performance. If you use parameters the reuse of execution plans could increase. For details see this article.
Reliability. It is always easier to make a mistake if you build SQL commands by concatenating strings.


Q:

compare two range and add missing entries by inserting a new row?

I have two ranges (A4:C13) and (E4:G13) and i want to compare column A (A4:A13) with Column E (E4:E13) if any of the value is missing in either columns then it should add missing value and fill other rows with 0 as shown attached image. Any idea how to achieve this?. so far i have found the following code it adds the value in one column but not in another. Should i run this code for another column or is there any other simple way to do it?.

Sub test()
Dim cl As Range

Set cl = Range("D1")

Do While cl.Row < 10
  If cl.Value <> cl.Offset(0, -3).Value Then
    cl.Offset(0, 1).Insert Shift:=xlDown
    cl.Insert Shift:=xlDown
    Set cl = cl.Offset(-1, 0)
  End If
  Set cl = cl.Offset(1, 0)
Loop
End Sub

A:

Try this code:
Sub Rng_Compare_B()
Dim RngA As Range, RngB As Range
Dim lValA As Long, lValB As Long
Dim vMatch As Variant, lRow As Long

    With ActiveSheet.Rows(4)
        Set RngA = .Cells(1).CurrentRegion
        Set RngB = .Cells(5).CurrentRegion
    End With

    Do

        lRow = 1 + lRow
        lValA = RngA.Cells(lRow, 1).Value2
        lValB = RngB.Cells(lRow, 1).Value2

        If lValA = Empty And lValB = Empty Then Exit Do

        Rem Compares Range A vs B - Adjust B
        If lValA <> Empty Then
            vMatch = 0
            On Error Resume Next
            vMatch = WorksheetFunction.Match(lValA, RngB.Columns(1), 0)
            On Error GoTo 0
            If vMatch = 0 Then
                RngB.Rows(lRow).Insert Shift:=xlDown
                RngB.Rows(lRow).Value = Array(lValA, 0, 0)
                GoTo Loop_Next
        End If: End If

        Rem Compares Range B vs A - Adjust A
        If lValB <> Empty Then
            vMatch = 0
            On Error Resume Next
            vMatch = WorksheetFunction.Match(lValB, RngA.Columns(1), 0)
            On Error GoTo 0
            If vMatch = 0 Then
                RngA.Rows(lRow).Insert Shift:=xlDown
                RngA.Rows(lRow).Value = Array(lValB, 0, 0)
        End If: End If

Loop_Next:
    Loop

End Sub


Q:

Check in a Twig template if the current route belongs from a specific Symfony2 bundle

A Symfony2 app is usually organized around bundles. Each bundle contains (many) controllers. Each controller should be mapped with a route.
Practically speaking, routes are usually stored in a specific file under the config folder of the bundle or, eventually, annotated inside each controller.
What I'm looking for is a way in Twig to identify if the current route belongs from a specific Symfony bundle. Is it possible?
Please, as a final remark, consider that the route name should follows the namespace of the controller, in my opinion, but it could also be a random but unique name, e.g. qwer_XX instead of ACME_HomeBundle_home. Hence, we cannot resort to a namespace-to-route-name association to do what I'm asking for.

A:

Looking at the Request object, I found a possible solution.
The controller is attached to the Request object, hence one can extract it in Twig from the string:
app.request.attributes.get('_controller')

and so retrieve the bundle name. For instance one can define through a TwigExtension such a filter function, e.g.
public function getFilters() {
    return array(
        ...//other filters
        'bundleName'=>new \Twig_Filter_Method($this, 'bundleNameFilter'),
    );
}

public static function bundleNameFilter($string){
  return strstr(substr(strstr($string, '\\'), 1), '\\', true);
}

Then, in twig use it as follows:
{{  app.request.attributes.get('_controller') | bundleName }}

Hope it helps.


Q:

JXLS grouping with xml markup

Is groupBy supported via xml configuration for JXLS 2.x?
Reason being I have a very basic grouping example that works with excel comments but simply refuses to work when I use the same configuration via xml markup. Output excel is grouped, but there is no data under each group.
I could not find any working examples online as well so either something is wrong with my syntax (see below) or groupBy is NOT supported in JXLS 2.x via xml markup.
excel comments (this works!)

detail_config.xml xml configuration (does not work!)
<xls>
    <area ref="Template!A1:D4">
        <each items="clockinouts" groupBy="employeeName" groupOrder="asc" ref="Template!A1:D3">
            <area ref="Template!A1:D3">
                <each items="_group.items" var="clockinout" ref="Template!A2:D2">
                    <area ref="Template!A2:D2"/>
                </each>
            </area>
        </each>
    </area>
</xls>

Java code to load xml configuration
public static void main(String args[]) throws IOException {
    List<ClockInOut> clockInOuts;

    clockInOuts = loadCSV();
    InputStream is = GroupingDemo.class.getResourceAsStream("detail_template.xlsx");

    try (OutputStream os = new FileOutputStream("target/detail.xlsx")) {
        Transformer transformer = TransformerFactory.createTransformer(is, os);
        try (InputStream configInputStream = GroupingDemo.class.getResourceAsStream("detail_config.xml")) {
            AreaBuilder areaBuilder = new XmlAreaBuilder(configInputStream, transformer);
            List<Area> xlsAreaList = areaBuilder.build();
            Area xlsArea = xlsAreaList.get(0);
            Context context = new Context();
            context.putVar("clockinouts", clockInOuts);
            xlsArea.applyAt(new CellRef("Template!A1"), context);
            transformer.write();
        }
    }
}

A:

Based on the source code, it looks like XML markup only supports item, var, dir, and ref attributes, hence the above behavior is expected. Raised an issue in the JXLS repository, so hopefully, this will get fixed in a future version.
Right now Excel markup seems to be the way forward.


Q:

MT / MD mismatch when compiling cryptopp despite no library dependencies

I'm currently trying to compile a static 64 bit version of cryptopp (more precisely, the cryptlib VS project) using MS Visual Studio 2013 on a Windows 8.1 machine. Since it is a static release build, I've set the Runtime Library to Multithreaded (/MT).
However the linker throws several of the following errors:
error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in adhoc.obj

In most of the similar cases I've found here and on google, this was caused by one library setting /MT and another one setting /MD. The weird thing about this case is that the linker does not include any libraries (except maybe some Visual-Studio-internal magic) and there are no additional include directories. The linker command line assembles as:
/OUT:"build\x64\static_release\cryptlib64.lib" /LTCG /MACHINE:X64 /NOLOGO

In the project file, I couldn't find any other <RuntimeLibrary> settings except for those on project level so I'd assume there is no .cpp file which has a /MD switch.
To sum it up, this means my library defines /MT, but something which is used by crytlib internally seems having /MD defined. Is there a way to find out what object/cpp/define/library/whatever has that switch defined?

A:

This linker diagnostic is a 100% accurate hint that you are in fact linking .obj or .lib files that were built wrong.  Almost always .lib files that you don't know about because you didn't have to explicitly list them as Additional Dependencies.  MSVC++ makes it pretty easy to specify link dependencies without having to use the setting, like using Add Reference or #pragma comment(lib, "yadayada.lib") in a source code file.  Very convenient of course, but not so visible when you are trying to troubleshoot linker errors like this.
It is easily diagnosable however, the linker has an option to show you what it is actually linking.  Use Project + Properties, Linker, Command Line and add the /VERBOSE option.  The linker now gets very chatty to the Output window, showing you every .lib file it loads and what symbols it uses from the .lib file.
The .lib name should be enough of a hint to know where to start looking, you ought to know the #include from there.  Whether you can really build with /MT is still up in the air, if it is an import library of a DLL then the odds dwindle rapidly.  Avoid forcing it, having more than one copy of the CRT in a process is fraught with trouble.


Q:

which delimeter to use while spliting String

I need to split this line string in each line, I need to get the third word(film name) but as you see the delimeter is one big blank character in some cases its small like before the numbers at the end or its big as in front of numbers at front.
I tried using string split with(" ") regex, and also \t but get the out of the bounds error.
400115305   Lionel_Atwill   The_Song_of_Songs_(1933_film)   7587
400115309   Brian_Aherne    A_Night_to_Remember_(1943_film) 7952

Did anyone have the same problem?

A:

Have you tried to split on all whitespaces like this: line.split("\\s+"). The split method supports regular expressions.
edit: sorry, should be \\s indeed.
The following code
String line = "400115305   Lionel_Atwill   The_Song_of_Songs_(1933_film)   7587";
System.out.println(Arrays.toString(line.split("\\s+")));

returns with [400115305, Lionel_Atwill, The_Song_of_Songs_(1933_film), 7587] on my machine (Java 6 SE).

A:

The solution was str.split("\\t");


Q:

how to merge some same keys from an array

I getting this array as a result for mysql query. I want to remove the duplicate hotel_id hotel_name from the array but keeping other data.
array(6) {
    [0] => array(17) {
        ["id"] => string(1) "1" ["hotel_id"] => string(1) "1" ["name"] => string(31) "Vilamendhoo Island Resort & Spa" ["city"] => string(11) "Vilamendhoo" ["country"] => string(8) "Maldives" ["image"] => string(6) "01.jpg" ["address"] => string(0) "" ["wifi"] => string(1) "1" ["atoll"] => string(14) "South Ari Atol" ["type"] => string(6) "Resort" ["stars"] => string(1) "4" ["room_id"] => string(1) "1" ["room_type"] => string(29) "Garden view room - full board" ["description"] => string(47) "Limited Time Offer. Rate includes 20% discount!" ["availability"] => string(12) "only 4 rooms" ["rates"] => string(2) "25" ["breakfast"] => string(1) "1"
    } [1] => array(17) {
        ["id"] => string(1) "2" ["hotel_id"] => string(1) "1" ["name"] => string(31) "Vilamendhoo Island Resort & Spa" ["city"] => string(11) "Vilamendhoo" ["country"] => string(8) "Maldives" ["image"] => string(6) "01.jpg" ["address"] => string(0) "" ["wifi"] => string(1) "1" ["atoll"] => string(14) "South Ari Atol" ["type"] => string(6) "Resort" ["stars"] => string(1) "4" ["room_id"] => string(1) "2" ["room_type"] => string(24) "Beach villa - full board" ["description"] => string(47) "Limited Time Offer. Rate includes 20% discount!" ["availability"] => string(9) "Available" ["rates"] => string(2) "50" ["breakfast"] => string(1) "1"
    } [2] => array(17) {
        ["id"] => NULL ["hotel_id"] => NULL ["name"] => string(28) "Kuredu Island Resort and Spa" ["city"] => string(9) "Kuredhdhu" ["country"] => string(8) "Maldives" ["image"] => string(14) "12137_Main.jpg" ["address"] => string(0) "" ["wifi"] => NULL ["atoll"] => string(15) "Lhaviyani Atoll" ["type"] => string(6) "Resort" ["stars"] => string(1) "4" ["room_id"] => NULL ["room_type"] => NULL ["description"] => NULL ["availability"] => NULL ["rates"] => NULL ["breakfast"] => NULL
    } [3] => array(17) {
        ["id"] => NULL ["hotel_id"] => NULL ["name"] => string(39) "Lily Beach Resort & Spa - All Inclusive" ["city"] => string(11) "Huvahendhoo" ["country"] => string(8) "Maldives" ["image"] => string(14) "41480_Main.jpg" ["address"] => string(0) "" ["wifi"] => NULL ["atoll"] => string(15) "South Ari Atoll" ["type"] => string(6) "Resort" ["stars"] => string(1) "5" ["room_id"] => NULL ["room_type"] => NULL ["description"] => NULL ["availability"] => NULL ["rates"] => NULL ["breakfast"] => NULL
    } [4] => array(17) {
        ["id"] => NULL ["hotel_id"] => NULL ["name"] => string(26) "Vakarufalhi Island Resort " ["city"] => string(11) "Vakarufalhi" ["country"] => string(8) "Maldives" ["image"] => string(14) "41483_Main.jpg" ["address"] => string(62) "ADh. Vakarufalhi, South Ari Atoll, Maldives Islands, Maldives " ["wifi"] => NULL ["atoll"] => string(15) "South Ari Atoll" ["type"] => string(6) "Resort" ["stars"] => string(1) "4" ["room_id"] => NULL ["room_type"] => NULL ["description"] => NULL ["availability"] => NULL ["rates"] => NULL ["breakfast"] => NULL
    } [5] => array(17) {
        ["id"] => NULL ["hotel_id"] => NULL ["name"] => string(29) "Banyan Tree Vabbinfaru Resort" ["city"] => string(10) "Vabbinfaru" ["country"] => string(8) "Maldives" ["image"] => string(14) "41485_Main.jpg" ["address"] => string(0) "" ["wifi"] => NULL ["atoll"] => string(15) "South Ari Atoll" ["type"] => string(6) "Resort" ["stars"] => string(1) "5" ["room_id"] => NULL ["room_type"] => NULL ["description"] => NULL ["availability"] => NULL ["rates"] => NULL ["breakfast"] => NULL
    }
}

A:

Its much easier if you use the index name (hotel name) on this one and assign them to a new array. The first above answer wont be able to filter the same value because they are different (observe the index id of the first and second nested array, they wont match). Consider this example:
$original_values = array( array( 'id' => '1', 'hotel_id' => '1', 'name' => 'Vilamendhoo Island Resort & Spa', 'city' => 'Vilamendhoo', 'country' => 'Maldives', 'image' => '01.jpg', 'address' => '', 'wifi' => '1', 'atoll' => 'South Ari Atoll', 'type' => 'Resort', 'stars' => '4', 'room_id' => '1', 'room_type' => 'Garden view room - full board', 'description' => 'Limited Time Offer. Rate includes 20% discount!', 'availability' => 'only 4 rooms', 'rates' => '25', 'breakfast' => '1', ), array( 'id' => '2', 'hotel_id' => '1', 'name' => 'Vilamendhoo Island Resort & Spa', 'city' => 'Vilamendhoo', 'country' => 'Maldives', 'image' => '01.jpg', 'address' => '', 'wifi' => '1', 'atoll' => 'South Ari Atoll', 'type' => 'Resort', 'stars' => '4', 'room_id' => '1', 'room_type' => 'Garden view room - full board', 'description' => 'Limited Time Offer. Rate includes 20% discount!', 'availability' => 'only 4 rooms', 'rates' => '25', 'breakfast' => '1', ), array( 'id' => NULL, 'hotel_id' => NULL, 'name' => 'Kuredu Island Resort and Spa', 'city' => 'Kuredhdhu', 'country' => 'Maldives', 'image' => '12137_Main.jpg', 'address' => '', 'wifi' => NULL, 'atoll' => 'Lhaviyani Atoll', 'type' => 'Resort', 'stars' => '4', 'room_id' => NULL, 'room_type' => NULL, 'description' => NULL, 'availability' => NULL, 'rates' => NULL, 'breakfast' => NULL, ), array( 'id' => NULL, 'hotel_id' => NULL, 'name' => 'Lily Beach Resort & Spa - All Inclusive', 'city' => 'Huvahendhoo', 'country' => 'Maldives', 'image' => '41480_Main.jpg', 'address' => '', 'wifi' => NULL, 'atoll' => 'South Ari Atoll', 'type' => 'Resort', 'stars' => '5', 'room_id' => NULL, 'room_type' => NULL, 'description' => NULL, 'availability' => NULL, 'rates' => NULL, 'breakfast' => NULL, ), array( 'id' => NULL, 'hotel_id' => NULL, 'name' => 'Vakarufalhi Island Resort ', 'city' => 'Vakarufalhi', 'country' => 'Maldives', 'image' => '41483_Main.jpg', 'address' => 'ADh. Vakarufalhi, South Ari Atoll, Maldives Islands, Maldives ', 'wifi' => NULL, 'atoll' => 'South Ari Atoll', 'type' => 'Resort', 'stars' => '4', 'room_id' => NULL, 'room_type' => NULL, 'description' => NULL, 'availability' => NULL, 'rates' => NULL, 'breakfast' => NULL, ), array( 'id' => NULL, 'hotel_id' => NULL, 'name' => 'Banyan Tree Vabbinfaru Resort', 'city' => 'Vabbinfaru', 'country' => 'Maldives', 'image' => '41485_Main.jpg', 'address' => '', 'wifi' => NULL, 'atoll' => 'South Ari Atoll', 'type' => 'Resort', 'stars' => '5', 'room_id' => NULL, 'room_type' => NULL, 'description' => NULL, 'availability' => NULL, 'rates' => NULL, 'breakfast' => NULL, ),);
$new_values = array();
foreach($original_values as $key => $value) {
    $new_values[$value['name']][] = $value;
}

// simple reindex
$new_values = array_values($new_values);

echo '<pre>';
print_r($new_values);

Sample Output
Edit: Simple output
foreach($new_values as $key => $values) {
    foreach($values as $element) {
        foreach($element as $index => $value) {
            echo $index . ' => ' . $value . '<br/>';
        }
    }
}


Q:

Continuous compounding in practice

A common explanation for the mathematical constant e (2.71828...) is that it is the factor by which an investment would grow at 100% interest rate over a period if it is continuously compounded.
In other words, if you were to invest 1 million dollars for one year at a rate of 100%, after one year, the balance would show about 2.71 M$ (or e M$)
However, it is not a case I have ever seen. We often see monthly compounding, sometimes daily, but I've never seen continuous compounding.
Does continuous compounding exist in practice? Is it ever part of a financial product offering? If so, in which cases might it be used?

A:

Continuous compounding at an interest rate of 100% is unlikely to be used in practice. More generally, if the interest rate is x% per annum and interest is compounded n times during the year (so that at the end of each sub-interval,
the amount increases by a factor of (1 + (x/100)/n) ), then the amount has
increased over the year by a factor of

(1 + (x/100)/n)^n which is approximately e^(x/100) = 1 + (x/100) + (x/100)^2/2 + (x/100)^3/6 + .... when n is large.

Mathematically, e^(x/100) is the limiting value of (1+(x/100)/n)^n as n
tends to infinity.
Heuristically, (1 + (x/100)/n)^n gets closer and closer to e^(x/100)
as n gets larger and
larger (from quarterly to monthly to daily to hourly .... compounding).
So, let us turn the problem around.  If the annual percentage
yield (not the same as the APR) is specified as y% per annum,
then let x be the solution to the equation

e^(x/100) - 1 = (y/100)

which gives x = 100 log_e (1 + y/100)% as the rate that would be quoted
as the APR for continuous compounding while the APR for monthly
compounding would be quoted as the solution to

(1 + (x/100)/12)^12 = 1 + y/100

which gives x = 12 times 100 times the 12th root of (1 + y/100) % as the APR.
As a comparison, an annual percentage yield of 5% per annum corresponds to a
quoted rate (APR) of 4.88894...% per annum compounded monthly and 4.8790...% per
annum compounded continuously.  Weekly and daily compounding would
result in quotes somewhere in between these two figures, but as
you can see, for a given annual percentage yield, continuous compounding
really does
not make that the APR significantly smaller than the more
common monthly compounding used for mortgages, auto loans, and
the like.


Q:

Does the category of local rings with residue field $F$ have an initial object?

Let $F$ be a field. Does the category $C_F$ of local rings with residue field isomorphic to $F$ have an initial object?
This is, for instance, true if $F=\mathbb{F}_{p}$ for some prime $p$: If $R$ is a local ring with residue field $\mathbb{F}_{p}$, then any $x\in\mathbb{Z}\setminus(p)$ must map to something invertible under the morphism $\mathbb{Z}\longrightarrow R$. Hence that morphism factors as $\mathbb{Z}\longrightarrow\mathbb{Z}_{(p)}\longrightarrow R$; thus $\mathbb{Z}_{(p)}$ is the initial object.
But what happens in the more general case? I guess it should be true at least if $F$ is of finite type over $\mathbb{Z}$, but I have no idea how to prove it.
(EDIT - To avoid any confusion: I am talking about an initial object in the category of local rings $R$ with a fixed surjection $R\longrightarrow F$.)

A:

Let $\mathbb{F_4}=\{0,1,w,1+w\}$ be the field of 4 elements.  Suppose $R$ is the initial object in the category described in the question for the field $\mathbb{F_4}$.  Then $R$ must contain some element $x$ which maps to $w\in\mathbb{F_4}$.  Thus we have a map $f\colon S\to R$, where $S=\mathbb{Z}[y]_M$, sending $y \mapsto x$.  Here $M$ is the maximal ideal of $\mathbb{Z}[y]$ containing $2,1+y+y^2$.
The following composition must be the identity: $$R \to S \stackrel f \to  R
$$
Thus  $R=S/I$ for some ideal $I\subset M$. Further we know $I\neq 0$ as $S$ cannot be the initial object: there are multiple distinct maps $S\to S$, such as the identity map and the map sending $y\mapsto y+2$.
Under the composition $S \stackrel f \to  R\to S$, we have $y\mapsto p/q$, for some $p,q$ integer polynomials in $y$. We know $p/q$ is not a rational number as $p/q\mapsto w\in\mathbb{F_4}$.  Thus $p/q$ is a non-constant rational function in one variable, taking infinitely many values, which cannot all satisfy the same polynomial over the integers.
On the other hand, as $I\neq 0$ there must be a polynomial over the integers satisfied by $p/q$.  This gives us the desired contradiction.


Q:

$\mathbb{Z}_5[x]$ is a UFD

Prove that $\mathbb{Z}_5[x]$ is a unique factorization domain.
My approach is to prove that $\mathbb{Z}_5[x]$ is a PID, which implies that it is a UFD.
Proof:
Suppose there exists an ideal $I$ in $\mathbb{Z}_5[x]$ such that it is generated by two or more elements of $\mathbb{Z}_5[x]$. That is, $I = \langle g_1(x), g_2(x), ..., g_n(x)\rangle$. Then $I=\{a_1(x)g_1(x)+a_2(x)g_2(x)+...+a_n(x)g_n(x):a_i(x)\in \mathbb{Z}_5[x] \}$. Consider $\max\{a_i(x)g_i(x)\}=\deg_{max} (I)$. Then, since $\mathbb{Z}_5$ is a PID, $\langle a_i(x)g_i(x)\rangle = \langle g_1(x), g_2(x), ..., g_n(x)\rangle$. Hence, $\mathbb{Z}_5[x]$ is a PID. This implies that $\mathbb{Z}_5[x]$ is a UFD.
It would be interesting to know one's opinion on my proof.

A:

Hint:
You have to use that, in a polynomial ring over a field, you can perform Euclidean divisions, and consider a non-zero polynomial of least degree in the ideal.


Q:

How to move Primefaces-Upload-Temp-Files instead of doing a time intensive copy process?

I want to upload files larger than 2 GB with Java EE with the use of primefaces. In general that it's not that big deal, but I have a little problem. The usually way with PrimeFaces is to upload a file, have that UploadedFile-Object, obtain the InputStream from that and then write it to disk.
But writing to disk large files is a time intensive task. Instead I would like to find the uploaded file in the file system and then move it to the folder, where I store all the files, because moving files is not wasting time.
So, according to this question here I figured out to set PrimeFaces-Tmp-folder and the size-limit, when files will put there. Now every uploaded file just goes directly into that folder. The point is, that I now have a file on disk, while the user is uploading - and not creating it afterwards.
So far, so good. I could identify the file and just move it (although it has a strange name). But pointing to Primefaces Userguide (Page 187), this Tmp-Folder is just used internally. And I even would steal the contents of the UploadedFile-Object from Primefaces. Seems not to be a clean solution to me.
Any hints how to achieve this ?
I also saw this question. Could also be my title, but it's not what I am looking for.
EDIT:
Because of the comment, some code. First I am collecting the UploadFile-Objects in the fileUploadListener:
   public void handleFileUpload(FileUploadEvent event) throws IOException {
    FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage(null, msg);

    getUploadedFilesDTO().add(new UploadedFileDTO(event.getFile(), uploadedFilesCounter));
    uploadedFilesCounter++;

}

Second in the EJB I am calling copyFile for every UploadedFile-Object:
private void copyFile(UploadedFile uploadedFile, String randomFilename) throws IOException {

    InputStream originalFile = uploadedFile.getInputstream();
    OutputStream fileOutput = null;

    try {
        fileOutput = new FileOutputStream("/pvtfiles/" + randomFilename);
        IOUtils.copy(originalFile, fileOutput);
    } finally {
        IOUtils.closeQuietly(fileOutput);
        IOUtils.closeQuietly(originalFile);
    }
}

A:

By creating your own filter It will not create temp files. Please read my answer below on another post
https://stackoverflow.com/a/19581257/185022


Q:

Writing logarithm formulas on LibreOffice Math

How to write a logarithm (LOG) formula on a base different than base 10 on LibreOffice Math?
In my case, it  seems to only allow me to change the value inside the formula but not the base.

A:

How do I write a logarithm (LOG) formula with a base different to base 10?
To change the base use log_x(y) where x is the base.
Example
To display the logarithm to base 3 of 10 use the following expression:
log_3(10)


Q:

It is possible to make a library that can be used in many languages?

It is possible to make a library that can be used in many languages?  Or at least a library that can be used in several languages.
If so, what documentation do you recommend me to achieve this?

A:

Yes, by providing a C interface to it. Most if not all mayor languages provide the ability to bind to C functions.

A:

In .NET, any assembly you create can be used by any other .NET language.  So if you create a library in C#, you can make use of it in J#, C++.NET, VB.NET, etc.


Q:

Oracle SQL - replace null with previous known value

I am looking to replace null values from my table's column with the previous known value from that column. I have tried and searched many things but I can't seem to figure out how to do it. If someone could help that would be great. Thanks in advance!
PROCESSO    DATAM   HOURM TEMP_T1
-------- ---------- ----- -------
508410   2015.03.29  19   36.15
508410   2015.03.30  11   NULL
508410   2015.03.30  14   NULL
508410   2015.03.30  15   35.36
508410   2015.03.30  23   36.52
508410   2015.03.31  11   NULL
508410   2015.04.01  02   37.06

I want it to appear like this:
PROCESSO    DATAM   HOURM TEMP_T1
-------- ---------- ----- -------
508410   2015.03.29  19   36.15
508410   2015.03.30  11   36.15
508410   2015.03.30  14   36.15
508410   2015.03.30  15   35.36
508410   2015.03.30  23   36.52
508410   2015.03.31  11   36.52
508410   2015.04.01  02   37.06

A:

Try last_value analytic function:
SELECT "PROCESSO", "DATAM", "HOURM",
       last_value( "TEMP_T1" ignore nulls )
       OVER (order by "DATAM"
             rows between unbounded preceding and current row
       ) as new_temp
FROM table1

Demo ==> http://sqlfiddle.com/#!4/48207/2
=========== EDIT ===================
If you want to update the table, and there is no primary key (unique identifiers), you can try a solution based on rowid pseudocolumn
==>http://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns008.htm) :
MERGE INTO table1 t1
USING (
    SELECT rowid rd, "PROCESSO", "DATAM", "HOURM",
           last_value( "TEMP_T1" ignore nulls )
           OVER (order by "DATAM"
                 rows between unbounded preceding and current row
           ) as new_temp
    FROM table1
) x
ON (t1.rowid = x.rd)
WHEN MATCHED THEN UPDATE SET t1."TEMP_T1" = x.new_temp
;

Demo ==> http://sqlfiddle.com/#!4/5a9a61/1

However you must ensure that there is no another process that deletes and inserts rows from/into this table while running the update, because when a row is deleted from the table, Oracle can assigng it's rowid to another, new row.


Q:

How to assert mock object's function invocation's object arguments

Consider
class Foo {
    public $att;
    public function __construct ( $a ) { $this->att = $a; }
}

class Some {
    public function callMe ( Foo $f ) {}
}

// class I want to test
class SuT {
    public function testMe ( Some $s ) {
        echo $s->callMe( new Foo('hi') );
    }
}

I want to check whether Sut::testMe() properly invokes Some::callMe(). Since the parameter is a (Foo) object (not a scalar type), I can't figure out how to call PHPUnit's with() to run assertions on it. There is an assertAttributeEquals method for example, but how do I feed it the invocation's argument?
What I'd like to do is this:
class SuTTest extends PHPUnit_Framework_TestCase {
    public function testSuT () {
        $stub = $this->getMock( 'Some' );
        $stub->expects( $this->once() )->method( 'callMe' )
            ->with( $this->assertAttributeEquals('hi', 'att', $this->argument(0) );

        /*
         * Will $stub->callMe be called with a Foo object whose $att is 'hi'?
         */
        $sut = new SuT();
        $sut->testMe( $stub );
    }
}

A:

Even though the question is already answered fully (how to assert attribute of object passed as argument to mock) I think it's worth noting that PHPUnit supports a callback constraint to be passed to with().
I kept bumping with this thread while trying to find out how to run further assertions on the mocked object arguments. For instance, I needed to check the return value of some method. Obviously, and for sanity sake, there is no methodReturnValueEqualTo() equivalent to the attribute assertion used in the answer above.
Fortunately, PHPUnit does support (as of 3.7 at least) a callback constraint, which makes a lot of sense and is something you can find in specialised Mock libraries like Mockery.
Current PHPUnit version docs state the following:

The callback() constraint can be used for more complex argument verification. This constraint takes a PHP callback as its only argument. The PHP callback will receive the argument to be verified as its only argument and should return TRUE if the argument passes verification and FALSE otherwise.

Therefore, using the callback constraint, the OP example can now be expressed as:
class SuTTest extends PHPUnit_Framework_TestCase {
    public function testSuT () {
        $stub = $this->getMock('Some');
        $stub->expects($this->once())
            ->method('callMe')
            ->with($this->callback(function($arg) {
                    return ($arg instanceof Some) && ($arg->att === 'hi');
                })
            );

        /*
         * Will $stub->callMe be called with a Foo object whose $att is 'hi'?
         */
        $sut = new SuT();
        $sut->testMe($stub);
    }
}

And a test fail would look something like:

1) SuTTest::testSuT
  Expectation failed for method name is equal to <string:callMe> when invoked 1 time(s)
  Parameter 0 for invocation Some::callMe(Foo Object (...)) does not match expected value.
  Failed asserting that Foo Object () is accepted by specified callback.

You can now run any logic on that argument.
Even better, despite not being a documented feature in PHPUnit docs, you can actually use assertions and get the benefits of assertion error messages:
class SuTTest extends PHPUnit_Framework_TestCase {
    public function testSuT () {
        // alias to circumvent php closure lexical variable restriction
        $test = $this;
        // proceed as normal
        $stub = $this->getMock('Some');
        $stub->expects($this->once())
            ->method('callMe')
            // inject the test case in the closure
            ->with($this->callback(function($arg) use ($test) {
                    // use test assertions
                    $test->assertInstanceOf('Some', $arg);
                    $test->assertAttributeEquals('hi', 'att', $arg);
                    // return true to satisfy constraint if all assertions passed
                    return true;
                })
            );

        /*
         * Will $stub->callMe be called with a Foo object whose $att is 'hi'?
         */
        $sut = new SuT();
        $sut->testMe( $stub );
    }
}

Don't really know how future proof is this strategy of using assertions and returning true. It is not documented and there is a tradeoff in the error message. You no longer get the parameter constraint message, so if you set assertions on multiple arguments you will have to infer, if possible, which one failed. But you do get a better description of the failed assertion inside the closure.

1) SuTTest::testSuT
  Expectation failed for method name is equal to <string:callMe> when invoked 1 time(s)
  Failed asserting that two strings are equal.
  --- Expected
  +++ Actual
  @@ @@
  -'hi'
  +'no'

Hope this helps anyone facing a similar problem.

A:

You just pass the expected values to the "with" method.
->with(1, $object, "paramThree");

you can also pass in a range of phpUnit assertions instead of the parameters (it defaults to equal to)
->with(1, $this->equalTo($object), "paramThree");

so for objects you would use $this->isInstanceOf("stdClass") as a parameter to ->with
For the list of possible assertions look into: PHPUnit/Framework/Assert.php
for functions that return a new PHPUnit_Framework_Constraint

Small Demo
The first testcase just matches 2 arguments and works
The second one matches two and fails on argument 2
The last one tests that the passed in object is of type stdClass
<?php

class MockMe {
    public function bla() {

    }
}

class Demo {

    public function foo(MockMe $x) {
        $x->bla(1, 2);
    }

    public function bar(MockMe $x) {
        $x->bla(1, new stdClass());
    }

}

class DemoTest extends PHPUnit_Framework_TestCase {

    public function testWorks() {
        $x = new Demo();
        $mock = $this->getMock("MockMe");
        $mock->expects($this->once())->method("bla")->with(1,2);
        $x->foo($mock);
    }

    public function testFails() {
        $x = new Demo();
        $mock = $this->getMock("MockMe");
        $mock->expects($this->once())->method("bla")->with(1,3);
        $x->foo($mock);
    }

    public function testObject() {
        $x = new Demo();
        $mock = $this->getMock("MockMe");
        $mock->expects($this->once())->method("bla")->with(1, $this->isInstanceOf("stdClass"));
        $x->bar($mock);
    }
}

Results in:
phpunit DemoTest.php
PHPUnit 3.5.13 by Sebastian Bergmann.

.F.

Time: 0 seconds, Memory: 4.25Mb

There was 1 failure:

1) DemoTest::testFails
Failed asserting that <integer:2> matches expected <integer:3>.

...DemoTest.php:12
...DemoTest.php:34

FAILURES!
Tests: 3, Assertions: 2, Failures: 1.

A:

This is a simple example that does what you need:
$mock->expects ($this->once())
     ->method ('dummyFunction')
     ->with ($this->logicalAnd ($this->isInstanceOf ('DummyClass')
                               ,$this->attributeEqualTo ('attribute1', 1001)
                               ,$this->attributeEqualTo ('attribute2', 200)))
     ->will ($this->returnValue (null));

And the rest of code:
class DummyClass {
   private $attribute1 = 1001;
   private $attribute2 = 200;
}
function dummyFunction (DummyClass $p) {...}
dummyFunction (new DummyClass());

I hope that I've helped you


Q:

summing up number of angular.foreach loop

I'm trying to sum ups a few numbers in what should be a simple function. I iterate through my list of numbers and can see form the log that I am seeing each number.
Then I have the following where I have a var that holds the sum and should return it.
But nothing happens!
Here is the code:
  angular.extend(self, {

    getTotalGood : function(){
      var total = 1;
      angular.forEach( self.myproducts, function( value, key ){
        console.log(key + ' : ' + value.product.cost);
        total = value.product.cost;
      })
      return total;
    }

  })

  self.getTotalGood();

A:

Change your method like below:
 getTotalGood : function(){
  var total = 0;
  angular.forEach( self.myproducts, function( value, key ){
    console.log(key + ' : ' + value.product.cost);
    total += value.product.cost;
  })
  console.log("total: " + total);
  return total;
}


Q:

Pygame colliderect precision issue

I'm designing a Pacman clone for a University exam.
I use pygame and I have some problems in the handling of the ghosts collisions with the wall.
For example when the ghost collides with the wall on the left side, the left side of the ghost's rectangle takes the value of the right side of the  wall's rectangle:
rectGhost.left = blockRect.right

But after multiple collision (on the left of wall) the ghost go over the wall, as if with motion the ghost rectangle overcome the wall and the collision is detected to the left of the wall, and then moves to the left side of the rectangle of the phantom to the right of the wall.
Collision issue example
This is the Ghost's class:
import character, random
from globalVar import *

class ghost(character.character):

    def __init__(self, imgSprite):
        super(ghost, self).__init__(imgSprite)
        self._direction = random.choice([LEFT, RIGHT, UP, DOWN])

    def catch(self, wall):

        # Keep the direction
        if self._direction ==  LEFT:
            self.moveToLeft()
        if self._direction ==  RIGHT:
            self.moveToRight()
        if self._direction ==  UP:
            self.moveToUp()
        if self._direction ==  DOWN:
            self.moveToDown()

        # Get ghost position
        rectGhost = self.getRectSprite()

        # Collision with wall
        for blockRect in wall:
            if rectGhost.colliderect(blockRect): # Check collision with the wall (wall contain a list of Rect object)

                if self._direction ==  LEFT:
                    rectGhost.left = blockRect.right
                    self._direction = random.choice([RIGHT, UP, DOWN])

                if self._direction ==  RIGHT:
                    rectGhost.right = blockRect.left
                    self._direction = random.choice([LEFT, UP, DOWN])

                if self._direction ==  UP:
                    rectGhost.top = blockRect.bottom
                    self._direction = random.choice([LEFT, RIGHT, DOWN])

                if self._direction ==  DOWN:
                    rectGhost.bottom = blockRect.top
                    self._direction = random.choice([LEFT, RIGHT, UP])

This is the superclass Character :
from globalVar import *

class character:

    def __init__(self, imgSprite):
        self._imageSprite = imgSprite
        self._spriteRect = self._imageSprite.get_rect()
        self._dimStep = 10
        self._direction = 0

    def setCharPos(self, charPos):
        self._spriteRect.centerx = charPos[0]
        self._spriteRect.centery = charPos[1]

    def moveToLeft(self):
        self._spriteRect.x -= self._dimStep

    def moveToRight(self):
        self._spriteRect.x += self._dimStep

    def moveToUp(self):
        self._spriteRect.y -= self._dimStep

    def moveToDown(self):
        self._spriteRect.y += self._dimStep

    def drawSprite(self):
        WINDOWSURF.blit(self._imageSprite, self._spriteRect)

    def getRectSprite(self):
        return self._spriteRect

    def setDirection(self, direction):
        self._direction = direction

This is the main:
def main():

    thisPacman = pacman.pacman(pacmanCImg) # Ghot obj

    thisGhost_a = ghost.ghost(ghostAImg) # Ghot obj

    thisGhost_o = ghost.ghost(ghostOImg) # Ghot obj

    thisGhost_p = ghost.ghost(ghostPImg) # Ghot obj

    thisGhost_r = ghost.ghost(ghostRImg) # Ghot obj

    # Coords of wall
    wall = thisLevel.getBlocksListPos()

    # Coords of Ghosts
    ghostsStartPos = thisLevel.getGhostsPos()

    # Start pos azure
    thisGhost_a.setCharPos(ghostsStartPos[0])

    # Start pos ghost orange
    thisGhost_o.setCharPos(ghostsStartPos[1])

    # Start pos ghost purple
    thisGhost_p.setCharPos(ghostsStartPos[2])

    # Start pos ghost red
    thisGhost_r.setCharPos(ghostsStartPos[3])

    while running:

        thisGhost_a.catch(wall)
        thisGhost_o.catch(wall)
        thisGhost_p.catch(wall)
        thisGhost_r.catch(wall)

        thisGhost_a.drawSprite()
        thisGhost_o.drawSprite()
        thisGhost_p.drawSprite()
        thisGhost_r.drawSprite()

        pygame.display.update()
        FPSCLOCK.tick(8)

Any ideas?
Many thanks for your attention!

A:

The solution is here, Just as David Jay Bredy explained.
Collision with the wall.
        #pdb.set_trace() # Debugging

        for blockRect in wall:
            if rectGhost.colliderect(blockRect):

                while 1:# Cycle that solve the problem
                    if self._direction ==  LEFT:
                        rectGhost.left = blockRect.right
                        self._direction = random.choice([RIGHT, UP, DOWN])
                        break

                    if self._direction ==  RIGHT:
                        rectGhost.right = blockRect.left
                        self._direction = random.choice([LEFT, UP, DOWN]
                        break

                    if self._direction ==  UP:
                        rectGhost.top = blockRect.bottom
                        self._direction = random.choice([LEFT, RIGHT, DOWN]
                        break

                    if self._direction ==  DOWN:
                        rectGhost.bottom = blockRect.top
                        self._direction = random.choice([LEFT, RIGHT, UP])
                        break


Q:

Secure https with nginx for Private IP address

Problem : I want to run nginx with https, like https://192.168.100.110
What I've tried : I've followed the quick guide at https://www.humankode.com/ssl/create-a-selfsigned-certificate-for-nginx-in-5-minutes , I am able to open https://localhost properly on chrome but i want the self signed certificate to work with https://192.168.100.110
Please let me know if more clarification is needed.

A:

Update : So the solution was pretty simple.
For IP addresses to work with the Subject Alternative Names we must provide the IP inside of the ext files that are used for creating certificate
subjectAltName = @alt_names
extendedKeyUsage = serverAuth

[alt_names]
DNS.1   = localhost
IP.1 = 192.168.98.18

Now it's working properly
Edit: You can see the complete steps that I've followed from here: https://medium.com/@pavanskipo/how-to-secure-a-private-ip-address-with-https-nginx-ubuntu-ef8374dbfa4e.


Q:

Textarea is taking lot of time to validate text when pasted from notepad using RegExp in javascript

I have a jsp page where I am validating the for characters entered in textarea. I pasted the following sentence in textarea:

Exception (Clause No. 2 pg.).

Then I clicked button which validates the characters entered in textarea. IE hangs for 5 min and after that it gives me desired alert. However if type same thing in textarea alert comes instantly. Code is working fine for firefox.
this code is in .js file
function SpecialCharacter(obj){

    if(Trim(obj.value) != "")
    {
        var objRegExp  = new RegExp("^[a-zA-Z0-9- \b]+([-:,.&=/a-zA-Z0-9 \b]+)*$");
        var errMsg = "Please enter alpha numeric and following special characters(:,.&=/) only.";
        if (! obj.value.match(objRegExp))
        {
            alert(errMsg);
            obj.focus();
            return false;
        }
    }
    return true;
}

JSP page
<textarea rows="5" cols="100" class="clsMultiLineTextBox" name="XYZ" id="XYZ" ></textarea>

<input type="button" class="button" onclick="doSubmit();return false;" id="btnPostQuery" value="Post Query">

function doSubmit(){
    if(Trim(document.forms[0].XYZ.value).length <= 0 ){
        alert("ABC cannot be empty.");
        return false;
    }else if( Trim(document.forms[0].XYZ.value).length >500){
        alert("Query allows you to enter max 500 characters.");
        return false;
    }else if( !SpecialCharacter(document.forms[0].XYZ)){
        return false;
    }else{
        document.forms[0].hidMode.value="post_query";
        document.forms[0].submit();
        return true;
    }
}

Kindly advise why this is happening.
Thanks,
Gaurav Chaudhary

A:

This is probably because the regexp goes into a loop. Try to find a simpler regexp that terminates faster in case of an error.
Look into *? or validate the text in pieces by first matching part of the regexp (the header). If there is no header -> error.
Then strip the header. Search the rest of the input for the inverse of the allowed characters ([^...allowed chars...]. If you have a match anywhere -> error


Q:

List view cell recycling issue

In my case list view on scroll showing duplicate cells. Not working properly. this is my code in getView()
    if(convertView == null)
        {
            LayoutInflater infalInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.contact_cell, null);
        }

        try {
            if(contacts.getContacts().get(position).getPhone() != null) {
                ImageView contactIcon = (ImageView) convertView.findViewById(R.id.pic);
                TextView contactName = (TextView) convertView.findViewById(R.id.name);
                contactName.setText(contacts.getContacts().get(position).getDisplayName());
                contactIcon.setImageBitmap(contacts.getContacts().get(position).getThumbNail());
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return convertView;

A:

Add this to yuor getView() method
if(contacts.getContacts().get(position).getPhone() != null) {
    ImageView contactIcon = (ImageView) convertView.findViewById(R.id.pic);
    TextView contactName = (TextView) convertView.findViewById(R.id.name);
    contactName.setText(contacts.getContacts().get(position).getDisplayName());
    contactIcon.setImageBitmap(contacts.getContacts().get(position).getThumbNail());
}else{
    ImageView contactIcon = (ImageView) convertView.findViewById(R.id.pic);
    TextView contactName = (TextView) convertView.findViewById(R.id.name);
    contactName.setText("");
    contactIcon.setImageBitmap(null);
}

It happens when getPhone() returns null and convertView does not update.


Q:

could not find Lazy implicit value of type io.circe.generic.decoding.DerivedDecoder[Staff]

I am very new to scala (just learned this week ) and trying to parse json using this example
https://medium.com/@djoepramono/how-to-parse-json-in-scala-c024cb44f66b
i add the first part of the code
import io.circe.parser
import io.circe.generic.semiauto.deriveDecoder

case class Staff(name: String)
object SimpleDecoder {
  def main(args: Array[String]): Unit = {
    val input =
      """
        {
          "name": "John Doe"
        }
      """.stripMargin

    implicit val staffDecoder = deriveDecoder[Staff]
    val decodeResult = parser.decode[Staff](input)
    decodeResult match {
      case Right(staff) => println(staff.name)
      case Left(error) => println(error.getMessage())
    }
  }
}

this is my pom.xml
<dependency>
    <groupId>io.circe</groupId>
    <artifactId>circe-core_2.11</artifactId>
    <version>0.3.0</version>
</dependency>

<dependency>
    <groupId>io.circe</groupId>
    <artifactId>circe-generic_2.12</artifactId>
    <version>0.12.0-M1</version>
</dependency>

<dependency>
    <groupId>io.circe</groupId>
    <artifactId>circe-parser_2.12</artifactId>
    <version>0.12.0-M1</version>
</dependency>

and when i run this i get the following error
Error:(14, 46) could not find Lazy implicit value of type io.circe.generic.decoding.DerivedDecoder[Staff]
    implicit val staffDecoder = deriveDecoder[Staff]
Error:(14, 46) not enough arguments for method deriveDecoder: (implicit decode: shapeless.Lazy[io.circe.generic.decoding.DerivedDecoder[Staff]])io.circe.Decoder[Staff].
Unspecified value parameter decode.
    implicit val staffDecoder = deriveDecoder[Staff]
Error:(15, 44) could not find implicit value for parameter d: io.circe.Decoder[Staff]
    val decodeResult = parser.decode[Staff](input)
Error:(15, 44) not enough arguments for method decode: (implicit d: io.circe.Decoder[Staff])cats.data.Xor[io.circe.Error,Staff].
Unspecified value parameter d.
    val decodeResult = parser.decode[Staff](input)
Error:(17, 42) value name is not a member of Any
      case Right(staff) => println(staff.name)
Error:(18, 41) value getMessage is not a member of Any
      case Left(error) => println(error.getMessage())

A:

As specified in the comment, your dependencies don't match the one in the blog post, as @Luis pointed out, 0.7.0 is an old version so it's better to use 0.11.1:
pom.xml
<dependency>
    <groupId>io.circe</groupId>
    <artifactId>circe-core_2.12</artifactId>
    <version>0.11.1</version>
</dependency>

<dependency>
    <groupId>io.circe</groupId>
    <artifactId>circe-generic_2.12</artifactId>
    <version>0.11.1</version>
</dependency>

<dependency>
    <groupId>io.circe</groupId>
    <artifactId>circe-parser_2.12</artifactId>
    <version>0.11.1</version>
</dependency>


Q:

Identify an event via a Linq Expression tree

The compiler usually chokes when an event doesn't appear beside a += or a -=, so I'm not sure if this is possible.
I want to be able to identify an event by using an Expression tree, so I can create an event watcher for a test. The syntax would look something like this:
using(var foo = new EventWatcher(target, x => x.MyEventToWatch) {
    // act here
}   // throws on Dispose() if MyEventToWatch hasn't fired

My questions are twofold:

Will the compiler choke? And if so, any suggestions on how to prevent this?
How can I parse the Expression object from the constructor in order to attach to the MyEventToWatch event of target?

A:

Edit: As Curt has pointed out, my implementation is rather flawed in that it can only be used from within the class that declares the event :) Instead of "x => x.MyEvent" returning the event, it was returning the backing field, which is only accessble by the class.
Since expressions cannot contain assignment statements, a modified expression like "( x, h ) => x.MyEvent += h" cannot be used to retrieve the event, so reflection would need to be used instead. A correct implementation would need to use reflection to retrieve the EventInfo for the event (which, unfortunatley, will not be strongly typed).
Otherwise, the only updates that need to be made are to store the reflected EventInfo, and use the AddEventHandler/RemoveEventHandler methods to register the listener (instead of the manual Delegate Combine/Remove calls and field sets). The rest of the implementation should not need to be changed. Good luck :)

Note: This is demonstration-quality code that makes several assumptions about the format of the accessor. Proper error checking, handling of static events, etc, is left as an exercise to the reader ;)
public sealed class EventWatcher : IDisposable {
  private readonly object target_;
  private readonly string eventName_;
  private readonly FieldInfo eventField_;
  private readonly Delegate listener_;
  private bool eventWasRaised_;

  public static EventWatcher Create<T>( T target, Expression<Func<T,Delegate>> accessor ) {
    return new EventWatcher( target, accessor );
  }

  private EventWatcher( object target, LambdaExpression accessor ) {
    this.target_ = target;

    // Retrieve event definition from expression.
    var eventAccessor = accessor.Body as MemberExpression;
    this.eventField_ = eventAccessor.Member as FieldInfo;
    this.eventName_ = this.eventField_.Name;

    // Create our event listener and add it to the declaring object's event field.
    this.listener_ = CreateEventListenerDelegate( this.eventField_.FieldType );
    var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;
    var newEventList = Delegate.Combine( currentEventList, this.listener_ );
    this.eventField_.SetValue( this.target_, newEventList );
  }

  public void SetEventWasRaised( ) {
    this.eventWasRaised_ = true;
  }

  private Delegate CreateEventListenerDelegate( Type eventType ) {
    // Create the event listener's body, setting the 'eventWasRaised_' field.
    var setMethod = typeof( EventWatcher ).GetMethod( "SetEventWasRaised" );
    var body = Expression.Call( Expression.Constant( this ), setMethod );

    // Get the event delegate's parameters from its 'Invoke' method.
    var invokeMethod = eventType.GetMethod( "Invoke" );
    var parameters = invokeMethod.GetParameters( )
        .Select( ( p ) => Expression.Parameter( p.ParameterType, p.Name ) );

    // Create the listener.
    var listener = Expression.Lambda( eventType, body, parameters );
    return listener.Compile( );
  }

  void IDisposable.Dispose( ) {
    // Remove the event listener.
    var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;
    var newEventList = Delegate.Remove( currentEventList, this.listener_ );
    this.eventField_.SetValue( this.target_, newEventList );

    // Ensure event was raised.
    if( !this.eventWasRaised_ )
      throw new InvalidOperationException( "Event was not raised: " + this.eventName_ );
  }
}

Usage is slightly different from that suggested, in order to take advantage of type inference:
try {
  using( EventWatcher.Create( o, x => x.MyEvent ) ) {
    //o.RaiseEvent( );  // Uncomment for test to succeed.
  }
  Console.WriteLine( "Event raised successfully" );
}
catch( InvalidOperationException ex ) {
  Console.WriteLine( ex.Message );
}

A:

I too wanted to do this, and I have come up with a pretty cool way that does something like Emperor XLII idea. It doesn't use Expression trees though, as mentioned this can't be done as Expression trees do not allow the use of += or -=.
We can however use a neat trick where we use .NET Remoting Proxy (or any other Proxy such as LinFu or Castle DP) to intercept a call to Add/Remove handler on a very short lived proxy object. The role of this proxy object is to simply have some method called on it, and to allow its method calls to be intercepted, at which point we can find out the name of the event.
This sounds weird but here is the code (which by the way ONLY works if you have a MarshalByRefObject or an interface for the proxied object)
Assume we have the following interface and class
public interface ISomeClassWithEvent {
    event EventHandler<EventArgs> Changed;
}

public class SomeClassWithEvent : ISomeClassWithEvent {
    public event EventHandler<EventArgs> Changed;

    protected virtual void OnChanged(EventArgs e) {
        if (Changed != null)
            Changed(this, e);
    }
}

Then we can have a very simply class that expects an Action<T> delegate that will get passed some instance of T.
Here is the code
public class EventWatcher<T> {
    public void WatchEvent(Action<T> eventToWatch) {
        CustomProxy<T> proxy = new CustomProxy<T>(InvocationType.Event);
        T tester = (T) proxy.GetTransparentProxy();
        eventToWatch(tester);

        Console.WriteLine(string.Format("Event to watch = {0}", proxy.Invocations.First()));
    }
}

The trick is to pass the proxied object to the Action<T> delegate provided.
Where we have the following CustomProxy<T> code, who intercepts the call to += and -= on the proxied object
public enum InvocationType { Event }

public class CustomProxy<T> : RealProxy {
    private List<string> invocations = new List<string>();
    private InvocationType invocationType;

    public CustomProxy(InvocationType invocationType) : base(typeof(T)) {
        this.invocations = new List<string>();
        this.invocationType = invocationType;
    }

    public List<string> Invocations {
        get {
            return invocations;
        }
    }

    [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
    [DebuggerStepThrough]
    public override IMessage Invoke(IMessage msg) {
        String methodName = (String) msg.Properties["__MethodName"];
        Type[] parameterTypes = (Type[]) msg.Properties["__MethodSignature"];
        MethodBase method = typeof(T).GetMethod(methodName, parameterTypes);

        switch (invocationType) {
            case InvocationType.Event:
                invocations.Add(ReplaceAddRemovePrefixes(method.Name));
                break;
            // You could deal with other cases here if needed
        }

        IMethodCallMessage message = msg as IMethodCallMessage;
        Object response = null;
        ReturnMessage responseMessage = new ReturnMessage(response, null, 0, null, message);
        return responseMessage;
    }

    private string ReplaceAddRemovePrefixes(string method) {
        if (method.Contains("add_"))
            return method.Replace("add_","");
        if (method.Contains("remove_"))
            return method.Replace("remove_","");
        return method;
    }
}

And then we all that's left is to use this as follows
class Program {
    static void Main(string[] args) {
        EventWatcher<ISomeClassWithEvent> eventWatcher = new EventWatcher<ISomeClassWithEvent>();
        eventWatcher.WatchEvent(x => x.Changed += null);
        eventWatcher.WatchEvent(x => x.Changed -= null);
        Console.ReadLine();
    }
}

Doing this I will see this output:
Event to watch = Changed
Event to watch = Changed


Q:

How to integrate $\large \frac{2x}{1+x^{2}}$

How to integrate $\;\large \frac{2x}{1+x^{2}}\;?\;$ Do I need to use u-substitution for $\,(1+x^2)\,$?

A:

That's the most straightforward way.
Let $u = 1 + x^2,\;$ then $du = 2x \,dx.\; $ Now you're all set to substitute:
$$\int \dfrac{2x\,dx}{1+x^2} \;\;=\; \;\int \dfrac{du}{u}\;\;=\;\; \ln |u| + C \;= \;\ln(1 + x^2) + C$$

Added (to address comment below): Note that we can omit the "absolute value sign" surrounding $\,(1 + x^2)\,$ when substituting $\,u = 1+x^2\,$ in the final expression because we know that $\,(1 + x^2) > 0\,$ for all real $x$.


Q:

Transductive SVM with Scikit-Learn

I read in an answer here :

If you only have a small set of labels but lots of unlabeled data,
  then you might try a Manifold Regularizer (i.e. Transductive SVM),
  with or without a non-linear Kernel

Is there implementation of Transductive SVM  on Scikit-Learn ?

A:

No, Scikit-Learn has only the standard SVMs via Cython bindings to LibSVM