text:
Q: Attemping Qualifying Exam Problems -- and failing My question is concerning learning strategy. I can solve the majority of the exercises in a typical graduate mathematics textbook like, say, Dummit/Foote's Abstract Algebra. To supplement my education (and, hopefully to increase my problem solving ability) I have been attempting many qualifying exams questions. Many are available online — as well as complete solutions. I find myself not being able to solve these — although I have the general idea in some cases. I am not particularly discouraged because I know these problems are not designed to routine; they are designed to ensure the student has an extremely deep understanding of the material and is ready for research mathematics.
My objective is to get to be better. I want to be able to attack these problems and solve them — or at least get closer than I am now.
The Question: To get better at problems like these, I would like to take a problem, give myself a time limit, say $3$ hours, to see where I get. Then, see (and study) the solution. Is this a reasonable strategy? I am looking for responses/advice from current PhD students studying for their exams and, of course, those who have passed such exams. My idea is if I implement the strategy above every day, there must be a point where I start getting better at these problems, right? (I should note that working on these has certainly made end-of-chapter problems look easy!)

A: I know this is way late to the party, but I can lend you my experience.
For a given subject, say a month prior (or longer if that time will be interrupted), commit to a full review of all the relevant material before attacking problems. It's important to keep all the relevant theorems and ideas front-loaded and relatively fresh. You'd be surprised how much rust builds up and how easily you can lose sight of otherwise handy results.
As you're reviewing, visualize. Draw pictures. For a given result, build the intuition through visualization that would lead someone to think it was true. Then note the correlation between the visualization and the machinery used to prove the result.
Different schools do things differently, but it's possible that if you can explain intuitively why something is true but can't muster the machinery, having the insight alone may grant partial credit. It's a hell of a lot better than leaving a blank space, anyway, and sometimes through the process of writing your intuition down (or reciting if oral), ideas for the machinery may come. Mathematics is at least as much about the insight as it is about the machinery.
Then, train in the format that the exam will be given. If oral, recite orally. If written in silence, practice writing in silence. Absolutely, work problems, but perhaps save the qual-level ones for when your review of the subject is complete. Once you start in on the qual-level problems, if written, obviously time management will be a factor, so identify quickly which problems you can handle and then handle them, leaving the ones which will require more effort for later.
Once you do groups of these, you'll start to see areas where your understanding isn't as strong, and that will prompt you to re-review those areas. Wash, rinse, repeat.
Good luck!

A: I am currently a mathematics Ph.D student.
My approach is a bit different than Ken's.
A lot of time may be wasted just reading a book.
Getting your hands dirty is the best option.
In my opinion, you don't know what you don't understand or have forgotten until you attempt a problem.
With that being said, I just do a lot of problems from old hw's and old prelim exams, make packets and revisit things that I got stuck on and thought about for at least an hour.
If you can, meet with other students or your advisor (or professor).
Generally it will serve as a distraction to just arbitrarily look at exams from other schools since they may have used different books which lends itself to different notation, definitions and bunch of other things.
If you can, look at exams from other schools which are very similar to your own university.
There is not guarantee (if ever) that you will be able to do every problem, but that's not the point. Getting the idea or having some feeling of how a problem is suppose to go is more than half the battle.
Also, there is no formula for success in mathematics. I've tried to imitate a lot of people's study habits, but you must see what works for you and then you'll see improvements.
Again, attack problems, build intuition and sketch rather than being rigorous all the time, consult with other students/professors and make notes of general trends (tricks) that you see occurring in problems.
''The first time you see it, it is a trick, but the next it is a technique'' haha. Hope this helps!


text:
Q: Pivoting the Data for last 6 Months in a column I have data for Loan instalment repayment by different customers.
The data includes basic details of customers like Name, Age, Salary, region, credit score etc.
There are some time variant fields as well like outstanding balance which is updated every month (but I am not really concerned with this data).
In my data set I have 6 rows for every customer (1 for each month till past 6 months). Each row contains a column called status (paid/not paid).
Example dataset looks as below:
Customer
Number      Age   Balance  Status
A123        34    1000     Paid
A123        34    2000     UnPaid
A123        34    1500     UnPaid
A123        34    1400     Paid
A123        34    1300     Paid
A123        34    1400     UnPaid
A234        36    1000     Paid
A234        36    4000     Paid
A234        36    3000     UnPaid
A234        36    5000     Paid
A234        36    6000     UnPaid
A234        36    1700     Paid

I want to convert the data in below format:
Customer
Number      Age Balance  Status1    Status2 Status3 Status4   Status5 Status6
A123        34  1000     Paid       UnPaid  UnPaid   Paid     Paid    UnPaid
A234        36  1000     Paid       Paid    UnPaid   Paid     UnPaid  Paid

Please note that, I am just interested in the latest values of other columns (Age, Balance etc.)
I have tried the casting() function but it did not do what I was after.
Can anyone help with this?

A: We can select the first value of Balance for each Number and create a column to assign unique Status number and then get the data in wide format.
library(dplyr)

df %>%
  group_by(Number) %>%
  mutate(Balance = first(Balance),
         col = paste0("Status", row_number())) %>%
  tidyr::pivot_wider(names_from = col, values_from = Status)

#  Number   Age Balance Status1 Status2 Status3 Status4 Status5 Status6
#  <fct>  <int>   <int> <fct>   <fct>   <fct>   <fct>   <fct>   <fct>
#1 A123      34    1000 Paid    UnPaid  UnPaid  Paid    Paid    UnPaid
#2 A234      36    1000 Paid    Paid    UnPaid  Paid    UnPaid  Paid

data
df <- structure(list(Number = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L), .Label = c("A123", "A234"), class = "factor"),
Age = c(34L, 34L, 34L, 34L, 34L, 34L, 36L, 36L, 36L, 36L,
36L, 36L), Balance = c(1000L, 2000L, 1500L, 1400L, 1300L,
1400L, 1000L, 4000L, 3000L, 5000L, 6000L, 1700L), Status = structure(c(1L,
2L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L), .Label = c("Paid",
"UnPaid"), class = "factor")), class = "data.frame", row.names = c(NA, -12L))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Animate (Oscillation) custom drawn shape on Canvas Good day.
I am looking for abit of advice.  Before judging, please take note I am new to coding, with only a few weeks of experience.
I am trying to make the cloud shape I have draw onto the canvas, animated, using JavaScript.  (Please see link below to the type of animation I am looking to achieve.)  I have searched everywhere for how to achieve this, but it seems all the links either deal with an actual image, or a rectangle, and not a custom drawn shape.  So my question is this, is it possible to do such an animation on a custom shape, and, if not, what is the best way to go about it to achieve said desired effect.
<!DOCTYPE HTML>
<HTML>
  <head>
    <style>
      body {
        margin: 100px;
        padding: 0px;
        }
    </style>
  </head>
<body>
  <canvas id="Canvas" width="700" height="600" style="border:1px solid #005BAB;"></canvas>
    <script>
    var canvas = document.getElementById('Canvas');
    var context = canvas.getContext('2d');

    // gradients
    var grd = context.createRadialGradient(550, 150, 25, 500, 200, 400);
    grd.addColorStop (0, '#0586f8');
    grd.addColorStop (1, '#015baa');

      // blue block shadow
    context.shadowColor = '#999';
    context.shadowBlur = 35;
    context.shadowOffsetX = 8;
    context.shadowOffsetY = 8;
    context.globalCompositeOperation = 'source-over';
    context.beginPath();
    context.fill();

      // blue block
    context.beginPath();
    context.moveTo(50, 35);
    context.lineTo(50, 525);
    context.lineTo(550, 525);
    context.lineTo(550, 35);
    context.closePath();
    context.lineWidth = 0;
    context.strokeStyle = '#999';
    context.fillStyle = grd;
    context.fill();

        // cloud shadow
      context.shadowColor = '#232323';
      context.shadowBlur = 20;
      context.shadowOffsetX = 0;
      context.shadowOffsetY = 0;
      context.beginPath();
      context.globalAlpha = 0.9;
      context.fill();

        // cloud drawing
      context.beginPath();
      context.moveTo(172, 180);
      context.bezierCurveTo(145, 180, 120, 234, 185, 240);
      context.lineTo(375, 240);
      context.bezierCurveTo(495, 234, 405, 110, 382, 168);
      context.bezierCurveTo(440, 85, 280, 60, 325, 120);
      context.bezierCurveTo(320, 42, 190, 60, 200, 120);
      context.bezierCurveTo(120, 100, 140, 200, 170, 180);
      context.lineWidth = 1;
      context.fillStyle = 'white';
      context.fill();
      context.strokeStyle();
      context.lineCap = 'round';
      context.lineJoin = 'round';
      context.stroke();
    </script>
</body>
</HTML>

http://www.html5canvastutorials.com/advanced/html5-canvas-oscillation-animation/

A: You could create another canvas with javascript:
var cloud = document.createElement('canvas');
cloud.width = <width of the cloud>;
cloud.height = <height of the cloud>;

Then draw your cloud onto that canvas. You should adjust your coordinates so that the top left of the cloud's bounding box is at point (0, 0). This way the cloud canvas is only as big as it needs to be.
Then you can treat your cloud just like you would an image.
context.drawImage(cloud, 0, 0);


text:
Q: What's a good way to make a PHP website approach the database object oriented? Please note I'm not looking for 'use a framework' answers. I'm trying to structurally improve the way I code websites and approach databases from PHP.
I'm building a web service from scratch, without any frameworks. I'm using a LAMP stack and am trying to learn a bit of PHP's OO functionality while I'm at it. I've previously only used OO to make mobile apps.
I've been at it for months now (as planned, no worries). Along the way I've bumped into a couple of structural problems, making me wonder what the best way would be to make the code object oriented.
Pretty much all of the problems involve the database in some way. Say we have a class DB and a class User. In most cases I only need to fetch a single user's information from the database. I thought a good way to handle it was to have a global $_db variable and have the User object query the database like so (oversimplified):
class User {
    function __construct($id) {
        global $_db;
        $q = $_db->query("SELECT name, mail FROM user WHERE id = ?", $id);
        $this->loadProperties($q);
    }
}

Now say we have a page that shows a list of users. I still want to make User objects for each of them, but I don't want to query the database for each separate user.
So, I extend the User class to take an object as an argument:
class User {
    function __construct($id) {
        if(is_object($id))
            $q = $id;
        else {
            global $_db;
            $q = $_db->query("SELECT name, mail FROM user WHERE id = ?", $id);
        }

        $this->loadProperties($q);
    }
}

Now I can create a list of, for example, the 100 most recently created and active accounts:
$user_list = [];

$q = $_db->query("SELECT name, mail FROM user WHERE banned = 0 ORDER BY date_created DESC LIMIT 100");

while($a = $_db->fetch($q))
    $user_list[] = new User($a);

This all works great, except for one big downside: the database queries for table user are no longer in one place, which is kind of making spaghetti code. This is where I'm starting to wonder whether this can be done more efficiently.
So maybe I need to extend my DB object instead of my User object, for example:
class DB {
    public function getUsers($where) {
        $q = $this->query("SELECT name, mail FROM user WHERE ".$where);

        $users = [];
        while($a = $this->fetch($q))
            $users[] = new User($a);
    }
}

Now I would create the user list as follows:
$user_list = $_db->getUsers("banned = 0 ORDER BY date_created DESC LIMIT 100");

