Q:

Singular Value Decomposition (SVD) in PHP

I would like to implement Singular Value Decomposition (SVD) in PHP. I know that there are several external libraries which could do this for me. But I have two questions concerning PHP, though:
1) Do you think it's possible and/or reasonable to code the SVD in PHP?
2) If (1) is yes: Can you help me to code it in PHP?
I've already coded some parts of SVD by myself. Here's the code which I made comments to the course of action in. Some parts of this code aren't completely correct.
It would be great if you could help me. Thank you very much in advance!

A:

SVD-python
Is a very clear, parsimonious implementation of the SVD.
It's practically psuedocode and should be fairly easy to understand
and compare/draw on for your php implementation, even if you don't know much python.
SVD-python
That said, as others have mentioned I wouldn't expect to be able to do very heavy-duty LSA with php implementation what sounds like a pretty limited web-host.
Cheers
Edit:
  The module above doesn't do anything all by itself, but there is an example included in the
opening comments.  Assuming you downloaded the python module, and it was accessible (e.g. in the same folder), you
could implement a trivial example as follow,
#!/usr/bin/python
import svd
import math

a = [[22.,10., 2.,  3., 7.],
     [14., 7.,10.,  0., 8.],
     [-1.,13.,-1.,-11., 3.],
     [-3.,-2.,13., -2., 4.],
     [ 9., 8., 1., -2., 4.],
     [ 9., 1.,-7.,  5.,-1.],
     [ 2.,-6., 6.,  5., 1.],
     [ 4., 5., 0., -2., 2.]]

u,w,vt = svd.svd(a)
print w

Here 'w' contains your list of singular values.
Of course this only gets you part of the way to latent semantic analysis and its relatives.
You usually want to reduce the number of singular values, then employ some appropriate distance
metric to measure the similarity between your documents, or words, or documents and words, etc.
The cosine of the angle between your resultant vectors is pretty popular.
Latent Semantic Mapping (pdf)
is by far the clearest, most concise and informative paper I've read on the remaining steps you
need to work out following the SVD.
Edit2:  also note that if you're working with very large term-document matrices (I'm assuming this
is what you are doing) it is almost certainly going to be far more efficient to perform the decomposition
in an offline mode, and then perform only the comparisons in a live fashion in response to requests.
while svd-python is great for learning, the svdlibc is more what you would want for such heavy
computation.
finally as mentioned in the bellegarda paper above, remember that you don't have to recompute the
svd every single time you get a new document or request.  depending on what you are trying to do you could
probably get away with performing the svd once every week or so, in an offline mode, a local machine,
and then uploading the results (size/bandwidth concerns notwithstanding).
anyway good luck!

A:

Be careful when you say "I don't care what the time limits are". SVD is an O(N^3) operation (or O(MN^2) if it's a rectangular m*n matrix) which means that you could very easily be in a situation where your problem can take a very long time. If the 100*100 case takes one minute, the 1000*1000 case would 10^3 minutes, or nearly 17 hours (and probably worse, realistically, as you're likely to be out of cache).  With something like PHP, the prefactor -- the number multiplying the N^3 in order to calculate the required FLOP count, could be very, very large.
Having said that, of course it's possible to code it in PHP -- the language has the required data structures and operations.

A:

I know this is an old Q, but here's my 2-bits:
1) A true SVD is much slower than the calculus-inspired approximations used, eg, in the Netflix prize. See: http://www.sifter.org/~simon/journal/20061211.html
There's an implementation (in C) here:
http://www.timelydevelopment.com/demos/NetflixPrize.aspx
2) C would be faster but PHP can certainly do it.
PHP Architect author Cal Evans: "PHP is a web scripting language... [but] I’ve used PHP as a scripting language for writing the DOS equivalent of BATCH files or the Linux equivalent of shell scripts. I’ve found that most of what I need to do can be accomplished from within PHP. There is even a project to allow you to build desktop applications via PHP, the PHP-GTK project."


Q:

Do Romans 7:6 & Romans 7:14 contradict each?

On one hand Paul seems to be saying in Romans 7:6:

We have been delivered from the LAW, that being dead wherein we were held, that we should serve in newness of spirit and not in the oldness of the letter

On the other hand he says in Romans 7:14:

But we know that the LAW is spiritual, but I am carnal sold under sin (KJV)

Is there a contradiction? How can we be delivered from the LAW since it is spiritual?

A:

No, I don't believe they do.
While one meaning of "deliver" is to rescue or liberate, when the KJV was written it also had a softer meaning of being handed over or "discharged".  A few years after the KJV was published, for example, Shakespeare wrote "O that I might not be delivered to the world till I had made mine own occasion mellow" (Twelfth Night).  The RSV, for example, translates 7:6 as:

But now we are discharged from the law, dead to that which held us captive, so that we serve not under the old written code but in the
  new life of the Spirit.

That is to say, that the Law was not something evil that we needed to be "rescued" from.  It was, in fact, spiritual (7:14) and holy (7:12).  What has changed from Old is that whereas before we were guided by the letter of a Law written of God's Spirit; we are now ourselves personally imbued with His Spirit, which came down upon us at Pentecost, and is now written in our hearts (viz. Jeremiah 31:33, Isaiah 59:21; also Hebrews 8:10, 10:16).


Q:

ISNULL Date month

I have two dropdownlists, one with months and the other one with year. The user selects the submit month and year  for the items they want to retrieve. In database the date is entered in full eg. 01/12/2009. There is an option for "All years" and "All months" in the dropdown lists but when users choose either they get null results. Many thanks. This is my query:
SELECT ItemID, YEAR(Submit) AS SubmitYear, MONTH(Submit) AS SubmitMonth
FROM Items
WHERE (YEAR(Submit) LIKE ISNULL(@YearPay, ''))
 AND (MONTH(Submit) LIKE ISNULL(@MonthPay, ''))

My parameter are:
<asp:ControlParameter ControlID="DropDownList1" DefaultValue="" Name="YearPay" PropertyName="SelectedValue" />
<asp:ControlParameter ControlID="DropDownList2" DefaultValue="" Name="MonthPay" PropertyName="SelectedValue" />

A:

Here's one way to solve the problem:
 SELECT ItemID, YEAR(Submit) AS SubmitYear, MONTH(Submit) AS SubmitMonth
 FROM Items
 WHERE (YEAR(Submit) = @YearPay OR @YearPay IS NULL)
 AND (MONTH(Submit) = @MonthPay OR @MonthPay IS NULL)

That way, if you pass in NULL for either variable, that part of the WHERE clause will return true.


Q:

Why did Sinclair and Ivanova, the two most senior officers, go to Epsilon III?

In A Voice in the Wilderness, parts 1 and 2, strange things are going on down on Epsilon III, the planet which Bablyon 5 orbits. Sinclair and Ivanova go down to investigate.
But since these two are the most senior officers aboard Bablyon 5, why are they sent? Since they have so many other duties to perform to keep the station running, why not send other people whose absence will be less disruptive?

A:

It's Earth Alliance policy, since untrained people making first contact led to the Earth/Minbari War
Showrunner J. Michael Straczynski conversed online with fans during the early days of the show. A few people asked this question, and he responded with a clear answer:

A First Contact situation is one unlike any other: you don't want junior officers around to screw it up. Remember, the Earth/Minbari War began when a First Contact situation got screwed up. EA's [Earth Alliance's] policy is that it's better to risk two people than a full war, and those two people have got to be command-level personnel. Soldiers get killed; it happens. And yeah, you can leave a backup person at the shuttle ...but what if he's the one to make actual first contact? You're screwed. Ivanova and Sinclair have been trained in this; in "Soul Hunter," Sinclair makes reference to the rules of First Contact Protocol. If you like, I'll elaborate on this in some future episode.
JMS on rec.arts.sf.tv.babylon5.moderated, 1994-07-28

I imagine that part of it is not only that they need someone who is trained, but also someone with the authority to negotiate any terms. Remember, this all started because weapons were fired on Babylon 5, and sending someone who then has to report to their higher ups introduces a delay that puts the station at additional risk.


Q:

Trying to change the name when uploading an image file using php

I am trying to change the name of a file I am uploading using PHP, I know this question has already been answered but I can't find the solution using someone else's example so bear with me please.
In the code below I have set var userid to the user which is logged in. I would like that the image that get's uploaded receives the name of the user.
<?php

session_start();

//database connectie
include_once('db/conn.php');

if(isset($_SESSION['user'])){

    $userid = $_SESSION['user'];
    $ran = $userid;
    $target = "uploads/";
    $target_file = $target . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 5000000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],$target_file)) {
            echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }

}else{
    echo "plz login before uploading an image";
}
?>

A:

When you are calling move_uploaded_file you can declare where the image goes AND change the name of the image.
//Moves image to 'uploads' and saves image as '$userid.$imageFileType (e.g '31029.png')
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target . $userid . $imageFileType);


Q:

spring-boot application.properties are not overwriten

I have one class:
package com.example.propertyorder;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@SpringBootApplication
@PropertySource(value="file:C:\\TEMP\\property-order.properties", ignoreResourceNotFound = true)

public class PropertyOrderApplication {

    public static void main(String[] args) {

        ConfigurableApplicationContext run = SpringApplication.run(PropertyOrderApplication.class, args);
        Environment env = (Environment) run.getBean("environment");
        System.out.println(env.getProperty("my.value"));
        System.out.println(env.getProperty("my.value2"));
    }
}

and I have one application.properties file:
my.value=application.properties

and I have my external properties file C:\\TEMP\\property-order.properties:
my.value=property-order.properties
my.value2=gotcha

but the result is always:
application.properties
gotcha

instead of:
property-order.properties
gotcha

So it looks like, that spring-boot's application.properties overrules all.
Is there a way to fix it.
The only solution that i found is to not use the application.properties, but a my-app.properties instead and place that one before my external file in the ProperySource-tree:
@PropertySource(value="classpath:my-app.properties")
@PropertySource(value="file:C:\\TEMP\\property-order.properties", ignoreResourceNotFound = true)

Is there a better way, so that I can stay with the application.properties ?
edit:
added missing value2 to the property file

A:

The actual behavior is conform to the Spring Boot documentation :

Spring Boot uses a very particular PropertySource order that is
  designed to allow sensible overriding of values. Properties are
  considered in the following order:
....
14.Application properties outside of your packaged jar (application.properties and YAML variants).
15.Application properties packaged inside your jar (application.properties and YAML variants).
16.@PropertySource annotations on your @Configuration classes.

The application.properties (inside or outside the jar) have a higher priority (14 and 15 respectively) than any @PropertySource annotations added in @Configuration class (16).

Is there a better way, so that I can stay with the
  application.properties ?

Of course you can use any of the 13 higher priority ways :

1.Devtools global settings properties on your home directory
  (~/.spring-boot-devtools.properties when devtools is active).
2.@TestPropertySource annotations on your tests.
3.@SpringBootTest#properties annotation attribute on your tests. Command
  line arguments.
4.Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an
  environment variable or system property).
