text:
Q: PIR sensors + Arduino + Python + email alerts We are working on a project for school, and we have 2 PIR motion sensors running off an Arduino microcontroller. We are able to view the output of the serial port in both the Ardunio IDE and Python IDLE.
What we want to do next is, after about 30 seconds of motion being detected, sending out an email alert, seeing that we don't have Ethernet capability at this point, we figured the easiest way would be to grab the emailing through Python.
How to achieve this?
Update:
At this point we can send an email from Python, we can read the Arduino serial port in Python, but we just have an issue putting it all together.
This is what our Python code looks like, at the while 1: is where confusion happens:
import smtplib,serial

ser = serial.Serial(port=2, baudrate=9200)

from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os

gmail_user = "usr@gmail.com"
gmail_pwd = "pw"

def mail(to, subject, text, attach):
   msg = MIMEMultipart()

   msg['From'] = gmail_user
   msg['To'] = to
   msg['Subject'] = subject

   msg.attach(MIMEText(text))

   part = MIMEBase('application', 'octet-stream')
   part.set_payload(open(attach, 'rb').read())
   Encoders.encode_base64(part)
   part.add_header('Content-Disposition',
           'attachment; filename="%s"' % os.path.basename(attach))
   msg.attach(part)

   mailServer = smtplib.SMTP("smtp.gmail.com", 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(gmail_user, gmail_pwd)
   mailServer.sendmail(gmail_user, to, msg.as_string())
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()

while 1: **// CONFUSION HAPPENS HERE //** <----------------------

   ser.readline()

   if ser.readline() = "motion"

   do this mail sequence?

   mail("usr2@gmail.com",
   "Alarm Alert!",
   "Both Motion Sensor A & B have been active for over # seconds",
   "stor_fight.jpg")

Any tips would be much appreciated.

A: I'm not sure exactly which part of this process you're having trouble with, but here's a sketch of a solution:
You can use the pyserial library to communicate with the Arduino from python when the Arduino is plugged into the computer via USB.
On the python side, your code would look like this:
serial = serial.Serial("/dev/tty.usbserial-A6007btF", 38400) # the serial name you can see in the Arduino GUI - you might just need to say "COM1" on Windows
result = serial.readline(); # blocks until you get something from the Arduino
if result == "motion":
    # send email here

On the Arduino side, you'd just do something like this:
void loop()
{
    if(30 seconds have passed with motion)
        Serial.println("motion");
}

Make sense?

A: ser.readline()

   if ser.readline() = "motion"

This code reads a line from the serial port twice and discards the first one.
You also need a double-equals for comparison, and the line will (I assume...) have carriage-return characters on the end of it.
You might want to try something like
if ser.readline().starts_with("motion")

A: From what I can tell the board has a standard RS-232 port. You can make a listener Python script that accepts a signal from the board when the event occurs then fire off a method that sends the email. If you want a nicely designed piece look into Twisted, which has packages for serial port comm and mail. Otherwise check:
http://docs.python.org/library/email
http://www.varesano.net/blog/fabio/serial+rs232+connections+python

A: You need to use the serial library in your Arduino sketch. See section Communication/Serial on this page:
http://arduino.cc/en/Reference/HomePage
There are examples for the serial library in folder 4.Communication of the Arduino environment.
On your host machine, use the pySerial module, as suggested by jder.
You might also find this page in the Arduino Playground to be a useful starting point:
http://www.arduino.cc/playground/Interfacing/Python

A: From the question, I think you already know how to read from the serial port.
So I'd suggest something like this
import time,smtplib

beginTime = time.time() + 86400 # stay one day ahead for now
while True:
  if serial port has values : # ie. motion detected
    beginTime = time.time()
  if time.time() - beginTime > 30 :
    mailObj = smtplib.SMTP('smtp_server_here', smtp_server_port)
    mailObj.sendmail('from', 'to..', 'message')
    beginTime = time.time() + 86400 # reset time

I hope that helps


text:
Q: Why are affine functions called "affine" functions? I am learning about affine functions and I do not understand why a certain type of function (functions that are in the form of $f(x)=ax+b$) are called affine functions. I read about the word "affine" and I know that it means related, but I do not understand how is it related to this type of function and what was the reason behind this naming. I believe that understanding the reason behind namings can help one better understand a concept.

A: According to Jeff Miller, the adjective affinis (in Latin: "bordering", "adjacent", "linked by marriage") was introduced in geometry by Euler, in analogy to similis, to denote a weaker equivalence relation  than the latter: "Because curves originated this way do keep a certain Affinity between them, we will name these curves  affine".

AFFINE. Affinis and affinitas were first used by Leonhard Euler in
  Introductio in analysin infinitorum (1748) Chapter XVIII: De
  similitudine et affinitate linearum curvarum. He also wrote (II.
  xviii. 239): "Quia Curvae hoc modo ortae inter se quandam Affinitatem
  tenent, has Curvas affines vocabimus."

redpajama_set_name: RedPajamaStackExchange


text:
Q: Methods as objects - How / when
Possible Duplicate:
PHP method chaining?

In a lot of APIs I've worked with, I've seen this sort of thing:
$object->method()->anotherMethod();

From the tutorials on OOP that I've read, this is how classes are written,
<?php
class myClass {
    public method() {
       // do something
    }
}
?>

When should this be used, and how can it be done? Apologies, but I am new to OOP.

A: If your method returns $this, you will be able to use the above style ($object->method()->anotherMethod()). This can be done only in cases where your method is not expected to return something else, e.g. a method named like getSomething() is expected to return Something, but if you have a method that has no relevant value to return, you can just return $this, allowing method call chains.

A: This is called Method Call Chaining.  There are no hard and fast rules about when you should use it, but the general rule I use is that method chaining makes sense when there are a series of object methods that are frequently called one after the other, such as initialization functions.


text:
Q: How to pass List in ImageCarousel? I am working with ImageCarousel library. I have image URLs in a list that I am getting from my server and now I want to show these images in an ImageCarousel. I've tried many methods but I am unable to pass the whole list. I am stuck with this piece of code, please help me.
Here is my code:
List<NetworkImage> networkimages;

for(int i=0 ; i< modelList[0].listThumbnails.length; i++ ) {
    networkimages.add(new
        NetworkImage(modelList[0].listThumbnails[i]));
}

new ImageCarousel(
    <ImageProvider>[
        new NetworkImage(CommonMethods.image_url + modelList[0].listThumbnails[0]),
        new NetworkImage(CommonMethods.image_url + modelList[0].listThumbnails[1],),
    ],
    interval: new Duration(seconds: 5),
    showCloseButtonOnZoom: true,
),

A: You can just pass the networkImages List to the ImageCarousel. Something like this:
List<ImageProvider> networkimages = <ImageProvider>[];

for(int i=0 ; i< modelList[0].listThumbnails.length; i++ ) {
    networkimages.add(new
        NetworkImage(modelList[0].listThumbnails[i]));
}

new ImageCarousel(
    networkimages,
    interval: new Duration(seconds: 5),
    showCloseButtonOnZoom: true,
),


text:
Q: Writing performant queries with EF usually bleeds business logic into data layer With my experience with Entity Framework I find that the more and more a queries needs to be optimized the more business logic bleeds into the data layer or even lower into the database via a stored procedure. This makes unit testing more difficult and I was just wondering how people deal with this?
E.g.
I may have a function in my business layer/repository that has a bunch of business rules and logic that I have unit tests for. However I find that I can combined this into a stored procedure and return multiple result sets etc. but now my unit tests are useless.
Here is an example of placing a buy order in a stock market scenario. There are many hits to the database that bring back data, and then need to go back to the database to check to see if certain criteria is met.
I could put this into a stored procedure, but then all that logic is then pushed into the database and is harder to unit test.
public IEnumerable<ValidationResult> PlaceBuyOrder(int sellOrderId, int requestedShares, int buyerUserId)
{
    if (sellOrderId <= 0) throw new ArgumentNullException("sellOrderId");
    if (requestedShares <= 0) throw new ArgumentNullException("requestedShares");
    if (buyerUserId <= 0) throw new ArgumentNullException("buyerUserId");

    // Get the sell order to check to see if the sell order still exists.
    var sellerOrderActivity = GetLatestUnprocessedOrderActivityForOrder(sellOrderId);
    if (sellerOrderActivity == null)
        yield return new ValidationResult(GlobalResources.OrderDoestExist);
    else
    {
        // Make sure when the order type is "sell all" that the
        if (sellerOrderActivity.Order.Type == OrderTypes.SellAll && requestedShares < sellerOrderActivity.QtyRemaining)
            yield return new ValidationResult("requestedShares", GlobalResources.RequestedSharesCannotBeLessthanWhatIsBeingSold);
        else
        {
            if (requestedShares > sellerOrderActivity.QtyRemaining)
                requestedShares = sellerOrderActivity.QtyRemaining;

            var requestedSharesAmount = requestedShares * sellerOrderActivity.Price;
            if (!_financeService.CanUserAffordSharesPurchase(buyerUserId, requestedSharesAmount))
                yield return new ValidationResult(GlobalResources.InsufficentFundsToPurchaseRequestedShares);
            else if (!_financeService.CanUserAffordSharesPurchase(sellerOrderActivity.Order.UserId, 0))
                yield return new ValidationResult(GlobalResources.SellerHasInsufficentFundsAfterCommission);
            else
            {
                using (var transactionScope = new TransactionScope(TransactionScopeOption.Required,
                    new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted, Timeout = TransactionManager.MaximumTimeout }))
                {
                    // Insert both the order and order activity.
                    var newBuyOrderActivity = new OrderActivity
                    {
                        Price = sellerOrderActivity.Price,
                        QtyRemaining = requestedShares,
                        Status = OrderActivityStatuses.Open,
                        Order = new Order
                        {
                            Type = OrderTypes.Buy,
                            UserId = buyerUserId,
                            VideoId = sellerOrderActivity.Order.VideoId
                        }
                    };

                    _orderRepository.AddOrderActivity(newBuyOrderActivity);
                    _orderRepository.SaveChanges();

                    var sellerProcessedOrderActivity = new ProcessedOrderActivity();
                    var buyerProcessedOrderActivity = new ProcessedOrderActivity();
                    ProcessBuyAndSellOrderActivities(newBuyOrderActivity.Id, sellerOrderActivity, requestedShares, sellerProcessedOrderActivity, buyerProcessedOrderActivity);

                    if (sellerOrderActivity.Order.Type == OrderTypes.Sell && requestedShares != sellerOrderActivity.QtyRemaining)
                    {
                        var newSellerPartialOrderActivity = new OrderActivity
                        {
                            OrderId = sellerOrderActivity.OrderId,
                            Price = sellerOrderActivity.Price,
                            QtyRemaining = sellerOrderActivity.QtyRemaining - requestedShares,
                            Status = OrderActivityStatuses.Partial
                        };

                        _orderRepository.AddOrderActivity(newSellerPartialOrderActivity);
                        _orderRepository.SaveChanges();
                    }

                    var sellerAccountId = _accountRepository.GetAccountIdForUser(sellerOrderActivity.Order.UserId);
                    var sellerAccountTransaction = new Data.Model.Transaction();
                    var buyerAccountTransaction = new Data.Model.Transaction();
                    _financeService.TransferFundsFromBuyerToSeller(buyerUserId, 0, sellerOrderActivity.Order.UserId, sellerAccountId, requestedSharesAmount,
                        sellerAccountTransaction, buyerAccountTransaction);

                    // Add the apporpriate transactions to the portfolio activity table and make
                    // sure the seller comes before the buyer to negate the portfolio first.
                    var sellerPortfolio = new UserPortfolioActivity
                    {
                        Price = sellerOrderActivity.Price,
                        ProcessedOrderActivityId = sellerProcessedOrderActivity.Id,
                        Qty = -requestedShares,
                        TransactionId = sellerAccountTransaction.Id,
                        UserId = sellerOrderActivity.Order.UserId,
                        VideoId = sellerOrderActivity.Order.VideoId
                    };

                    var buyerPortfolio = new UserPortfolioActivity
                    {
                        Price = sellerOrderActivity.Price,
                        ProcessedOrderActivityId = buyerProcessedOrderActivity.Id,
                        Qty = requestedShares,
                        TransactionId = buyerAccountTransaction.Id,
                        UserId = buyerUserId,
                        VideoId = sellerOrderActivity.Order.VideoId
                    };

                    _userRepository.AddUserPortfolio(sellerPortfolio);
                    _userRepository.AddUserPortfolio(buyerPortfolio);
                    _userRepository.SaveChanges();

                    transactionScope.Complete();
                }
            }
        }
    }
}