But now I'm calling the getUsers() method in various places using various SQL queries, solving nothing. I also don't want to load the same properties each time, so my getUsers() method will have to take entire SQL queries as an argument. Anyway, you get the point.
Speaking of loading different properties, there's another thing that has been bugging me writing OO in PHP. Let's assume our PHP object has at least every property our database row has. Say I have a method User::getName():
class User {
    public function getName() {
        return $this->name;
    }
}

This function will assume the appropriate field has been loaded from the database. However it would be inefficient to preload all of the user's properties each time I make an object. Sometimes I'll only need the user's name. On the other hand it would also be inefficient to go into the database at this point to load this one property.
I have to make sure that for each method I use, the appropriate properties have already been loaded. This makes complete sense from a performance perspective, but from an OO perspective, it means you have to know beforehand which methods you're gonna use which makes it a lot less dynamic and, again, allows for spaghetti code.
The last thing I bumped into (for now at least), is how to separate actual new users from new User. I figured I'd use a separate class called Registration (again, oversimplified):
class Registration {
    function createUser() {
        $form = $this->getSubmittedForm();

        global $_db;
        $_db->query("INSERT INTO user (name, mail) VALUES (?, ?)", $form->name, $form->mail);
        if($_db->hasError)
            return FALSE;

        return $_db->insertedID;
    }
}

But this means I have to create two separate classes for each database table and again I have different classes accessing the same table. Not to mention there's a third class handling login sessions that's also accessing the user table.
In summary, I feel like all of the above can be done way more efficiently. Most importantly I want pretty code. I feel like I'm missing a way to approach the database from an OO perspective. But how can I do so without losing the dynamics and power of SQL queries?
I'm looking forward to reading your experiences and ideas in this field.
Update
Seems most of you condemn my use of global $_db. Though you've convinced me this isn't the best approach, for the scope of this question it's irrelevant whether I'm supplying the database through an argument, a global or a singleton. It's still a separate class DB that handles any interaction with the database.