5.ServletConfig init parameters.
6.ServletContext init parameters.
7.JNDI attributes from java:comp/env.
8.Java System properties (System.getProperties()).
9.OS environment variables.
10.A RandomValuePropertySource that has properties only in random.*.
11.Profile-specific application properties outside of your packaged jar
  (application-{profile}.properties and YAML variants).
12.Profile-specific application properties packaged inside your jar
  (application-{profile}.properties and YAML variants).
13.Application properties outside of your packaged jar
  (application.properties and YAML variants).

For example renaming property-order.properties to application-order.properties to make it a Spring Boot profile properties and run your application with order as active profile would give it a higher priority and so it should be enough :
@SpringBootApplication
public class PropertyOrderApplication {...}


Q:

adding a static UITableView to a regular custom view

I have a custom view controller that has a view on the bottom half.
I would like to add a static UITableView on the top half.
So I dragged a UITableView on the view controller but apparently that is not allowed since static table views only are only embeddable in UIViewControllers.
I went to my code and made my controller extend UITableView but that doesn't fix the issue.
How do I add my static UITableView as a second view in my custom controller?
EDIT: Perhaps having a table view not taking up the whole screen is not very well supported in iOS storyboards. Maybe I will just use regular tables on a view since i just need 3 static rows.

A:

I solved this issue by making my second view controller a simple UIViewController that implements the delegate and datasource, dragging a dynamic table on it and setting the rows and sections "statically" in code. Now I have my two views correctly cohabiting in a large view.


Q:

create animated appearing slide css/jquery from payday2