text:
Q: Checking if email is valid using Pregmatch error? Hello I want to check if email is valid like blabla@blabla.com and not like just plain text 'BLbalbalba'.
I have this function:
function VerifyEmail($address)
{
   $Syntax='#^[w.-]+@[w.-]+.[a-zA-Z]{2,5}$#';
   if(preg_match($Syntaxe,$adrdess))
      return true;
   else
     return false;
}

And checking it like this:
    $email = htmlentities($_POST['email']);
if (!empty($email) && !empty($password) && !empty($message) && VerifyEmail($email) === true) {

Getting these errors:
Notice: Undefined variable: Syntaxe in C:\xampp\htdocs\recover\inc\functions.inc.php on line 20

Notice: Undefined variable: adrdess in C:\xampp\htdocs\recover\inc\functions.inc.php on line 20

Warning: preg_match() [function.preg-match]: Empty regular expression in C:\xampp\htdocs\recover\inc\functions.inc.php on line 20

Notice: Undefined variable: Syntaxe in C:\xampp\htdocs\recover\inc\functions.inc.php on line 20

Notice: Undefined variable: adrdess in C:\xampp\htdocs\recover\inc\functions.inc.php on line 20

Warning: preg_match() [function.preg-match]: Empty regular expression in C:\xampp\htdocs\recover\inc\functions.inc.php on line 20

Why is this happening? What did I do wrong? Is it a stable way of checking if email is valid?
Thanks!

A: No, it's not "stable", it's not "valid", and it will not do a good job. use
filter_var($email, FILTER_VALIDATE_EMAIL)

instead. relevant docs: http://www.php.net/manual/en/function.filter-var.php

A: some spelling mistakes here
should be
function VerifyEmail($address)
{
   $Syntax='#^[w.-]+@[w.-]+.[a-zA-Z]{2,5}$#';
   if(preg_match($Syntax,$address))


text:
Q: Using JPA on startup singleton I want to access database using JPA 2.1 eclipselink on startup. When it runs, I get login successful in the console log but it throws table or view does not exist. However, if I call my dao in servlet through rest service, everything runs fine. Am I missing something?
public abstract class BaseDao {
   @PersistenceContext(unitName = "myUnit")
   protected EntityManager em;
   public void create(Object entity);
   public Ojbect get();
}

@Stateless
public class MyDaoService extends BaseDao {
   @Override
   public void create(Object entity) {
      this.em.persit(entity);
   }
   // ...
}

@Singleton
@Startup
public class MySingleton{
   @EJB
   private MyDaoService service;
   @Schedule(hours="*", minutes="*", seconds="*/30")
   public void doSomething() {
      MyEntity entity = new MyEntity();//assumed I have entity object
      entity.setFirstName("firstName");
      entity.setLastName("lastName");
      service.create(entity); // >>>Table or view does not exist exception
   }
}

A: The doSomething would need a @PostConstruct if you want it to be called after your bean is initialized. Also if you have dependencies you need to be available before that bean is initialized then you can use @DependsOn

A: This solved my problem.

If a JEE and JTA managed entity manager is used, specifying a proxy user and password can be more difficult, as the entity manager and JDBC connection is not under the applications control. The persistence unit properties can still be specified on an EntityManager object as long as this is done before establishing a database connection. EclipseLink Solutions Guide for EclipseLink

EDIT: Make sure you set it before each transaction


text:
Q: How could i reduce compilation time without using less templates? I am part of a small project that is doing some research code in C++.
Our work involves a lot of mathematics and due to its nature we often need to temporarily use other people's code/libraries. To speed our own iteration times we designed a template based interface that allows to treat almost any vector type, e.g. Eigen::Vector3f, glm::vec4...  As if they were the same, this is fantastic for prototyping and making demos (which is what our needs are), since you don;t need to explicitly write down conversion code between one math implementation to another.
We are however running into the problem of really long compile times. It takes about 2 minutes at the moment to compile a file with a few hundred lines of code, and we are starting to loose some of the advantages of the template strategy (fast iteration).
Are there tricks we could use to speed up compilation without outright re-implementing everything without templates? (which is likely to bloat the codebase significantly). We already tried template instanciation, but since our types are often dissimilar and not known beforehand it's not helping much.


text:
Q: ordering results based on combine weightage of fields I have a very interesting question for all you SQL masters out there.
As you all know that one of the prime requirement of any e-commerce based shopping cart is a good search.
Few days back, I got to know about MySQL full-text search, and I must say it's quiet interesting.
I want to go one step ahead in search query, and need to provide weightage to fields. These weightage would allow sorting of search result.
For example: I have following fields in product table
productid
name
description
price

'name' and 'description' fields are full-text indexed.
For any search keyword, query should look into both fields: name, description. But name field should have more weightage compared to description field.
Incase, if you haven't understand my question well, then following example should help.
 productid             name                   description                price
 1                  nice keyboard      this is a nice nice keyboard     10
 2                  nice nice keyboard this is a nice nice keyboard     10
 3                  keyboard           this is a nice keyboard     10

when search keyword is 'nice', and 'name' field have weightage: 10, and 'description' field have weightage: 1
for productid: 1, nice was found 1 (once) in name, 2 (twice) in description. so combine weightage is (1*10 + 2*1 = 10 + 2 = 12)
for productid: 2, nice was found 2 (twice) in name, 2 (twice) in description. so combine weightage is (2*10 + 2*1 = 20 + 2 = 22)
for productid: 3, nice was found 0 (none) in name, 1 (once) in description. so combine weightage is (0*10 + 1*1 = 0 + 1 = 1)
2 questions
(1) How can I provide weightage to a particular field? Do I need to create full-text index again to provide weightage?
(2) I need query, which can output results in desc. order of combine weightage.

A: The full text search can give you the relative relevance of the search:
SELECT * FROM
(
    SELECT id,
    (MATCH(name) AGAINST ('nice')*10 ) + MATCH(description) AGAINST('nice') AS relevance
    FROM products
    WHERE MATCH(name) AGAINST ('nice') OR
    MATCH(description) AGAINST ('nice')
) ORDER BY revelence DESC

By multiplying the name relevance by 10 I have skewed the relevance score towards that of names


text:
Q: Is there any way to ignore local commit history when merging and pushing to remote? We want to have per-developer branches on git. In other words, developers would branch off of the "development" branch and create a local "feature" branch of their own to work on.
When they feel satisfied with their work, they can swap over to devel, make sure they have the latest files, and then merge in their "feature" branch and push the result to origin after dealing with any conflicts.
However, there is a problem - this makes the commit history very messy.
If you do git log --graph, the "feature" branches don't show up, which is what we want. However, every single commit that developer made now shows up on the devel branch. That's ugly. If there's 10 developers and each one made 30 commits to their feature branch before they all got merged into devel, devel now shows a history of 180 commits for a total of 6 features. It would be nicer if the history just showed messages for the 6 merges into devel.
Is there some way to avoid making the history "messy" and ignore the history of a local branch when merging? Or is this just fighting git too much?
I realize this might sound odd, but they very much dislike the idea of all those objects ending up on the remote repo.

A: As  your team has observed, if you make a habit of merging first-draft work with all its initial errors and crappy organization and almost-good-enough experiments and the fixes, your history will be an unholy terror of a swamp.
Don't Do That.
Do the first-draft work in your local repo¹.  Then completely rewrite that first-draft history for publication, git rebase -i is the usual command recommended for this, but I've found a git reset --soft followed by git add --patchs is more convenient to create a reviewable history, one that's fit for public consumption. Then completely rework it as the feedback makes any infelicities apparent, and publish/merge the clean result.
The first-draft commit series that's local to the developer repo is of no more use to others than a readout of their editor undo-buffer history.  In fact, that's what a first-draft Git history essentially is: a project-wide editor undo buffer, with notes to help with next week's inevitable "what was I thinking?" questions.  Nobody else ever needs to see those. They're the notes on your desk, work product, destined for the trash can at birth.

¹ it's fine to have a swamp repo where developers can push their WIP stuff for visibility and collaboration, the important thing is to not treat WIP histories as anything but discardable notes no matter who has a copy.  How you administer them is very, very different from how you administer anything that's been pushed into production

A:
If you do git log, the "feature" branches don't show up, which is what we want. However, every single commit that developer made now shows up on the devel branch.

git log, by default, shows you a linear version of history that is simple and false. Git history is not linear. Branches really branch.
Instead of this...
A - B - C - D - E - F - G - H [devel]

Your history really looks like this.
A ---------- E ----- H [devel]
 \          / \     /
  B - C - D    F - G

You can see this with git log --graph or a Git visualization tool like Gitup.
Each of those "feature bubbles" are the commits from each branch. Using the true history you can see what commits were developed as part of one feature. While this might seem "messy", this is important to understanding the code. Its especially useful along with git blame.

Is there some way to avoid making the history "messy" and ignore the history of a local branch when merging? Or is this just fighting git too much?

My advice is to get used to it, and to learn how to navigate it. For example, git log --merges will only show the merge commits. A good Git visualization tool will help a lot.
The other is to encourage developers to clean up their branches before committing. If you have a lot of commits that are "typo fix" and "oops" and "broke the tests" these are of little value going forward. They can use git commit --amend to change the previous commit, and git rebase -i "fixup" to merge existing commits together. This ensures all commits are of some consequence.
If you really want to, you can do a "squash merge", git merge --squash. Rather than retaining the complete commit history this smashes all the changes and all the commit messages in the branch into one commit.
While this produces a "clean" history, it loses a lot of granular information about how the code was developed. If there are, for example, 30 commits in the branch and you do a git blame to understand some code you'll get the commit messages for all 30 commits with no way to know which one applies to the code.
What you see as "messy" is valuable insights into why the code was written the way it is. This is gold for anyone working with the code down the line. Once smashed together it can never be recovered.

A:
Is there some way to avoid making the history "messy" and ignore the history of a local branch when merging? Or is this just fighting git too much?

Absolutely. Simply, don't merge anything. Have a public repo where you individually cherry-pick the commits. One way to do this is via a review system like Gerrit.
Cherry-picking will ensure you have clean, linear history without the merge mess.
However, it's important to get the individual changes: i.e. if 15 commits were required to develop a feature, then 15 commits should be recorded. It's important for various reasons. One is that multiple smaller commits make it easier to find and isolate bugs with git bisect. If a small commit which changes a single line is implicated as the cause of a regression, that is easier to figure out than if a commit with three hundred changes is implicated as that same regression.
What should be encouraged is that developers clean up their feature branches before merging. For instance, don't have commits which just fix trivial compiler errors ("Forgot a semicolon in parse_descriptor, oops!").  Or commits that "clean up" code that was only made messy in by that same feature development in the first place.
Commits "off topic" to the feature branch should also be discouraged.
A good rule to adopt is that every commit should build; no commit should break anything such that it requires a subsequent commit. Such commits should be squashed together.
Everyone should understand how to use git's interactive rebase to re-order, squash and correct commits.

A: It's not always possible to only commit working branches. Maybe you meant "merge to master" where I agree: only commit working code (passes all tests at least). One of the best ways to screw your other team members is putting broken code into something they will end up merging. You end up with a tangled mess, especially if the broken code doesn't immediately reveal its problem and more commits get piled on top of it, where you then need to use git-bisect to find which commit broke the build, and thus you need an unsquashed history to be able to find the exact commit that is causing the problem.
But there are all sorts of reasons to commit unfinished work in a separate branch.

*

*Saving your current workspace before you try something new that might not work out and you may need to easily restore your workspace.

*You need to stop using one computer and pick up work on another, like going home from work.

*You may have done some great unfinished work on a feature, that ends up not being used but the utility functions you wrote to support the new feature will probably be useful at a later date. By parking it in a branch, you get around the urge to keep "all that work you did" in the main product.

The problem with squashing is, every once in a while you encounter a really nasty bug and you need to do a git bisect (binary search of commits) to discover the exact commit that caused the bug. Git has become a code organizer, not a version control system due to all this mania about squashing and having clean commits. You can always do
git log --simplify-by_decoration

if you only want to see important or primary commits.
You can have the best of both worlds by creating a separate squashed branch before you merge to master, but leave the old unsquashed one intact. Or vice versa, create an unsquashed branch, and squash the original one before merging to master.
Then you have a way to see individual commits if you need to, but don't mess up your master branch.


text:
Q: Как из одного открытого cmd вписать что-то в другой открытый cmd? У меня один bat вызывает другой bat по кругу до истечения перебора файлов. В первый закинул таймаут на примерное время работы второго bat.
Можно ли как-то прописать, чтобы вместо таймаута первый батник дальше продолжал работать после завершения второго?
Обдумав, решил, что есть вариант в конце второго bat прописать продолжение работы первого, стоячего на таймауте. Поэтому задался вопросом: как из одного открытого cmd вписать что-то в другой открытый cmd?
Из моих предположений: через powershell вызвать net-класс, найти окно по хандлеру или тайтлу, вызвать метод отправки строки/клавиш, но не понимаю как это реализовать в коде.
Может есть альтернативный вариант решения задачи, был бы рад услышать.
for /R "vids" %%f in (*.mp4) do ( md temp & ffmpeg -i "%%f" "temp\%%~nf-.mp4" & start start.bat & timeout 30)

A: Добрый человек из комментариев подсказал.
start /wait start.bat


text:
Q: how to handle floating point with openmp parallel for properly After hours of debugging and small scale example in attempts to find what I was doing wrong, I finally got one of my theory confirmed.
floating point rounding-off error.
floating point calculations are non-associative in computers
what can be done to reduce the errors ?
code :
                        double energy = 0;
                        double contrast = 0;
                        double homogeneity = 0;
                        double entropy = 0;
                        double correlation = 0;
                        double shade = 0;
                        double prominence = 0;
                        double glcmMean = 0;
                        double sigma = 0;
                        double squaredVarianceIntensity = 0;
                        double A = 0;
                        double B = 0;

                        for(int c = 0; c <normalizedGlcm.cols; c++){
                            #pragma omp parallel for reduction(+:homogeneity,energy,contrast,entropy,glcmMean)
                            for(int r = 0; r<normalizedGlcm.rows; r++){

                                double pij = normalizedGlcm.at<double>(r,c,0);
                                double intensity = (double)img.at<uchar>(col,row,0);

                                if(pij != 0){
                                    homogeneity += pij/(1.0+((c-r)*(c-r)));
                                    energy += pij * pij;
                                    contrast += (c-r)*(c-r)*pij;
                                    entropy += -(log(pij)*pij); // pij will never be under 0
                                    glcmMean += pij * intensity;
                                }
                            }
                        }

after that bit there's more loops and some other calculations with the glcmMean variable. And so far I only get error with the glcmMean variable.
error examples :
serial     -      parrallel
1.66905e+28 vs 1.55964e+30
4.09033e+28 vs 3.62704e+30
8.38877e+30 vs 3.35551e+31

A: Based on the information in the comments, you can simply try the following code that accumulate the glcmMean so the accumulated value are more on the same order of magnitude than in the initial code. This assume normalizedGlcm.cols and normalizedGlcm.rows are relatively close (eg. not 2 and 2000 for example).
double energy = 0;
double contrast = 0;
double homogeneity = 0;
double entropy = 0;
double correlation = 0;
double shade = 0;
double prominence = 0;
double glcmMean = 0;
double sigma = 0;
double squaredVarianceIntensity = 0;
double A = 0;
double B = 0;

for(int c = 0; c <normalizedGlcm.cols; c++){
    double local_homogeneity = 0;
    double local_energy = 0;
    double local_contrast = 0;
    double local_entropy = 0;
    double local_glcmMean = 0;

    #pragma omp parallel for reduction(+:local_homogeneity,local_energy,local_contrast,local_entropy,local_glcmMean)
    for(int r = 0; r<normalizedGlcm.rows; r++){
        double pij = normalizedGlcm.at<double>(r,c,0);
        double intensity = (double)img.at<uchar>(col,row,0);

        if(pij != 0){
            local_homogeneity += pij/(1.0+((c-r)*(c-r)));
            local_energy += pij * pij;
            local_contrast += (c-r)*(c-r)*pij;
            local_entropy += -(log(pij)*pij); // pij will never be under 0
            local_glcmLocalMean += pij * intensity;
        }
    }

    homogeneity += local_homogeneity;
    energy += local_energy;
    contrast += local_contrast;
    entropy += local_entropy;
    glcmMean += local_glcmMean;
}

If the problem was due to the FP saturation / imprecision, then it should strongly improve the accuracy of the result, especially in sequential.


text:
Q: SignalR Message Bus OnConnected not called I am adding a MongoDB SignalR (version 2.2.1) backplane to an existing SignalR hub.  Without the backplane the OnConnected method on the Hub is called, once the backplane is registered the OnConnected method is not called.  With the debugger I can see the Subscribe and Send methods of my backplane's ScaleoutMessageBus being called when the client subscribes, but the OnConnected method is never called.
My OnConnected method:
public override Task OnConnected()
{
        var connectionManager = NestedContainer().GetInstance<IHubConnectionManager>();
        var userName = Context.User.Identity.Name;
        connectionManager.AddConnection<T>(userName, Context.ConnectionId);
        return base.OnConnected();
    }

My ScaleoutMessageBus:
public class MongoMessageBus : ScaleoutMessageBus
{
    private readonly MongoCollection<MongoMessage> _collection;
    private readonly ILog _log;
    private readonly Task _backgroundTask;

    public MongoMessageBus(IDependencyResolver resolver, MongoScaleoutConfiguration configuration)
        : base(resolver, configuration)
    {
        _log = GlobalValues.Container.GetInstance<ILog>();
        var database = GlobalValues.Container.GetInstance<IMongoDatabaseProvider>().GetSwimlaneDatabase();
        CreateCappedCollection(database, configuration);

        _collection = database.GetCollection<MongoMessage>(configuration.CollectionName);

        if (!_collection.IsCapped())
            throw new Exception($"Mongo collection {configuration.CollectionName} must be capped.");

        var cancellationToken = new CancellationToken();
        _backgroundTask = Task.Run(() => ProcessMessages(cancellationToken), cancellationToken);
    }

    protected override Task Send(int streamIndex, IList<Message> messages)
    {
        return Task.Run(() =>
        {
            var message = new MongoMessage(streamIndex, messages);
            _collection.Save(message);
        });
    }

    protected override Task Send(IList<Message> messages)
    {
        return Task.Run(() =>
        {
            var message = new MongoMessage(messages);
            _collection.Save(message);
        });
    }

    protected override void Dispose(bool disposing)
    {
        _backgroundTask.Dispose();

        base.Dispose(disposing);
    }

    private void ProcessMessages(CancellationToken cancellationToken)
    {
        try
        {
            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var messages = _collection.Find(Query<MongoMessage>.EQ(i => i.Processed, false))
                    .SetFlags(QueryFlags.TailableCursor | QueryFlags.NoCursorTimeout | QueryFlags.AwaitData);

                foreach (var message in messages)
                {
                    var id = (ulong) message.Id.CreationTime.Ticks;
                    var msg = ScaleoutMessage.FromBytes(message.Value);
                    OnReceived(message.StreamIndex, id, msg);

                    var query = Query<MongoMessage>.EQ(i => i.Id, message.Id);
                    var update = Update<MongoMessage>.Set(i => i.Processed, true);
                    _collection.Update(query, update);
                }
            }
        }
        catch (Exception ex)
        {
            _log.Write.Error(ex, $"An error occurred processing the Mongo message bus: {ex.Message}");
        }
    }

    private void CreateCappedCollection(MongoDatabase database, MongoScaleoutConfiguration configuration)
    {
        if (!database.CollectionExists(configuration.CollectionName))
        {
            var collectionOptions = CollectionOptions.SetCapped(true)
            .SetMaxSize(configuration.CollectionMaxSize)
            .SetMaxDocuments(configuration.MaxDocuments);
            database.CreateCollection(configuration.CollectionName, collectionOptions);
        }
    }
}

I am only testing on one server so I am expecting that I should see the OnConnected event called on that server.  Is there something I need to handle to make sure OnConnected is called with a backplane?


text:
Q: Serial Communication between two microprocessor (H8S2633R) in C language I am doing a school project that required communication between two microprocessor, I did not convert to RS232 for this communication as the two processor is place next to each other. The program should be able to send and receive the information.When the other party receive it, it will send back a letter back to the processor telling the processor that it has receive it. The program should be an interrupt driven and I am using the high-performance Embedded workshop to write the program. Please help me, struck at this for quite a while. Thanks :)