A: It's a common thing to have a separate class to handle SQL queries and to keep the fetched data. In fact, it is the real application of the Single Responsibility Principle.
What I usually do is keep a class with all the information concerning the data, in your case the User class, with all the user information as fields.
Then comes the business layer, for instance UserDataManager (though the use of "Manager" as a suffix is not recommended and you'd better find a more suitable name in each scenario) which takes the pdo object in its constructor to avoid use of global variables and has all the SQL methods. You'd thus have methods registerNewUser, findUserById, unsuscribeUser and so on (the use of "User" in the method can be implied by the class name and be omitted).
Hope it helps.

A: I've liked to use the data mapper pattern (or at least I think that's how I'm doing it). I've done this for some sites built on Silex, though it's applicable to going without a framework since Silex is very lightweight and doesn't impose much on how you architect your code. In fact, I recommend you check out Symfony2/Silex just to get some ideas for ways to design your code.
Anyway, I've used classes like UserMapper. Since I was using the Doctrine DBAL library, I used Dependency injection to give each mapper a $db. But the DBAL is pretty much a wrapper on the PDO class as far as I understand, so you could inject that instead.
Now you have a UserMapper who is responsible for the CRUD operations. So I solve your first problem with methods like LoadUser($id) and LoadAllUsers(). Then I would set all the properties on the new User based on the data from the database. You can similarly have CreateUser(User $user). Note that in "create", I'm really passing a User object and mapping it to the database. You could call it PersistUser(User $user) to make this distinction more clear. Now all of the SQL queries are in one place and your User class is just a collection of data. The User doesn't need to come from the database, you could create test users or whatever else without any modification. All of the persistence of `User is encapsulated in another class.
I'm not sure that it's always bad to load all of the properties of a user, but if you want to fix that, it's not hard to make LoadUsername($id) or other methods. Or you could do LoadUser($id, array $properties) with a set of properties taht you want to load. If your naming is consistent, then it's easy to have set the properties like:
// in a foreach, $data is the associative array returned by your SQL
$setter = 'set'.$property;
$user->$setter($data[$property]);

Or (and?) you could solve this with Proxy objects. I haven't done this, but the idea is to return a bunch of UserProxy objects, which extend User. But they have the Mapper injected and they override the getters to call into the Mapper to select more. Perhaps when you access one property on a proxy, it will select everything via the mapper (a method called populateUser($id)?) and then subsequent getters can just access the properties in memory. This might make some sense if you, for example, select all users then need to access data on a subset. But I think in general it may be easier to select everything.
public function getX()
{
    if (!isset($this->x)) {
        $this->mapper->populateUser($this);
    }
    return $this->x;
}

For new users, I say just do $user = new User... and set everything up, then call into $mapper->persist($user). You can wrap that up in another class, like UserFactory->Create($data) and it can return the (persisted) User. Or that class can be called Registration if you'd like.
Did I mention you should use Dependency Injection to handle all of these services (like the Mappers and others like Factories maybe)? Maybe just grab the DIC from Silex, called Pimple. Or implement a lightweight one yourself (it's not hard).
I hope this helps. It's a high-level overview of some things I've picked up from writing a lot of PHP and using Syfmony2/Silex. Good luck and glad to see PHP programmers like yourself actually trying to "do things right"! Please comment if I can elaborate anywhere. Hope this answer helps you out.

A: You should first begin by writing a class as a wrapper to your Database object, which would be more clean that a global variable (read about the Singleton Pattern if you don't know it, and there is a lot of examples of Singleton Database Wrapper on the web). You'll then have a better view of the architecture you should implement.
Best is to separate datas from transactions with the database, meaning that you can for example have two classes for your User ; one that will only send queries and fetch responses, and the other that will manage datas thanks to object's attributes and methods. Sometimes, there can be also some action that doesn't require to interact with the database, and that would be implemented in these classes too.
Last but not least, it can be a good idea to look a MVC frameworks and how they work (even if you don't want to use it) ; that would give you a good idea of how can be structured a web application, and how to implement these pattern for you in some way.


text:
Q: Join where one row should be duplicated Struggling to come up with a mysql only solution to this.
Simplified setup:
Two tables:

Table A
id | value | price
 1 | 2     | 5.95
 2 | 5     | 7.95
 3 | 30    | 8.95

Table B:
 color | min_value | max_value
green  |     1     |  3
blue   |     3     | 10
red    |    10     | 35
orange |    25     | 50

Based on the definitions from table B, i would like to join the color column onto the data from table A.  I need to know, in this example, the average price associated with all the items in table A by color.  However the definitions can be overlapping (i.e. id 3 is both red and orange).
I know I can use python (in this project's case) to recursively go through each color and pull out the matching values and then the average price, but i would love to simplify this by doing it mysql.
Thanks for any help/guidance!

A: You don't need to do anything special, the default case in SQL is that if one row from a table matches two rows in the other, you'll get two rows in the result.
SELECT color, avg(price)
  FROM A, B
 WHERE A.value BETWEEN B.min_value AND B.max_value
 GROUP BY color


text:
Q: c# query duration problem including ternary operator in linq I have quite a difficult query to DB. I am using EF. Query looks like this:
bool useSearch = true;

return db.Entity.Where(...)
                .Select(x=> new Model(){
                        PropertyA = x.PropertyA,
                        PropertyB = useSearch ? 0
                                              : x.PropertyList.where(y=>...).Sum(z=>z.Pieces)
                })
                .ToList();

Problem is, that code is about 10 seconds. If i change property useSearch to false, than still have same time. Does the ternary operator do both conditions in LINQ?


text:
Q: mysql selecting a union where values in one don't appear in the other sorry for the poorly titled post.
Say I have the following table:
C1 | C2       | c3
1  | foo      | x
2  | bar      | y
2  | blaz     | z
3  | something| y
3  | hello    | z
3  | doctor   | x
4  | name     | y
5  | continue | x
5  | yesterday| z
6  | tomorrow | y

I'm trying to come up w/ a sql statement which performs the following union:
1st retrieval retrieves all records w/ c3 = 'y'
2nd retrieval retrieves the first instance of a record where c3 <> 'y' and the result is not in the previous union
So, for the result, I should see:
C1 | C2
1  | foo
2  | bar
3  | something
4  | name
5  | continue
6  | tomorrow

So two questions:  1:  Am I totally smoking crack where I think I can do this, and 2: (assuming I can), how do I do this?

A: Try this one:
SELECT   a.C1, a.C2
  FROM   MyTable a
 WHERE   a.C3 = 'y'
    UNION
SELECT   b.C1, b.C2
  FROM   MyTable b
 WHERE   b.C3 <> 'y' AND
         b.C1 not in
            (
               SELECT c.C1
                 FROM MyTable c
                WHERE c.C3 = 'y'
            )

UPDATE 1
by the way, why is that there is only one record of 5 in your desired result? where, in fact, there could be two.
SEE FOR DEMO 1
OR
SELECT g.C1, MIN(g.C2) C2
FROM
(SELECT   a.C1, a.C2
  FROM   MyTable a
 WHERE   a.C3 = 'y'
    UNION
SELECT   b.C1, b.C2
  FROM   MyTable b
 WHERE   b.C3 <> 'y' AND
         b.C1 not in
            (
               SELECT c.C1
                 FROM MyTable c
                WHERE c.C3 = 'y'
            )
) g
GROUP BY g.C1

SEE FOR DEMO 2 (yields same result with your desired result)

A: DEMO @ Sql Fiddle.
select *
  from table1
 where c3 = 'y'
 union all
(select table1.*
  from table1
  left join table1 t1
    on table1.c1 = t1.c1
   and t1.c3 = 'y'
 where table1.c3 <> 'y'
   and t1.c1 is null
 -- The meaning of first becomes clear here
 order by table1.c3, table1.c2
 limit 1)

Note: foo is not in a list because it is marked as x.

A: Try this:
    SELECT C1, C2
    FROM   Table1
    Where  C3 = 'y'

    UNION

   (
    SELECT  C1, C2
    FROM  Table1
    Where C3 <> 'y' ORDER BY C1 LIMIT 1
   )
 ORDER BY C1


text:
Q: translate canvas and offset actionbar Please bear with me if this isn't clear, this is my first posting here.
I'm drawing a couple of lines on a canvas and trying to translate the canvas to centre the lines on the screen. The trouble is, I have an actionbar (using actionbarsherlock) which I want to exclude from the translation i.e. I want the top of the view to be under the action bar.
As it is, the data is centred vertically on the whole screen height, but I want it to be centred vertically only on the visible part of the canvas under the action bar.
Any ideas of the best way to achieve this?
@Override
protected void onDraw(Canvas canvas) {
    Paint paint = mPaint;

    paint.setAntiAlias(true);
    paint.setColor(Color.WHITE);
    paint.setStyle(Paint.Style.FILL);

    int centrew = canvas.getWidth()/2;
    int centreh = canvas.getHeight()/2;

    canvas.translate(centrew, centreh);
    canvas.drawLine(0, -5, 0, 5, mPaint);
    canvas.drawLine(5, 0, -5, 0, mPaint);

}

A: if you know the exact size of the bar, you could apply it it to the overall canvas height to increase the shift:
int maxV = canvas.getHeight() + barHeight;
int centreh = maxV/2;

I am assuming, the bar is on top, covering apart of the canvas, so the shift (from the top left corner) has to be greater. If the bar is on the bottom, the shift should be reduced:
int maxV = canvas.getHeight() - barHeight;
int centreh = maxV/2;

EDIT: If the bar has a different size in pixels on different devices, you have to hack a bit to make it work. You can safely make assuptions about the bar and revise them in case they don't hold. You could assume a certain ratio reserved for the bar and adapt the absolute pixel count accordingly (the oneliner is rather for illustration):
int maxV = Math.round(canvas.getHeight()*(1f + barRatio));

You can further adapt the ratio depending on the aspect ratio of the screen to make it work even better.
Unfortunately there is no really clean solution as you cannot read the current layout and extract sizes.

A: The solution I used was as described here :
http://developer.android.com/resources/samples/HoneycombGallery/src/com/example/android/hcgallery/TitlesFragment.html
Basically my activity has the following layout listener defined:
ViewTreeObserver.OnGlobalLayoutListener layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        mmv.setAbShift(MunroBag.this.actionBar.getHeight());
    }
};

Then the view class has the following method defined:
    public void setAbShift(int shift)
    {
        abShift = shift;
        this.invalidate();
    }

So onDraw gets called and the shift is applied to the view depending on the actionBar height.


text:
Q: Converting bib database into csv I have a bibliography on a subject (don't matter what subject it is, there is about 20 different files and about 1000 records).
I need to convert it into csv (or any other table format which can be opened in Excel/LibreOffice Calc etc.)
Can anyone name a tool for this?

A: A python version using bibtexparser bibtexparser and pandas
with open('ref.bib') as bibtex_file:
  bib_database = bibtexparser.load(bibtex_file)
df = pd.DataFrame(bib_database.entries)
df.to_csv('ref.csv', index=False)

And a minimal working example:
import bibtexparser
import pandas as pd

bibtex = """@article{ einstein1935can,
            title={Can quantum-mechanical description of physical reality be considered complete?},
            author={Einstein, Albert and Podolsky, Boris and Rosen, Nathan},
            journal={Physical review},
            volume={47},number={10},
            pages={777},
            year={1935},
            publisher={APS}}
            @inproceedings{sharma2017daniel,
            title={DANIEL: A deep architecture for automatic analysis and retrieval of building floor plans},
            author={Sharma, Divya and Gupta, Nitin and Chattopadhyay, Chiranjoy and Mehta, Sameep},
            booktitle={2017 14th IAPR International Conference on Document Analysis and Recognition (ICDAR)},
            volume={1},pages={420--425},year={2017},organization={IEEE}}"""

with open('ref.bib', 'w') as bibfile:
  bibfile.write(bibtex)
with open('ref.bib') as bibtex_file:
  bib_database = bibtexparser.load(bibtex_file)
df = pd.DataFrame(bib_database.entries)
df.to_csv('ref.csv', index=False)

A: Open the .bib-files in Jabref and export them as OpenOffice .csv-files. You find the option under the menu File, Export

Since you can run Jabreffrom the program's home page, you don't have to install it. You need Java, though.

A: It is also possible to do if you use a reference manager as Zotero. Then you can import a bibtex file. It will result in its own folder, and then you can export it to whatever format you want.
Just another solution :)

A: Best bet would be a scripting language, e.g. Python. I don't know if you are a programmer, but making a script taking each entry and converting them should be pretty quick (provided typing python script_file.py in the prompt doesn't scare you!). Python is also installed by default on most Unix OSes.
Here's a basic python script which accesses a few fields:
from pybtex.database.input import bibtex

#open a bibtex file
parser = bibtex.Parser()
bibdata = parser.parse_file("myrefs.bib")

#loop through the individual references
for bib_id in bibdata.entries:
    b = bibdata.entries[bib_id].fields
    try:
        # change these lines to create a SQL insert
        print(b["title"])
        print(b["journal"])
        print(b["year"])
        #deal with multiple authors
        for author in bibdata.entries[bib_id].persons["author"]:
            print(author.first(), author.last())
    # field may not exist for a reference
    except(KeyError):
        continue

You can adapt it to your needs and save desired fields to a .csv file.

A: Another option in R is to use the package bib2df:
# Install bib2df
install.packages('bib2df')

# Load bib2df
library(bib2df)

# Set path to .bib
# (Example data)
path <- system.file("extdata", "LiteratureOnCommonKnowledgeInGameTheory.bib", package = "bib2df")

# (Alternatively, your own file)
# path <- 'refs.bib'

# Read .bib as a data.frame
df <- bib2df(path)

# Parse the author and editor columns (list columns cannot be saved directly in a csv)
df$AUTHOR <- vapply(df$AUTHOR, paste, collapse = ' and ', '')
df$EDITOR <- vapply(df$EDITOR, paste, collapse = ' and ', '')

# Export to csv
write.csv(df, 'refs.csv')


text:
Q: Xcode 6.3 - shell script invocation error (Parse Crash Reporting) I recently got an error when I turn off the internet connection and build my project. When I turn the internet back on the error dissapears and the build is successful.

I have the following shall script when using Parse Crash Reporting:
export PATH=/usr/local/bin:$PATH
cd <path_to_cloudcode_folder>

parse symbols -p "${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}"

Thank you for your help!

A: I had the same issue because I didnt have a default app after parse new because it wouldnt accept my password.

*

*curl -s https://www.parse.com/downloads/cloud_code/installer.sh | sudo /bin/bash

*parse new (delete exsisting parse folder if any)

*enter your email / password

*then you will be prompted to choose the app you are working on by typing the # and enter on the terminal


text:
Q: How to type cast decode JSON as if it came from the database When loading date/time types from the database, Ecto will cast to a Ecto.DateTime type.  How can the same type casting be applied when loading a model from a JSON string
defmodule Rocket.User do
  use Rocket.Model

  schema "users" do
    field :created_at, :datetime
    field :name, :string
    field :email, :string
    field :password, :string
    field :timezone, :string
  end
end

iex(40)> Poison.decode!(~s({"created_at":"2015-01-21T06:05:10.891Z"}), as: Rocket.User)
%Rocket.User{created_at: "2015-01-21T06:05:10.891Z", email: nil, id: nil,
 name: nil, password: nil, timezone: nil}

A: If you are using Ecto 0.6.0, the best way is to use changesets:
Ecto.Changeset.cast Poison.decode!(data), %Rocket.User{},
                    ~w(required_fields), ~w(optional_fields)

Using changeset is actually recommended if you are receiving this as external data since you need to cast, filter and validate this data before adding it to the model. You can find more information about them in the Ecto introduction and also in the Ecto.Changeset module documentation.
There is one issue left though: Ecto does not know how to cast the string to datetime. You can however teach it how to by using custom types. I have created a template below, you just need to implement the casting function:
https://gist.github.com/josevalim/1ed574b388c32f056da1
Then in your schema:
timestamps type: Rocket.DateTime

You can find more information in Ecto.Type docs. I am aware we need to improve this in Ecto, I think we should at least be able to parse datetimes in the format specified in JSON.


text:
Q: Add IE Edge meta tag after title tag from ASP include I have thousands of pages on a CMS driven site that render poorly from within the company network because IE treats them as intranet pages, and the default setting for IE is to render intranet pages in compatibility mode.
I want to insert the IE Edge meta tag after the title tag to force the browser into its latest version, but I can't edit every page for this. To avoid editing individual pages or having to regenerate pages in the CMS, I think I should be able to update an include that is common to all pages with a server side script that does it. Is that possible? I think it needs to be server side because adding the meta tag at onload doesn't force the browser mode, but maybe I'm wrong.
So I want this:
<head>
...some stuff...
<title>My Title</title>
...some other stuff...
<!--#include virtual="/myinclude.asp"-->
</head>

To become this:
<head>
...some stuff...
<title>My Title</title>
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
...some other stuff...
...rendered include...
</head>

Is there a way to do this? Or some other workaround I'm not seeing?

A: It turns out you can add things to the header with this:
<%  Response.AddHeader "CustomHeader","CustomValue" %>

It also appears that it doesn't matter where I put it on the page, so I can stick it in the common include, and all pages will get the custom header. In this case:
<% Response.AddHeader "X-UA-Compatible","IE=Edge,chrome=1" %>

Wish I had known about this way sooner! Here's the spec:
http://msdn.microsoft.com/en-us/library/ms524327(v=vs.90).aspx

A: You can set IIS to send the header for all pages served. An MSDN article describes the steps as:
Configuring the EmulateIE7 HTTP Header in IIS7 (via the user interface)

*

*Open Internet Information Services (IIS) Manager

*Select the Server from the connections pane

*Right-click on "HTTP Response Headers" from the center task pane, and choose "Open Feature"

*Select "Add" from the Actions Pane

*Add a custom header with the Name "X-UA-Compatible" and the Value "IE=Edge"

They also have the steps for making the changes via command line.
There's an article on the IIS Blog that gives you a list of possible values and what they will do.

Emulate IE8 mode  -->   IE=EmulateIE8
Emulate IE7 mode  -->   IE=EmulateIE7
IE5 mode          -->   IE=5
IE7 mode          -->   IE=7.5
IE8 mode          -->   IE=8
Edge mode         -->   IE=Edge


text:
Q: How to generate ANTLR recognizer again in Intellij after editing grammar I have written a grammar to rotate a robot.
grammar RobotController;

//Parser
program: statement+;
statement: rotateStatements;
rotateStatements: ROTATE EOS;

//lexer
ROTATE: 'rotate';
EOS: ';';

Then i created ANTLR recognizer and it worked, It created some Java files with some code.
Later on I modified my grammar
to
grammar RobotController;

//Parser
program: statement+;
statement: rotateStatements;
rotateStatements: ROTATE (LPAREN direction RPAREN)? EOS;
direction: STRING;

//lexer
ROTATE: 'rotate';
LPAREN: '(';
RPAREN: ')';
EOS: ';';
STRING:  '"' (~[\r\n])* '"';

Now I am creating ANTLR recognizer again but the previously generated Java files remain the same in the system. No new code is added to them.
Does anyone know how to generate ANTLR recognizer after modifying the grammar?

A: INFO: Restarting Intellij and invalidating cache solved the problem


text:
Q: Mount error after power outage My Linux knowledge is rather limited, but I'll try to explain. Last night we had a power outage. When I restarted my server this morning I got an error message telling me that a disk failed to mount. Got the option to skip mounting and continue booting. Now when I try to mount the disk (media disk, not a system disk) I get this error:
Error mounting system-managed device /dev/sda2: Command-line `mount "/mnt/sda2"' exited with non-zero exit status 13: ntfs_mst_post_read_fixup_warn: magic: 0x04e2adc6  size: 4096   usa_ofs: 16595  usa_count: 25841: Invalid argument
Actual VCN (0x103f339f56a78da1) of index buffer is different from expected VCN (0x3).
Failed to mount '/dev/sda2': Input/output error
NTFS is either inconsistent, or there is a hardware fault, or it's a
SoftRAID/FakeRAID hardware. In the first case run chkdsk /f on Windows
then reboot into Windows twice. The usage of the /f parameter is very
important! If the device is a SoftRAID/FakeRAID then first activate
it and mount a different device under the /dev/mapper/ directory, (e.g.
/dev/mapper/nvidia_eahaabcc1). Please see the 'dmraid' documentation
for more details.
(udisks-error-quark)

Is there anyone that can give me some assistance. Would hate loosing 2 GB of my media files.

A: The error message tells you exactly what to do: boot into windows, run chkdsk /f and reboot into windows twice more.

From Ubuntu (but only use this if you have not got a Windows system (better safe than sorry)):
ntfsck /dev/sda2

This is part of the ntfs-progs sudo apt-get install ntfsprogs if not installed yet.


text:
Q: Any command we can use to convert windows file to unix or mac file? I don't want to use dos2unix tool. I want to use command in Ubuntu terminal to convert Windows file to Unix file. Is that possible. I have looked through other articles and tried those commands but none working. Anyone can help?

A: You can use tr to remove carriage returns like this:
tr -d '\r' < WindowsFile > UnixFile

You can use
cat -vet WindowsFile

to see if there are carriage returns in your file and they'll show up as ^M

A:
I want to use command in Ubuntu terminal to convert Windows file to Unix file.

dos2unix path/to/file/to/convert

I don't want to use dos2unix tool.

alias notdos2unix=dos2unix

notdos2unix path/to/file/to/convert

A: For Ubuntu(and Debian) you can use the tofrodos package.
sudo aptitude install tofrodos
fromdos file.txt # converts the file to UNIX line-endings
todos   file.txt # converts the file to Windows line-endings

OSX (being a derivative of UNIX) should have the same line-endings as UNIX.
If you're on Windows, you can find tofrodos binaries here.
If you're on a Mac, you can use the brew package manager and install the tofrodos on OSX.


text:
Q: How to convert this sql query to pyspark? SELECT A.* FROM df1 A
WHERE ID NOT IN (SELECT ID FROM df2)

This is the code I'm trying to convert

A: from Spark-2.2+ supports subqueries, as you can register temp view and execute the same query.
In DataFrameApi for NOT IN use left_anti join to mimic the same query.
Example:
df.show()
#+----+---+
#|name| id|
#+----+---+
#|   a|  1|
#|   c|  3|
#+----+---+

df1.show()
#+----+---+
#|name| id|
#+----+---+
#|   a|  1|
#|   b|  2|
#+----+---+

df.join(df1,'id','left_anti').show()
#+---+----+
#| id|name|
#+---+----+
#|  3|   c|
#+---+----+

#only if you have few id values in df2 then
ids=df1.select("id").rdd.map(lambda x:x.id).collect()

#isin accepts only values not columns from another dataframe
df.filter(~col("id").isin(ids)).show()
#+----+---+
#|name| id|
#+----+---+
#|   c|  3|
#+----+---+

If two dataframes having same number of columns then you can use exceptAll function
df.exceptAll(df1).show()
#+----+---+
#|name| id|
#+----+---+
#|   c|  3|
#+----+---+

For in subquery use left_semi join.
df.join(df1,'id','left_semi').show()
#+---+----+
#| id|name|
#+---+----+
#|  1|   a|
#+---+----+


text:
Q: Question about Legendre Symbol and Division Q12(a) Let $q>3$ be an odd prime and let $q=2Q+1$. Prove that:
(a) $q\,|\,(3^Q-1) \iff q\equiv ±1 \pmod {12}$
adpated from Number Theory with Applications, James A. Anderson, James M. Bell. Ch 3.9 Q12 (a)
Any hint from the question? Thanks.
Edit 1: (DELETED BECAUSE IT IS WRONG)
Edit 2: I have proved for the one-sided statement. Let me put it here first and wait for me to prove the another side of statement
Lemma 1: Iff $\exists x \in \mathbb{Z}^+, x>3:  x^2\equiv 3 \pmod {p}$, then $p\equiv\pm1 \pmod{12}$
Proof:
Forward Statement:
By quadratic reciprocity, $(\frac{p}{3})=(\frac{3}{p})(-1)^{\frac{p-1}{2} \frac{3-1}{2}}=(-1)^{\frac{p-1}{2}}$
For $y^2\equiv p \pmod{3}$,
Case 1: If $(\frac{p}{3})=0$, then $3 \mid p \Rightarrow p \equiv 0 \pmod{3}$
Case 2: If $(\frac{p}{3})=1$, then by Fermat little thm, $y^2 \equiv 1 \pmod{3}$, $\therefore p \equiv 1 \pmod{3}$
On the other hand, $1=(-1)^{\frac{p-1}{2}} \Rightarrow p$ is even.
$\therefore$ By Chinese Remainder theorem, $p \equiv 1 \pmod{12}$
Case 3: If $(\frac{p}{3})=-1$, then $y^2 \equiv 2 \pmod{3}$, $\therefore p \equiv 2 \pmod{3}$
On the other hand, $-1=(-1)^{\frac{p-1}{2}}$
$\therefore \exists t \in \mathbb{Z}^+: \frac{p-1}{2} = 2t+1 \Rightarrow p-1=4t+2\Rightarrow p=4t+3\Rightarrow p\equiv 3 \pmod{4}$
By Chinese Remainder theorem, $p \equiv 11 \pmod{12}$
Combining the latter two cases, $p \equiv \pm 1 \pmod{12}$
Edit 3: Here is the proof of backward statement:
If $p$ is an odd prime, then $(\frac{p}{3}) \equiv p \pmod{3}$
Case 1: $p\equiv 1 \pmod{12} \Rightarrow p\equiv 1 \pmod{3}, \therefore (\frac{p}{3})=1$
Also, $\exists \alpha \in \mathbb{Z}^+: p-11=12 \alpha \Rightarrow p=12\alpha +11$
$(\frac{3}{p})=(\frac{p}{3}) (-1)^{\frac{p-1}{2}}=1(-1)^{\frac{12t}{2}}=1$
Case 2: $p\equiv 11 \pmod{12} \Rightarrow p\equiv -1 \pmod{3}, \therefore (\frac{p}{3})=-1$
$\therefore \exists \beta \in \mathbb{Z}^+ : p-11=12 \beta \Rightarrow p=12\beta +11$
$(\frac{3}{p})=(\frac{p}{3})(-1)^{\frac{12\beta+11-1}{2}}=(-1)(-1)=1$
Combining the above two cases, $(\frac{p}{3}) = 1$
Edit 4:
There are two cases: $q \equiv 1 \pmod{4}$ and $q\equiv 3 \pmod{4}$:
Case 1: $q \equiv 1 \pmod{4} \Rightarrow (\frac{q}{3}) = (\frac{3}{q})(-1)^{\frac{q-1}{2}} = 1, \therefore q\equiv 1 \pmod{3}$
$\therefore$ By Chinese Remainder thm, $q \equiv 1 \pmod{12}$
Case 2: $q \equiv 3 \pmod{4} \Rightarrow (\frac{q}{3}) = -1, \therefore q \equiv 2 \pmod{3}$
$\therefore$ By Chinese Remainder thm, $q \equiv 11 \pmod{12}$
(The converse way is similar to that in edit 3).
(Edit 5: I changed the above from "statement" to "lemma 1")
Edit 5:
By using Lemma 1,
$(\frac{3}{q}) = 1 \Leftrightarrow (\frac{3}{q})  \equiv 3^{\frac{p-1}{2}} \pmod{q} \Leftrightarrow 1 \equiv 3^{\frac{q-1}{2}} \pmod{q}$
$\therefore$ The thm is proved.


text:
Q: Programmatically load .Net assembly with symbols I've got a C# tool that loads arbitary assemblies using Assembly.LoadFrom(). It then does some reflection on the assemblies and reports back to the user. The problem is there is no debugging information, so my tool can't report on line numbers or file names, for instance.
The assemblies I'm loading have symbol files in the same directory (they're mdb files, because I'm on OSX and using mono). How can I load these files and associate them with the relevant assemblies?

A: AFAIK the .mdb files should just work if they are located in the same directory as the dll files.
What you might be missing is the flag --debug passed to mono when launching your program.


text:
Q: gnuplot -- plot range different from axes range I have this very simple, working gnuplot code:
splot x * x

This plots a surface from -10 < x < 10 and -10 < y < 10.

I want to plot the same surface from  -10 < x < 10 and -10 < y < -9 HOWEVER I still want the graph's axes to use -10 < x < 10 and -10 < y < 10.  The axes bounds should not change, but the range of values plotted should be smaller.
In other words, the surface should look like a thin band in one small section of the plot.  The rest should be empty space.  Below is a very poor effort at creating what I want using the graph I have.

I have tried manipulating yrange, but this changes BOTH the surface bounds and the axes bounds.  I have also tried disabling autoscale but I'm unsure what to do next.

A: In current gnuplot (version 5.2.4) you can separate the sampling range from the axis range whether or not you enable parametric mode.   See example in the on-line demo set:
sampling.html (see plot #9)

A: One way to do this is through parametric mode, which gives you a separate set of coordinates (u and v) to set ranges for
f(x,y) = x*x

set xrange [-10:10]
set yrange [-10:10]
set urange [-10:10]
set vrange [-10:-9]
set parametric
splot u, v, f(u,v)

Alternatively you can achieve the same effect by using the ++ special filename instead of parametric mode:
f(x,y) = x*x

set xrange [-10:10]
set yrange [-10:10]
set urange [-10:10]
set vrange [-10:-9]

splot "++" u 1:2:(f($1,$2)) w l

A: Using a programming language with gnuplot might give better control over plots.
Here is an example using c and a script.
plot.c
#include <stdio.h>
#include <math.h>

int main()
{
   int x, y;
   double z;

   for (y=-10; y <= 10; y++)
   {
      for (x=-10; x <= 10; x++)
      {
         z = x * 0.025;
         printf("%f %f %f\n", (double)x, (double)y, 100 - cos(z * M_PI*2) * 100);
      }
      printf("\n");
   }

   fflush(stdout);
   return 0;
}

plot.bat
gcc plot.c -o prog.exe -lm
prog > data.txt
echo splot "data.txt" using 1:2:3 with lines | gnuplot -p

plot.sh
gcc plot.c -o prog -lm
./prog > data.txt
echo 'splot "data.txt" using 1:2:3 with lines' | gnuplot -p

Here is an example using python and a script.
It will output:

plot.py
import math

print("\"Surface One\"")
for y in range(-10, 10+1):
   for x in range(-10, 10+1):
      z = x * 0.025
      print("%f %f %f 1" % (float(x), float(y), 100 - math.cos(z * math.pi*2) * 100))
   print("")
print("")

print("\"Surface Two\"")
for y in range(-10, -8+1):
   for x in range(-10, 10+1):
      z = x * 0.025
      print("%f %f %f 2" % (float(x), float(y), 100 - math.cos(z * math.pi*2) * 100))
   print("")
print("")

print("\"Surface Three\"")
for y in range(-10, 10+1):
   for x in range(-10, 10+1):
      z = x * 0.1
      print("%f %f %f 7" % (float(x)/2, float(y)/2, math.sin(z * math.pi*2) * 10))
   print("")
print("")

plot.bat
cd %~dp0
python plot.py > data.txt

echo ^
set terminal wxt size 570,420; ^
stats "data.txt" u 1:2 nooutput; ^
set border 0x7F linecolor rgb "#555555"; ^
set grid xtics linecolor rgb "#888888" linewidth 0.2 linetype 9; ^
set grid ytics linecolor rgb "#888888" linewidth 0.2 linetype 9; ^
set grid ztics linecolor rgb "#888888" linewidth 0.2 linetype 9; ^
set xrange [-10.0:10.0]; ^
set yrange [-10.0:10.0]; ^
set zrange [-10.0:100.0]; ^
splot for [IDX=0:STATS_blocks-1] "data.txt" i IDX using 1:2:3:4 with lines ^
lc variable title columnheader(1) | gnuplot -p

plot.sh
#!/bin/bash

python plot.py > data.txt

echo \
'set terminal wxt size 570,420; \
stats "data.txt" u 1:2 nooutput; \
set border 0x7F linecolor rgb "#555555"; \
set grid xtics linecolor rgb "#888888" linewidth 0.2 linetype 9; \
set grid ytics linecolor rgb "#888888" linewidth 0.2 linetype 9; \
set grid ztics linecolor rgb "#888888" linewidth 0.2 linetype 9; \
set xrange [-10.0:10.0]; \
set yrange [-10.0:10.0]; \
set zrange [-10.0:100.0]; \
splot for [IDX=0:STATS_blocks-1] "data.txt" i IDX using 1:2:3:4 with lines \
lc variable title columnheader(1)' | gnuplot -p

A: Example without explicit parametric
This was mentioned at: https://stackoverflow.com/a/51546029/895245 with a link to the docs, here is a minimal example:
set terminal png
set output 'splot-domain.png'

# Number of x and y samples.
set isosamples 10, 5

# Plotted domain.
set urange [-5.0 : 0.0]
set vrange [-5.0 : 5.0]

# Visible domain.
set xrange [-5.0 : 5.0]
set yrange [-5.0 : 5.0]

# Just to make plot look nicer.
set hidden3d
set xyplane at 0
set xlabel 'x'
set ylabel 'y'

splot '++' using 1:2:($2**2) with lines

GitHub upstream.
Output:

Tested on gnuplot 5.2 patchlevel 8.


text:
Q: Javascript keypress into keypress I wrote a function addMoney(), which calls by clicking Enter into input field:
$('body').on('keypress', 'input[type=text]', function(e){
     if(e.keyCode==13){
         var val = $('input[type=text]').val();
         switch(val) {
             case '-help':
                 SeeComands();
                 break
             case '-copyright':
                 SeeAuthors();
                 AddNewLine();
                 break
             case '-addmoney':
                 addMoney();
                 break
             default:
                 SaveCommand();
                 Animal('I see nothing here, try smthing else',function(){AddNewLine();})
         }
     }

This function creates a new input field, clicking an Enter in which starts a finding of regular expression in string, which was handed over last input:
function addMoney() {
SaveCommand();

Animal('E', function(){//интсрукция ко вводу  Enter the number of banknotes introduced through the gap
    Animal('U',function(){ //Use a template <count of banknotes>x<nominal of banknotes>
        AddNewLine();
        $('body').on('keypress', 'input[type=text]', function(e){//Checking the input string
             if(e.keyCode==13){
                 var vali = $('input[type=text]').last().val();
                 console.log('val: ', vali);
                 SaveCommand();
                 var reg100 = /([1-9]{1,})(?=x100)/g; //RegExp to find the amount of the nominal value of 100 bills
                 var reg200 = /([1-9]{1,})(?=x200)/g; //RegExp to find the amount of the nominal value of 200 bills
                 var reg500 = /([1-9]{1,})(?=x500)/g; //RegExp to find the amount of the nominal value of 500 bills
                 var reg1000 = /([1-9]{1,})(?=x1000)/g; //RegExp to find the amount of the nominal value of 1000 bills
                 var reg5000 = /([1-9]{1,})(?=x5000)/g; //RegExp to find the amount of the nominal value of 5000 bills
                 var result100 = vali.match(reg100);
                 var result200 = vali.match(reg200);
                 var result500 = vali.match(reg500);
                 var result1000 = vali.match(reg1000);
                 var result5000 = vali.match(reg5000);
                 console.log('100:', result100, '200:', result200, '500:', result500, '1000:', result1000);
             };
        });
    });
});
};

But brake of the switch is working earlier, till AddMoney() is working.
As Result vali declared in:
var vali = $('input[type=text]').last().val();

is undefined and as result i have not a result of addMoney(), but have a default switch result:
Animation "I see nothing here, try smthing else"
I think it can b due function Animal():
function Animal(string, callback) {
    var a = ''; //The variable which will be entered character by character string
    var i= 0;//Counter of a letters
    var p = document.createElement('p');
    $('body').append(p);

    Anima();
    function Anima() {//Animation Function
        a=a+string[i];
        i++;
        $('p').last().text(a);
        var timer = setTimeout(Anima, 100);
        if(i==string.length){
            clearTimeout(timer);
            callback();//For running in order
        };
    };
};

...due function Anima(), which runs as recursion through SetTimeOut()

A: i did it by done a new function DefaultCase():
function addMoney(str){
var reg100 = /([0-9]+)(?=x100)/g; //Регулярка для поиска количества купюр номинала 100
var reg200 = /([0-9]+)(?=x200)/g; //Регулярка для поиска количества купюр номинала 200
var reg500 = /([0-9]+)(?=x500$|x500\s)/g; //Регулярка для поиска количества купюр номинала 500
var reg1000 = /([0-9]+)(?=x1000)/g; //Регулярка для поиска количества купюр номинала 1000
var reg5000 = /([0-9]+)(?=x5000)/g; //Регулярка для поиска количества купюр номинала 5000
var result100 = str.match(reg100);
var result200 = str.match(reg200);
var result500 = str.match(reg500);
var result1000 = str.match(reg1000);
var result5000 = str.match(reg5000);

if((result100 == 0) && (result200 == 0) && (result500 == 0) && (result1000 == 0) && (result5000 == 0)){
    Animal('Enter the amount u need to add. Check the errors', function(){
        AddNewLine();
    });
} else {
    if ((valFree(100)<result100) || (valFree(200)<result200) || (valFree(500)<result500) || (valFree(1000)<result1000) || (valFree(5000)<result5000)) {
        Animal('U r tryig to add too many banknotes. Check free place in ATM', function(){
            AddNewLine();
        });
    } else {
        var resstring = 'success: '+str;
        Animal(resstring, function(){
            resstring = '100:+['+result100+']bills 200:+['+result200+']bills 500:+['+result500+']bills 1000:+['+result1000+']bills 5000:+'+result5000;
            Animal(resstring, function() {
                AddNewLine();
            })
        })};
    }
};

//Функция изменения имени
function ChangeName(str) {
if(str.indexOf('@')<(str.length-1)){
    name = str.match(/@(\w+)/)[1];//Регулярка поиска имени
    AddNewLine();
} else {
    Animal('Enter Valid Name.', function(){
        AddNewLine();
    });
};
};

//Функция Стандартного Default case в switch
function defaultCase(str) {
SaveCommand()
if(str.match(/-addmoney/)) {
    addMoney(str);
} else {
    if(str.match(/-name @/)){
        ChangeName(str);
    } else {
    Animal('I see nothing here, try smthing else',function(){AddNewLine();})

    }
}
};


text:
Q: При восстановлении свернутого приложения, из бд выводится только последняя строка В бд есть несколько строк.
Вывожу их "добавлением" layout'a в основной layout таким методом:
Cursor q = sql.query(...);
q.moveToPosition(-1);
while (q.moveToNext()) {
    ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.lin_info, Ll, false);
    ((TextView)layout.findViewById(R.id.tv)).setText(q.getString(0));
    ....addView(layout);
}

Все нормально и правильно выводится. Но, если свернуть приложение или выключить экран и вернуться к нему через полчаса, во всех добавленных layout'ах будет только последнее значение из бд.
Если свернуть и развернуть быстро (даже спустя 10 минут), все данные останутся, но если долго подождать, то будет только последнее значение.
Если выводить данные немного другим способом, без добавления layout'a и использования LayoutInflater'a
while (q.moveToNext()) {
    TextView t = new TextView(context);
    t.setText(q.getString(0));
    ....addView(t);
}

То такого эффекта нет.
Подскажите, из-за чего это происходит и как этого избежать?


text:
Q: Rails function returns HTML-name characters instead of the actual character I have a function:
def div
"
blah
"
end

and in the view:
<%= div %>

but in the resulting page source:
<div>blah</div>

instead of the actual string text.
However, the console displays the correct tags.
<% logger.info(div) %>

Outputs in the console:

blah

Can anyone help?

A: Use this instead.
<%= raw div %>

Rails 3 escapes everything coming from the server in views, you can use raw if you're sure you trust the data.

A: Alternatively, if you want to be able to use
<%= div %>

in your view, you can define your function like this and it will work too:
def div
  "
blah
".html_safe
end

A: Yes, in Rails 2 text was raw by default, now in Rails 3 they make vice versa


text:
Q: MySQL SELECT statement where value is in array I need some help with an MySQL statement that I cannot really make to work.
I have a table like this:
+---+-------------------------------+
|id | fruit                         |
+---+-------------------------------+
| 1 | apple,orange,pear,grape,lemon |
| 2 | pear,melon,apple,kiwi,lemon   |
| 3 | orange,kiwi,pear,apple,cherry |
| 4 | grape,lemon,cherry,apple,melon|
+---+-------------------------------+

What I need to do is to SELECT all rows where the column fruit contains the word melon. The word in question might be at any position in the array.
I tired with the below query but for some reason I only get 3-4 rows, definitely not all of them:
$fruit = $_GET['fruit'];
$query1= "SELECT * FROM tbl_fruits WHERE ".$fruit." IN (fruit)";

Any comments will be appreciated.

A: You can use FIND_IN_SET
SELECT * FROM tbl_fruits
WHERE find_in_set('$fruit', fruit)

But you actually should rather change your table design.
Never store multiple values in a single column!
A better table design would be
fruits table
------------
id    name
1     melon
2     orange
3     apple
...

products table
-------------------
id    name   price
1     P1     1.50
2     P2     2.99
3     P3     0.99

product_fruits table
--------------------
product_id   fruit_id
1            1
1            2
2            2
3            1

That is a classic many to many relation (m to n).

A: $fruit = $_GET['fruit'];
$query1= sprintf("SELECT * FROM tbl_fruits WHERE fruit LIKE '%%s%'",
        mysql_real_escape_string($fruit ));

A: Try below sql
$fruit = $_GET['fruit'];
$query1= "SELECT * FROM tbl_fruits WHERE fruit LIKE '%".$fruit."%'";

A: Use a LIKE clause:
SELECT * FROM tbl_fruits
    WHERE fruit LIKE '%apple%';

A: select * from tbl_fruits WHERE fruit like '%melon%'

A: As mentioned before you can/should build your table structure differently.
It's the "relational" in "relational database". see http://en.wikipedia.org/wiki/Database_normalization
As always: not a silver bullet. There are other kinds of daabases and there can be rasons for not normalizing (parts of) tables. But anyway, here's an sscce using PDO:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
//echo 'client version: ', $pdo->getAttribute(PDO::ATTR_CLIENT_VERSION), "\n";
//echo 'server version: ', $pdo->getAttribute(PDO::ATTR_SERVER_VERSION), "\n";
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
setup($pdo);

$stmt = $pdo->prepare("
    SELECT
        m.name
    FROM
        soFruits as f
    JOIN
        soMixXFruits as x
    ON
        f.id=x.idFruit
    JOIN
        soFruitMix as m
    ON
        x.idMix=m.id
    WHERE
        f.name=?
");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
foo($stmt, 'apple');
foo($stmt, 'melon');

function foo(PDOStatement $stmt, $param) {
    echo "----- $param -----\r\n";
    $stmt->execute( array($param) );
    foreach($stmt as $r) {
        echo join(', ', $r), "\r\n";
    }
}

function setup($pdo) {
    $queries = array(
        '
            CREATE TEMPORARY TABLE soFruits (
                id INT auto_increment,
                name varchar(64),
                primary key(id)
            )
        ',
        '
            CREATE TEMPORARY TABLE soFruitMix (
                id INT auto_increment,
                name varchar(32),
                primary key(id)
            )
        ',
        '
            CREATE TEMPORARY TABLE soMixXFruits (
                idMix int,
                idFruit int,
                primary key(idMix, idFruit)
            )
        ',
        "INSERT INTO soFruits (id,name) VALUES (1,'apple'),(2,'cherry'),(3,'grape'),(4,'kiwi'),(5,'lemon'),(6,'melon'),(7,'orange'),(8,'pear')",
        "INSERT INTO soFruitMix (id,name) VALUES (1, 'mix1'),(2,'mix2'),(3,'mix3'),(4,'mix4')",
    );
    foreach( $queries as $q ) {
        $pdo->exec($q);
    }

    $data = [
        '1'=>['apple','orange','pear','grape','lemon'],
        '2'=>['pear','melon','apple','kiwi','lemon'],
        '3'=>['orange','kiwi','pear','apple','cherry'],
        '4'=>['grape','lemon','cherry','apple','melon']
    ];

    $stmt = $pdo->prepare('
        INSERT INTO soMixXFruits (idMix, idFruit)
            SELECT
                :idMix, id
            FROM
                soFruits
            WHERE
                name=:nameFruit
    ');
    $stmt->bindParam('idMix', $idMix);
    $stmt->bindParam('nameFruit', $nameFruit);

    foreach($data as $idMix=>$mix) {
        foreach($mix as $nameFruit) {
            $stmt->execute();
        }
    }
}

Take a look at the table definitions in function setup($pdo). You have entities like fruits and mixes and then there's a table that represents their relationship.
side-note: I didn't pay attention to the indicies. But for performance that is usually crucial, see http://www.sitepoint.com/using-explain-to-write-better-mysql-queries/


text:
Q: How to sort ListView items when ListView is in VirtualMode? I realize i have to sort the collection where the ListView gathers the items from:
ListView listCollection = new ListView();
But this doesn't seem to work unless the ListView is added as a GUI-control to the form, that in turn makes it very slow to add items to, hence why i have to use VirtualMode on my GUI-ListView in the first place.
Anyone know how to go about this or point me in the right direction?

A:
basically, you will need to apply sort to the data pump itself.

I did a quick search on Google for listview sort virtualmode. First result was this page, where the above quote was taken from.
For example, if your datasource is a DataView, apply sorting on this instead of the ListView.
If it is just a question of performance when adding items, I would do as barism suggests; use BeginUpdate/EndUpdate instead of VirtualMode.
try {
  listView1.BeginUpdate();
  // add items
}
finally {
  listView1.EndUpdate();
}

A: If you are using virtual mode, you have to sort your underlying data source. As you may have found, ListViewItemSorter does nothing for virtual lists.
If you are using a non-virtual listview, you can also use AddRange(), which is significantly faster than a series of Add() -- In addition to using BeginUpdate/EndUpdate that has already been described.
ObjectListView (an open source wrapper around .NET WinForms ListView) already uses all these techniques to make itself fast. It is a big improvement over a normal ListView. It supports both normal mode and virtual mode listviews, and make them both much easier to use. For example, sorting is handled completely automatically.

A: I had the same problem switching VirtualMode True with an existing project, but the solution was surprisingly easy:
First step I am populating a list of ListViewItem, instead of ListView.Items collection:
private List<ListViewItem> _ListViewItems;

Then I have implemented the RetrieveVirtualItem method
private void mLV_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
    e.Item = _ListViewItems[e.ItemIndex];
}

Finally I am sorting my list of ListViewItem using the same class I was using before, I had just only to change the base class
_ListViewItems.Sort((System.Collections.Generic.IComparer<ListViewItem>)new ListViewItemComparer(new int[] { e.Column }, mLV.Sorting));

This is my IComparer class implementation:
class ListViewItemComparer : System.Collections.Generic.IComparer<ListViewItem>
{
    int[] mColonne;
    private System.Windows.Forms.SortOrder order;
    public ListViewItemComparer(int[] mCols)
    {
        this.mColonne = mCols;
        this.order = System.Windows.Forms.SortOrder.Ascending;
    }

    public ListViewItemComparer(int[] mCols, System.Windows.Forms.SortOrder order)
    {
        this.mColonne = mCols;
        this.order = order;
    }

    public int Compare(ListViewItem x, ListViewItem y)
    {
        int returnVal = -1;

        foreach (int mColonna in mColonne)
        {
            double mNum1;
            double mNum2;

            String mStr1 = "";
            String mStr2 = "";

            if ((x.SubItems[mColonna].Text == "NULL") && (x.SubItems[mColonna].ForeColor == Color.Red))
            {
                mStr1 = "-1";
            }
            else
            {
                mStr1 = x.SubItems[mColonna].Text;
            }

            if ((y.SubItems[mColonna].Text == "NULL") && (y.SubItems[mColonna].ForeColor == Color.Red))
            {
                mStr2 = "-1";
            }
            else
            {
                mStr2 = y.SubItems[mColonna].Text;
            }

            if ((double.TryParse(mStr1, out mNum1) == true) && (double.TryParse(mStr2, out mNum2) == true))
            {
                if (mNum1 == mNum2)
                {
                    returnVal = 0;
                }
                else if (mNum1 > mNum2)
                {
                    returnVal = 1;
                }
                else
                {
                    returnVal = -1;
                }
            }
            else if ((double.TryParse(mStr1, out mNum1) == true) && (double.TryParse(mStr2, out mNum2) == false))
            {
                returnVal = -1;
            }
            else if ((double.TryParse(mStr1, out mNum1) == false) && (double.TryParse(mStr2, out mNum2) == true))
            {
                returnVal = 1;
            }
            else
            {
                returnVal = String.Compare(mStr1, mStr2);
            }

            if (returnVal != 0)
            {
                break;
            }
        }

        // Determine whether the sort order is descending.
        if (order == System.Windows.Forms.SortOrder.Descending)
        {
            // Invert the value returned by String.Compare.
            returnVal *= -1;
        }
        return returnVal;
    }
}

Hope this will help you.

A: Did you try beginupdate() and endupdate()? Adding data is much faster when you use beginupdate/endupdate.(when you call beginupdate, listview doesn't draw until you call endupdate)
listView1.BeginUpdate();
for (int i = 0; i < 20000; i++)
{
listView1.Items.Add("abdc", 1);
}
listView1.EndUpdate();

A: For very large lists, the Virtual Mode ListView is the answer for certain.  In non-virtual mode it seems to draw the entire list and then clip it to the view, while in Virtual mode it simply draws the ones in the view.  In my case the list was 40K+ records. In non-virtual mode an update to the ListView could take minutes.  In virtual mode it was instantaneous.
To sort the list, you must sort the underlying datasource, as has already been mentioned.  That is the easy part.  You will also need to force a refresh to the display, which is not done automatically.  You can use ListView.TopItem.Index to find the index in the underlying data source that corresponds to the top row of the Virtual ListView before the sort.  There is also an API call that returns the number of display rows in the ListView that you can implement as C# function, like this:
public const Int32 LVM_GETCOUNTPERPAGE = 0x1040;

public static int GetListViewRows( ListView xoView )
{
   return (int)WindowsMessage.SendMessage( xoView.Handle, LVM_GETCOUNTPERPAGE, 0, 0 );
}

That will let you calculate the range you have to update.  About the only remaining question is how you reconcile the existing display with what will appear after the data have been sorted.  If you want to leave the same data element in the top row, you must have some mechanism in place that will find its new index in the newly sorted list, so you can replace it in the top position - something essentially equivalent to an SQL IDENTITY.


text:
Q: Using Maven to Deploy to Weblogic Clusters org.codehaus.mojo
weblogic-maven-plugin
2.9.1
We're currently using the weblogic maven plugin successfully to deploy to our local WebLogic 9.2 instances.
When we try to deploy to a remote environment we have a problem. We use a two machine cluster, with the admin server and managed server on one machine, and another managed server on a seperate machine.
When your plugin uploads the application to the admin server, it doesn't copy it to the second managed server on the seperate machine. This then causes the second managed server a problem, as it cannot find the application in the location where the admin server saved it on its own machine.
Config below
            <configuration>
                <adminServerHostName>${weblogic.adminServerHostName}</adminServerHostName>
                <adminServerPort>${weblogic.adminServerPort}</adminServerPort>
                <adminServerProtocol>${weblogic.adminServerProtocol}</adminServerProtocol>
                <userId>${weblogic.userId}</userId>
                <password>${weblogic.password}</password>
                <upload>${weblogic.upload}</upload>
                <remote>${weblogic.remote}</remote>
                <verbose>${weblogic.verbose}</verbose>
                <debug>${weblogic.debug}</debug>
            <stage>${weblogic.stage}</stage>
                <targetNames>${weblogic.targetNames}</targetNames>
                <exploded>${weblogic.exploded}</exploded>
            </configuration>

<profile>
  <id>localhost</id>
  <properties>
<weblogic.adminServerHostName>localhost</weblogic.adminServerHostName>
    <weblogic.adminServerPort>7001</weblogic.adminServerPort>
    <weblogic.adminServerProtocol>t3</weblogic.adminServerProtocol>
    <weblogic.userId>weblogic</weblogic.userId>
    <weblogic.password>weblogic</weblogic.password>
    <weblogic.upload>false</weblogic.upload>
    <weblogic.remote>false</weblogic.remote>
    <weblogic.verbose>true</weblogic.verbose>
    <weblogic.debug>true</weblogic.debug>
<weblogic.stage>false</weblogic.stage>
    <weblogic.targetNames>AdminServer</weblogic.targetNames>
    <weblogic.exploded>false</weblogic.exploded>
  </properties>
</profile>

<profile>
  <id>dev</id>
  <properties>
<weblogic.adminServerHostName>******</weblogic.adminServerHostName>
    <weblogic.adminServerPort>9141</weblogic.adminServerPort>
    <weblogic.adminServerProtocol>t3</weblogic.adminServerProtocol>
    <weblogic.userId>******</weblogic.userId>
    <weblogic.password>******</weblogic.password>
    <weblogic.upload>true</weblogic.upload>
    <weblogic.remote>true</weblogic.remote>
    <weblogic.verbose>true</weblogic.verbose>
    <weblogic.debug>true</weblogic.debug>
<weblogic.stage>true</weblogic.stage>
    <weblogic.targetNames>dev_cluster01</weblogic.targetNames>
    <weblogic.exploded>false</weblogic.exploded>
  </properties>
</profile>

A: This may not relate because my experience has only ever been with WebLogic 10 but...
Make sure you have the clustered configured correctly because it should be WebLogic (not Maven or any plugin) which is responsible for distributing a deployed application to each managed server. The maven plugin should only ever deploy to the admin server and WebLogic handles all the other magic to make sure each managed server it knows about also gets the app deployed. I don't think the fact you are using the MOJO is relevant.
Also, ensure you have NodeManager configured correctly and that it is running. NodeManager (at least on WebLogic 10) is responsible for all communication between nodes. It may be the case that you NodeManager process is hung or killed on the managed server which is not getting the application. This is however unlikely if you have tried doing a deploy from the Admin Console which you stated you did try in your comments on the original question.
Hope this leads you in the right direction.


text:
Q: Synonym for "hold on to" I want to say "This institution encourages its students to hold onto their passions"
I felt like "hold onto" sounds odd. I mean the institution lets students keep their passions and doesn't force them to give them up. Any advice,

A: Alternatively  embrace; hold on to is good though too.

She embraces diversity, and believes that all students should have an opportunity to contribute to music lessons.

According to Macmillan Dictionary, the most common collocations with ebrace are:
challenge, change, concept, diversity, ethos, idea, innovation, notion, opportunity, principle, technology

You should hold on to her, she's too good to lose to a competitor.
Cambridge Dictionary

A: If you wish to use hold on to as to maintain or sustain the quality of the student's passion, you might want to consider uphold

This institution encourages its students to uphold their passions

Wiktionary describes this word as:

To keep erect; to support; to sustain; to keep from falling

List of other alternatives:

*

*maintain

*sustain (if the 'institution' wants to assist the increase of the student's passion)

*preserve

*affirm (if the 'institution' wishes to support the student emotionally)

A: "Pursue" would be a good fit here. It evokes both a sense of not giving up, and advancing one's interest in an area.
"The institution encourages its students to pursue their passions."


text:
Q: tesseract command not working from command line in windows I installed tesseract-OCR for windows and it resides in C:\Program Files\Tesseract-OCR path in my system.
I set up an environment variable by adding C:\Program Files\Tesseract-OCR in the PATH variable.
I also set up TESSDATA_PREFIX in system variable to the same above tesseract location.
Still, when I try to run the command "tesseract some path\image.tif somepath\output", it gives message as "'tesseract' is not recognized as an internal or external command".
when i run the same command from the location where tesseract is installed, it works fine but i need to have it set in the environment variables as it will also allow PYOCR wrapper to recognise it.
PYOCR is currently giving "pyocr.get_available_tools()[0]" as empty list.
any help is much appreciated.

A: Perhaps my answer is a little bit late, but I will give my setup that seems to work from few minutes. As you, I was using PYOCR library, and at the beginning I get an empty list when using  pyocr.get_available_tools().
I'm running it on a Windows 10 laptop.
First, I installed Tesseract in version 4 in alpha from here:
https://github.com/UB-Mannheim/tesseract/wiki and then added location in my windows user PATH variable. From here, run a new command line and check that tesseract tool is detected, if not you're environmment is not properly configured!
Then, I installed PyOCR using a simple pip pyocr and use the follow imports
before using pyocr functions:
import pyocr
import pyocr.builders

EDIT:
I've look in current source files of PYOCR and I've found this:
def is_available():
    _set_environment()
    return util.is_on_path(TESSERACT_CMD)

PyOCR is just  looking for tesseract.exe in your os Path variable, so I think you just have to solve the mention issue and it will work.
EDIT 2:
I updated the download link with UB Mannheim version. Seems more efficient on my data. Also, I downgraded to Tesseract 3, because a lot of flags was not supported in 4.0 alpha build.
Hope it can help a little bit,
Best regards

A: Please check the correct path of installation of Tesseract-OCR. Setting the correct path, i.e. C:\Program Files (x86)\Tesseract-OCR worked for me.


text:
Q: Android Studio How to fix cannot create class-file error? I am following the steps mentioned here: https://priyankvex.wordpress.com/2015/08/30/how-to-build-tesseract-ocr-library-for-android-studio/
Step 3 tells to copy and paste the tess-two folder to my Project but when I paste, I get an error stating Cannot create class-file and none of my `.java' files get copied.
Where am I going wrong?

A: I don't know what the problem is but it works, if you copy the folder directly into the project folder instead of copying through the Android Studio.
Maybe for some reason the files are not copied in the Android Studio.

A: It is because some .class files are included in your copy files.
Some IDE will not include .class file in project and show this tips.


text:
Q: React: Getting an object on click I have an array of objects which is passed as a property to a list that maps them to
.
I would like to be able, for any individual item, to click on an item from the list, and receive that object and then assign it to the root component's state - so I could then pass it on to another child comp.
var Menu = React.createClass({
render: function() {
    return (

        {
            this.props.posts.map(function(post){
                return
{post.title}

            })
        }

)
}

})
https://jsfiddle.net/nbenita/yxw1z42q/
Thanks!

A: Pass a callback function into your Menu component as a prop and use Function.prototype.bind() to partially apply the relevant post object as an argument:

Updated fiddle: https://jsfiddle.net/yxw1z42q/2/
var Blog = React.createClass({
    getInitialState: function() {
        return {
            selectedPost:this.props.posts[0]
        };
    },
    onPostSelected: function(selectedPost) {
        this.setState({
            selectedPost: selectedPost
        });
    }
    render: function() {
        return (

            <Menu posts={this.props.posts} onClick={this.onPostSelected} />
            <Post content={this.state.selectedPost} />

)
    }
})

var Menu = React.createClass({
    render: function() {
        return (

            {
                this.props.posts.map(function(post){
                    return
{post.title}

                }, this)
            }

)
    }
})

Further reading

*

*React Docs - Communicate Between Components

*react-training - Simple Component Communication


text:
Q: how to declare variables based on other params in C++ I have the below code (eg):

void Foo(int ip_selector)
{
    ipv4_hdr_t ipv4;
    ipv6_hdr_t ipv6;
    {
        …
        if(ip_selector == 0)
            addStack(ipv4);
        else
            addStack(ipv6);
    }
{
        …
        if(ip_selector == 0)
            addStack(ipv4);
        else
            addStack(ipv6);
    }
     …
}
int main()
{
    for (int i = 0; i < 2; i++) {
        Foo(i);
    }
}

In the above code, addStack param depends on the selector param in Foo(). The above code works fine, but does to the scale it can grow, I do not want to add if ip_selector check everywhere in Foo() to see which arg to be passed in addStack(). I am trying to find a way to select either ipv4_hdr_t/ipv6_hdr_t without writing an if else condition. Infact, I dont even need the ipv6 declaration of ip_selector is 0 (vice versa for that matter)

A: here is one way to solve such a problem.
1.have a base class for your protocols, say Protocol.
2.derive your ip4/ip6/whateverelse classes from the base class.
3.create an array of available protocols.
4.use the selector to pick an array element.
class Protocol {
    virtual void addStack() = 0;
    ...
 };
 class Ip4Protocol : public Protocol {
     ip4_hdr_type hdr;
     void addStack(){...}
  };

vector<Protocol*> availableProtocols = {
    new Ip4Protocol(),
    new IP6Protocol(),
    ...
};
...
for (int i = 0; i < availableProtocols.size(); i++) {
    avalableProtocols[i]->addStack();
}

or you can probably use templates on the derived classes as well
termplate <class P> class IP : public Protocol {
      P hdr;
      void addStack()  {addGlobalStack(hdr)};
}

ther are tons of other possibilities as well.


text:
Q: VBA Excel Userform Clear Range after vbYesNo The code below is intended to check if the cells in a given range are empty. If they are not, the user is asked if they want to save the contents of the range. If they select "No" the contents of the range is cleared.
 Dim answer As Integer

If Not WorksheetFunction.CountA(Worksheets("Temp").Range("A1:D101")) = 0    Then
    answer = MsgBox("Save changes for this account?", vbYesNo)
 If answer = vbYes Then
   'do nothing
 Else
   Worksheets("Temp").Range("A1:D101").ClearContents
 End If
End If

For some reason the clear method just won't clear anything. I have tried first activating the sheet. First selecting the range. First selecting the sheet then selecting the range. Using ".Clear" instead of ".ClearContents". Adding an Else statement to the outer If statement. I've tried selecting a range of only filled cells. No matter what I've done, the contents of the range will stay there until I delete it manually. Everything else seems to work fine. I cannot for the life of me figure out what is missing from my code.
Any suggestions?
Edit: Here is the code for the entire function:
Private Sub NameBox_Change()

Dim answer As Integer

If Not WorksheetFunction.CountA(Worksheets("Temp").Range("A1:D101")) = 0 Then
    answer = MsgBox("Save changes for this account?", vbYesNo)
 If answer = vbYes Then
   'do nothing
 Else
   Worksheets("Temp").Range("A1:D101").ClearContents
 End If
End If

With Me

    Worksheets("Temp").Cells(1, 1).Value = Format(Date, "mm-dd-yyyy")
    Worksheets("Temp").Cells(1, 2).Value = Worksheets("Users").Cells(.NameBox.ListIndex + 1, 1).Value
    Worksheets("Temp").Cells(1, 3).Value = Worksheets("Users").Cells(.NameBox.ListIndex + 1, 6).Value
    Worksheets("Temp").Cells(1, 4).Value = Worksheets("Users").Cells(.NameBox.ListIndex + 1, 7).Value

    ReadLabel.Caption = Worksheets("Temp").Cells(102, 3).Value
    SpentLabel.Caption = Worksheets("Temp").Cells(102, 4).Value
    ToSpendLabel.Caption = Worksheets("Temp").Cells(102, 3).Value - Worksheets("Temp").Cells(102, 4).Value

End With

End Sub

A: I am an idiot. This function is triggered when a the user selects a new name from a dropdown list. The original name was being cleared and then replaced by the new name. I just hadn't realized that the names had changed. Thanks for helping my look at this with fresh eyes. I will leave the question up in case someone finds my code useful.


text:
Q: What is the difference: "would" vs "will" Would you please to explain the differences?

For example, this would be the exception to throw if the caller
  attempted to use some object before it had been properly initialized.
For example, this will be the exception to throw if the caller
  attempted to use some object before it had been properly initialized.

A: Would is conditional and will is not. In the usage listed in your example, I don't see any practical difference that a listener or reader might register. I think that the first sentence is more correct, because if indicates the condition under which that particular exception is to be thrown. If the word if were replaced with the word when, I would favor the second sentence. You will not be misunderstood or thought to be using English oddly with either sentence.
Would also has some common, colloquial uses that are not conditional in modern English (at least in the United States version of it), but in my experience these are generally verbal hedging. For example, I initially typed "I would say that the first sentence is more correct...", but that is confusing given this specific question and I can't think of a single grammar-based argument for why that's an acceptable construction.

A: The uses of will and would are distinguished succinctly in When should I use would / would have / will / will have?.
In the context of your example, would is used when you are describing a condition - something which would happen if something else happened first. Will is used when you are stating an intention or predicting the future - ie when the condition has already happened.
In your example there is a condition, so would is correct : "If the caller attempted to use some object, then ... would be the result."
However, I think there may be bigger problems with your sentence than the choice between would and will. The meaning of the sentence is far from clear. Perhaps the context would provide enough explanation. Otherwise, your concern about which word is correct is misplaced. Clear communication is much more important than using correct grammar.
In common practice, would and will are used interchangeably. English as a first language is not taught as thoroughly as when it is a second language. Considerable laxity is tolerated, especially in spoken English.


text:
Q: url_field to accept non http:// or https:// links I have tried useing url_field tag in my form.
I should be able to enter non http:// urls, e.g I would need to enter www.google.com. But rails url_field does not allow this.
Is there any way to do it?
This is my current setup:
<%= f.url_field :english_link,  :class => "form-control", :placeholder =>"Type your message", :rows => "4", maxlength: 130, spellcheck: true %>

I also tried using a regex within f.text_field , but it is not working.
<%= f.text_field :english_link, pattern: /(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/, :class => "form-control", :placeholder => "Enter URL Link Here" %>

I checked to see if the regex works in rubular.com, and it is working.

A: Pattern would be evaluated on the browser side. Nice solution but it wont work everywhere (depends on the browser). Not sure if regex is exactly same syntax as Ruby perhaps you should cross reference taht. Check in your HTML output if the regex follows the requred syntax (perhaps you should replace // with "")
https://www.w3schools.com/tags/att_input_pattern.asp

A: In your model for example Posts.rb lets say it contains the field english_link
So in your model Post.rb you can do a check like this:
validates_format_of : english_link, :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix


text:
Q: How to initialize nested 2D int array (or array of pointers to int[]?) with arrays of different length in c++? I'm trying to do such init in first line and then peek whats inside first 5 sub-arrays:
    int * v [] = {new int[20001], new int[10001], new int[5001], new int[2501], new int[1251], new int[626], new int[313], new int[157], new int[79], new int[40], new int[20], new int[10], new int[5], new int[3], new int[2]};

    int ind_array = 15;
    int ind_element = 1;
    while (ind_array-- > 10)
            cout << ind_array << "[" << ind_element << "] = " << v[ind_array][ind_element] << endl;

This seem to compile, but I can't see elements that I expect (zeros): for every array when ind_element = 0 or = 1 it returns me some (overflow) value (-1094795586) and when ind_element >= 2 crashes with "==31==ERROR: AddressSanitizer...".
How can I initialize such structure and how can I access its elements?


text:
Q: jackson provider not available when run application I am trying to test java application(have main method). I am using maven to add dependencies into my project. I am running application from IntelliJ IDE directly rather than creating a fat jar and then run. But somehow i unable to find JSON class at runtime and getting exception
Exception in thread "main"
java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/ObjectMapper
at com.hospitality.component.visma.websocket.Test.<init>(Test.java:10)
at com.hospitality.component.visma.websocket.Test.main(Test.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.databind.ObjectMapper

Here is my pom.xml:
     <dependency>
       <groupId>com.fasterxml.jackson.jaxrs</groupId>
       <artifactId>jackson-jaxrs-json-provider</artifactId>
     </dependency>

This project have a parent pom.xml file which have already included this jar.mvn dependecy:tree showing following jar list:
[INFO] Building visma-websocket-server 0.0.1-SNAPSHOT
[INFO] -----------------------------------------------------------
  -------------
[INFO]
[INFO] --- maven-dependency-plugin:2.1:tree (default-cli) @ visma-websocket-server ---
[INFO] com.hospitality.hp.components:visma-websocket-server:jar:0.0.1-SNAPSHOT
[INFO] +- org.glassfish.metro:webservices-rt:jar:2.3:provided
[INFO] |  \- org.glassfish.metro:webservices-api:jar:2.3:provided
[INFO] |     \- javax.annotation:javax.annotation-api:jar:1.2-b03:provided
[INFO] +- junit:junit:jar:4.11:test
[INFO] |  \- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] +- org.hamcrest:hamcrest-all:jar:1.3:test
[INFO] +- javax:javaee-api:jar:7.0:provided
[INFO] |  \- com.sun.mail:javax.mail:jar:1.5.0:provided
[INFO] |     \- javax.activation:activation:jar:1.1:provided
[INFO] +- org.slf4j:slf4j-api:jar:1.7.21:compile
[INFO] +- ch.qos.logback:logback-classic:jar:1.1.7:compile
[INFO] |  \- ch.qos.logback:logback-core:jar:1.1.7:compile
[INFO] +- org.eclipse.jetty.websocket:websocket-server:jar:9.0.3.v20130506:compile
[INFO] |  +- org.eclipse.jetty.websocket:websocket-common:jar:9.0.3.v20130506:compile
[INFO] |  |  +- org.eclipse.jetty.websocket:websocket-api:jar:9.0.3.v20130506:compile
[INFO] |  |  \- org.eclipse.jetty:jetty-util:jar:9.0.3.v20130506:compile
[INFO] |  +- org.eclipse.jetty.websocket:websocket-servlet:jar:9.0.3.v20130506:compile
[INFO] |  \- org.eclipse.jetty:jetty-http:jar:9.0.3.v20130506:compile
[INFO] +- com.hospitality.hp.components:jndi-tools:jar:0.0.1-SNAPSHOT:compile
[INFO] +- org.eclipse.jetty:jetty-server:jar:9.0.3.v20130506:compile
[INFO] |  +- org.eclipse.jetty.orbit:javax.servlet:jar:3.0.0.v201112011016:compile
[INFO] |  \- org.eclipse.jetty:jetty-io:jar:9.0.3.v20130506:compile
[INFO] +- com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:jar:2.2.1:provided
[INFO] |  +- com.fasterxml.jackson.jaxrs:jackson-jaxrs-base:jar:2.2.1:provided
[INFO] |  +- com.fasterxml.jackson.core:jackson-core:jar:2.2.1:provided
[INFO] |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.2.1:provided
[INFO] |  |  \- com.fasterxml.jackson.core:jackson-annotations:jar:2.2.1:provided
[INFO] |  \- com.fasterxml.jackson.module:jackson-module-jaxb-annotations:jar:2.2.1:provided
[INFO] \- org.projectlombok:lombok:jar:1.16.8:provided

Can someone tell me how i can fix this as default scope is compile so why this is not available when i run my application in IDE? However in a  JunitTest run without any issue. Any idea how to fix this ?
-------------------------dependencyManagement---------------------------------
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <scope>compile</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

A: |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.2.1:provided

Scope is provided so it is normal to have NoClassDefFoundError; should leave out the scope statement and use the default.


text:
Q: JedisPool vs JedisPooled Looking at the Jedis Getting Started, I understand it's better to use connection pools to be threadsafe. To do so, I would need a JedisPool and a try-with-resources statement like so:
try (Jedis jedis = pool.getResource()) {
  jedis.set("hello", "world");
}

But then there's JedisPooled, which is the same as JedisPool just without the try-with-resources.
JedisPooled jedis = new JedisPooled("localhost", 6379);
jedis.sadd("hellow", "world");

So the question is, is there any other difference between JedisPool/Pooled, and why should I prefer JedisPool over JedisPooled (or vice versa)?

A: With JedisPool you can do transactions, e.g., something like this:
try (Jedis jedis = pool.getResource()) {
  Transaction t = jedis.multi();
  t.sadd("planets", "Venus");
  t.sadd("planets", "Mars");
  t.exec();
}

It doesn't seem like you can do anything similar with JedisPooled.
Probably, there's more to that, but that's what I've stumbled on by myself.
Hope that helps!


text:
Q: Solved Resources exceeded in GROUP BY, but I need to make it less expensive I solved the resources exceeded error when doing a GROUP BY EACH on a table with billions of rows.
However, the solution is very costly and I would like to bring those costs down.
The error was almost for certain not caused by a skewed grouping key, but by a too high cardinality of the grouping key (is there a fixed max?).
My solution:
SELECT key FROM
(SELECT key FROM [table] WHERE ABS(HASH(key)) % 4 = 0 GROUP EACH BY key),
(SELECT key FROM [table] WHERE ABS(HASH(key)) % 4 = 1 GROUP EACH BY key),
(SELECT key FROM [table] WHERE ABS(HASH(key)) % 4 = 2 GROUP EACH BY key),
(SELECT key FROM [table] WHERE ABS(HASH(key)) % 4 = 3 GROUP EACH BY key)

This works, but it reads my multi TB table multiple times, and I believe that's a bit pricey.
Is there a solution to cut down the costs?
Thanks, Ruben

A: It reads the entire key column from "table" only once.


text:
Q: How to delay showing the header of a modal until an ajax call has returned in Twitter bootstrap? I am using plain vanilla twitter bootstrap modals like:
Add signal

The data-id is used in a small piece of jQuery to make an ajax request, render out some html and then inject that into the modal-body div:
$(document).on('click', '.open-signal', function () {
    var id = $(this).data('id');
    $.get('@Url.Action("CreateSignal")', { "id": id })
        .done(function (d) {
            $('.modal-body', '#addSignal').html(d);
            $('#addSignal').modal('show');
        });
    });

However the header and footer of the modal already show while the ajax call, could be several seconds or longer, already shows and only if the ajax call is done it injects the retrieved html.
How can I delay the modal (header + footer) to appear entirely until the ajax call has finished?

A: Remove the data-toggle="modal" from the  tag. Note however, you should also catch .error on the $.get and provide feedback to the user, otherwise it will appear that clicking Add signal does nothing.
Example here: http://jsfiddle.net/mccannf/HK26K/2/

A: The Bootstrap documentation has an example that uses the show.bs.modal event as the trigger to load ajax into a modal dialog rather than the click event on the opener. I've modified that pattern in my solution:
$('#mainModal')
    .on('show.bs.modal', function (e) {
        var $source = $(e.relatedTarget);
        var $modal = $(this);
        var title = $source.data('modalTitle'); //data-modal-title="@item.Name"
        var url = $source.attr("href"); //assumes source is a hyperlink

        if (title && url) {
            $modal.find('.modal-title').text(title);
            $modal.find(".modal-body").load(url, function () {
                //the call to modal('show') triggers the event again,
                //but the $source won't have a title or an href
                $modal.modal('show');
                $modal.find('.modal-body input').first().focus();
            });

            //don't show the dialog immediately
            return e.preventDefault();
        }
    });


text:
Q: Member is Null JDA 4.X - Spigot When running the / verify coderandom
on the console launch Null
This code was executed in an old version of the JDA

HashMap<UUID, String> uuidCodeMap =  new HashMap<>();;
Bukkit.getScheduler().runTaskLater(plugin, () -> guild = jda.getGuilds().get(0), 100L);

String discordid = uuidIdMap.get(player.getUniqueId());
        //Member is null
        Member target = guild.getMemberById(discordid);
        if (target == null) {
            uuidCodeMap.remove(player.getUniqueId());
            uuidIdMap.remove(player.getUniqueId());
            player.sendMessage("§cError! It seems that you left our Discord server!");
            return true;
        }


text:
Q: adding select field stops iteration; knockoutjs I am on the knockoutjs tutorial at http://learn.knockoutjs.com/#/?tutorial=collections, and I have lost my iterable item foreach: seats. First, my view looked like:

Your seat reservations

            Passenger name	Meal	Surcharge

            <input data-bind="value: name"/>
            <select data-bind="options: $root.availableMeals, value: meal, optionsText: 'mealName'"></select>

<button data-bind="click: addSeat">Reserve another seat</button>

and got

Now I have
view

Your seat reservations

            Passenger name	Meal	Surcharge

            <input data-bind="value: name"/>
            <select data-bind="options: $root.availableMeals, value: meal, optionsText: 'mealName'"></select>
            <select data-bind="options: $root.availableMeals, value: price, optionsText: 'price'"></select>

<button data-bind="click: addSeat">Reserve another seat</button>

the VM hasn't changed
// Class to represent a row in the seat reservations grid
function SeatReservation(name, initialMeal) {
    var self = this;
    self.name = name;
    self.meal = ko.observable(initialMeal);
}

// Overall viewmodel for this screen, along with initial state
function ReservationsViewModel() {
    var self = this;

    // Non-editable catalog data - would come from the server
    self.availableMeals = [
        { mealName: "Standard (sandwich)", price: 0 },
        { mealName: "Premium (lobster)", price: 34.95 },
        { mealName: "Ultimate (whole zebra)", price: 290 }
    ];

    // Editable data
    self.seats = ko.observableArray([
        new SeatReservation("Steve", self.availableMeals[0]),
        new SeatReservation("Bert", self.availableMeals[0])
    ]);

    //operations
    self.addSeat = function() {
        self.seats.push(new SeatReservation("", self.availableMeals[0]));
    }
}

ko.applyBindings(new ReservationsViewModel());

With this new view, I get

I know knockout is new, but I can't see why changing a display to a select field should interrupt an iterable

A: Take a look at the developer console, and you'll see that an error is being thrown:

Uncaught ReferenceError: Unable to process binding "foreach: function
  (){return seats }" Message: Unable to process binding "value: function
  (){return price }" Message: price is not defined

So the problem is that you are trying to access price which doesn't exist on SeatReservation. The rendering for the foreach gets interrupted because of the error that is thrown.
I don't think you want a dropdown for price, you just want to display the price for whatever meal they have selected.

A: Checking the console will really help you get the reason why something have gone wrong. In my console I got this with your code.

So it's said there that price is not defined. Thus we need to check in your model if there is really a price object, and then there was none.
So you should just add price property in your model.
function SeatReservation(name, initialMeal) {
    var self = this;
    self.name = name;
    self.meal = ko.observable(initialMeal);
    self.price = ko.observable();
}