Dear Stackoverflow members. Im looking for something simular to payday 2`s assault introduction. where there is nothing first, but then animating in, and ends up like this:

I also have a youtube video that are showing how its appearing: https://youtu.be/RgGwj0ULslg?t=5m36s
**Q: How can i make this kind of appearing bar?
i tried for myself, but all i could do is something like this, and nothing else ( no fadein like payday2, etc)
:

                    Police Assault in progress

Assault against Journey

 @keyframes marquee {
                    0%   { text-indent: 14.5em }
                    100% { text-indent: -14.5em }
                }
                .marquee {
                    overflow:hidden;
                    width: 180px;
                    margin: 0 auto;
                    font-size: 16px;
                    padding-top: 18px;
                    font-weight: bold;
                    white-space: nowrap;
                    color:#a75144;
                    box-sizing: border-box;
                    animation: marquee 7s linear infinite;
                }

                .colorback {
                    background-image: url('http://caviar.dtmcdn.com/static/images/box/white.png');
                    background-repeat: repeat-x;
                }

   .assault {
                    height:70px;
                    width:185px;
                    background-color:yellow;
                    opacity: 0.4;
                    border: 1px solid #cccc00;
                    position:relative;
                }

A:

How I see this making the simplest way is trough CSS Animations. The main component of CSS animations are @keyframes you should look it up.
http://webdesign.tutsplus.com/tutorials/a-beginners-introduction-to-css-animation--cms-21068
http://www.w3schools.com/css/css3_animations.asp


Q:

GIT: How dangerous is "deleted by us" conflict?

A few days ago I made a new branch called "new_branch" based on "master". While I worked on my "new_branch" with file "file.php", a second developer on his branch deleted the file "file.php" and merged his branch with "master". Now I need to rebase my branch on current "master". After the command git pull --rebase origin master I have the conflict

deleted by us:   app/file.php

I don't know what to do, I don't want to lose changes I've made in this file. After commands
git add -A
git rebase --continue

will the file disappear in my "new_branch"?

A:

The message deleted by us: app/file.php means precisely what you described, namely that someone deleted this file in the master branch on which you are rebasing new_branch.
Assuming that the delete has not yet been staged and you want to keep this file, then you should git add the file to mark it that it should be kept:
git add app/file.php

Then, resolve all other merge conflicts and do git rebase --continue
Note that if you wanted to accept the delete you would do git rm instead.


Q:

How to change icon size?

I'm using primereact and according to there website this is how they change there icon size.
However this doesn't work in jsx as it won't let you directly reference style without it being an object.
Are there any workarounds to this?
EDIT: Code for Button where icon is nested in below:
<Button
  label=""
  icon="pi pi-cog"
  className="cogIcon"
  onClick={(e) => this.setState({visibleRight:true})}
  style={{marginTop:'.25em', marginRight:'.25em'} }
/>

A:

In the link you provide, they have an example

<i class="pi pi-check" style="font-size: 3em"></i>

Just add fontSize: 3em (or the size you want).
<Button
  label=""
  icon="pi pi-cog"
  className="cogIcon"
  onClick={(e) => this.setState({visibleRight:true})}
  style={{marginTop:'.25em', marginRight:'.25em', fontSize: '3em'} }
/>


Q:

stretch image in imageview to fit screen in xml

I have image in drawable, which needs to work as the background. It needs to stretch to fill the screen..
I know how to stretch the image full screen using java code.. but in XML itselt how can do this.

A:

android:scaleType="fitXY" will stretch the image to fit the full size of the ImageView

A:

Try with this property:
android:scaleType="fitXY"

Here you can find other constant values for resizing.

A:

Try to implement your ImageView like this and change the ic_launcher to your own image name which you are trying to add.
  <ImageView
    android:id="@+id/mImageView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scaleType="fitXY"
    android:src="@drawable/ic_launcher" />

Hope this will be helpful. Thanks


Q:

How to find average of two lines in NiFi?

I need to find average of two values in separate lines.
My CSV file looks like this
Name,ID,Marks
Mahi,1,90
Mahi,1,100

Andy,2,85
Andy,2,95

Now I need to store that average of 2 marks in database.
"Average" column should add two marks and divide with 2 and store that result in SQL query
Table:
Name,ID,Average
Mahi,2,95
Andy,2,90

Is it possible to find the average of two values in separate rows using NiFi?

A:

Given a lot of assumptions, this is doable. You are definitely better off pre-processing the data in NiFi and exporting it to a tool better suited to this, like Apache Spark using the NiFi Spark Receiver library (instructions here), because this solution will not scale well.
However, you could certainly use a combination of SplitText processors to get the proper data into individual flowfiles (i.e. all Mahi rows in one, all Andy rows in another). Once you have a record that looks like:
Andy,1,85
Andy,1,95

you can use ExtractText with regular expressions to get 85 and 95 into attributes marks.1 and marks.2 (a good example of where scaling will break down -- doing this with 2 rows is easy; doing this with 100k is ridiculous). You can then use UpdateAttribute with the Expression Language to calculate the average of those two attributes (convert toNumber() first) and populate a third attribute marks.average (either through chaining plus() and divide() functions or with the math advanced operation (uses Java Reflection)). Once you have the desired result in an attribute, use ReplaceText to update the flowfile content, and MergeContent to merge the individual flowfiles back into a single instance.
If this were me, I'd first evaluate how static my incoming data format was, and if it was guaranteed to stay the same, probably just write a Groovy script that parsed the data and calculated the averages in place. I think that would even scale better (within reason) because of the flexibility of having written domain-specific code. If you need to offload this to cluster operations, Spark is the way to go.


Q:

Do mass update on the table based on two different IDs

I'm trying to do a mass update on my table tbl
This how the table looks like when I do a select statement
SELECT * FROM tbl

It returns this:

What I'm trying to accomplish is to do a single update where UID are different but CID are the same. If this criteria is true update the second UID and set it with the first UID and set the OLDUID where UID was updated with the same UID.
So the output will be like this:

What I'm trying to accomplish here is if I do a select statement:
SELECT * FROM tbl where UID = 1

It should return both rows. I have tried to join the two table and then do the update, but every time I try to do a select statement before the update it returns more rows than expected.
Any suggestions?
NOTE* this is just a sample table. The original table contains thousands of rows. Also there're will be times where I will have 3 or 4 different UIDs but ONE CID. The concept is still the same. Update the two rows with the first UID and set the OLDUID with the ones that were updated.
UPDATE:
There're cases where two rows will have the SAME CID but UID are also the SAME. In this case, I don't want to update and set the OLDUID.
Here's an example:

Here's the output:

In this case it should ignore and do nothing. All of the rows where UID = OLDUID are the same type.

A:

You can do this with a cte and the ROW_NUMBER() function as well as a windowed MIN():
with cte AS (SELECT *,ROW_NUMBER()OVER(PARTITION BY CID ORDER BY UID) RN
                      ,MIN(UID) OVER(PARTITION BY CID) Min_UID
              FROM Table1
              )
UPDATE cte
SET OLDUID = UID
   ,UID = MIN_UID
WHERE RN > 1

Demo: SQL Fiddle
Update:
To handle the additional case where the UID is the same and you don't want to update it, you can just add to your WHERE criteria:
with cte AS (SELECT *,ROW_NUMBER()OVER(PARTITION BY CID ORDER BY UID) RN
                      ,MIN(UID) OVER(PARTITION BY CID) Min_UID
              FROM Table1
              )
UPDATE cte
SET OLDUID = UID
   ,UID = MIN_UID
WHERE RN > 1
  AND UID <> MIN_UID

Demo: SQL Fiddle


Q:

Contract transaction was sent to a 'null' address

I have attempted to deploy a contract through geth, my understanding was that a null value could be given when creating the transaction to deploy the contract.
After mining the transaction I attempted to look up the transaction via the hash returned by the rcp call, I was given the following response in geth:
{
  blockHash: "0x06fe2ca8aae95b44057dbb663bed0faf9e8cc4d33418b21067d64de0eaa02f51",
  blockNumber: 37,
  from: "0x3440825288a9de705e2dbc26e4f6494b4d1f6426",
  gas: 90000,
  gasPrice: 20000000000,
  hash: "0x5e4c06e62aa70544f3349f51521e19454d4b43a224a402492cc256b115208391",
  input: "0x",
  nonce: 2,
  r: "0x3397da9897ee38d81511288de20e19d9b83ec98c056dc28604726749f350fd97",
  s: "0x44e3a8ef63f6e39118287b74deed6aa5b53f4234ad7f0669680bf9f2a4f7e030",
  to: null,
  transactionIndex: 0,
  v: "0x1c",
  value: 0
}

Is my understanding of how contract deployment works incorrect? Why is the address null on the blockchain? How can I call the contract or associated methods/functions?
I would be very grateful for any assistance that could be provided, thank you.

A:

Did you remember to mine it?
About half way down this page, "If a transaction creates a contract it will also contain the contract address."  https://github.com/ethereum/homestead-guide/blob/master/source/contracts-and-transactions/accessing-contracts-and-transactions.rst
Hopefully something on that page helps.


Q:

Unittest for click module

I wrote a simple command line utility that accepts a text file and searches for a given word in it using the click module.
sfind.py
import click
@click.command()
@click.option('--name', prompt='Word or string')
@click.option('--filename', default='file.txt', prompt='file name')
@click.option('--param', default=1, prompt="Use 1 for save line and 2 for word, default: ")
def find(name, filename, param):
    """Simple program that find  word or string at text file and put it in new"""
    try:
        with open(filename) as f, open('result.txt', 'w') as f2:
            count = 0
            for line in f:
                if name in line:
                    if param == 1:
                        f2.write(line + '\n')
                    elif param == 2:
                        f2.write(name + '\n')
                    count += 1
            print("Find: {} sample".format(count))
            return count
    except FileNotFoundError:
        print('WARNING! ' + 'File: ' + filename + ' not found')

if __name__ == '__main__':
    find()

Now I need to write a test using unittest (using unittest is required).
test_sfind.py
import unittest
import sfind

class SfindTest(unittest.TestCase):
    def test_sfind(self):
        self.assertEqual(sfind.find(), 4)

if __name__ == '__main__' :
    unittest.main()

When I run the test:
python -m unittest test_sfind.py

I get an error

click.exceptions.UsageError: Got unexpected extra argument (test_sfind.py)

How can I test this click command?

A:

You can not simply call a click command and then expect it to return.  The decorators applied to make a click command considerably change the behavior of the function.  Fortunately the click frameworks provides for this through the CliRunner class.
Your command can be tested via unittest with something like this:
import unittest
import sfind
from click.testing import CliRunner

class TestSfind(unittest.TestCase):

    def test_sfind(self):

        runner = CliRunner()
        result = runner.invoke(
            sfind.find, '--name url --filename good'.split(), input='2')
        self.assertEqual(0, result.exit_code)
        self.assertIn('Find: 3 sample', result.output)


Q:

Fill two-dimensional array with Chars from String Input

I'm making a basic game of Tic Tac Toe, accepting player input in the form of a string (i.e. a2). The first char is made into an int called row depending on the letter, the same being said for the second char into col (for array grid[row][col]). I have a block of code that throws a custom exception in the event that the first char isn't a, b, or c, and if the second char isn't 1, 2, or 3:
if(input == null) {
        throw new NullInputException();
    }
    else if(input.length() != 2) {
        throw new InvalidInputException();
    }
    else if(!(input.substring(0,1).equalsIgnoreCase("a") &&
            input.substring(0,1).equalsIgnoreCase("b") &&
            input.substring(0,1).equalsIgnoreCase("c") ||
            input.substring(1).equals("1") &&
            input.substring(1).equals("2") &&
            input.substring(1).equals("3"))) {
        throw new InvalidInputException();
    }

The problem is, this code throws an error even when the input is valid, and I don't know why. I've tried using .charAt() as opposed to .substring(), as well as messed around with my conditional statements. My question is: How do I fix this so that it accepts valid input?
Other questions that just don't help:
fill two dimensional array with parts of a string;
fill a 2d array with chars of 2 string

A:

Sometimes it is better to write a series of simpler tests which are easier to read and verify
row = input.substring(0,1).toUpperCase();
col = input.substring(1);
boolean validRow = (row.equals("A") ||
                    row.equals("B") ||
                    row.equals("C"));
boolean validCol =
        (col.equals("1") ||
        col.equals("2") ||
        col.equals("3"));

if(!(validRow && validCol)) {

A:

You AND two conditions:
input.substring(0,1).equalsIgnoreCase("a") &&
            input.substring(0,1).equalsIgnoreCase("b")

Both cannot be true in the same time. That is why the result is always false and an exception is thrown.
What you really want is:
String first = input.substring(0,1);
String second = input.substring(1);
    if (!((first.equalsIgnoreCase("a") ||
                first.equalsIgnoreCase("b") ||
                first.equalsIgnoreCase("c")) &&
                (second.equals("1") ||
                second.equals("2") ||
                second.equals("3"))) {
        throw new InvalidInputException();
    }

Small edit for Neil...


Q:

MongoDB: not all the results are returned from a query, using $geoNear

I got this query :
 exports.search = (req, res) => {

  let lat1 = req.body.lat;
  let lon1 = req.body.lng;
  let page = req.body.page || 1;
  let perPage = req.body.perPage || 10;
  let radius = req.body.radius || 100000; // This is not causing the issue, i can remove it and the issue is still here

  var options = { page: page, limit: perPage, sortBy: { updatedDate: -1 } }

  let match = {}

  var aggregate = null;

  if (lat1 && lon1) {

    aggregate = Tutor.aggregate([
      {
        "$geoNear": {
          "near": {
            "type": "Point",
            "coordinates": [lon1, lat1]
          },
          "distanceField": "distance", // this calculated distance will be compared in next section
          "distanceMultiplier": 0.001,
          "spherical": true,
          "key": "loc",
          "maxDistance": radius
        }
      },
      {
        $match: match
      },
      { "$addFields": { "islt": { "$cond": [{ "$lt": ["$distance", "$range"] }, true, false] } } },
      { "$match": { "islt": true } },
      { "$project": { "islt": 0 } }
    ])
    // .allowDiskUse(true);
  } else {
    aggregate = Tutor.aggregate([
      {
        $match: match
      }
    ]);
  }

  Tutor
    .aggregatePaginate(aggregate, options, function (err, result, pageCount, count) {

      if (err) {
        console.log(err)
        return res.status(400).send(err);
      }
      else {

        var opts = [
          { path: 'levels', select: 'name' },
          { path: 'subjects', select: 'name' },
          { path: 'assos', select: 'name' }
        ];
        Tutor
          .populate(result, opts)
          .then(result2 => {
            return res.send({
              page: page,
              perPage: perPage,
              pageCount: pageCount,
              documentCount: count,
              tutors: result2
            });
          })
          .catch(err => {
            return res.status(400).send(err);
          });
      }
    })
};

The query is supposed to retrieve all the tutors in a given range (which is a field from the tutor model, an integer in km, indicating how far the tutor is willing to move) around a certain location. (lat1, lon1).
The issue is that all the documents are not returned. After many tests, I have noticed that only tutors that are less than approximatively 7.5km away from the location are returned and not the others. Even if the tutor is 10km away and has a range of 15km, he won't be returned as he is farer than 7.5km.
I have tried switching location between two tutors (one that is returned and one that is not but should be) to see if this is the only thing causing the issue and it is. After I switched their location (lng and loc), the one that was returned before is no longer and vice versa.
I really don't get why this is happening.
Also, I know the result size is less than 16MB since I don't get all the results, even with allowDiskUse:true.
If you have any other idea about why I'm not getting all the results, don't hesitate !
Thank you !
PS : this is a part of the tutor model with the concerned fields (loc):
import mongoose from 'mongoose';
import validate from 'mongoose-validator';
import { User } from './user';
import mongooseAggregatePaginate from 'mongoose-aggregate-paginate';

var ObjectId = mongoose.Schema.Types.ObjectId;

var rangeValidator = [
    validate({
        validator: (v) => {
            v.isInteger && v >= 0 && v <= 100;
        },
        message: '{VALUE} is a wrong value for range'
    })
];

var tutorSchema = mongoose.Schema({
    fullName: {
        type: String,
        trim: true,
        minlength: [1, 'Full name can not be empty'],
        required: [true, 'Full name is required']
    },
    location: {
        address_components: [
            {
                long_name: String,
                short_name: String,
                types: String
            }
        ],
        description: String,
        lat: Number,
        lng: Number

    },
    loc: {
        type: { type: String },
        coordinates: []
    },

});

tutorSchema.plugin(mongooseAggregatePaginate);
tutorSchema.index({ "loc": "2dsphere" });
var Tutor = User.discriminator('Tutor', tutorSchema);

module.exports = {
    Tutor
};

The user model is using two indexes. The ID and this one ;
db['system.indexes'].find() Raw Output
{
  "v": 2,
  "key": {
    "loc": "2dsphere"
  },
  "name": "loc_2dsphere",
  "background": true,
  "2dsphereIndexVersion": 3,
  "ns": "verygoodprof.users"
}

A:

I also have some similar kind of problem, in my case there is problem with limit
https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/
by default limit is 100 (Optional. The maximum number of documents to return. The default value is 100).
If you want you can increase the limit. Hope it help


Q:

Get event object from SequenceWaiter

When I add SequenceWaiter step into the SequenceRunner, how can I get event object which was passed into the event? There is the code from my test function:
var sequence: SequenceRunner = new SequenceRunner(this);
sequence.addStep(new SequenceCaller(manager, function(): void {
    manager.startUpload();
}));
sequence.addStep(new SequenceWaiter(manager, PackageUploadEvent.BEFORE_PACKAGE_UPLOAD, 1000));
sequence.addStep(new SequenceCaller(manager, function(): void {
    // TODO: Get event object from PackageUploadEvent.BEFORE_PACKAGE_UPLOAD event
}));

A:

Answered on flexunit forum. The basic idea is to extend SequenceWaiter class, override setupListeners function to set up additional event listener and save event object to the public field in this listener.


Q:

Black areas on different screen sizes

I'm currently facing some problems with sprites/images on different screen sizes. For now the game stage is stretched to maximum width and height of the screen.
In Samsung Galaxy S2, SGS3 and SGS4 the game is working as normal as expected:

But... yesterday I tested it on GT-P5110 android tablet.. and the result was:

The screen background and car sprite was replaced by black rectangles...
Does somebody know what's happening?
The same result occurs on sgs2/sgs3/sgs4 when any of the sprite image has more than ~4100px of height. Maybe it's something with image limits? If yes... how to know that limit? Currently (working on sgs2, but not on tablet) the background image size is 3117x480. It's so wide because it used for parallax background. If it exceeds the limit how should I handle this (join two images)?

A:

Some Googling reveals that the max texture size may be 2048x2048 on the tablet, and your ~4100px limit implies a max texture size of 4096x4096 on the phones, though I've never seen this particular rendering artifact result from that.  Generally the texture won't load at all, not somehow get its alpha component chopped off, but if that's the reproducible cause of the problem, then texture size must be it.  Honestly it looks more like the alpha test or blend state is just wrong, but maybe the PowerVR drivers do something silly with over-sized textures instead of just erroring out on texture object initialization.
Yes, the correct thing to do in that case is to split your image up (preferably into power-of-two sizes that are within the GL_MAX_TEXTURE_SIZE size; you have to query it at runtime with glGetIntegerv or the like as the spec only guarantees a size of 64 texels to be supported by any particular device/driver.)  You can then render multiple quads/triangles to cover the multiple source textures.  With a little leg work you can set up a system to take any texture, split it into tiles of the maximum size, and then create both the necessary texture objects and vertices for the split image.


Q:

¿Como hacer que un panel pueda abrir distintos control de usuario?

Hola buenas estoy aprendiendo a hacer aplicaciones de escritorio en C#, el cual estuve leyendo que decian que era mala practica usar un windows form hijos cuando se queria poner sobre el windows form padre formulario, por lo cual recomendaban usar control de usuarios.

El problema es que logro abrir en el panel el control de usuario pero al querer seleccionar otra opción del menú no me abre y tengo claro que es porque nunca oculto el formulario anterior pero no se me ocurre como crear un metodo general para validarlo, he buscado tutoriales o alguna guia pero todos ocupan windows form para crear todos los formularios y el codigo que he intentado probar me tira error al leer el objeto.
Igualmente que si cambio la parte donde dice Form por userController me sigue tirando errores de ensamblaje
//Metodo para abrir formulario dentro del panel.
        private void abrirFormulario<MiForm>() where MiForm : Form, new()
        {
            Form formulario;
            formulario = panelCentral.Controls.OfType<MiForm>().FirstOrDefault();//Busca en la colección el formulario.

            //Si el formulario/instancia no existe
            if (formulario == null)
            {
                formulario = new MiForm();
                formulario.TopLevel = false;
                panelCentral.Controls.Add(formulario);
                formulario.Show();
            }
            else
            {
                //si el formulario/instancia existe
                formulario.BringToFront();
            }
        }

        private void btnViewListarEmpleados_Click(object sender, EventArgs e)
        {
            ListadoCtrl uc1 = new ListadoCtrl();
            abrirFormulario<uc1>(); //Me tira error porque lo reconoce como variable y no tipo.
            //panelCentral.Controls.Add(uc1); // Este funciona
        }

A:

Recomendaria utilices user controls en lugar de form para mostrar en un Panel
private void abrirFormulario<ctrl>() where ctrl : UserControl, new()
{
    UserControl control = panelCentral.Controls.OfType<ctrl>().FirstOrDefault();

    if (control == null)
    {
        control = new ctrl();
        panelCentral.Controls.Add(control);
    }
    else
    {
        control.BringToFront();
    }
}

la idea es simplemente instanciar el control y lo asignas a la coleccion de controles
Pero crea un UserControl si quieres tener un diseñador similar al form solo que sin los bordes


Q:

Bullet or number is placed at bottom of ListItem in WPF RichTextBox

I am creating a Bullet/Numbered List in WPF RichTextBox. If the content of ListItem grows, the bullet/number is displayed at vertical bottom.
<List MarkerStyle="Decimal">
    <ListItem>
        <Paragraph>Hello</Paragraph>
    </ListItem>
    <ListItem>
        <Paragraph>Hi</Paragraph>
    </ListItem>
    <ListItem>
        <Paragraph>
            <Image Source="C:\my images\image.png" />
        </Paragraph>
    </ListItem>
    <ListItem>
        <Paragraph>Fourth</Paragraph>
    </ListItem>
</List>

The output of this code can be found here - http://i.imgur.com/dNBeV.png
You can see that Number 3 is displayed at bottom instead of top.
How can I move the position of number/bullet at top of item?
Thank you in advance.

A:

Got the solution. We can use Span tag with BaseAlignment property.
<ListItem>
    <Paragraph>
        <Span BaselineAlignment="Center">
            <Image Source="C:\Users\Public\Pictures\Sample Pictures\desert.jpg" />
        </Span>
    </Paragraph>
</ListItem>

Posting here for help of others.
Ritesh


Q:

Server and Client type Subscriptions

What is Server and Client type subscriptions in Merge Replication? How to select one of these during merge replication setup?

A:

Server subscriptions are for:

Republishing data
Serve as alternate synchronization partners (This has been deprecated)
Resolving conflicts according to a priority

If your subscription(s) do not require this behavior then a client subscription will work just fine.  This is covered in Subscription Type.
The Merge subscription type can be specified on the Subscription Type page of the New Subscription Wizard or by specifying a value of local (client) or global (server) for the @subscriber_type parameter in sp_addmergesubscription and sp_addmergepullsubscription.  This is covered in Specify a Merge Subscription Type and Conflict Resolution Priority.
I hope this helps.


Q:

C++ Calling functions with different signatures, depending on type

I'm wondering what is a good design pattern is for the following scenario. Three questions:
1) I have a templated "Container" class for subclasses of "Derived". I want to be able to store different kinds of template objects (of either type A or B, both subclasses of Derived) in a vector. How to do this?
2) I have a template-specific function "func" that operates on Containers and has a variable number of arguments, depending on whether the template type of Container is A or B. What's a good way to check template types at runtime to call the appropriate function?
3) Do templates even make sense for this use case?
#include <iostream>
#include <string>
#include <vector>
#include <memory>

using namespace std;

struct Derived {};

struct A : Derived {
    int x;
    A(int x) : x(x) {}
};
struct B : Derived {
    bool y;
    B(bool y) : y(y) {}
};

template <typename T>
struct Container
{
    T item;
    Container(T i) : item(i) {}
};

// definition of a template function for type a, with specialization
void func(Container<A> c, int a, int b) {
    cout << "update for A called" << endl;
}

void func(Container<B> c, bool x) {
    cout << "update for B called" << endl;
}

int main(int argc, char const *argv[])
{
    Container<A> * foo = new Container<A>(A(1));
    Container<B> * bar = new Container<B>(B(true));
    // test that func() works
    func(*foo,1,2);
    func(*bar,false);

    vector< Container<Derived>* > vec;

    // this does not work
    vec.push_back(unique_ptr< Container<Derived *> >(foo));
    vec.push_back(unique_ptr< Container<Derived *> >(bar));

    for (Container<Derived>* d : vec) {
        // how to call the proper func(d)?
    }
    return 0;
}

A:

1)   You can store pointers to A (type A *) or pointers to B (type B *) in a std::vector<Derived *>, because Derived is a base for both A and B.   It is not possible to store a Container<A> and a Container<B> into the same vector, because there is no inheritance relationship between them.    This is also (indirectly) the reason that converting foo and bar to unique_ptr<Container<Derived *> > is being rejected by your compiler.
2)  Your func() is not a "template specific function".   It is not even a templated function.   It is a function that is overloaded, with one variant that accepts two arguments, and one variant that accepts three.
3)   Given that your code is invalid, it is not possible to infer what your use case is.   Given that you are trying to convert objects to unrelated types, my guess is that your use case does not make sense in C++, let alone using templates for it.
Also, don't use Java (or whatever other language you are thinking in) techniques in C++, because they do not work the same way.   Specifically;
Container<A> * foo = new Container<A>(A(1));
Container<B> * bar = new Container<B>(B(true));
func(*foo,1,2);
func(*bar,false);

is unnecessary.   It is used in Java for various reasons that are invalid in C++, even if the code compiles.   Instead, do this;
Container<A> foo A(1);
Container<B> bar B(true);
func(foo,1,2);
func(bar,false);

This is valid and safe C++  (and will not work in Java, but that's another story).


Q:

Preenchimento de campo input

Boa tarde pessoal, é o seguinte, tenho dois campos input em um formulário, no primeiro input insiro um valor, logo depois clico em calcular e o segundo input é preenchido com valor que é calculado pela multiplicação do valor recebido no primeiro input por 2,40. até aí tudo certo, está funcionando legal, porém gostaria que o segundo input fosse preenchido logo quando o primeiro perdesse o focu sem a necessidade de clicar no botão calcular. segue o código e o exemplo

function calcularUFM(){
 var formulario = document.getElementById("formulario");

 var valor_ufm = +formulario.valor_ufm.value;

 var reais = (valor_ufm * 2.40);

 formulario.reais.value = reais.toFixed(2);

}

  <title></title>
  <link rel="stylesheet" href="css/estiloImc.css" type="text/css" media="all">

  <form id="formulario">
    <fieldset>
      <legend>CACULADORA UFM / REIAIS</legend>

      VALOR EM UFM
      <input type="text" name="valor_ufm" />

      <input type="text" name="reais" disabled="disabled" />

      calcular
    </fieldset>
  </form>

A:

Pode aplicar um onblur no campo chamando a função:
formulario.valor_ufm.onblur = calcularUFM;

Ou direto no elemento:
<input type="text" name="valor_ufm" onblur="calcularUFM()" />


Q:

What does inflater.inflate() do?

I went through the API but could not understand well. I could not understand the result of this method. I am completely new to Android & require help.
package com.javacodegeeks.android.fragmentstest;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentTwo extends Fragment
{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        return inflater.inflate(R.layout.fragment_two, container, false);
    }
}

A:

Basically, Inflate is a method which parses the first parameter view and puts it inside the second parameter ViewGroup.
third parameter says, put the view in the ViewGroup or not now?
if it's false, You will have to manually addView(view) , it's benefits are maybe if you want to add a view based on a condition,
If (view != null){
addView(view);
}

It's true by default if you didn't specify it.
inflate(R.layout.popup,myLinearLayout,true);
basically, changes the layout file called Popup.xml to a real layout & not just text, then puts in inside the LinearLayout specified in this case , it's myLinearLayout, True says put it now, I have no conditions or anything to do before.

A:

You have a View defined in your xml file. E.g. you have a layout for a list row.
You want to create a View from that xml. E.g. your ListAdapter requires you to create a View for a list row in ListAdapter.getView();
So by using inflater.inflate() you create your View from your XML file.
There's also a static method View.inflate() which does the same.


Q:

Cannot create property 'fillColor' on string ''

I using google maps to draw polygon and has function to add Polygon object
Here is listener to polygon
drawingManager = new google.maps.drawing.DrawingManager({
  drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
  drawingControlOptions: {
    drawingModes: [
      google.maps.drawing.OverlayType.RECTANGLE,
      google.maps.drawing.OverlayType.POLYGON

    ]
  }
});

drawingManager.addListener('polygoncomplete', function(polygon) {

  currentShape = addPolygonPlace('unsaved', polygon.getPath().getArray(), '');
  polygon.setMap(null);
  drawingManager.setMap();
});

And here is function to adding Polygon.
function addPolygonPlace(id, paths, colors) {

  var place = new Polygon(id, paths, colors);
  mapWrapper.addPlace(place);

  place.addEventListener('mouseover', function() {
    placeInfobox.update(place);
    placeInfobox.show();
  });

  place.addEventListener('mouseout', function() {
    placeInfobox.hide();
  });

  place.addEventListener('click', function() {
    if (selectedShape) {
      selectedShape.setEditable(false);
      google.maps.event.trigger(selectedShape, 'edit_end');
    }

    place.setEditable(true);
    selectedShape = place;
  });

  google.maps.event.addListener(place, 'edit_end', function() {
    if (place.id === 'unsaved') {
      return;
    }
    var placeToEdit = getPlaceByDescription(place.id);
    var path = place.googleEntity.getPath().getArray();

    updatePlace(place.id);
  });

  return place;
}

Also as you can see from this row var place = new Polygon(id, paths, colors);
I have using Polygon object with properties , here is it's code.
var Polygon = (function() {

  'use strict';

  function Polygon(id, paths, colors) {

    this._visible = true;
    this.id = id;
    this.paths = paths;
    // this.infoboxDescription = infoboxDescription;

    if (colors === undefined || colors === null) {
      colors = {
        fillColor: '#006400',
        strokeColor: '#646464'
      };
    }

    if (colors.fillColor === undefined || colors.fillColor === null) {
      colors.fillColor = '#006400';
    }

    if (colors.strokeColor === undefined || colors.strokeColor === null) {
      colors.strokeColor = '#646464';
    }

    this.googleEntity = new google.maps.Polygon({
      strokeColor: colors.strokeColor,
      fillColor: colors.fillColor,
      paths: paths
    });
  }

  Object.defineProperty(Polygon.prototype, 'visible', {
    get: function() {
      return this._visible || (this._visible = false);
    },
    enumerable: true,
    configurable: true
  });

  Polygon.prototype.remove = function() {
    this.googleEntity.setMap(null);
  }

  Polygon.prototype.addEventListener = function(eventName, callback) {
    this.googleEntity.addListener(eventName, callback.bind(this));
  }

  Polygon.prototype.setEditable = function(editable) {
    this.googleEntity.setEditable(editable);
  }

  return Polygon
})()

But I have error. In this row
if (colors.fillColor === undefined || colors.fillColor === null) {
       colors.fillColor = '#006400';
   }
I have this one

Cannot create property 'fillColor' on string ''
      at new Polygon (Place.js:65)
      at addPolygonPlace (Index.js:1895)

How I can solve it?

A:

"use strict";

var colors = 'string';
colors.fillColor = 'abc';

Uncaught TypeError: Cannot create property 'fillColor' on string 'string'

"use strict";

var colors = {};
colors.fillColor = 'abc';

No error

If this needs any comment: you can't create an object property on a variable of type string.


Q:

Can't pull without saying which branch to rebase against

I've written a script that does rebasing.
When I run $ my-rebase, I get an error:

You asked me to pull without telling me which branch you want to
  rebase against, and 'branch.rohan_branch1.merge' in your configuration
  file does not tell me, either. Please specify which branch you want to
  use on the command line and try again (e.g. 'git pull
  '). See git-pull(1) for details.
If you often rebase against the same branch, you may want to use
  something like the following in your configuration file:
[branch "rohan_branch1"]
remote = <nickname>
merge = <remote-ref>
rebase = true

[remote "<nickname>"]
url = <url>
fetch = <refspec>

I have master branch (working copy) and then I created rohan_branch1; it seems like at some point in time I did rebase in master.
Now I want to keep rohan_branch1 up-to-date. How can I get rid of this error ?

A:

If you want to rebase when pulling (git pull --rebase), you need to have an upstream branch associated with the local branch on which you are pulling to:
git branch --set-upstream rohan_branch1 nickname/anotherBranch

(as CharlesB describes in "“git rebase origin” vs.“git rebase origin/master”")
From there, you could consider the gup script (from "gup: A friendlier git pull --rebase") from Jason Weathered:
function gup
{
  # subshell for `set -e` and `trap`
  (
    set -e # fail immediately if there's a problem

    # use `git-up` if installed
    if type git-up > /dev/null 2>&1
    then
      exec git-up
    fi

    # fetch upstream changes
    git fetch

    BRANCH=$(git symbolic-ref -q HEAD)
    BRANCH=${BRANCH##refs/heads/}
    BRANCH=${BRANCH:-HEAD}

    if [ -z "$(git config branch.$BRANCH.remote)" -o -z "$(git config branch.$BRANCH.merge)" ]
    then
      echo "\"$BRANCH\" is not a tracking branch." >&2
      exit 1
    fi

    # create a temp file for capturing command output
    TEMPFILE="`mktemp -t gup.XXXXXX`"
    trap '{ rm -f "$TEMPFILE"; }' EXIT

    # if we're behind upstream, we need to update
    if git status | grep "# Your branch" > "$TEMPFILE"
    then

      # extract tracking branch from message
      UPSTREAM=$(cat "$TEMPFILE" | cut -d "'" -f 2)
      if [ -z "$UPSTREAM" ]
      then
        echo Could not detect upstream branch >&2
        exit 1
      fi

      # can we fast-forward?
      CAN_FF=1
      grep -q "can be fast-forwarded" "$TEMPFILE" || CAN_FF=0

      # stash any uncommitted changes
      git stash | tee "$TEMPFILE"
      [ "${PIPESTATUS[0]}" -eq 0 ] || exit 1

      # take note if anything was stashed
      HAVE_STASH=0
      grep -q "No local changes" "$TEMPFILE" || HAVE_STASH=1

      if [ "$CAN_FF" -ne 0 ]
      then
        # if nothing has changed locally, just fast foward.
        git merge --ff "$UPSTREAM"
      else
        # rebase our changes on top of upstream, but keep any merges
        git rebase -p "$UPSTREAM"
      fi

      # restore any stashed changes
      if [ "$HAVE_STASH" -ne 0 ]
      then
        git stash pop
      fi

    fi

  )
}

Instead of calling git pull --rebase directly, it will manage untracked files (stash) and will preserve merge commits (git rebase -p) when rebasing.
(See "Rebasing Merge Commits in Git" from the "Envato Notes blog")


Q:

D3 Path in Group does not show up in Firefox, only shows up in Chrome

I have the following - I've been tinkering around with it for a while, but I can't seem to get the path to appear in Firefox. Does anyone have any clue why? The circles show up. Firefox code inspector also gives it a size of 0x0.
<g transform="translate(85 460)" class="avatar">
  <circle cy="0" cx="0" r="6" class="base"></circle>
  <path transform="translate(0, 0) rotate(0) scale(1)" fill="black" d="M 0,0, L 0,8, L 10,0 Z"></path>
  <circle cy="0" cx="0" r="3" class="dot"></circle>
</g>

Any help would be very much appreciated.
EDIT:
Full svg:
<svg style="border: 1px solid black;" height="500" width="500">
  <image height="500" width="500" y="0" x="0" xlink:href="image.jpg"></image>
  <path style="opacity: 1;" d="M85,460Q81,150,85,110C91,49.99999999999999,113,60,125,60S162.75,77,165,110S131,250,140,280S204,305.5,225,310S268.75,322,280,310S291,254,300,230S328,150,340,150S371,209,380,230S394.75,278,400,290S410.5,307,415,310S424,310,430,310S449.75,307,455,310S463.5,324,465,330S465,338.75,465,350Q465,357.5,465,405" class="path selected"></path>
  <path d="M110,395L380,395" class="path"></path>
  <g transform="translate(85 460)" class="avatar">
    <circle cy="0" cx="0" r="6" class="base"></circle>
    <path transform="rotate(0) scale(1)" fill="black" d="M 0,0, L 0,8, L 10,0 Z"></path>
  </g>
</svg>

A:

Per the SVG specification if a comma occurs in a path it must have a number on either side of it.
Your path is invalid and Firefox rendering of the path is correct. I don't know if there is a Chrome bug on its invalid rendering of this path bug if there isn't you could create one.
To get your path to work in FF, remove the stray commas:
<path transform="rotate(0) scale(1)" fill="black" d="M 0,0 L 0,8 L 10,0 Z"></path>


Q:

Why is Python more strict with circular imports when using from-imports?

I know that Python discourages any situation which can get you into a circular import. But I wanted understand the Python internals of why from-imports are seemingly arbitrarily less forgiving than normal imports in circular import situations.
For example, this code compiles:
# main.py
import CommonUtil

# commonutil.py
import util
class CommonUtil:
    # some code that uses util.Util
    pass

# util.py
import commonutil
class Util:
    # some code that uses commonutil.CommonUtil
    pass

But this code does not:
# main.py
import CommonUtil

# commonutil.py
import util
class CommonUtil:
    # some code that uses util.Util
    pass

# util.py
from commonutil import CommonUtil
class Util:
    # some code that uses CommonUtil
    pass

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import CommonUtil
  File "commonutil.py", line 1, in <module>
    import util
  File "util.py", line 1, in <module>
    from commonutil import CommonUtil
ImportError: cannot import name CommonUtil

You don't hit compiler errors as long as you don't try to use the relevant classes before all the imports have completed. But when you try to do some aliasing, then it fails. Can someone explain what's going on internally in the Python that causes this error to rear its head only when from-import is used? And secondarily, is there any easy way around this? (Besides the obvious "pull shared code out to a third module," which I'll likely do anyways.)

A:

see http://effbot.org/zone/import-confusion.htm#circular-imports for an explanation of what is happening.
I assume you launch the main.py file. Python will first try to load commonutil. It will create a module object, and start filling it with class and function and global variable when encountering their definition. The first statement is an import, so now python creates the util module and start filling it. The common module exist, but is empty. In the first version, you do not access any commonutil object at load time, so everything is fine. In the second one, you try to fetch a specific variable in commonutil which does not exist at this moment. If you had used something like f(commonutil.CommonUtil) in the first version, it would have also crashed.


Q:

Pandas.replace not removing character from data

I have a pandas data frame with the character " in some places (Python 2.7).
I want to remove all of the " from the data. I'm using the following method:
data_frame.replace(to_replace'"', value = '')

However, the data frame stays the same and the action doesn't take place.
Any advice on what the problem is would be greatly appreciated.

A:

You can try replace with regex=True:
import pandas as pd

df = pd.DataFrame({'ItemID': {0: 8988, 1: 8988, 2: 6547, 3: 6547},
                   'Description': {0: 'Tall Chair', 1: 'Tall Chair', 2: 'Big" Pillow', 3: 'Big Pillow'},
                   'Feedback': {0: 'I hated it""', 1: 'Best chair" ever', 2: 'Soft and amazing', 3: 'Horrific color'}})
print df
   Description          Feedback  ItemID
0   Tall Chair      I hated it""    8988
1   Tall Chair  Best chair" ever    8988
2  Big" Pillow  Soft and amazing    6547
3   Big Pillow    Horrific color    6547

print df.replace({'"': ''}, regex=True)
  Description          Feedback  ItemID
0  Tall Chair        I hated it    8988
1  Tall Chair   Best chair ever    8988
2  Big Pillow  Soft and amazing    6547
3  Big Pillow    Horrific color    6547


Q:

Make a python script API

I have a script on python, which prints some data. The script is on Centos7, nginx.
How could I connect to the script via URL (GET query) to be able to parse the data?

A:

You can use a framework like Django or flask to make an api out of it. I'll suggest flask since it's very light-weight, making it ideal for such small tasks.
E.g.
def your_function(input):
    # do something
    return output

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/my_api')
def your_api_function():
    input = request.args.get('my_query_string')
    return your_function(input)

if __name__ == '__main__':
    app.run(debug=True)

And then use the endpoint

/my_api?my_query_string=my_input

You can further play around with it to return JSON, take parameters from request body and so on and so forth.
Read more here http://flask.pocoo.org/


Q:

Teaching People to Read Documentation

For many questions posted to Stack Overflow, the questioner could have solved the problem themselves in a few minutes of reading the documentation. However, much as the workings of a for loop seem so much more obvious to an experienced programmer, it occurs to me that the instinct to go for the manual and the knowledge of how to efficiently read it are not obvious and innate to all people.
How can we help people learn to RTFM? Beyond simply telling people to do it, what resources can we provide to teach them to do it? What kind of comments should we leave? Is it just something that needs practice before it becomes second nature, or are there specific documentation-locating and documentation-reading techniques we should point out? Is there a canonical question to link to (and if so, is it structured in a way that's useful to the people it targets)?

A:

I dispute the premise of this question.
We can help askers read documentation, but in order to do so we will, by definition, write answers and comments — a kind of documentation. In fact this documentation persists on SO and has a name: "duplicates".
Will we then have to help people RTFA and RTFC? By writing more answers and comments? (Related: http://xkcd.com/1343/)
This leads to an intractable "turtles all the way down" meta-problem.
My answer is: Just point to the documentation*. Let the user have a shot at it. If the user tries to apply it and fails, then they can ask a question about that including what they tried, which is fine. If.
* In a comment, of course. Link-only answers suck. So do answers to non-RTFM questions more generally.

A:

One of the best features of S/O, in my opinion, is the fact that so often it succeeds where documentation fails.  This is for one of two reasons: the documentation is insufficient, or does not contain a good searching mechanism.  Stack overflow (often via Google) is superbly searchable, and so it is often much faster to find the answer to a question here than it is to RTFM.
If someone asks a good quality (short, sweet, useful, non-duplicate) question, I think that's great even if the answer is in the manual.  If nobody feels like bothering to answer it, that's fine too.
On a related note, my favorite answers often have a bonus link to the relevant documentation.

A:

I think learning by doing will work.
The trick is how to get people to start reading in the documentation at all.
Suggestion:
Mention in your answer the existence of some interesting additional information
about the topic.
Do not explain that information, but include a hyperlink to it.
I think this can work well in short answers
as well as longer ones.


Q:

A Neat Identity Involving Zeta Zeroes

While playing around, I encountered the following very curious and cool identity. Consider the exponential integral $\text{Ei}(x)$ and the $n$th nontrivial zero of the Riemann Zeta function $p_n$.
Now, look at the first few imaginary parts of the following function:
$$f(x)=\sum_{n=1}^x \text{Ei}(p_n)$$
$$\Im \ \ f(1)=3.13732$$
$$\Im \ \ f(10)=31.3169$$
$$\Im \ \ f(100)=314.097$$
$$\Im \ \ f(1000)=3141.54$$
$$\Im \ \ f(10000)=31415.9$$
As you can see, it is each time adding a digit of pi.
Question: Is this a known result that can be proved easily? Does this pattern even continue?

A:

The result found by OP turns out to be quite generic; it holds for a wide range of sequences $\rho_n$ and not just the zeros of the $\zeta$-function. A precise formulation of what is observed is the following:
$$\lim_{N\to\infty} \frac{1}{N}\sum_{n=1}^N \text{Ei}(\rho_n) = \pi i \tag{1}$$
The sum above is the Cesaro mean of the sequence $a_n = \text{Ei}(\rho_n)$. If a sequence $a_n$ converges to $a$ then the Cesaro mean of $a_n$ also converges to $a$ (see e.g. this question) so $(1)$ would follow if we could show that $\lim_{n\to\infty}\text{Ei}(\rho_n) = \pi i$.
This is indeed true and the reason for this is as follows:

We can write $\text{Ei}(z)$ on the form $\text{Ei}(z) = -\Gamma(0,z) + \pi i$ where the incomplete $\Gamma$-function has the asymptotical expansion $\Gamma(0, z) = \frac{e^{-z}}{z} + \mathcal{O}(z^{-2})$. This implies that $\Gamma(0, z_n) \to 0$ for any sequence $z_n = x_n + i y_n$ where $y_n\to \infty$ and where $x_n$ is bounded.
The non-trivial zeros of the $\zeta$-function satisfy the conditions on the sequence above since they all lie in the strip $0<\Re[z]< 1$ in the complex plane and $\lim_{n\to\infty}\Im[\rho_n] = \infty$. This means that $\lim_{n\to\infty}\Gamma(0,\rho_n) = 0$ so $\lim_{n\to\infty} \text{Ei}(\rho_n) = \pi i$ and $(1)$ follows.

Note that the conditions in point 1. above are far from being very restrictive so there are infinitely many sequences for which $(1)$ holds (random examples are $\rho_n = 7 + n^2i$ and $\rho_n = \frac{2n}{1+n} + n\log(n)i$).

A:

This is not a proof, just some tips that can may be leads to a proof
(I really hope someone manage to find a proof for this result)

You can consider the other form for the exponential integral:
$$Ei(z)=\gamma +\ln(x)+\sum_{k=1}^\infty\frac {x^k}{k\cdot k!},$$
where $\gamma$ is the Euler-Mascheroni's constant.
Call the $n$-th non trivial zero
$$p_n=:\frac 12 +i \alpha_n.$$
So you get
$$Ei(p_n)=\gamma +\ln\left(\frac 12 +i \alpha_n\right)+\sum_{k=1}^\infty\frac {\left(\frac 12 +i \alpha_n\right)^k}{k\cdot k!}.$$
Use the principal determination of the complex logarithm: $\ln(x+iy)=\ln(x)+i\arg(x+iy)$, where
$$\arg(x+iy)=\arctan\left(\frac yx\right).$$
So
$$Ei(p_n)=\gamma +\ln\left(\frac 12\right) +i\arctan(2\alpha_n)+\sum_{k=1}^\infty\frac {\left(\frac 12 +i \alpha_n\right)^k}{k\cdot k!}.$$
So
$$\mathfrak I(Ei)(p_n)=\arctan(2\alpha_n)+\sum_{k=1}^\infty\left(\sum_{\substack{m=0 \\ m\equiv 1 (4)}}^{k}\frac {\binom km\alpha_n^m}{2^{k-m}k\cdot k!}-\sum_{\substack{m=0 \\ m\equiv 3 (4)}}^{k}\frac {\binom km\alpha_n^m}{2^{k-m}k\cdot k!}\right),$$
using
$$\binom km=\frac{k!}{m!(k-m)!}$$
you get
$$\mathfrak I(Ei)(p_n)=\arctan(2\alpha_n)+\sum_{k=1}^\infty\left(\sum_{\substack{m=0 \\ m\equiv 1 (4)}}^{k}\frac {\alpha_n^m}{2^{k-m}k\cdot m!(k-m)!}-\sum_{\substack{m=0 \\ m\equiv 3 (4)}}^{k}\frac {\alpha_n^m}{2^{k-m}k\cdot m!(k-m)!}\right).$$
The key is to use now the approximation:
$$\alpha_n\approx \frac{2\pi n}{\ln(n)}$$
to put $\pi$ in the place.
To conclude, you have to prove that
$$\lim_{x\to \infty}\frac 1x\sum_{n=1}^x\mathfrak I(Ei)(p_n)=\pi.$$
For the first term, you can say that
$$\frac 1x\sum_{n=1}^x \arctan(2\alpha_n)=\frac 1x\left(\text{a finite number of terms}\right)+\frac 1x(x-K)\left(\text{something close to $\frac\pi2$}\right),$$
so
$$\lim_{x\to \infty}\frac 1x\sum_{n=1}^x \arctan(2\alpha_n)=\frac\pi 2.$$
Now, you need to deal with the second term, you can use Stirling formula
$$y!\sim \sqrt{2\pi y}\frac{y^y}{e^y}$$
to get
$$\frac {\alpha_n^m}{2^{k-m}k\cdot m!(k-m)!}=\frac{(2\pi n)^m e^m e^{k-m}}{\ln(n)^m 2^{k-m}k\sqrt{2\pi m}m^m \sqrt{2\pi(k-m)}(k-m)^{k-m}}$$
$$=k\left(\frac{2\pi n}{m\ln(n)}\right)^m\left(\frac e{2(k-m)}\right)^{k-m}\sqrt{2\pi k}.$$


Q:

Is it possible to restrict the amount of data ('gate' the data) sent to unauthenticated (angularFire) clients in firebase?

Here I am fetching the data using angularFire:
angular.module('FireApp', ['firebase'])
  .controller('Document', function($scope, $routeParams, angularFire){
    var url = "https://my-account.firebaseio.com/test" + "/" + $routeParams.data;
    angularFire(url, $scope, data);
});

The problem is that this will load the 'https://my-account.firebaseio.com/test/data' and all of its children and grandchildren etc..
The '/data' is an array of objects, which can (but doesn't have to - it could very well be an array of Strings) look similar to the parent of "/data":
data: ["0" : {
    "data" : [...],
    "meta" : {
      "active" : false
    },
    "sign" : [...]
  },
  "1" : {
    "data" : [...],
    "meta" : {
      "active" : true
    },
    "sign" : {...}
  },
  "2" : {
    "data" : [...],
    "meta" : {
      "active" : false
    },
    "sign" : {...}
  }]

Basically, I want all unauthenticated angularFire clients to receive ONLY those elements of the data array, where the boolean flag meta.active = true, i.e. the active flag need to decide whereas its grandparent will be sent to the client upon the angularFire request. Also unauthenticated clients can't write/edit any of the data. The rule I want to set should say: "whenever the 'active = false' flag is set do not send the flag's grandparent to the angularFire client, unless the client is authenticated.". So yes the rule need to be relative rather than absolute.
Only authenticated clients should be able to receive/edit all the data.
Can I make such rules with Firebase Simple Login and Security Rules?
If this can't be done for a grandparent, the 'active' flag can be moved one level up to affect its parent instead.
Thank you for your time,
Jared

A:

You'll need to restructure your data in order to achieve this with Firebase. See this blog post for some background on this: https://www.firebase.com/blog/2013-04-12-denormalizing-is-normal.html
One way to structure the data would be to create two separate lists, one for active items and another for inactive items. When an item becomes active or inactive, be sure to remove it from one list and put it in another.
{
  "active": {
    0: {
      "data": {...},
      "sign": {...}
    }
  },
  "inactive": {
    0: {
      "data": {...},
      "sign": {...}
    }
  }
}

In your security rules, you can simply prevent access to inactive items to unauthenticated users:
{
  "rules": {
    "active": {
      ".read": true
    },
    "inactive": {
      ".read": "auth != null"
    }
  }
}

Hope this helps!


Q:

Nothing to commit, working tree clean after calling git checkout

I tried to delete my last commit. I thought that git checkout followed by the hash of the commit would replace my current code with the code of the commit. This didn't work and I get now a message which says Nothing to commit, working tree clean. How can I get rid of this message and delete my last commit?

A:

By doing git checkout <hash> you went into so called "detached head" state, which in simple terms means you're not on any branch right now. If you want to return to your normal branch just do:
git checkout <branch name>
(where <branch name> can be any of master, develop, hotfix - it really depends how you name them and what flow you use to manage your development/release cycle... try git branch --list to get a list).
After that, if you want to delete the last commit you can do:
git reset --hard HEAD~1
but be very careful about the --hard switch as it will physically delete the most recent commit, which basically means it's unrecoverable (and I don't really remember if manipulating the reflog would help restore it in this situation).


Q:

How do I get images from 35 mm positive film?

How do I get images made from a roll of 35 mm positive film?
I've had a professional try to create individual prints, but they said they couldn't as the film was positive not a negative roll.

A:

i need to make images from a roll of 35 mm positive film?

The path of least resistance here is surely to just have the film scanned, or do it yourself, and print the images digitally.

A:

I think your 'professional' is just saying he isn't set up to do this job.  It's certainly possible to make prints from colour slides. Here's one company that offers this service in the UK.
https://www.snappysnaps.co.uk/photo-printing/prints-photos-from-slides.html
Years ago, this was done using either the Ilfochrome or 'Type R' processes.   Now, I imagine everyone scans the film and does the job digitally.

A:

The easiest way to get prints of your positive film is to do the following:

Digitize the film or have this done for you. (this is sometimes called duplicating, see note on historical nomenclature below)
Retouch / remaster the image as desired
Have the image printed or print it yourself. Note that if you want a photographic print, doing so is still possible from a digital image using a wet process. See Photo Printers versus Fine Art Printers

I'm going to assume that you know how to do items 2 and 3. Elsewise you can probably find answers here or ask a separate question. Below is a quick run-down of your options for duplicating this film in descending order of quality but not necessarily in descending order of price.

A professional film digitizing service. I have utmost respect for anyone still running their own photo service but duplicating and digitizing film requires special training. If your Pro did not know that he could just skip inverting the scanned images... he's not trained. Price is per frame, usually in the range of 20 to 75 US cents. sometimes there is a setup fee. Talk to the service you select first and ask them for a sample file, preferably from a scanned positive slide. Make sure they understand that you are asking them to scan positive film that is not slide mounted. This is uncommon but, again, a professional should have no problem with it.
A dedicated film scanner. This will produce the highest quality images possible, especially if you invest some time studying an experimenting with it. The professional scanning service is likely using a unit that costs between $1.5k and $15k USD but you can get great results from a scanner in the $300 USD range
A flatbed scanner. These used to be much more common a decade ago when scanners were a bit more expensive. Basically you need a flatbed scanner with a light in the top half. You could try to make your own by sandwiching the negative between an ordinary flatbed scanner and an LCD screen displaying white but since reasonably good scanners designed for the purpose can be had for under $200 USD, Occum's razor should prevail. Again, if possible, do your research and find a review where someone has included an image they scanned before you select your scanner.
A Slide Duplicator Camera Adapter. Assuming you own an SLR you could try one of these units. Note that you will need to also purchase a film strip carrier which is compatible with the slide adapter. Since the "slide duplicators" generally include a dioptric lens, there is a definite "get what you pay for" relationship. Shop around on ebay and amazon but expect to pay around $100 for something that actually works. Note that there are special variants of this device available if you happen to own a lens capable of 1:1 (or near 1:1) magnification. I recommend capturing images in raw then exporting the at half the raw dimensions with a bit of sharpening. This will help to limit aliasing. Capturing as JPEG and downres-ing is OK too.
There's an app for that. Sorry, I couldn't resist. This technique also makes use of an LCD monitor as the light source. Your smartphone then acts as the scanner. I wouldn't use this to reproduce imagery in any professional capacity but if you goal is to get a positive onto the internet or to make a couple of 4x6's of family memories to share with relatives you could get away with it. Regardless it's free so you could always try it out before you climb the cost ladder.

Finally, if you are really set on making a photographic print from film that is possible. Aside from nearly extinct processes that offer "positive printing" you can print your positive using something called an internegative. To expose the internegative you will perform emulsion contact printing. This means you bring the emulsion of the positive into direct contact with the emulsion of an unexposed negative (generally by taping them together or trapping them between glass) and then provide a controlled exposure. Commercial examples of film contact duplicators, the original namesake of this process are now used exclusively in medical imaging and are therefore quite expensive. However, you could perform this task with careful use of two panes of glass, some masking tape, a black bag, and a photographic enlarger. I've done it in the past but honestly wouldn't recommend it to anyone who values their time.
Note: any items or retailers I've linked to are as examples. I've used a few of the items listed but am not explicitly endorsing any of them.


Q:

WSO2 get user by claim value

I need to know how to get wso2 users by claim value, to perform some kind of search?
example:
getUsersByClaimValue(String claimUri, String claimValue);

A:

Yes.This API method has been introduced  to user store API to get user names associated with particular user's attribute. say you want to get users whose "country" attribute value is "USA". then you can use this method as follows.
getUserList("http://wso2.org/claims/country", "USA", null);
You can find this method as web service API in RemoteUserStoreManagerService  of WSO2IS.  Your SOAP message would look likes follows.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.ws.um.carbon.wso2.org">
   <soapenv:Header/>
   <soapenv:Body>
      <ser:getUserList>
         <ser:claimUri>http://wso2.org/claims/country</ser:claimUri>
         <ser:claimValue>USA</ser:claimValue>
         <ser:profile></ser:profile>
      </ser:getUserList>
   </soapenv:Body>
</soapenv:Envelope>
Here, this claim uri is generic one which is independent of the user store. With WSO2 Identity server you can map these claim uri in to any attribute in your user store. More details from here


Q:

Open and closed mapping are not necessarily continuous

In the link http://en.wikipedia.org/wiki/Open_and_closed_maps,
it says
"To every point on the unit circle we can associate the angle of the positive x-axis with the ray connecting the point with the origin. This function from the unit circle to the half-open interval $[0,2π)$ is bijective, open, and closed, but not continuous."
So is $(1,0)$ the only point on the circle that isn't continuous?
Also, the Wikipedia article says the floor function is both open and closed. I don't see how it can be open since the image of the set $(0,1)$ under the floor function is $\{0\}$, which is definitely not open.

A:

1) Yes, $(1,0)$ is the only point on the circle where this function is discontinuous.
2) You left out something: it says "the floor function from R to Z is open and closed, but not continuous."  $\{0\}$ is open as a subset of the discrete space $\mathbb Z$.

A:

You're correct that the only point where the map
$$f: S^1 \longrightarrow [0, 2\pi),$$
$$f(\cos \theta, \sin \theta) = \theta$$
is discontinuous is $(1, 0)$.
As for the floor map, they are considering it as a map
$$\lfloor \cdot \rfloor : \Bbb R \longrightarrow \Bbb Z,$$
where $\Bbb Z$ has the discrete topology. Hence every subset of $\Bbb Z$ is both open and closed. Of course $\lfloor \cdot \rfloor$ is not continuous since, for example, the inverse image of the open set $\{0\}$ is $[0, 1) \subset \Bbb R$, which is not open.


Q:

JFreeChart Merged point

I'm using JFreechart to analyze sample data of some devices.
The data i collect is high frequency recorded and when i try to visualize the data the chart seems unreadable cause full of point.

One solution i think is to merge the nearest point in unzoomed state and then see them all when i zoom.

I don't find the way to change the data point between zoomed and unzoomed state.
Anyone know if is possible? (I accept also other solution! :) )

A:

As shown here, you can invoke ChartPanel methods to alter the zoom state.


Q:

Orika: Map from String to a List of SomeObjects

Consider the following situation:
public class A {
    private String stringA;

    public String getStringA() {
        return stringA;
    }

    public void setStringA(String stringA) {
        this.stringA = stringA;
    }

}

public class B {

    List<SomeObject> someObjects;

    public List<SomeObject> getSomeObjects() {
        if (someObjects == null) {
            someObjects = new ArrayList<SomeObject>();
        }
        return someObjects;
    }

}

public class SomeObject {
    private String stringSomeObject;

    public String getStringSomeObject() {
        return stringSomeObject;
    }

    public void setStringSomeObject(String stringSomeObject) {
        this.stringSomeObject = stringSomeObject;
    }

}

I want to map from A to B. Whilst mapping these, stringA needs to be  mapped to stringSomeObject in SomeObject. I tried to write a Orika-Mapper for this:
public class MyMapper extends ConfigurableMapper {

    @Override
    protected void configure(MapperFactory factory) {
        ConverterFactory converterFactory = factory.getConverterFactory();
        converterFactory.registerConverter(new StringToSomeObjectConverter());

        factory.classMap(A.class, B.class) //
                .field("stringA", "someObjects") //
                .byDefault() //
                .register();
    }

}

It maps class A to B and whenever it encounters a conversion from String to List<SomeObject> it calls a custom-converter:
public class StringToSomeObjectConverter extends CustomConverter<String, List<SomeObject>> {

    private static final String BORROWER_PARTY_TYP_CODE = "147";

    @Override
    public List<SomeObject> convert(String source, Type<? extends List<SomeObject>> destinationType) {
        SomeObject someObject = new SomeObject();
        someObject.setStringSomeObject(source);
        return Arrays.asList(someObject);
    }

}

I wrote an unit-test to ensure that this works:
@Test
public void testMap() throws Exception {
    A a = new A();
    a.setStringA("a");

    B outcome = new MyMapper().map(a, B.class);

    assertThat(outcome.getSomeObjects.size(), is(1));
}

Sadly this test fails with:
java.lang.AssertionError:
Expected: is <1>
   but: was <0>

It seems like the Converter is never executed so I tried to debug it. And indeed: The debugger never reaches the converter. Am I doing something wrong? It seems like. I know there are more methods which one could go with like: mapAToB e.g...
Ok I found a solut...nah! It's not a solution, it's just a workaround. I defined the stringA as List<String> as well and defined a converter extending CustomConverter<String, LoanContrReqERPCrteReqLoanContrBrrwrPty>.
Because this feels a little "hacky", I am still interested in a nice solution. (Though I am just thinking that this solution might be fine: Now the datastructure of both objects is more equal than before. The problem is, that object B is coming from an external service, I can't modify it.)

A:

You mapping doesn't work because you don't have setter for someObjects.
When Orika tries to generate code for mapper, it checks all fieldMaps in classMap for sourceProperty is readable and destinationProperty is assignable. If this checks passed, generator puts field conversion into generated mapper. If check failed, Orika just skip this field conversion.
Few options you can use to solve a problem:

You can add setter for someObjects field in class B:
public static class B {

    List<SomeObject> someObjects;

    public List<SomeObject> getSomeObjects() {
        if (someObjects == null) {
            someObjects = new ArrayList<SomeObject>();
        }
        return someObjects;
    }

    public void setSomeObjects(List<SomeObject> someObjects) {
        this.someObjects = someObjects;
    }
}

Use custom mapper instead of converter:
    factory.classMap(A.class, B.class)
            .customize(
                    new CustomMapper<A, B>() {
                        @Override
                        public void mapAtoB(A a, B b, MappingContext context) {
                            SomeObject someObject = new SomeObject();
                            someObject.setStringSomeObject(a.getStringA());
                            b.getSomeObjects().add(someObject);
                        }
                    }
            )
            .byDefault()
            .register();

Orika will put invocation customMapper after resolving of field maps.
Generated mapper will looks like:
    b.setOtherField(a.getOtherField());
    if (customMapper != null) {
        customMapper.map(source, destination); <-- Your mapper invocation
    }

Use follow syntax for fields:
    factory.classMap(A.class, B.class)
            .field("stringA", "someObjects[0].stringSomeObject")
            .byDefault()
            .register();

Generated mapper will looks like:
    if (source.getStringA() != null) {
        if (((((java.util.List) destination.getSomeObjects()).size() <= 0 || ((List) destination.getSomeObjects()).get(0) == null))) {
            ((java.util.List) destination.getSomeObjects()).add(0, ((BoundMapperFacade) usedMapperFacades[0]).newObject(((String) source.getStringA()), mappingContext));
        }
    }

    if (!(((java.lang.String) source.getStringA()) == null)) {
        (((java.util.List) destination.getSomeObjects()).get(0)).setStringSomeObject(source.getStringA());
    } else if (!(((java.util.List) destination.getSomeObjects()) == null) && !((((java.util.List) destination.getSomeObjects()).size() <= 0 || ((List) destination.getSomeObjects()).get(0) == null))) {
        ( ((java.util.List) destination.getSomeObjects()).get(0)).setStringSomeObject(null);
    }

Also there was a bug in Orika to map from single property to property of collection using syntax .field("stringA", "elements{stringB}") ( Incorrect mapper code generated for mapping from a single property to property of collection element). Bug closed at 31 Dec 2016 here: Fix for bug


Q:

Return records that are not in a query

I have this query:
SELECT *
FROM Table.Diet
WHERE Diet.Date NOT IN (

SELECT Diet.Date
FROM Table.Diet
WHERE Diet.FruitsEatenToady = 'Banana'
Group BY Diet.Date)

Many fruits can be eaten in a single day.
But the query is returning days with in which banana's were eaten.
I'm new to db2 is there another syntax I can use for not in? Maybe some grouping?
Thanks
Edit Diet Table layout
  DATE-----FruitsEatenToday--Calories
  3/11/2014|Apple          | 116
  3/11/2014|Banana         | 106

Edit 2 totally butchered that first query updated it

A:

Given your table structure and query requirements, it looks like you need an anti-join:
SELECT d1.*
FROM Table.Diet AS d1
LEFT JOIN Table.Diet AS d2
ON d1.Date = d2.Date
AND d1.FruitsEatenToday <> d2.FruitsEatenToday
AND d2.FruitsEatenToday = 'Banana'
WHERE d2.FruitsEatenToday IS NULL


Q:

Setting default application in tomcat 7

I've gone through the threads that describe how to configure a given WAR (say abc.war) as default web-app in tomcat.
Either

Rename the abc.war to ROOT.war

or

Create a context ROOT.xml in ${tomcat.home}/conf/Catalina/localhost with path="" and docBase set to relative/absolute path to the war (keeping the abc.war
  outside of webapps to avoid double deployment).

Both the solutions result in ROOT.war in webapps (appBase) directory. However I want to retain the WAR name (abc.war) in webapps and not have a separate ROOT.war to achieve this.
One solution that worked in my case was adding a context under <Host> tag in server.xml . But as per Tomcat 7 Doc , it's not recommended to add context directly in server.xml.
Could someone point me to an alternative?
Thanks.

A:

detailed approach
First Method:

first shutdown your tomcat [from the bin directory (sh shutdown.sh)] then you
  must delete all the content of your tomcat webapps folder (rm -fr *) then
  rename your WAR file to ROOT.war finally start your tomcat
  [from the bin directory (sh startup.sh)]

Second Method:

leave your war file in CATALINA_BASE/webapps, under its original name - turn off
  autoDeploy and deployOnStartup in your Host element in the server.xml file.
  explicitly define all application Contexts in server.xml, specifying both path
  and docBase. You must do this, because you have disabled all the Tomcat
  auto-deploy mechanisms, and Tomcat will not deploy your applications anymore
  unless it finds their Context in the server.xml.

Note:

that this last method also implies that in order to make any change to any
  application, you will have to stop and restart Tomcat.

Third Method:

Place your war file outside of CATALINA_BASE/webapps (it must be outside
  to prevent double deployment). - Place a context file named ROOT.xml in
CATALINA_BASE/conf//. The single element in this context file MUST have a
  docBase attribute pointing to the location of your war file. The path element
  should not be set - it is derived from the name of the .xml file, in this
  case ROOT.xml. See the Context Container above for details.


Q:

Can`t send array using ajax with asp.net core