A: Download the data sheet for that processor (can one really call a 1500-page document a "data sheet"?) and read chapter 16, "Serial Communication Interface". In particular, it looks like you'll be most interested in section 16.3.3, "Multiprocessor Communication Function."


text:
Q: java - cannot assign value in invokeAndWait to global string variable  I am developing an application using the java-simple-serial-connector API to read
and write to serial port. I am facing a problem when I try to read data bytes
and assign them to a global String variable (sReader). sReader does not get the whole string and its length is random each time. I am sure that I am receiving all of the bytes because when I append string sBuffer to Output (Output.append) the whole string is displayed always. Please take a look at my sample code below:
public class SerialPortTest extends javax.swing.JFrame {

    private String sReader = "";
    private JTextArea outputTextArea;
    private JLabel outputLabel;

    private class Reader implements SerialPortEventListener {

        private String sBuffer = "";

        @Override
        public void serialEvent(SerialPortEvent spe) {

            if (spe.isRXCHAR() || spe.isRXFLAG()) {

                if (spe.getEventValue() > 0) {

                    try {

                        //Read chars from buffer
                        byte[] bBuffer = serialPort.readBytes(spe.getEventValue());
                        sBuffer = new String(bBuffer);

                        SwingUtilities.invokeAndWait(
                                new Runnable() {

                                    @Override
                                    public void run() {

                                        sReader = sBuffer;//does not assign full string

                                        outputLabel.setText(sBuffer);//does not set full string

                                        outputTextArea.setText(sBuffer);//does not set full string

                                        outputTextArea.append(sBuffer);//This works! Why the above don't work?

                                    }
                                });

                    } catch (SerialPortException | InterruptedException | InvocationTargetException ex) {
                    }
                }
            }
        }
    }
}

A: I'm assuming that you want access to sReader from some other portion of the code.  In that case consider making sReader volatile and also assigning it before making the Runnable.  Also, if sBuffer is only used to make a String to use in the Runnable consider making it a final local variable.
private volatile String sReader = "";
...

final String sBuffer = new String(bBuffer);
sReader = sBuffer;

SwingUtilities.invokeAndWait(
...


text:
Q: How to fix 'Expected mock function to have been called, but it was not called' in Jest I want to test that a class method is called on 'mousedown' event. Please take a look on the code below.
This is my component:
import React, { Component } from 'react';
import styled from 'styled-components';

import MyChildClass from './MyChildClass';

export default class MyClass extends Component {

constructor(props) {
    super(props);

    // Init state
    this.state = {
      balls: []
    };

    this.onMouseUpHandler = this.onMouseUpHandler.bind(this, this.state.balls);
  }

onMouseDownHandler = (balls, e) => {
    ...
  };

render() {

    return (

    );
  }

And this is my test:
import React from 'react';
import { mount, shallow } from 'enzyme';

import MyClass from '../MyClass';

it('should call onMouseDownHandler on mouse down', () => {
    //...arrange
    const instance = component.instance();
    const wrapper = component.find('.wrapper').at(0);
    instance.setMousePosition = jest.fn();
    instance.onMouseDownHandler = jest.fn();
    instance.forceUpdate();
    component.update();
    //...act
    wrapper.simulate('mouseDown');
    //...assert
    expect(instance.onMouseDownHandler).toHaveBeenCalled();
  });

So, I eventually expect the test to pass, but still the runner returns fail, with message

Expected mock function to have been called, but it was not called.

I've gone through many examples on Google, and found out that this is proper pattern of testing events.

A: Use arrow function as the method of class is not easy to test. Because it will be used as property of class, not instance method of class. So I suggest you refactor the method.
After refactoring, you can use jest.spyOn(object, methodName) to spy on the onMouseDownHandler method.
For example,
index.tsx:
import React, { Component } from 'react';

const StyledEnvironment = ({ children, className }) =>
{children}
;

export default class MyClass extends Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      balls: []
    };
  }

  onMouseDownHandler(balls, e) {
    // TBD
  }
  onMouseUpHandler(balls, e) {
    // TBD
  }

  render() {
    return (

    );
  }
}

index.spec.tsx:
import React from 'react';
import { shallow } from 'enzyme';
import MyClass from './';

describe('MyClass', () => {
  test('should handle mousedown event', () => {
    const wrapper = shallow(<MyClass></MyClass>);
    const onMouseDownHandlerSpy = jest.spyOn(MyClass.prototype, 'onMouseDownHandler');
    wrapper.find('div').simulate('mouseDown');
    expect(onMouseDownHandlerSpy).toBeCalled();
  });
});