I`ve wrote this ajax function:
$(function () {
        $("#showReport").click(function () {
            var data = [];
            for (var i = 0; i <@Model.LiFilters.Count;i++) {
                data[i] = $("#filter" + i).val();
                $("#myDiv").html("Hello!");
            }

            alert('{filters:' + JSON.stringify(data) + '}');
            $("#myDiv").remove();
            $.ajax({
                type: "POST",
                url: '@Url.Action("ShowReport", "Report")',
                traditional: true,
                //data: '{filters:' + JSON.stringify(data) + '}',
                data: { filters : data },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert(data);
                    alert(response[0]);
                    $("#myDiv").html(response[0]);
                    alert(response);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
            return false;
        });
    });

And have this action in Report controller:
 [HttpPost]
public JsonResult ShowReport(string[] filters)
{
    C_AminReport aminReport = null;
    string sErr = string.Empty;
    //C_ReportParams aminParams = null;
    //C_AminReport aminReport;
    string sReport = "Empty Report!";
    if (C_AminReport.U_GetReport(aminReport.ID, out aminReport))
    {
        int iConIndex = Get_ServiceIndex();
        aminReport.U_RenderReport(iConIndex, ref sErr);
        aminReport.U_GetReportFromAmin(iConIndex, aminReport, out sReport, ref sErr);
    }
    string[] asReport;
    JsonBuilder.U_TryReadJson(sReport, out asReport);
    return Json(asReport);
}

But when run code i see data array filled but inside of the ShowReport action, fillters array is an empty array and not filled!
I also tries [FromBody] tag inside action params but it not works to!
What is the problem?

A:

I tested your JavaScript and it's trying send all the data in the query string.
You have to use JSON.stringify. One of these should work:
data: '{filters:' + JSON.stringify(data) + '}'

or
data: JSON.stringify(data)

I suspect it's the second that will work.
You may still need [FromBody].


Q:

Report generator for C++/Qt (Windows)

I have a program un C++/Qt written for Windows, which prints some graphs in pdf format and some other data in HTML.
I need to print all together into a single PDF, a single-file report.
I have looked for some libraries similar to Crystal reports, but I just find paid ones and I need a free open-source solution. I finally found RTK reports but it looks to run only with UNIX.
Any library or different solution for my needs?

A:

You might want to check out what Qt has built into it in versions 4.7 & 4.8.  From Qt 4.8: Printing with Qt, there is this little tidbit "Qt's printing system also enables PostScript and PDF files to be generated...."  The QPrinter class supports several different Output Formats, including PDF.
Disclaimer: I haven't played with this part of Qt, so YMMV.


Q:

Which players won both FIFA U-20 World Cup and FIFA World Cup?

Which players won both FIFA U-20 World Cup (until 2005 known as the FIFA World Youth Championship) and FIFA World Cup?
This would show players who excelled both in the young age and in their later career.
I guess that there will not be too many such players but, of course, I might be wrong.
I did not find any source where I could systematically search for statistics like this. By some more-or-less random searching I was able to find Maradona, Dunga and Xavi.

A:

If this source is correct, then the only players who won both U-20 World Cup and senior World Cup (as of 2013) were:

Diego Maradona. Maradona won FIFA World Youth Championship in 1979, he also received Golden Ball award for the best player in this tournament. In 1986 he won FIFA World Cup, again receiving the Golden Ball trophy.
Iker Casillas won FIFA World Youth Chamiponship in 1999. He won World Cup in 2010 World Cup, where he was also voted a member of the all-star team of the tournament  and he also won the Golden Glove for the best goalkeeper.
Xavi Hernandez won FIFA World Youth Championship in 1999. He was a member of the victorious Spanish team at 2010 World Cup, where he was also voted a member of the all-star team of the tournament.
Dunga helped Brazil to win World Youth Championship in 1983 and the World Cup in 1994 where he also became member of the all-star team.
Bebeto was a member of golden Brazilian team at the same tournaments as Dunga.
Jorginho won the gold medal at the same tournaments as Dunga and Bebeto. He was in all-star team of the 1994 World Cup.
Cláudio Taffarel won World Youth Championship in 1985 and World Cup in 1994.
Müller won golden medal at the same tournaments as Taffarel.
Dida won World Youth Championship in 1993. He was a member of Brazil winning team at 2002, although he did not play a game there.
Carlos Marchena won World Youth Championship in 1999 and World Cup in 2010.

Sources:

Maradona and other youth and senior world champions
Coupe du monde U20 : Que vont-ils devenir? (Internet Archive)


Q:

Получить ближайшие по индексу значения датафрейма

Имеется dataframe df

print(type(df.index[0]))
<class 'pandas._libs.tslibs.timestamps.Timestamp'>

Из столбцов max_high и max_rsi_14 нужно получить две равные по длине серии данных. В первой серии должны быть все не пустые значения из max_high, а во второй значения max_rsi_14 только ближайшие по индексу к не пустому значению max_high.
Пример желаемого итога:

Пробовал решать с помощью
df.index.get_loc(dt, method='nearest')

Но не смог разобраться. Пожалуйста помогите и спасибо за помощь!

Пример датасета
                       high     low     volume    open     ...      min_high  max_high  min_rsi_14  max_rsi_14
timestamp                                                  ...
2018-10-02 11:00:00  6553.0  6542.5   25845962  6552.0     ...           NaN       NaN         NaN         NaN
2018-10-02 12:00:00  6574.0  6534.0   99602546  6542.5     ...           NaN    6574.0         NaN   44.320898
2018-10-02 13:00:00  6557.0  6542.0   42124982  6552.0     ...           NaN       NaN         NaN         NaN
2018-10-02 14:00:00  6552.5  6497.0  136742416  6549.5     ...           NaN       NaN   34.712926         NaN
2018-10-02 15:00:00  6529.5  6505.5   55167626  6519.0     ...           NaN       NaN         NaN   39.25009

A:

Можно воспользоваться pd.merge_asof():
res = pd.merge_asof(df.loc[df['max_high'].notna(), 'max_high'],
                    df.loc[df['max_rsi_14'].notna(), 'max_rsi_14'],
                    left_index=True,
                    right_index=True,
                    direction='nearest')

Пример:
In [36]: df
Out[36]:
                     max_high  max_rsi_14
timestamp
2018-10-02 11:00:00       NaN         NaN
2018-10-02 12:00:00    6574.0   44.320898
2018-10-02 13:00:00       NaN         NaN
2018-10-02 14:00:00    6666.0         NaN
2018-10-02 15:00:00       NaN   39.250090

In [37]: %paste
res = pd.merge_asof(df.loc[df['max_high'].notna(), 'max_high'],
                                        df.loc[df['max_rsi_14'].notna(), 'max_rsi_14'],
                                        left_index=True,
                                        right_index=True,
                                        direction='nearest')

## -- End pasted text --

In [38]: res
Out[38]:
                     max_high  max_rsi_14
timestamp
2018-10-02 12:00:00    6574.0   44.320898
2018-10-02 14:00:00    6666.0   39.250090