Unit test result with coverage report:
 PASS  src/stackoverflow/58652312/index.spec.tsx
  MyClass
    ✓ should handle mousedown event (12ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |    76.47 |      100 |     62.5 |    91.67 |                   |
 index.tsx |    76.47 |      100 |     62.5 |    91.67 |                25 |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.951s, estimated 9s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58652312


text:
Q: Prove that $\ k {n \choose k } = n {n - 1 \choose k -1}$ by counting the set $\{(i, S) ∈ [n] × P([n]) : i ∈ S, \#S = k\}$ in two ways. Need help constructing the proof for $\displaystyle k {n \choose k} = n {n - 1 \choose k -1}$ by counting the set $\{(i, S) ∈ [n] × P([n]) : i ∈ S, \#S = k\}$ in two ways.
I understand how to algebraically prove the equality, as well as combinatorially by providing examples of counting the LHS and RHS; however, I am confused as to how to count the equality using the set-builder notation.
Any help would be much appreciated, thank you!

A: Call the set in question $\mathscr{P}$; it is just the set of all pairs $\langle i,S\rangle$ such that $S$ is a $k$-element subset of $[n]$, and $i\in S$. We can count this set either by

*

*looking at each $i\in[n]$ and asking how many $k$-element subsets of $[n]$ contain that $i$,

or by

*

*looking at each $k$-element subset $S$ of $[n]$ and asking how many elements of $[n]$ are in that set $S$.

The second approach is easy: if $S$ is a $k$-element subset of $[n]$, there are obviously $k$ elements of $[n]$ that belong to $S$. There are $\binom{n}k$ $k$-element subsets of $[n]$, so $|\mathscr{P}|=k\binom{n}k$.
Can you finish the argument by explaining why the first approach yields the result $|\mathscr{P}|=n\binom{n-1}{k-1}$?


text:
Q: Creating Magento Site's Native Android Application I have the following questions which I have researched a lot on Google as well as in SO but found nothing::

*

*I have to create a Native Android Application of a Magento based Site, and I have to use the same database of Magento Site. Now, I have found that we can't Access the PHP files of the Magento project as the access is denied. So how to call a Magento Login Function from the Android Client?

*I have come to know that we have to call the function through using XML-Connect file in Magento. Please any one can give me a Example how to call that file and how?

*Last Parsing. Which parser would be more handy? (DOM, SAX, SIMPLE XML Serialization parser?)

*How to manage the Sessions with the Magento Store So that the user can add to cart items and could do Online Transaction.
Anyone who has worked on Magento Site's App Development provide some direction to move further. I am totally lost and getting nothing from the Online Research.
Any help would be highly Appreciated.
And Regards.

A: I've not worked with Magento site. But I've worked with similar websites to connect to the mobile applications.
Short Answer: XML-Connect is the best way to minimize your work. And its easy to use API than connecting to the database using php files. For mobile applications, it is always advisable to use a simple xml format, however, in your case, you have to stick to xml-connect's protocol.
For some more information, see this link http://inchoo.net/ecommerce/magento/develop-your-own-magento-mobile-application/


text:
Q: HAProxy random Empty Response I installed a HAPROXY for balance between two servers. Unfortunately the HAPROXY return random ERR_EMPTY_RESPONSE. I installed the stats also but the stats does not appear frequently because sometimes the stats is shown. I double check with some friends my configuration and I did not found problems.
defaults
    timeout connect 3000ms
    timeout server 10000ms
    timeout client 10000ms

global
    log 127.0.0.1 local0 notice
    maxconn 2000
    user haproxy
    group haproxy

frontend stats
    bind *:1936
    mode http
    stats enable
    stats hide-version
    stats realm Haproxy\ Statistics
    stats uri /
    stats auth user:password

frontend http_in
    bind *:80
    acl is_audio hdr_end(host) -i subdomain.myserver.com
    acl is_proxystats hdr_end(host) -i stats.myserver.com
    use_backend srv_audio if is_audio
    use_backend srv_stats if is_proxystats
#    acl url_blog path_beg /blog
#    use_backend blog_back if url_blog
    default_backend srv_audio

backend srv_audio
    balance roundrobin
    server audio1 10.10.10.1:80 check
    server audio2 10.10.10.2:80 check

backend srv_stats
    server Local 127.0.0.1:1936

My configuration:

*

*HA Proxy version 1.6.3 (package 1.6.3-1ubuntu0.1 amd64)

*Ubuntu 16.04.2 LTS

*Cloud Machine on AWS LightSail 512KB RAM

*System with all packages updated.

I already read the answer of similar question at HAProxy random HTTP 503 errors and the answer is not the same. As suggested there the command netstat -tulpn | grep 80 does not show two HAPROXY running:
tcp    0  0 0.0.0.0:80    0.0.0.0:*  LISTEN      -

But ps ax | grep haproxy returns:
22890 ?        Ss     0:00 /usr/sbin/haproxy-systemd-wrapper -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid
22891 ?        S      0:00 /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -Ds
22894 ?        Ss     0:31 /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -Ds

A: Well, I dig more into HAProxy and read a lot of tutorials and I believe I found the solution.
I did two changes:

*

*Changed hdr_end(host) to hdr_dom(host)

*Added mode httpto: frontend http_in, backend srv_audio and backend srv_stats
Now, HAPROXY is very stable without bizarre behavior


text:
Q: Java Game with JavaFX Canvas | Canvas stops updating I use Java to create a game with the JavaFX Canvas.
I pass the Canvas graphicsContext to my GameLoop, which launches an extra thread. From there, I pass my graphicsContext via an ObjectHandler to every object that is to be drawn on the canvas.
It works that way for a while, but then the canvas somehow stops and no object is redrawn. The game is still running in the background. At the logs I can see that all objects continue to run and be updated.

Does anyone have an idea why this may be or how I could solve it?
This is my part from my Window Class:
canvas = new Canvas(Config.getCANVAS_WIDTH(), Config.getCANVAS_HEIGHT());
canvas.setFocusTraversable(true);
gc = new GameContainer(canvas.getGraphicsContext2D(), canvas);
primaryStage.setTitle(gc.getTitle());
primaryStage.setResizable(false);

This is part from my Gameloop:
if (render) {
    gc.clearRect(0, 0, width, height);
    handler.render(gc);
    gc.setFill(Color.GRAY);
    if (Config.isDebug()) {
         debugText.printDebug(fps);
    }
    frames++;
}

The HandlerClass is only a list with an arrayList  and two loops (for ticks and render).
This is an example for an a typical render function
public void render(GraphicsContext gc) {
    gc.save();
    gc.translate(x, y);
    gc.rotate(rotation);
    gc.setFill(Color.RED);
    gc.fillRect(-4, -4, 8, 8);
    gc.restore();
}

A: The drawing on the canvas with the GraphicsContext must be in
Platform.runLater (() -> {});

See JavavFX is not thread safe


text:
Q: One script for app in Unity game engine (performance difference) Is there a difference in performance between the application (in Unity game engine) uses one script (one class) or more scripts (more classes)?
P. S. In case of using multiple scripts only one MonoBehaviour (remaining connected to it classes)

A: No, the performance does not depends on how many scripts you used but it depends on the content of your script.
For example, if you have many GameObject that will be instantiated and destroyed rapidly, you should use object pool pattern instead of instantiating and destroying because instantiating and destroying are performance heavy actions.
Another example is about the complexity. An algorithm that performs  compare to an algorithm that performs  can yield a different especially those being executed every frames.


text:
Q: Converter todas strings para minúsculas Existe uma maneira de configurar o modelBuider, para deixar minhas strings com caixa baixa? Por exemplo, quando eu quero que todas as meu dados do tipo string, seja no meu banco um varchar, eu faço a seguinte configuração:
 modelBuilder.Properties<string>()
                .Configure(p => p.HasColumnType("varchar"));

tem como fazer essas strings serem salvar todas minúsculas no meu banco?
e se não tem como fazer pelo modelbuider, qual seria a forma mais eficiente?

A: Fui dar uma pesquisada para ter certeza que não tinha nada já que esses frameworks por vezes gostam de fazer mágicas, embora este caso eu acho que seria muito sem sentido fazê-lo. Realmente não tem nada que possa configurar isto, ainda bem.
Como eu já disse em comentário não faz sentido ligar isso para todos os campos, ou até mesmo fazê-lo manualmente em todos. Eu já vi alguns softwares que o fazem e fica horrível, desvirtuando o que digitou o usuário que tem mais condições de determinar o que é certo. Em geral vai normalizar algo que não deveria para evitar algum possível abuso, se quer dificultar um abuso indique que algo possivelmente está abusando de caixa alta, mas deixe o usuário fazê-lo, se for o caso crie um log, mande um alerta pra alguma auditoria, mas não tome decisão pelo usuário quando não tem condições de fazer isto.
Se tiver algum raro caso que deseja isto normalmente é mais adequado tratar na entrada de dados, pela máscara ou validação. Em algum caso bem mais específico poderia fazer isso no modelo ou banco de dados.
Se for fazer no modelo então trate a propriedade para fazer assim, ou seja, crie uma lógica que toda vez que atribuir uma valor na propriedade a caixa seja normalizada, algo assim:
string descricao;
public string Descricao { get => descricao; set => descricao = value.ToLower(); }

Coloquei no GitHub para referência futura.
Possivelmente deve ter alguma outra lógica de validação e normalização.
Se não quer fazer isso pode personalizar o SaveChanges() do DbContext herdando em um contexto seu, mas duvido que seja melhor que a solução acima. Se o fizer você trata o objeto aí antes de salvar.
E sim, em qualquer caso você precisa fazer um por um, não tem mágica. Programar é dizer o que cada coisa faz. Claro, existe uma coisa que se aproxima de mágica, você pode usar reflexão, um recurso que pode tratar várias coisas de uma forma padronizada, mas aí ou você faz todos campos string agirem igual ou monta um sistema de anotações pra dizer que quer que faça isso naquele campo, o que provavelmente dará o mesmo trabalho de mandar fazer na propriedade como demonstrei acima, com chance de algo dar errado e ficar muito mais lento, que são os dois pontos negativos principais da reflexão, então não faça.
A outra possibilidade é mudar o dado manualmente, um por um, antes de salvar, assim não tem que criar seu próprio contexto nem colocar a lógica na propriedade, mas isso só faz sentido se for para realizar a normalização de caixa em algum ponto específico do código e não nos demais.


text:
Q: React application on Safari throws SyntaxError: Invalid regular expression: invalid group specifier name I've just updated some depencencies in a React project using npm install and the updated project works nicely on all browser except Safari.
On Safari it shows a blanks screen and an error in the console:
SyntaxError: Invalid regular expression: invalid group specifier name
file: 2.f80ba52b.chunk.js

I can exclude breaking changes from updated dependencies, otherwise it would have broken on other browsers too. Despite that, I cannot figure out what is causing it.

A: Even if similar questions exist, and the root cause has been already recognized as the missing Safari support for lookbehind regex, I would like to provide a general way to handle those situations where, as described in the main question, you can not just fix a line of code - for example when the issue is caused by an external library.
How to handle broken external depencencies
In my case, the bug had been introduced with draft-js-utils 1.4.1, so I solved it downgrading to the first know working version (1.4.0). In order to achieve this, I edited the package.json file changing the dependency line from
"draft-js-utils": "^1.4.0"

to
"draft-js-utils": "1.4.0"

TIP: Avoiding the caret range, you can stick it to a specific version.
How to find broken external depencencies
The only way to find out what dependencies have been affected by this bug is to look for the error message in Github/Gitlab search - currently almost 300 public repositories have a related issue opened.
The hardest thing about this bug is that it could be hidden inside transitive dependencies.
You might not even know you are using that package.
If you are not lucky enough to spot it using a Github/Gitlab search, you could try with a local search using your IDE or grep. You need to look for the lookbehind symbols ?<!:
grep -r "?<\!" node_modules

Being a last resort, this approach could be either very slow or produce a huge-and-hard-to-read output.

A sad note
It looks like Webkit developers are not going to add lookbehind regex support soon - the issue has been created in July 2017 without receiving attention from them. Moreover, even if the Safari's issue has been recognized and tracked, no polyfill exists to fix it at the build level (e.g. using Babel).

A: I just want to add that I spent a week downgrading Babel and other packages to pre-2018 packages, only to realise that my problem was in a helper function within my own code that was to filter for malicious html code.
@lifeisfoo mentions to grep for the string '?<!' above in node_modules, but i  recommend also grepping the entire project.
fyi, my regex that was breaking Safari was '?<=!'. Which is also an unsupported lookbehind
I tested my regex: (?<=![)(.*?)(?=]) in Safaris regex tester https://www.regextester.com/ and the output says 'Lookbehind is not supported in Javascript'
To end, I found Safaris console error message worthless and spread around the 10,000s of lines of the bundle.js, giving the impression that the issue was within the packages/dependancies, which it clearly was not.
I spent ages downgrading the packages only to find the same error message appear on a different line of the bundle.js code.


text:
Q: Python: Sending a variable to another script I'm new to python and kind of been chucked in the deep end at work.
If i had a script which has creates a list such as below:
test = 'string'

l = []

for i in test:
    l.append(i)

print l

How would i send that this to another python script?

A: I'm assuming you want to use the variable some_list defined in a script called first.py into a second script called second.py
So it would be:
$ cat first.py second.py
#first.py
def demo():
    some_list = []
    for i in 'string':
         some_list.append( i )
    return some_list

#second.py
from first import demo

some_list = demo()
print some_list

$python second.py
['s', 't', 'r', 'i', 'n', 'g']

The code in a file is declared as code module. To use it, you have to use:
from module import thing
So in this case the function demo was defined as a function in the module first
In the second file you import it and use it.
You can run arbitrary code in modules and declare variables but it is  better if they are placed in functions ( or classes ) as shown above.
I hope this is what you needed.

A: It is not clear whether you first script is itself running the second script, or if they are called one after the other by something external. In either case, a simple method to pass the list to the second process is via stdin, where the data itself is a pickle of the list.
For example:
script1.py:
import sys
import pickle
list = [item for item in test]
pickle.dump(list, sys.stdout)

script2.py:
import sys
import pickle
list = pickle.load(sys.stdin)
for item in list:
    print item

The run: script1.py | script2.py

A: It depends on whether you mean sending the results of the computation to another, separately running Python process, or simply sharing that result with another component of a multi-file project.
In the former case, you'll want to use some kind of inter-process communication - some examples are writing the result to a file and reading it from the other process, establishing a socket between the two processes, or using a semaphore.
In the latter case, use Python's concept of modules to share the result of this computation with another script in your project.

A: I'd suggest looking at the Shelve and Pickle modules.  They allow you to serialize data in a way that it can be stored between launches or shared between scripts.

A: $ cat one.py
from functools import lru_cache
@lru_cache(maxsize=2048)
class One(object):
     def __init__(self):
         self.a = None

     def set_a(self,val):
         self.a = val

     def get_a(self):
         return self.a

class One_nocache(object):
     def __init__(self):
         self.a = None

     def set_a(self,val):
         self.a = val

     def get_a(self):
         return self.a

$ cat two.py
import one
import three

# Cache
second=one.One()
second.set_a(4)
three.print_cache()

# No cache
second=one.One_nocache()
second.set_a(4)
three.print_nocache()

$ cat three.py
import one
def print_cache():
    three=one.One()
    print(three.get_a())

def print_nocache():
    three=one.One_nocache()
    print(three.get_a())

$ py two.py
4
None

4 - Is set in three.py by invoking the cached class instance in one.py
  None - When the same class instance is invoked when the class is not
  cached.


text:
Q: How to add an sql function to a laravel eloquent model I'm wanting to create a laravel model with a computed column. I've seen how to do this once the data is downloaded however the computation I wish to do is expensive but accessible as a function in my sql. Essentially I'd like to append one more column to the query builder but I'm unsure how to go about it.
The query needs to be something like:
select *, my_function(ID) as my_value from my_table;

and I need to get an instance of the model in return (not a raw recordset).
I'm also hoping to avoid multiple queries.
Thanks.

A: Your query can be something like this:
User::select([
   'users.*',
   \DB::raw('YEAR(created_at) as year')
])->get()

Replace YEAR function with whatever function you want. should append to the results that column as well.

A: Building on the answer from musicvicious I ended up going with:
class User extends Model
{
...

    public function newQuery()
    {
        return parent::newQuery()->select('users.*', \DB::raw('YEAR(created_at) as year'));
    }

}

Now I can just fetch the models as normal.
User::all();


text:
Q: Laravel5 Json get file contents I'm using Laravel-5 right now and I've just created a JSON file called test(test.json). My question is:

*

*Where should I put my JSON file?

*How can I use file_get_contents and point to that one file I wanted?

This is what I've tried which is obviously wrong:
$string = file_get_contents("../json/test.json");
$json_file = json_decode($string, true);

Thank you so much for helping!

A: You can store it in your storage folder in Laravel:
$path = storage_path() . "/json/${filename}.json"; // ie: /var/www/laravel/app/storage/json/filename.json

$json = json_decode(file_get_contents($path), true);


text:
Q: removing non alaphanumeric character from end and starting of all columns I have few tables having more than 20 columns and I have to

*

*Trim first

*Remove all non alphanumeric characters and non symbol ')'  in the end of each column

*Remove all non alphanumeric characters and non symbol '(' from the 1st position of each column

If it is from the whole string I can simply use replace method, but in my case only in the first position and from the last position. So now I am using substring, checking for special characters and replacing with empty space. I felt like this is some kind of manual cleaning, I am sure this is not a elegant one.
Any quick approach (query) that helps me to clean up the data?

A: Does the database have to be online for this? Faced with this problem, I would be thinking about dumping the data out to files to process with perl, awk or some other tool suited to text processing in this manner.
If that's not possible, another alternative is to construct the munging algorithm inside a FUNCTION that receives a VARCHAR, and returns the cleaned up string as a VARCHAR (NB untested code, explanatory only):
CREATE FUNCTION cleanup(instr VARCHAR(255)) RETURNS VARCHAR(255));
    DECLARE outstr VARCHAR(255);
    SET outstr = TRIM(instr);
    IF NOT (outstr REGEXP '^[[:alnum:][.left-parenthesis.]]');
        SET outstr = SUBSTRING(outstr,2);
    END IF;
    WHILE NOT (outstr REGEXP '[[:alnum:][.right-parenthesis.]]$' DO
        SET outstr = LEFT(outstr, LENGTH(outstr)-1);
    END WHILE;
    SELECT outstr;
END FUNCTION;

Then you can write a query that reads the system catalogs, ie information_schema.columns and generates the UPDATE statements required. Something along the lines of (untested):
SELECT CONCAT_WS(" ", "UPDATE", table_name,
                 "SET", column_name, " = cleanup(", column_name, ")")
  FROM information_schema.columns
  WHERE table_schema = "your-database" AND collation_name IS NOT NULL

Save the output of that, check it, and run it.
The collation_name filter should ensure we limit this to only text-type fields. Again, this is untested, but should give you the general idea. You could even use GROUP_CONCAT to build a version of this that creates a single SQL statement per table rather than per column, but that's getting a bit fancy.
Obviously you would take a backup of the database before running anything that was going to perform such wide-ranging updates...


text:
Q: How to return a filtered result of array inside a documents through a query in mongoose I'm looking for a query that can return only certain document inside an array of a main document. Below is the collection stored in DB:
{
            "_id": "5ed49b42d6fc0c3878c875a2",
            "stockID": "Stock-1",
            "openingBalance": 30000,
            "closingBalance": 29960,
            "userEmail": "kumarshreyas073@gmail.com",
            "stockName": "Coconut",
            "unitMeasure": "Kgs",
            "referenceName": "U16H",
            "gstApplicable": true,
            "rateOfDuty": 15,
            "price": 30,
            "total": 900000,
            "idCounter": 1,
            "transactions": [
                {
                    "particulars": "To demo",
                    "voucherNumber": "1234567",
                    "voucherType": "Sales",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed630530de9f419fc45d2ed",
                    "transactionID": "5ed630530de9f419fc45d2eb",
                    "date": "23/05/2020"
                },
                {
                    "particulars": "To demo",
                    "voucherNumber": "1234567",
                    "voucherType": "Sales",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed630c72218b03658bf8191",
                    "transactionID": "5ed630c62218b03658bf818f",
                    "date": "23/05/2020"
                },
                {
                    "particulars": "To demo",
                    "voucherNumber": "1234567",
                    "voucherType": "Sales",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed64ebd89ee57327cd46772",
                    "transactionID": "5ed64ebd89ee57327cd46770",
                    "date": "23/05/2020"
                },
                {
                    "particulars": "To demo",
                    "voucherNumber": "1234567",
                    "voucherType": "Sales",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed64f0cf5891925f0f0a8b1",
                    "transactionID": "5ed64f0cf5891925f0f0a8af",
                    "date": "23/05/2020"
                },
                {
                    "particulars": "To demo",
                    "voucherNumber": "1234567",
                    "voucherType": "Sales",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed64f42b56b7d1380df8b70",
                    "transactionID": "5ed64f42b56b7d1380df8b6e",
                    "date": "23/05/2020"
                },
                {
                    "particulars": "To demo",
                    "voucherNumber": "1234567",
                    "voucherType": "Sales",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed650674961b126a4092f3f",
                    "transactionID": "5ed650674961b126a4092f3d",
                    "date": "23/05/2020"
                },
                {
                    "particulars": "To demo",
                    "voucherNumber": "U123",
                    "voucherType": "Purchase Return",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed72df8f497fb0edc745c4b",
                    "transactionID": "CN-126656",
                    "date": "14/05/2020"
                },
                {
                    "particulars": "To demo",
                    "voucherNumber": "U123",
                    "voucherType": "",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed73bf9c922270020db492d",
                    "transactionID": "CN-126665",
                    "date": "14/05/2020"
                },
                {
                    "particulars": "To demo",
                    "voucherNumber": "U123",
                    "voucherType": "Purchase Return",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed753a85c61c71e3089f40f",
                    "transactionID": "CN-196700",
                    "date": "14/05/2020"
                },
                {
                    "particulars": "To demo",
                    "voucherNumber": "U123",
                    "voucherType": "Purchase Return",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed753ed5c61c71e3089f415",
                    "transactionID": "CN-196000",
                    "date": "14/05/2020"
                },
                {
                    "particulars": "By demo5",
                    "voucherNumber": "1230456",
                    "voucherType": "Purchase",
                    "inward": 50,
                    "outward": 0,
                    "_id": "5ee735e807a0112c9c079d9a",
                    "transactionID": "5ee735e807a0112c9c079d98",
                    "date": "15/06/2020"
                },
                {
                    "particulars": "To demo",
                    "voucherNumber": "12345670",
                    "voucherType": "gdbxdkvghj",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ee9a4b2b8d4c72440e7a6a1",
                    "transactionID": "5ee9a33a6c1f103fa82992fd",
                    "date": "23/06/2020"
                },
                {
                    "particulars": "To demo1",
                    "voucherNumber": "1234567000",
                    "voucherType": "gdbxdkvghj",
                    "inward": 0,
                    "outward": 20,
                    "_id": "5ee9e28ef327db4358b7465d",
                    "transactionID": "5ee9e15cf327db4358b74651",
                    "date": "17/06/2020"
                }
            ],
            "__v": 0
        }

The code Below returns above result:
var stockAccount = await Stock.aggregate([
    {
      $match: {
        userEmail: req.body.userEmail,
      },
    },
    {
      $match: {
        "transactions.date": {
          $gte: req.body.fromDate,
          $lte: req.body.toDate,
        },
      },
    },
  ]);

I need to filter the "transactions" array based on date. For example: From "09/05/2020" to "23/05/2020". Expected Output:
{
            "_id": "5ed49b42d6fc0c3878c875a2",
            "stockID": "Stock-1",
            "openingBalance": 30000,
            "closingBalance": 29960,
            "userEmail": "kumarshreyas073@gmail.com",
            "stockName": "Coconut",
            "unitMeasure": "Kgs",
            "referenceName": "U16H",
            "gstApplicable": true,
            "rateOfDuty": 15,
            "price": 30,
            "total": 900000,
            "idCounter": 1,
            "transactions": [
                {
                    "particulars": "To demo",
                    "voucherNumber": "1234567",
                    "voucherType": "Sales",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed630530de9f419fc45d2ed",
                    "transactionID": "5ed630530de9f419fc45d2eb",
                    "date": "23/05/2020"
                },
                {
                    "particulars": "To demo",
                    "voucherNumber": "1234567",
                    "voucherType": "Sales",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed630c72218b03658bf8191",
                    "transactionID": "5ed630c62218b03658bf818f",
                    "date": "23/05/2020"
                },
                {
                    "particulars": "To demo",
                    "voucherNumber": "1234567",
                    "voucherType": "Sales",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed64ebd89ee57327cd46772",
                    "transactionID": "5ed64ebd89ee57327cd46770",
                    "date": "23/05/2020"
                },
                {
                    "particulars": "To demo",
                    "voucherNumber": "1234567",
                    "voucherType": "Sales",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed64f0cf5891925f0f0a8b1",
                    "transactionID": "5ed64f0cf5891925f0f0a8af",
                    "date": "23/05/2020"
                },
                {
                    "particulars": "To demo",
                    "voucherNumber": "1234567",
                    "voucherType": "Sales",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed64f42b56b7d1380df8b70",
                    "transactionID": "5ed64f42b56b7d1380df8b6e",
                    "date": "23/05/2020"
                },
                {
                    "particulars": "To demo",
                    "voucherNumber": "1234567",
                    "voucherType": "Sales",
                    "inward": 0,
                    "outward": 10,
                    "_id": "5ed650674961b126a4092f3f",
                    "transactionID": "5ed650674961b126a4092f3d",
                    "date": "23/05/2020"
                }
            ],
            "__v": 0
        }

Is there an query to achieve this? Thank you.

A: I believe aggregation is not needed in your case.
var stockAccount = await Stock.find({
      userEmail: req.body.userEmail,
      "transactions.date": {
        $gte: req.body.fromDate,
        $lte: req.body.toDate,
      }
});

Note: It seems like the format of the date in the database is a string. So, date comparison should not work.


text:
Q: Copying set of points perpendicular along polyline I have a polyline which represents the middle of a river. Perpendicular to this polyline there is a layer with a set of points. These points all have an "X" and "Y" coordinates as well as a height relative to sea level and represent the profile of the river.
However, these points are only present at one point. I want to copy this set of points to multiple locations along my polyline so that I can interpolate these points and get a DEM to load into a simulation programme that needs river cross-sections as input.
How to copy the point layer perpendicular along the polyline given a set interval (e.g. a meter between each set of points is sufficient)?

The points are lying on the same line, but I think the visualisation of QGIS makes it look like they are not.

A: So i started with a line which represents a river and a set of points with a certain
"X","Y" and "Z" coördinate, which represents the profile of the river. Every points also contains information on the distance between the first point (most northern point in this case) and the point itself.

*

*First i measured the distance from the line to the first point with the measure line tool and created a parallel through the first point. This causes some discrepancy, because the measure line tool is not comepletly exact, but for my problem this does not really matter

*From the created parallel, I used offset lines to create a parallel through each point

*Then I manually added a "Z" coördinate to each line, used densify by interval to create more vertices and lines to points to create a raster of points.

*Lastly i used Natural neighbour to create a grid that represents my river, which is shown below.

This solution does currently work for me as my project area is not that large, but in the future the project area will become larger and this will take a lot of time. Therefore, I am still interested in a more convenient solution.


text:
Q: Scala pattern matching Java enum value I have my java enum such as: FOO("foo"), BAR("bar") ...
and I have a getValue() method to return the value "foo" and "bar" of the enum and this has to be in Java.
On the other hand, I have to match this in Scala:
result match {
  case "foo" =>

I am trying to do:
result match {
  case Enum.FOO.getValue() =>

I get this error:
method getValue is not a case class constructor, nor does it have an
unapply/unapplySeq method

I'm not quite sure what is happening here since my getValue() method returns a String so why I can't use it for pattern matching? Thanks

A: You can pattern match on Java enums, but you can't call methods in the destructuring part of the match.  So this works:
j match { case Jenum.FOO => "yay"; case _ => "boo" }

if j is an instance of your Java enum (cleverly labeled Jenum).
You can however do something like this:
"foo" match {
  case s if s == Jenum.FOO.getValue => "yay"
  case _                            => "boo"
}

Or you can convert your string to the enum first:
Jenum.values.find(_.getValue == "foo") match {
  case Some(Jenum.FOO) => "yay"
  case _               => "boo"
}

(you might also want to unwrap the option first to avoid repeating Some(...) so many times).
For reference, this is the test enum I used (Jenum.java):
public enum Jenum {
  FOO("foo"), BAR("bar");

  private final String value;
  Jenum(String value) { this.value = value; }

  public String getValue() { return value; }
}

A: You can't use a method call result as a pattern. Instead just write
if (result == YourEnum.FOO.getValue()) {
  ...
} else if {
  ...
}

or
try {
  val resultAsEnum = YourEnum.valueOf(result)

  resultAsEnum match {
    case YourEnum.FOO => ...
    ...
  }
} catch {
  case e: IllegalArgumentException => // didn't correspond to any value of YourEnum
}

A: You receive the comment "method". So scala does not evaluates your function. It tried to call unapply on method.
You can implement something like (in MyEnum class):
 public static MyEnum fromText(String text) {
        for (MyEnum el : values()) {
            if (el.getValue().equals(text)) {
                return el;
            }
        }
        return null;
    }

And then
MyEnum.fromText("foo") match{
 case FOO => ..
}

A: JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features. This library can nicely work with enums.
   matches(myEnum).as(
      MyEnum.FOO,  () ->  System.out.println("FOO value");
      MyEnum.BAR,  () ->  System.out.println("BAR VALUE");
      Else.class,  () ->  System.out.println("Default value: " + data)
   );


text:
Q: Failed to retrieve directory listing on Amazon workspace I have recently moved from remote desktop (pval) to amazon workspaces and while using filezilla on amazon workspace i am not able to retrieve directory listing from a specific client's ftp. not sure but i think it is either stemming from filezilla configuration difference or a performance drop causing filezilla to time out but i have also tried using 9999 or 0 to disable timeout and tried enabling ICMP as well.
port : 22,
SFTP connection,
number of files in root folder: 102918
any idea why is it not working on amazon workspace ?
PVAL

Amazon workspace

A: I think its is because of large number of files which is clogging the directory, try to archive the files


text:
Q: [iOS][Background] updating map pins | drawing lines Hy :)
I am trying to update in background the position of the device (iPhone) and it works with the simulator http://grab.by/meLq (the annotations are only added in Background).
But when I am testing with my iPhone it does not work, I have got a line between the last position (before being in background) and the position when the becomes active.
What about the coding ?
I made a test of making a list when the app is in background and when the application becomes active again I load the list of positions recorded. (work with the simulator)
    - (void)handleAddLocations {
        NSLog(@"%s | %@", __PRETTY_FUNCTION__, self.locationBackgroundList);

        if ([self.locationBackgroundList count] > 0) {
            for (CLLocation *backgroundLocation in self.locationBackgroundList) {

                if (YES){
                    LocAnnotation* annotation = [[LocAnnotation alloc] initWithCoordinate:backgroundLocation.coordinate];
                    NSLog(@"%s %@", __PRETTY_FUNCTION__, [annotation description]);
                    [self.mapView addAnnotation:annotation];
            }

        MKUserLocation *userLocation = [[MKUserLocation alloc] init];
        [userLocation setCoordinate:backgroundLocation.coordinate];

        [self mapView:self.mapView didUpdateUserLocation:userLocation];

         }
        [self.mapView updateConstraints];

        [self.locationBackgroundList removeAllObjects];
        self.locationBackgroundList = [[NSMutableArray alloc] init];
      }
  }

Thanks for helping ;)

A: Its a better option to add the annotation by creating a list in of locations in background.This is not possible to manage uielements when the app is in background.For this you should add all the positions in array while yous app is in background.


text:
Q: Pandas why index prohibits some operation on dataframe (like loc results in IndexingError:) There are similar issues asked about (like pandas: iterating over DataFrame index with loc) but I could not find mine. I just do not understand why in pandas many functionality stops working when index is added to dataframe. Like just now I have dataframe d1 and can do below to add new column:
df4 = df1
df4.loc[df1.crash_type_name == 'pedestrian','Pedestrian_type'] = 1

But the same fails for df2 - same one but index added with df2 = df1.set_index('date_time').
The error

IndexingError: (0        False 1        False ....

I know the workaround is to reset_index() and then to recreate it back, but what is the logic behind index prohibiting certain operations on dataframe?


text:
Q: JavaScript Broken in UIWebView's "Start Load" Callback I'm trying to execute some JS before the page's onLoad event fires.
But I'm having trouble successfully calling stringByEvaluatingJavaScriptFromString in the webViewDidStartLoad delegate method.
To reproduce the issue, you can use the following code.
Delegate implementation:
-(void)webViewDidStartLoad:(UIWebView *)webView {
    [webView stringByEvaluatingJavaScriptFromString:@"window.valueHasBeenSet=true"];
}

View this HTML:

Reload

This page works on the first view ("Everything is OK.") but fails on all reloads, regardless of the reload method. As you'd probably expect, this doesn't work in the shouldStartLoadWithRequest delegate, either.
I also tried executing the javascript immediately following webViewDidStartLoad with performSelector:withObject:afterDelay:0, to no avail.
Any ideas?

A: I managed to make it work using a NSTimer
- (void)viewDidLoad {
    timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(update) userInfo:nil repeats:YES];
}

-(void)update{
    if (Progress.progress <= 1.0) {
        [website stringByEvaluatingJavaScriptFromString:@"window.valueHasBeenSet=true"];
    }
}

A: You have to do something like this:
Delegate implementation:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"webViewDidFinishLoad");
    [webView stringByEvaluatingJavaScriptFromString:@"foo(true);"];
}

.html file:


text:
Q: Reformatting Strings from Scraped Data in order to Satisfy Keyword Argument I am working on a baseball analysis project where I web-scrape the real-time lineups for a given team, on a given date.
I am currently facing an issue with the names that I receive in the scraped dataframe -- in random cases, the player names will come in a different format and are unusable (I take the player name and pass it into a statistics function which will only work if I have the players name formatted correctly.)
Example:
     Freddie Freeman
     Ozzie Albies
     Ronald Acuna
     Austin RileyA. A.Riley
     Dansby Swanson
     Adam Duvall
     Joc PedersonJ. J.Pederson

As you can see, most of the names are formatted normally, however, In a few cases, the player name is displayed, along with the first letter of their first name added onto their last name, followed by a period, and then their First initial and last name.
If I could turn: Austin RileyA. A.Riley, into Austin Riley, then everything would work.
This is a consistent theme throughout all teams and data that I pull -- sometimes there a few players whos names are formatted in this exact way -- FirstName + LastName+First letter of First Name. + First initial. + Last Name
I am trying to figure out a way to re-format the names so that they are usable and doing so in a way that is generalized/applicable to any possible names.

A: If the theme is really consistent you could do something like this:
name_list = ['Freddie Freeman',
         'Ozzie Albies',
         'Ronald Acuna',
         'Austin RileyA. A.Riley ',
         'Dansby Swanson',
         'Adam Duvall',
         'Joc PedersonJ. J.Pederson']
new_list = []
for n in name_list:
    new_list.append(n[:n.find('.')-1])
new_list

There are several methods to achieve this (also using regex which I would not reccomend). The example I have posted is the best in my opinion ( find() documentation)


text:
Q: Ansible for Windows: Cannot access Windows machine via WinRM I have installed Ansible on my Linux (14.04) workstation, along with Python (2.7.6), ansible (2.3.0), pywinrm (0.2.1). I want to use Ansible to configure my Windows VMs. I have a Windows VM (Win2k12r2) in Azure. I have opened all ports in the Azure network security group, and I have opened ports in the Windows Firewall for WinRM (5985 and 5986).
I also ran the script located at https://github.com/ansible/ansible/blob/devel/examples/scripts/ConfigureRemotingForAnsible.ps1, in my Windows VM to ensure that WinRM is enabled.
I am able to RDP into the Windows VM, so I know that its public network interface is working.
As per the ansible docs (http://docs.ansible.com/ansible/intro_windows.html) I have an inventory file inventories/test1
[windows]
<azure_ip_address>

And I have a file group_vars/windows.yml
ansible_user: <my_user_id>
ansible_password: <azure_vm_password>
ansible_port: 5986
ansible_connection: winrm
# The following is necessary for Python 2.7.9+ when using default WinRM self-signed certificates:
ansible_winrm_server_cert_validation: ignore
ansible_winrm_scheme: https

When I run the command:
ansible windows -i inventories/test1 -m win_ping --ask-vault-pass -vvvvv

I get the following response:
No config file found; using defaults
Vault password:
Loading callback plugin minimal of type stdout, v2.0 from /home/jgodse/ansible/lib/ansible/plugins/callback/__init__.pyc
Using module file /home/jgodse/ansible/lib/ansible/modules/core/windows/win_ping.ps1
<azure_vm_ip_address> ESTABLISH SSH CONNECTION FOR USER: None
<azure_vm_ip_address> SSH: ansible.cfg set ssh_args: (-C)(-o)(ControlMaster=auto)(-o)(ControlPersist=60s)
<azure_vm_ip_address> SSH: ansible_password/ansible_ssh_pass not set: (-o) (KbdInteractiveAuthentication=no)(-o)(PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey)(-o)(PasswordAuthentication=no)
<azure_vm_ip_address> SSH: ANSIBLE_TIMEOUT/timeout set: (-o)(ConnectTimeout=10)
<azure_vm_ip_address> SSH: PlayContext set ssh_common_args: ()
<azure_vm_ip_address> SSH: PlayContext set ssh_extra_args: ()
<azure_vm_ip_address> SSH: found only ControlPersist; added ControlPath: (-o)(ControlPath=/home/jgodse/.ansible/cp/ansible-ssh-%h-%p-%r)
<azure_vm_ip_address> SSH: EXEC ssh -vvv -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/home/jgodse/.ansible/cp/ansible-ssh-%h-%p-%r <azure_vm_ip_address> '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo $HOME/.ansible/tmp/ansible-tmp-1477490434.84-228998637685624 `" && echo ansible-tmp-1477490434.84-228998637685624="` echo $HOME/.ansible/tmp/ansible-tmp-1477490434.84-228998637685624 `" ) && sleep 0'"'"''
<azure_vm_ip_address> | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: OpenSSH_6.6.1, OpenSSL 1.0.1f 6 Jan 2014\r\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: /etc/ssh/ssh_config line 19: Applying options for *\r\ndebug1: auto-mux: Trying existing master\r\ndebug1: Control socket \"/home/jgodse/.ansible/cp/ansible-ssh-<azure_vm_ip_address>-22-jgodse\" does not exist\r\ndebug2: ssh_connect: needpriv 0\r\ndebug1: Connecting to <azure_vm_ip_address> [<azure_vm_ip_address>] port 22.\r\ndebug2: fd 3 setting O_NONBLOCK\r\ndebug1: connect to address <azure_vm_ip_address> port 22: Connection timed out\r\nssh: connect to host <azure_vm_ip_address> port 22: Connection timed out\r\n",
    "unreachable": true
}

I tried telnetting to the machine as follows:
$ telnet <azure_vm_ip_address> 5986
Trying <azure_vm_ip_address>...
Connected to <azure_vm_ip_address>.
Escape character is '^]'.

This tells me that telnet worked to 5986, and therefore my firewall rules were OK.
Do I have to do something to tell Ansible that I'm trying to connect to a Windows VM using WinRM?  Or am I missing something to help my Ansible workstation connect to my Windows VM via WinRM?

A: It turns out that putting the connection variables in group_vars/windows.yml didn't work. I got rid of that file completely, and edited inventories/test1 to look like this:
[windows]
<azure_ip_address>

[windows:vars]
ansible_user=<my_user_id>
ansible_password=<azure_vm_password>
ansible_port=5986
ansible_connection=winrm
ansible_winrm_server_cert_validation=ignore

Running the command worked, and running win_ping worked successfully.
I then tried encrypting inventories/test1, and I got:
  [WARNING]: No hosts matched, nothing to do

And win_ping didn't run.
My guess at this point is that variables needed for connection initialization have to be in an inventory file, and are read before encrypted variables are decrypted and used.


text:
Q: Most specific subclass for a Java object? I have two classes A and B, where B is subclass of A and A is not abstract. Therefore I can have objects that are instance of A and objects that are instance of B (and therefore of A).
How can I distinguish objects that are only instance of A?
Sure, I can write something like "object instaceof A && !(object instance of B)" but this is a very poor design since I'll need to change the code every time I add new subclasses to A. Better alternatives?

A: object.getClass() == A.class

A: Why you want them to distinguish? Usually this is the opposite of OO. You have different instances that you don't need to distinguish because the different implementation does everything right.
If you need to do so than there should be a protocol for it. Have a method for that purpose that returns something to recognize. That is more flexible,too.
I would instanceOf and getClass already consider bad style if this is used without good reason

A: Doesn't this show that B isn't really an A?
I'm not entirely sure you should get into this situation? Perhaps you could improve your design??

A: A better approach is to make the test the result of a method
class A {
   public boolean isSomeTest() {
      return true;
   }
}
class B extends A {
   public boolean isSomeTest() {
      return false;
   }
}

Then if you add a C which extends A you can allow it to return true or false.
The name of isSomeTest should make it clear what returning true or false should mean.

A: This is what I think you're saying:
public class A {
}

public class B extends A {
}

later in code:
A apple = new A();
B banana = new B();

Here are some options that you may find useful:
if (apple.getClass() == A.class) { // Found an A }
if (banana.getClass() == A.class) { // This is not an A, won't get here. }
if (apple instanceof A) { // This is definitely an A }
if ((apple instanceof A) && (!(apple instanceof B))) { // It's an A but not a B }

Regarding the last option, you write the following:

Sure, I can write something like
  "object instaceof A && !(object
  instance of B)" but this is a very
  poor design since I'll need to change
  the code every time I add new
  subclasses to A. Better alternatives?

Polymorphism almost always helps us here.  Your point about changing code every time you add a subclass is exactly the kind of symptom that you should recognize as standard object-oriented design evolution.  Think about the behavior that you are trying to produce.  Can you push that into the class itself rather than delegating it to an outside provider looking in that has to deduce what class it's currently working on?
Without more information, I can't give too much guidance but here's a fairly straightforward example:
// Instead of this
if (apple.isClassA()) { // run class A code
} else if (apple.isClassB()) { // run class B code
// And so forth
}

Modify the design to become more like this:
public class A {
    public void executeCommand() {
        // run class A code
        // This method knows that it's definitely an A, not a B
    }
}

public class B extends A {
    public void executeCommand() {
        // run class B code
        // This method knows that it's a B (and, therefore, an A as well).
    }
}

Where later in the execution code, you replace your previous if test with:
apple.executeCommand();
banana.executeCommand();

Admittedly, this is a nearly trivial object-oriented design review but it may shake something loose and help you with your subclassing problem.


text:
Q: Standard deck of cards. Draw until you have one from each suit, find Pr(took n draws) From 52 cards (without 2 jokers), we keep taking cards randomly one by one with replacement, until all the cards taken by us can cover all 4 suits. Compute the probability that we have picked exactly n cards.
I began with simple cases n=4,5 etc but realized quickly that this will probably be an inclusion/exclusion problem which I am horrible at. Could anyone show their process/solution for this one

A: Using Stirling Numbers of the Second Kind, where ${n\brace k}$ represents the number of ways of partitioning a set of $n$ elements into $k$ unlabeled non-empty parts:
The first $n-1$ cards will represent exactly three suits.  Choose how to split the cards up among three parts and choose what suit each of those parts represents.  Finally, the $n$'th card itself must be the fourth suit.
$\Pr(X=n)=\dfrac{{{n-1}\brace 3}\cdot 4!}{4^n}$

A: I missed the with replacement part.
Each suit has a probability of $\frac14$ of being drawn each time.
We want the last suit to be seen first on the $nth$ draw,
Any three suits with at least one draw from each suit and total draws $(n-1)$ with the $nth$ draw being the missing suit are needed.
This leads to the formula
$$Pr =\binom43*\frac{(n-1)!}{i!j!k!}(1/4)^n$$
$ with\;1\leq i,j,k, \;\;and\;\; (i+j+k)= (n-1)$