text:
Q: What makes Shen so hard to hit, and how can I counter it? It's really hard to hit him sometimes, even when I'm beefed up with AD and Attack Speed.  Why is this, and how can I counter it?

A: The main reason shen takes so little damage in trades is because his W skill, Feint, is a shield. Essentially this adds to his hp every time it comes off cooldown. In order to help damage him, you can make sure to hit him as soon as his shield disappears and is on cooldown. It's a bit tricky, but manageable. Damage dealt when his shield is on is reduced by the strength of his shield.
Another reason you might be dealing less damage than you expect is because of the damage reduction effect of his E skill, shadow dash. Taunted champions deal 50% reduced damage.
Also, Shen gains very high HP regen after hitting a unit he has marked with Vorpal Blade. This lets him regain health lost to harassment much quicker than most other champions.
The final reason you might not be dealing as much damage as you want to is shen's defensive items. If shen is stacking armor, then he is also going to take less physical damage. The solution to this is building armor penetration, such as Last Whisper or Brutalizer, or simply taking more armor penetration from runes.

A: Assuming that your question means it's hard to deal damage to him, you should build a last whisper after you're beefed up wtih AD and ASPD. This is because Shen is a taking who will more than likely have high amounts of armor, which causes your physical damage to be reduced by a certain percent. Last whisper counters this by getting rid of 40% of the armor he has, which means he reduces less damage.


text:
Q: How to get the common name for a pytz timezone eg. EST/EDT for America/New_York Given a pytz timezone for a particular user(calculated from his offset), i want to display the common name for that timezone. I'm assuming people are more accustomed to seeing EST or PST instead of spelled out like America/NewYork.
Does pytz give me those standard names somewhere, or will i have to manually do this via a table? This could potentially get messy, since for example places are EST in a season and shift to showing EDT during others.

A: This may not have been around when this question was originally written, but here is a snippet to get the time zone official designation:
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'

Further, this can be used with a non-naive datetime object (aka a datetime where the actual timezone has been set using pytz.<timezone>.localize(<datetime_object>) or datetime_object.astimezone(pytz.<timezone>) as follows:
>>> import datetime, pytz
>>> todaynow = datetime.datetime.now(tz=pytz.timezone('US/Hawaii'))
>>> todaynow.tzinfo # turned into a string, it can be split/parsed
<DstTzInfo 'US/Hawaii' HST-1 day, 14:00:00 STD>
>>> todaynow.strftime("%Z")
'HST'
>>> todaynow.tzinfo.zone
'US/Hawaii'

This is, of course, for the edification of those search engine users who landed here. ... See more at the pytz module site.

A: You can use the tzname() method of tzinfo instances:
>>> tz = timezone('America/St_Johns')
>>> normal = datetime(2009, 9, 1)
>>> tz.tzname(normal, is_dst=False)
'NDT'

A: If you are looking for the abbreviations then there are a few ways that come to mind.
First would be:
>>> from pytz import timezone
>>> eastern = timezone('US/Eastern')
>>> eastern._tzname
'EST'

Although since that references a property with the preceding single underscore it may be considered private and might not be the best place to grab it. The other would be from a localized datetime object.
>>> from datetime import datetime
>>> loc_dt = eastern.localize(datetime.now())
>>> loc_dt.strftime('%Z')
'EST'

A:
Given a pytz timezone for a particular user(calculated from his offset), i want to display the common name for that timezone. I'm assuming people are more accustomed to seeing EST or PST instead of spelled out like America/NewYork.

If you need this derived from a datetime object localized with pytz...
>>> import pytz as tz
>>> from datetime import datetime as dt
>>> CT = tz.timezone('America/Chicago')
>>>
>>> summer_day = dt(2010, 7, 4, 0, 1, 1)
>>> bar = CT.localize(summer_day, is_dst=None)
>>> bar.tzname()
'CDT'
>>>
>>> christmas = dt(2010, 12, 25, 0, 1, 1)
>>> foo = CT.localize(christmas, is_dst=None)
>>> foo.tzname()
'CST'
>>>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Neo4j: Create various Nodes of type 1 and type 2 relate these 2 types of Nodes with 2 different relationships I'm using Neo4j to store data.
I have 2 types of data of GDP and Health. Each data has set of countries(say around 20) and set of years (say 1990-2013). Now I want to store each country as unique Node with label as country's name and each year as unique node with label as year. Countries and years are related(mapped) to one another by the above relationships of GDP,health.
I have already collected country names and years in 2 different SortedSet (java code).
I'm not sure if it will be best to add each country and year one-by-one as graphDB.createNode() as I think this will be too cumbersome to create and then define relationships or if it will be best to batchinsert all of these countries at one go and similarly batchinsert years at one time. But again when I have batch inserted all countries and years, how will I then define 2 relationships between them.
I would like if someone has a piece of java code or give advice on finding best solution for storage of data.
I must point that not all country has data for every year for any given relationship.
Thanks,
Hazel

A: I have faced such a case to some extent..I had some nodes of different types

x, y,z

and there was a relationship between x and it's corresponding y or z. I simply used the BatchInserter to insert all the nodes of all types, and after that I had some sql queries to get the relations between nodes, by finding the ids of nodes that must be connected.
So, I think you can insert all the nodes for both YEARS and COUNTRIES by looping through the tow sets you have, after that you may need a query or whatever else to get the relation between those nodes.

A: See here for a guide to importing data into Neo4j and here for additional tools (you can 'batch insert' both nodes and relationships, not sure what your hesitation is there).
I don't know what you mean by 'cumbersome'. If you use the batch tools above you can do first all nodes and then all relationships, but if you use the Java embedded API there is no need to do that. If you are concerned about duplicates, f.i. a case where you come upon a node first as a 'subject' as you iterate through your SortedSet and then again as an 'object' or end node of a relationship, you can take a look at UniqueFactory. It would allow you to build your graph in an order that is convenient given your data without worrying about creating duplicate nodes–just create each node, the remote nodes of its relationships, and the relationships between these. If the nodes already exist they will be updated, not duplicated. This is perhaps the most straightforward way, give it a try and ask again, a little more specifically, if you have trouble.


text:
Q: Tampermonkey script blocked by a CSP error I am new to javascript and Tampermonkey. I wanted to add a frame to the Memrise's website. The code is as follows:

// ==UserScript==
// @name         Merise
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       k1
// @match        https://app.memrise.com/aprender/*
// @icon         https://www.google.com/s2/favicons?domain=memrise.com
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    var word = document.getElementsByClassName("sc-1nck79x-5 jPETsr")[0]
    var bdy = document.getElementsByClassName("sc-r1ec2z-1 evBYsl")[0]
    var defl = "https://learnersdictionary.com/definition/" + word.innerHTML
    var fr = document.createElement("IFRAME");
    fr.height = "500px"
    fr.src = defl
    fr.style.maxWidth="90%"
    bdy.appendChild(fr);
})();

But the code execution blocked due to the error: Content Security Policy: The page's settings blocked the loading of a resource at inline ("script-src").
Please let me know how can I fix this if there is any way to do that. Thanks.

A: Use GM_addElement to circumvent such CSP restrictions:
// ==UserScript==
// @name         Merise
// @match        https://app.memrise.com/aprender/*
// @grant        GM_addElement
// ==/UserScript==

var word = document.getElementsByClassName('sc-1nck79x-5 jPETsr')[0].textContent;
var bdy = document.getElementsByClassName('sc-r1ec2z-1 evBYsl')[0];
GM_addElement(bdy, 'iframe', {
  src: 'https://learnersdictionary.com/definition/' + encodeURIComponent(word),
  style: 'width: 90%; height: 500px;',
});


text:
Q: How can I use database of mysql with android online application Hello I have some questions please.
the situation is I have a web site made by Laravel using mysql database. And I need to create android application for this web site and the application use sqlite. how can I use the database of my web site to work with my application, and also make the data into sqlite when there's no connection in phone.
I need the idea in ionic and in java app please.


text:
Q: How do I generate an AES256 key in the build script phase in Xcode and make it an accessible variable from inside my application? I would like to generate an encryption key from the build script and make the key an accessible variable from within my application.
I don't have very much shell scripting experience, and I'm looking for more examples similar to this:
http://aptogo.co.uk/2010/07/protecting-resources/
OR, if there are any current data protection frameworks that I am not aware of.
The intent is to add a layer of e n c r y p t i o n to my bundle resources. So that the media files are not accessible outside of the device.
Current script:
DIRNAME=CCResource
ENC_KEY="Generate and store key here and make available from within application"

INDIR=$PROJECT_DIR/$DIRNAME
OUTDIR=$TARGET_BUILD_DIR/$CONTENTS_FOLDER_PATH/$DIRNAME

if [ ! -d "$OUTDIR" ]; then
mkdir -p "$OUTDIR"
fi

for file in "$INDIR"/*
do
 echo "Encrypting $file"
 "$PROJECT_DIR/crypt" -e -k $ENC_KEY -i "$file" -o "$OUTDIR/`basename "$file"`"
done


text:
Q: How to get rid of "Folders" and "Network locations" links in Explorer in Windows 8.1? Let me explain with a couple of screenshots. I just upgraded from Windows 8 to 8.1 and now I get a bunch of useless shortcuts in Windows Explorer when I try to open a file, or if I just plainly go to My Computer. Stuff like this:

Or this:

Can I hide the links circled in red?
The reason I don't need them there is because now I have to constantly scroll down to get to the files and folders that I actually need. (And if I fold them up with that little arrow, they come right out after a while.) It just wastes time!

A: Download the tool called This PC Tweaker, this tool allows you to remove and add new folders:

With This PC Tweaker, you will be able to perform the following
  customizations:

*

*to add any folder to the Computer/This PC folder. Really any.

*to remove any folder from the Computer/This PC folder.

*to change the icon for any folder inside Computer/This PC.

*to add any shell location like Administrative tools, God Mode, Network Connections

*you can pin or unpin Computer/This PC items from the Navigation Pane of Explorer in Windows 8.1, Windows 8 and even in Windows 7!

*You can remove or add any item from the Folders category inside the Computer/This PC folder.

*to restore defaults with one click.


text:
Q: How to use Cognito identity pool with UnAuthenticatd users in Amplify for Android I've been going through the AWS Amplify docs and tutorials for how to use Amplify and Cognito identity pools together with UNauthenticated users. The example given by the Amplify docs is:
Amplify.Auth.fetchAuthSession(
    result -> {
        AWSCognitoAuthSession cognitoAuthSession = (AWSCognitoAuthSession) result;
            switch(cognitoAuthSession.getIdentityId().getType()) {
                case SUCCESS:
                    Log.i("AuthQuickStart", "IdentityId: " + cognitoAuthSession.getIdentityId().getValue());
                    break;
                case FAILURE:
                    Log.i("AuthQuickStart", "IdentityId not present because: " + cognitoAuthSession.getIdentityId().getError().toString());
            }
        },
        error -> Log.e("AuthQuickStart", error.toString())
);

But in practice when I use this code - I get an error printed out in LogCat:
AuthQuickStart: FAILURE IdentityId not present because: AmplifyException {message=You are currently signed out., cause=null, recoverySuggestion=Please sign in and reattempt the operation.}

Note: I did configure AWS Cognito to support Unauthenticaed users!
I've also looked everywhere for the Amplify Android API doc to see what other APIs are supported - couldn't find any Android API docs.
And looking into the AWS Amplify.Auth methods i could not find ANY function that deals with unauthenticated users
Question:
Any clue how can i use Amplify (Android) and have AWS credentials via AWS Cognito for unauthenticated users ???

A: This is David from the Amplify Android team. I was actually just looking into this the other day and currently there's a hack that's required to make unauth users work.
After setting up unauth/guest users through the CLI (as you mentioned you had) you have to call the getAWSCredentials method on the underlying escape hatch once for the app to get it to work.
Here's a code snippet I'd written that you can run after Amplify.configure (and again, this only needs to be run once per app install):
AWSMobileClient mobileClient = (AWSMobileClient) Amplify.Auth.getPlugin("awsCognitoAuthPlugin").getEscapeHatch();

mobileClient.getAWSCredentials(new Callback<AWSCredentials>() {
     @Override
     public void onResult(AWSCredentials result) {

        // Now you'll see the Identity ID and AWSCredentials in the resulting auth session object.
        Amplify.Auth.fetchAuthSession(
            result2 -> Log.i(TAG, result2.toString()),
            error -> Log.e(TAG, error.toString()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
     }

     @Override
     public void onError(Exception e) {
          // Handle the error however is best for your app
     }
});

I'm working on a solution to avoid this hack right now and adding a documentation section on Unauth users to our site but in the meantime this should get it working for you.
Again note you only have to do this once and from then on out, it should just work when you call fetchAuthSession.
UPDATE: The non patched (official) version:
Amplify.Auth.fetchAuthSession(
    result -> {
        AWSCognitoAuthSession cognitoAuthSession = (AWSCognitoAuthSession) result;
        switch (cognitoAuthSession.getIdentityId().getType()) {
            case SUCCESS:
                Log.i(TAG, "identity: " + cognitoAuthSession.getIdentityId().getValue());
                Log.i(TAG, "credentials: " + cognitoAuthSession.getAWSCredentials().getValue(););
                break;
            case FAILURE:
                Log.i(TAG, "FAILURE IdentityId not present because: " + cognitoAuthSession.getIdentityId().getError().toString());
        }
    },
    error -> Log.e(TAG, "UNAUTH USERS ERR: " + error.toString()));

A: You wont be able to retrieve an authenticated session unless you have a logged in user.
If your Identity Pool (not User Pool) is configured for unauthenticated or guest users you can make a simple call to the GetId endpoint:
GetId
Generates (or retrieves) a Cognito ID. Supplying multiple logins will create an implicit linked account.
This is a public API. You do not need any credentials to call this API.
Request Syntax
{
   "AccountId": "string",
   "IdentityPoolId": "string",
   "Logins": {
      "string" : "string"
   }
}

https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html
You should then be able to use the ID to retrieve a token using:
GetOpenIdToken
Gets an OpenID token, using a known Cognito ID. This known Cognito ID is returned by GetId. You can optionally add additional logins for the identity. Supplying multiple logins creates an implicit link.
The OpenID token is valid for 10 minutes.
This is a public API. You do not need any credentials to call this API.
Request Syntax
{
   "IdentityId": "string",
   "Logins": {
      "string" : "string"
   }
}

https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdToken.html


text:
Q: Why do two functions have the same address? Consider this function template:
template<typename T>
unsigned long f(void *) { return 0;}

Now, I print the addresses of f<A> and f<B> as:
std::cout << (void*)f<A> << std::endl;
std::cout << (void*)f<B> << std::endl;

Why do they print the same address if compiled in MSVS10? Are they not two different functions and therefore should print different addresses?
Updated:
I realized that on ideone, it prints the different address.  MSVS10 optimizes the code, as the function doesn't depend on T in any way, so it produces same function. @Mark's answer and comments on this are valuable. :-)

A: You need to cast to void *:
std::cout << (void*)(ftype*)f<A> << std::endl;
std::cout << (void*)(ftype*)f<B> << std::endl;

If you cast to a function pointer (or several other classes of non-void pointers), it will be interpreted as a bool by the operator<< for std::ostream (hence the 1).

A: Since the function doesn't depend on the template parameter, the compiler can condense all instantiations into a single function.
I don't know why you get 1 for the address.

Added by Nawaz:
I experimented with my real code, and concluded that what @Mark said above is very important here :
Since the function doesn't depend on the template parameter, the compiler can condense all instantiations into a single function.
I also came to a conclusion that if the function-body depends on T*, not on T, it still produces the same function for different type arguments in my real code (not on ideone, though). However, if it depends on T, then it produces different functions, because sizeof(T) differs (fortunately for me) for different type arguments.
So I added a dummy automatic variable of type  T in the function template, so that the function could depend on the size of T so as to force it to produce different functions.

A: This is simply a case of undefined behavior because the results of casting a pointer to a function to a pointer to object type are undefined.
A more interesting expression to examine would bef<A> == f<B> which should evaluate to true if and only if A and B refer to the same type.


text:
Q: Protect web directories from other SSH users but allow apache access? So my linux box has 2 users :

*

*root (which I use)

*dev (the user that my developer uses)

I have a few directories on my web server which I need to restrict access from the "dev" user.
So, for example :
/var/www/html/www.mysecuresite.com (dev user should not access)
/var/www/html/www.mysecuresite2.com (dev user should not access)
/var/www/html/www.devsite.com (both root and dev should access)
/var/www/html/www.devsite2.com (both root and dev should access)
..
..
..

Apache is currently running as apache:apache
How do i make sure that apache can run all directories but the dev user cannot access the directories he is not supposed to ? What permissions do I give to the directories, and run apache as so that the above rules are fulfilled ?
Is this technically possible to do by just tinkering with permissions, users and groups ?
Edit: The above folders contain fully dynamic web applications written in PHP, connecting to MySQL, file uploads etc.
There are no groups currently set up on my linux box. I am not a seasoned linux user, so I would really appreciate detailed advice on what would be the best way forward for me.
Thanks !


text:
Q: why zoom doesn't work in Dash plotly with my line graph I am plotting a line graph in the Dash app this graph update frequently let's say every 1 second, But when I am trying to zoom in it immediately gets back to the initial view. What am I doing wrong? I am new to Dash and web UI so any help will be of great help to me, Thank you in advance.
import dash
from dash.dependencies import Output, Input
import dash_core_components as dcc
import dash_html_components as html
import plotly
import random
import plotly.graph_objs as go
from collections import deque

X = deque()
X.append(1)
Y = deque()
Y.append(1)

app = dash.Dash(__name__)
app.layout = html.Div(
    [
        dcc.Graph(id='live-graph', animate=True),
        dcc.Interval(
            id='graph-update',
            interval=1*1000
        ),
    ]
)

@app.callback(Output('live-graph', 'figure'),
              [Input('graph-update', 'n_intervals')])
def update_graph_scatter(input_data):
    X.append(X[-1]+1)
    Y.append(Y[-1]+Y[-1]*random.uniform(-0.1,0.1))

    data = plotly.graph_objs.Scatter(
            x=list(X),
            y=list(Y),
            name='Scatter',
            mode= 'lines+markers'
            )

    return {'data': [data],'layout' : go.Layout(
    xaxis=dict(range=[0, max(X) + 1]),
    yaxis=dict(range=[min(Y) - 0.15, max(Y) + 1]),
    title="Plot Title",
    xaxis_title="x Axis Title",
    yaxis_title="y Axis Title",
    font=dict(
        family="Courier New, monospace",
        size=20,
        color="#7f7f7f"
    )
)}

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

A: This is because I was rendering the whole graph every time, which in turn reset the view of the graph even though you zoom in/out. The solution for this is to use an extendable graph. Dash plotly has this support visit this Link to know more about it. .


text:
Q: How to reuse slide up menu class in any view controller? I am trying to create a slide up menu, completely defined in a custom class named OldMenu.
It would show every time a user tap a UIBarButtonItem, that is also defined in that class.
So the button, the menu, and the menu animation to show the menu are all defined in this custom class.
For now, I can just access the button from an other class but it doesn't seem to trigger the animation to show the menu.
Any one knows why this code isn't working?
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let oldMenu = OldMenu()
        navigationItem.rightBarButtonItems = [oldMenu.MenuButton]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

class OldMenu: NSObject, UITableViewDelegate, UITableViewDataSource {
    var tableView: UITableView {
        let tableView = UITableView()
        tableView.isScrollEnabled = true
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "Cell")
        return tableView
    }

    var transparentView = UIView()

    let height: CGFloat = 250

    var MenuButton: UIBarButtonItem {
        let btn = UIBarButtonItem()
        btn.title = "Menu"
        btn.target = self
        btn.action = #selector(onClickMenu)
        return btn
    }
}

extension OldMenu {

    @objc func onClickMenu(_ sender: Any) {
        let window = UIApplication.shared.keyWindow
        transparentView.backgroundColor = UIColor.black.withAlphaComponent(0.9)
        transparentView.frame = window?.bounds ?? .zero
        window?.addSubview(transparentView)

        let screenSize = UIScreen.main.bounds.size
        tableView.frame = CGRect(x: 0, y: screenSize.height, width: screenSize.width, height: height)
        window?.addSubview(tableView)

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onClickTransparentView))
        transparentView.addGestureRecognizer(tapGesture)

        transparentView.alpha = 0

        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: {
            self.transparentView.alpha = 0.5
            self.tableView.frame = CGRect(x: 0, y: screenSize.height - self.height, width: screenSize.width, height: self.height)
        }, completion: nil)

    }

    @objc func onClickTransparentView() {
        let screenSize = UIScreen.main.bounds.size

        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: {
            self.transparentView.alpha = 0
            self.tableView.frame = CGRect(x: 0, y: screenSize.height, width: screenSize.width, height: self.height)
        }, completion: nil)
    }
}

extension OldMenu {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }

}

A: Code
class ViewController: UIViewController {

var oldMenu: OldMenu!

   override func viewDidLoad() {
      super.viewDidLoad()

       oldMenu = OldMenu(controller: self)
       navigationItem.rightBarButtonItem = oldMenu.MenuButton
   }

   override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
   }
}

extension ViewController: MenuDelegate {

   func tableRowDidSelect(_ indexPath: IndexPath) {

   }
}

OldMenu
class OldMenu: NSObject {

    var presenter: UIViewController?

    var menuController = MenuViewController()

    var MenuButton: UIBarButtonItem!

    init(controller: UIViewController?) {
        super.init()
        presenter = controller
        MenuButton = UIBarButtonItem(title: "Menu", style: .plain, target: self, action: #selector(onClickMenu))
    }

    @objc func onClickMenu() {
        menuController.modalPresentationStyle = .custom
        menuController.transitioningDelegate = self
        menuController.delegate = presenter as! MenuDelegate
        presenter?.present(menuController, animated: true, completion: nil)
    }
}

extension OldMenu: UIViewControllerTransitioningDelegate {

    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        PresentationController(presentedViewController: presented, presenting: presenting)
    }

}

MenuViewController
Configure your tableView in MenuViewController, and use delegates to communicate back to the main view
protocol MenuDelegate {
    func tableRowDidSelect(_ indexPath: IndexPath)
}

// Configure your tableView in MenuViewController
// Use delegates to communicate back to main view
class MenuViewController: UIViewController {

    var delegate: MenuDelegate?

    override func viewDidLoad() {
        view.backgroundColor = .gray
    }
}

PresentationController
You can reuse PresentationController to present view controllers in half screen.
import Foundation
import UIKit

class PresentationController: UIPresentationController {

  let blurEffectView: UIVisualEffectView!
  var tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer()

  override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) {
      let blurEffect = UIBlurEffect(style: .dark)
      blurEffectView = UIVisualEffectView(effect: blurEffect)
      super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
      tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissController))
      blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
      self.blurEffectView.isUserInteractionEnabled = true
      self.blurEffectView.addGestureRecognizer(tapGestureRecognizer)
  }

  override var frameOfPresentedViewInContainerView: CGRect {

      // Set your presentation height
      let presentHeight: CGFloat = 300

      return CGRect(origin: CGPoint(x: 0, y: self.containerView!.frame.height - presentHeight),
             size: CGSize(width: self.containerView!.frame.width, height: presentHeight))
  }

  override func presentationTransitionWillBegin() {
      self.blurEffectView.alpha = 0
      self.containerView?.addSubview(blurEffectView)
      self.presentedViewController.transitionCoordinator?.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) in
          self.blurEffectView.alpha = 0.5
      }, completion: { (UIViewControllerTransitionCoordinatorContext) in })
  }

  override func dismissalTransitionWillBegin() {
      self.presentedViewController.transitionCoordinator?.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) in
          self.blurEffectView.alpha = 0
      }, completion: { (UIViewControllerTransitionCoordinatorContext) in
          self.blurEffectView.removeFromSuperview()
      })
  }

  override func containerViewWillLayoutSubviews() {
      super.containerViewWillLayoutSubviews()

      // set your corner radius
    presentedView!.roundCorners([.topLeft, .topRight], radius: 18)
  }

  override func containerViewDidLayoutSubviews() {
      super.containerViewDidLayoutSubviews()
      presentedView?.frame = frameOfPresentedViewInContainerView
      blurEffectView.frame = containerView!.bounds
  }

  @objc func dismissController(){
      self.presentedViewController.dismiss(animated: true, completion: nil)
  }
}

extension UIView {
  func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
      let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners,
                              cornerRadii: CGSize(width: radius, height: radius))
      let mask = CAShapeLayer()
      mask.path = path.cgPath
      layer.mask = mask
  }
}

Result


text:
Q: Can't bind to 'ngFormControl' since it isn't a known native property EDIT: the angular 2 dropdown multiselect hasnt been updated for angular 2 rc 4 because it has old syntax:  [ngFormControl]="search" and import {Control} from 'angular2/common' and I have been trying to update the source code syntax of angular 2 dropdown multiselect to make it work
I'm trying to use angular 2 dropdown multiselect, just trying to get the most basic demo up and running.
But when I try to load the page I get this error:

Can't bind to 'ngFormControl' since it isn't a known native property
  ("" class="form-control" placeholder="{{ texts.searchPlaceholder }}"
  aria-describedby="sizing-addon3" [ERROR ->][(ngFormControl)]="search">

Why do I get this error and how can I fix it?
Here is the relevant information:
folder structure:

my component that depends on the angular 2 dropdown multiselect
import { Component } from '@angular/core';
import { MultiselectDropdown, IMultiSelectOption } from 'angular2-multiselect/src/multiselect-dropdown';
@Component({
   selector: 'multiselect',
   templateUrl: 'app/shared/multiselect.component.html',
   directives: [MultiselectDropdown]
})
export class MultiselectComponent {
    private myOptions: IMultiSelectOption[] = [
        { id: 1, name: 'Option 1' },
        { id: 2, name: 'Option 2' },
    ];
}

The ts file of angular 2 dropdown multiselect is correctly being transpiled to js.
js file structure:

the source code of angular 2 dropdown multiselect:
/*
 * Angular 2 Dropdown Multiselect for Bootstrap
 * Current version: 0.1.0
 *
 * Simon Lindh
 * https://github.com/softsimon/angular-2-dropdown-multiselect
 */

import {Component, Pipe, OnInit, HostListener, Input, ElementRef, Output, EventEmitter} from '@angular/core';
import {Control} from '@angular/common'
import {Observable} from 'rxjs/Rx';

export interface IMultiSelectOption {
    id: number;
    name: string;
}

export interface IMultiSelectSettings {
    pullRight?: boolean;
    enableSearch?: boolean;
    checkedStyle?: 'checkboxes' | 'glyphicon';
    buttonClasses?: string;
    selectionLimit?: number;
    closeOnSelect?: boolean;
    showCheckAll?: boolean;
    showUncheckAll?: boolean;
    dynamicTitleMaxItems?: number;
    maxHeight?: string;
}

export interface IMultiSelectTexts {
    checkAll?: string;
    uncheckAll?: string;
    checked?: string;
    checkedPlural?: string;
    searchPlaceholder?: string;
    defaultTitle?: string;
}

@Pipe({
    name: 'searchFilter'
})
class SearchFilter {
    transform(options: Array<IMultiSelectOption>, args: Array<string>): Array<IMultiSelectOption> {
        return options.filter((option: IMultiSelectOption) => option.name.toLowerCase().indexOf(args[0].toLowerCase()) > -1);
    }
}

@Component({
    selector: 'ss-multiselect-dropdown',
    pipes: [SearchFilter],
    styles: [`
        a { outline: none; }
    `],
    template: `

            <button type="button" class="dropdown-toggle btn" [ngClass]="settings.buttonClasses" (click)="toggleDropdown()">{{ getTitle() }} </button>

                        <input type="text" class="form-control" placeholder="{{ texts.searchPlaceholder }}" aria-describedby="sizing-addon3" [(ngFormControl)]="search">
                         0">
                            <button class="btn btn-default" type="button" (click)="clearSearch()"></button>

                        {{ texts.checkAll }}

                        {{ texts.uncheckAll }}

                        <input *ngIf="settings.checkedStyle == 'checkboxes'" type="checkbox" [checked]="isSelected(option)" />

                        {{ option.name }}

    `
})
export class MultiselectDropdown implements OnInit {
    @Input() options: Array<IMultiSelectOption>;
    @Input() settings: IMultiSelectSettings;
    @Input() texts: IMultiSelectTexts;
    @Input('defaultModel') selectedModel: Array<number> = [];
    @Output('selectedModel') model = new EventEmitter();
    @Output() selectionLimitReached = new EventEmitter();
    @HostListener('document: click', ['$event.target'])
    onClick(target) {
        let parentFound = false;
        while (target !== null && !parentFound) {
            if (target === this.element.nativeElement ) {
                parentFound = true;
            }
            target = target.parentElement;
        }
        if (!parentFound) {
            this.isVisible = false;
        }
    }

    private numSelected: number = 0;
    private isVisible: boolean = false;
    private search = new Control();
    private searchFilterText: string = '';
    private defaultSettings: IMultiSelectSettings = {
        pullRight: false,
        enableSearch: false,
        checkedStyle: 'checkboxes',
        buttonClasses: 'btn btn-default',
        selectionLimit: 0,
        closeOnSelect: false,
        showCheckAll: false,
        showUncheckAll: false,
        dynamicTitleMaxItems: 3,
        maxHeight: '300px',
    };
    private defaultTexts: IMultiSelectTexts = {
        checkAll: 'Check all',
        uncheckAll: 'Uncheck all',
        checked: 'checked',
        checkedPlural: 'checked',
        searchPlaceholder: 'Search...',
        defaultTitle: 'Select',
    };

    constructor(
        private element: ElementRef
    ) { }

    ngOnInit() {
        this.settings = Object.assign(this.defaultSettings, this.settings);
        this.texts = Object.assign(this.defaultTexts, this.texts);
        this.updateNumSelected();
        this.search.valueChanges
            .subscribe((text: string) => {
                this.searchFilterText = text;
            });
    }

    clearSearch() {
        this.search.updateValue('');
    }

    toggleDropdown() {
        this.isVisible = !this.isVisible;
    }

    modelChanged() {
        this.updateNumSelected();
        this.model.emit(this.selectedModel);
    }

    isSelected(option: IMultiSelectOption): boolean {
        return this.selectedModel.indexOf(option.id) > -1;
    }

    setSelected(event: Event, option: IMultiSelectOption) {
        var index = this.selectedModel.indexOf(option.id);
        if (index > -1) {
            this.selectedModel.splice(index, 1);
        } else {
            if (this.settings.selectionLimit === 0 || this.selectedModel.length < this.settings.selectionLimit) {
                this.selectedModel.push(option.id);
            } else {
                this.selectionLimitReached.emit(this.selectedModel.length);
                return;
            }
        }
        if (this.settings.closeOnSelect) {
            this.toggleDropdown();
        }
        this.modelChanged();
    }

    getTitle() {
        if (this.numSelected === 0) {
            return this.texts.defaultTitle;
        }
        if (this.settings.dynamicTitleMaxItems >= this.numSelected) {
            return this.options
                .filter((option: IMultiSelectOption) => this.selectedModel.indexOf(option.id) > -1)
                .map((option: IMultiSelectOption) => option.name)
                .join(', ');
        }
        return this.numSelected + ' ' + (this.numSelected === 1 ? this.texts.checked : this.texts.checkedPlural);
    }

    updateNumSelected() {
        this.numSelected = this.selectedModel.length;
    }

    checkAll() {
        this.selectedModel = this.options.map(option => option.id);
        this.modelChanged();
    }

    uncheckAll() {
        this.selectedModel = [];
        this.modelChanged();
    }

}

A: Try to use version 0.2.0:
angular-2-dropdown-multiselect
Quick guid:

*

*Install as local npm package (npm install angular-2-dropdown-multiselect --save-dev).

*Add to my component file: import { IMultiSelectOption, IMultiSelectSettings, IMultiSelectTexts } from '../../node_modules/angular-2-dropdown-multiselect/src/multiselect-dropdown';.

*in node_modules/angular-2-dropdown-multiselect/src/multiselect-dropdown.ts, add export in front of class MultiSelectSearchFilter so it can be imported in my module file in next step.

*Add to my module file: import { MultiselectDropdown, MultiSelectSearchFilter } from '../../node_modules/angular-2-dropdown-multiselect/src/multiselect-dropdown'; Note the README says MultiselectDropdownModule, but I think it's a typo and should be MultiselectDropdown (PR).

*Add MultiselectDropdown and MultiSelectSearchFilter to @NgModule declarations.

Guid reference from issue: issue 14


text:
Q: GREATEST and LEAST in SQL standard My understanding is that GREATEST() and LEAST() are not part of the SQL standard, but are very common.
I'm wondering, is there a way to clone the functionality of GREATEST keeping within the SQL standard?
SELECT id, GREATEST(1,2,3,4,5,6,7) AS number FROM table

The fully query:
  SELECT SUBSTR(section,1,2) AS campus,
           AVG(GREATEST(maximum - enrolled, 0)) AS empty
    FROM sectionrun
   WHERE coursenumber = '105' AND subject = 'ENGL'
GROUP BY campus

A: GREATEST(1,2,3,4,5,6,7) AS number

can become
(select max(tmp) from (
        select 1 tmp from dual
        union all
        select 2 tmp from dual
        union all
        select 3 tmp from dual
        union all
        select 4 tmp from dual
        union all
        select 5 tmp from dual
        union all
        select 6 tmp from dual
        union all
        select 7 tmp from dual
) ) AS number

A: You can use the CASE expression:
  SELECT SUBSTR(section,1,2) AS campus,
           AVG(CASE WHEN maximum - enrolled > 0
                    THEN maximum - enrolled
                    ELSE 0
               END) AS empty
    FROM sectionrun
   WHERE coursenumber = '105' AND subject = 'ENGL'
GROUP BY campus

A: As of now, GREATEST() and LEAST() are supported in Azure SQL.  SQL Server 2022 will have it for on-premises installations.
GREATEST documentation:
https://learn.microsoft.com/en-us/sql/t-sql/functions/logical-functions-greatest-transact-sql?view=sql-server-ver15


text:
Q: How could I update MongoDB array fileds based on array of another array fields I have this document in my collection
{
  "_id": ObjectId("609111c7ba749712215cff37"),
  "CompanyExperience" : {
    "Company1" : {
      "CompanyName" : "NWS Pvt. Ltd",
      "JobTitle" : "",
      "From" : "01/03/2017",
      "Till" : "30/11/2020",
      "ExperienceMonths" : NumberDecimal("9"),
      "ExperienceYears" : NumberDecimal("3")
    },
    "Company2" : {
      "CompanyName" : "KHS InfoTech Studio Pvt",
      "JobTitle" : "Sales-Coordinators",
      "From" : "01/08/2016",
      "Till" : "28/02/2017",
      "ExperienceMonths" : NumberDecimal("6"),
      "ExperienceYears" : NumberDecimal("0")
    }
  }
}

I just want to update CompanyExperience.Company1.JobTitle = CompanyExperience.Company2.JobTitle
I have tried with this code
db.mongodb_tbl_resumecard_all.updateOne(
    {"_id" : ObjectId("609111c7ba749712215cff37")},
    {$set:
        {
            "CompanyExperience.Company1.JobTitle": "$CompanyExperience.Company2.JobTitle"
        }
    }
)

But I got
{
  "_id": ObjectId("609111c7ba749712215cff37"),
  "CompanyExperience" : {
    "Company1" : {
      "CompanyName" : "NWS Pvt. Ltd",
      "JobTitle" : "$CompanyExperience.Company2.JobTitle",
      "From" : "01/03/2017",
      "Till" : "30/11/2020",
      "ExperienceMonths" : NumberDecimal("9"),
      "ExperienceYears" : NumberDecimal("3")
    },
    "Company2" : {
      "CompanyName" : "KHS InfoTech Studio Pvt",
      "JobTitle" : "Sales-Coordinators",
      "From" : "01/08/2016",
      "Till" : "28/02/2017",
      "ExperienceMonths" : NumberDecimal("6"),
      "ExperienceYears" : NumberDecimal("0")
    }
  }
}

I wanted to update its value but It is updating like string.
Please help me out.

A: You need to put your $set operation in [] brackets to form an aggregation pipeline:
db.mongodb_tbl_resumecard_all.update({
  "_id": ObjectId("609111c7ba749712215cff37")
},
[
  {
    "$set": {
      "CompanyExperience.Company1.JobTitle": "$CompanyExperience.Company2.JobTitle"
    }
  }
])


text:
Q: Comparing TIMEDIFF in MySQL I have these following data:
ID   TIMEIN                 TIMEOUT
1    2016-08-24 20:44:00    2016-10-22 19:35:36
2    2016-08-24 20:58:00    2016-08-24 20:59:09

and the following query that I want to use to find all the entries where the timediff is lesser than 50 hours
SELECT TimeDiff(TimeOut,TimeIn)
from table where TimeDiff(TimeOut,TimeIn) < '50:00:00'

The second row should be returned because it's lesser than 50 hours, but the first row, which the timediff is more than 50 hours keep returning as well.
02:04:57
15:10:49
125:00:25

It returns all sort of value, including those larger than 50
What query should I be using? Thank you

A: Please use the following:
SELECT id,
       timeIn,
       timeOut,
       TIMEDIFF( timeOut,
                 timeIn ) AS timeDifference
FROM table
WHERE TIMESTAMPDIFF( SECOND,
                     timeOut,
                     timeIn ) > 180000;

This statement will output the fields for each record where the difference between the two timedates is one second or more over 50 hours (or 180000 seconds).

A: Try getting the difference in hours and then comparing.
SELECT TimeDiff(TimeOut,TimeIn)
from table where HOUR(TIMEDIFF(endDate, startDate)) < 50


text:
Q: read one line with "read" in bash, but without "while" I was trying to understand how "while read" works in bash, and i came accross a behaviour that i can't explain:
root@antec:/# var=old_value
root@antec:/# echo "new_value" | read var && echo $var
old_value
root@antec:/#

It works fine with "while read":
root@antec:/# var=old_value
root@antec:/# echo "new_value" | while read var; do echo $var; done
new_value
root@antec:/#

Can someone explain why it does not work when read is used without while ? Moreover, i don't understand how the value of "var" in the main shell can be seen from the allegedly subshell after the pipe ..
Thank you

A: I believe this is precedence problem, with | having higher precedence than &&.  First is grouped as:
(echo "new_value" | read var) && echo $var

Second is grouped as:
echo "new_value" | (while read var; do echo $var; done)

A: Why do you think it works in the second case? It doesn't really update var. do echo $var after the line with while and see.
Explanation: whatever comes after | is executed in a subshell that has its own copy of var. The original var is not affected in either case. What is echoed depends on whether echo is called in the same subshell that does read or not.

A: I didn't want to print the variable immediately but use it later on and this works:
var=old_value
read var < <(echo "new_value")
echo $var
> new_value

alternatively:
var=old_value
tmp=$(echo "new_value")
read var <<<"$tmp"
echo $var
> new_value

A: You don't need a while loop:
echo "new_value" | (read var; echo $var)


text:
Q: getting Incorrect syntax near '08'. error I have been doing some research about how to pass variables to an openquery. Here is the query I have built.
DECLARE @firstday int;
DECLARE @lastday int;

SELECT @firstday = CONVERT(nvarchar(8), (DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)), 112)
SELECT @lastday = CONVERT(nvarchar(8), (DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1)), 112)

DECLARE @SqlCommand NVARCHAR(MAX) = N'SELECT * FROM OPENQUERY(EPAK,
''SELECT WOADAT,WOROUT,BCDESC,WDWO#,BCSIZE,BCCHG
FROM CUST INNER JOIN (BCDE INNER JOIN (WO2 INNER JOIN WO1
ON (WDCMP = WOCMP) AND (WDCUS# = WOCUS#) AND (WDWO# = WOWO#)) ON (BCCMPY = WDCMP)
AND (BCSIZE = WDSIZE) AND (BCCHG = WDCHG)) ON (CCMPNY = BCCMPY) AND (CCUST# = WDCUS#)
WHERE (((WOADAT) between @firstday and @lastday) AND ((WDCMP)=''08''))order by WDWO#'')'

EXEC sp_ExecuteSQL @SqlCommand;

My linked server is a DB2 server and when I run my query I am getting the following error
Incorrect syntax near '08'.

When I double clic on it, it highlighted this
SELECT @lastday = CONVERT(nvarchar(8), (DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1)), 112)

Could someone please take a look and let me know what is the error?

A: I think you need two more single quotes:
((WDCMP)=''''08''''))

You have a quoted string being passed in as a query.  Two levels of quoting.  I think the problem is happening after the first round of substitution, which produces:
((WDCMP)='08'))

This "looks" right, but not for a quoted substring.  The first quote ends the substring, generating the error.


text:
Q: Having Trouble with Understanding the Minimum of Exponential Random Variables I'm learning about exponential distributions, and we've been given this distribution $Z = \min\left[X, Y\right]$, where $X$ and $Y$ follow exponential distributions.
How can I visualize this?
If $X \sim \operatorname{Exp}(2)$, and $Y \sim\operatorname{Exp}(3)$, then $f_X(x) = 2e^{-2x}$ and $f_Y(x) = 3e^{-3x}$.
Would that just mean that $f_Z(x) = \min\left[2e^{-2x}, 3e^{-3x}\right]$, i.e. a piecewise function containing both distributions?
And how is $Z$ another exponential distribution if it is piecewise? I believe I am misunderstanding the meaning of minimum.

A: The output of the minimum function will give the smallest of an observation of $X$ and $Y$ but not the p.d.f. itself since a value of a random variable does not take the value of the p.d.f. but rather take the "probability" from the p.d.f.
In general the trick is that if $Z>z$ and $Z=\min\left[X,Y\right]$, then it implies that $X>z$ and $Y>z$. Assuming $X$ and $Y$ are independent, you will have
$$P(Z>z)=P(X>z)\cdot P(Y>z)$$
When you work everything out, you will have $Z\sim\operatorname{Exp}(\lambda_x+\lambda_y)$.


text:
Q: remove files from git is difficult Again and again I follow the instructions but the files are not removed.
fatal: pathspec 'build' did not match any files
dac@dac-Latitude-E7450 ~/p/spaceworld> git rm --cached -r build/distributions/
fatal: pathspec 'build/distributions/' did not match any files
dac@dac-Latitude-E7450 ~/p/spaceworld> git commit -m "refactored"
On branch master
Your branch is ahead of 'origin/master' by 5 commits.
  (use "git push" to publish your local commits)
Changes not staged for commit:
    modified:   .gradle/2.10/taskArtifacts/cache.properties.lock
    modified:   .idea/workspace.xml

Untracked files:
    .gitignore
    Effects/
    Textures/
    assets/Textures/3D/
    assets/Textures/BumpMapTest/
    assets/Textures/ColorRamp/
    assets/Textures/ColoredTex/
    assets/Textures/Cursors/
    assets/Textures/HdrTest/
    assets/Textures/Sky/
    assets/Textures/Terrain/
    build/

no changes added to commit
dac@dac-Latitude-E7450 ~/p/spaceworld> git push
warning: push.default is unset; its implicit value has changed in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the traditional behavior, use:

  git config --global push.default matching

To squelch this message and adopt the new behavior now, use:

  git config --global push.default simple

When push.default is set to 'matching', git will push local branches
to the remote branches that already exist with the same name.

Since Git 2.0, Git defaults to the more conservative 'simple'
behavior, which only pushes the current branch to the corresponding
remote branch that 'git pull' uses to update the current branch.

See 'git help config' and search for 'push.default' for further information.
(the 'simple' mode was introduced in Git 1.7.11. Use the similar mode
'current' instead of 'simple' if you sometimes use older versions of Git)

Username for 'https://github.com': montao
Password for 'https://montao@github.com':
Counting objects: 889, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (844/844), done.
Writing objects: 100% (889/889), 214.55 MiB | 348.00 KiB/s, done.
Total 889 (delta 383), reused 0 (delta 0)
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
remote: error: Trace: 0f0c9d2b284114de3032395332d440e1
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File build/distributions/spaceworld.zip is 150.17 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File build/distributions/spaceworld.tar is 154.00 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File build/assets/libs/assets.jar is 149.27 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File build/assets/libs/assets.jar is 136.69 MB; this exceeds GitHub's file size limit of 100.00 MB
To https://github.com/montao/spaceworld.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/montao/spaceworld.git'
dac@dac-Latitude-E7450 ~/p/spaceworld> git rm -r --cached build
fatal: pathspec 'build' did not match any files
dac@dac-Latitude-E7450 ~/p/spaceworld> ls build
assets/  classes/  dependency-cache/  distributions/  libs/  scripts/  tmp/
dac@dac-Latitude-E7450 ~/p/spaceworld>

I committed too many files and git makes it difficult to remove them. What can I do?
I try again follow the instructions and the same error appears.
M   .idea/workspace.xml
dac@dac-Latitude-E7450 ~/p/spaceworld> git rm --cached -r build/distributions/
fatal: pathspec 'build/distributions/' did not match any files
dac@dac-Latitude-E7450 ~/p/spaceworld> git commit -m "refactored"
On branch master
Your branch is ahead of 'origin/master' by 5 commits.
  (use "git push" to publish your local commits)
Changes not staged for commit:
    modified:   .gradle/2.10/taskArtifacts/cache.properties.lock
    modified:   .idea/workspace.xml

Untracked files:
    .gitignore
    Effects/
    Textures/
    assets/Textures/3D/
    assets/Textures/BumpMapTest/
    assets/Textures/ColorRamp/
    assets/Textures/ColoredTex/
    assets/Textures/Cursors/
    assets/Textures/HdrTest/
    assets/Textures/Sky/
    assets/Textures/Terrain/

no changes added to commit
dac@dac-Latitude-E7450 ~/p/spaceworld> git push
warning: push.default is unset; its implicit value has changed in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the traditional behavior, use:

  git config --global push.default matching

To squelch this message and adopt the new behavior now, use:

  git config --global push.default simple

When push.default is set to 'matching', git will push local branches
to the remote branches that already exist with the same name.

Since Git 2.0, Git defaults to the more conservative 'simple'
behavior, which only pushes the current branch to the corresponding
remote branch that 'git pull' uses to update the current branch.

See 'git help config' and search for 'push.default' for further information.
(the 'simple' mode was introduced in Git 1.7.11. Use the similar mode
'current' instead of 'simple' if you sometimes use older versions of Git)

Username for 'https://github.com': montao
Password for 'https://montao@github.com':
Counting objects: 889, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (844/844), done.
Writing objects: 100% (889/889), 214.55 MiB | 922.00 KiB/s, done.
Total 889 (delta 383), reused 0 (delta 0)
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
remote: error: Trace: d05f62b01f57f07531635f28bda11733
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File build/distributions/spaceworld.zip is 150.17 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File build/distributions/spaceworld.tar is 154.00 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File build/assets/libs/assets.jar is 149.27 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File build/assets/libs/assets.jar is 136.69 MB; this exceeds GitHub's file size limit of 100.00 MB
To https://github.com/montao/spaceworld.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/montao/spaceworld.git'
dac@dac-Latitude-E7450 ~/p/spaceworld>

A: git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch *.sql'

Note: Replace *.sql with your file name or file type. Be very careful because this will go through every commit and rip this file type out.

A: Try the BFG Repo Cleaner.
A one-line command once it's installed:
$ java -jar bfg.jar --strip-blobs-bigger-than 100M spaceworld.git

I'd also stash changes or rebase from master before running it.


text:
Q: Wordpress: using query_posts with custom sort I'm using
  <?php query_posts('cat=34546&posts_per_page=5&order=DESC');

in order to get five posts from a certain category. The order is determined by the ID of the post. I would like it to be determined by another field, like post_date column in posts (let's say for the sake of this question that I manually change post_date that in the database). How can this be done?

A: Using the Query Posts orderby parameters.
https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
For example:
<?php query_posts('cat=34546&posts_per_page=5&order=DESC&orderby=date');

The reference I linked above has what values you can use for orderby.


text:
Q: A particular exact sequence in an abelian category Let $\mathcal{A}$ be an abelian category and let $(X^\bullet, d^\bullet)$ be a chain complex in $\mathcal A$. I want to show that there exists an exact sequence $$0\to \text{im}(d^{i-1})\to \ker(d^i)\to H^i(X^\bullet)\to 0.$$
This is easy to show if $\mathcal{A}$ is the category of modules over a ring (for example), but it seems quite tedious to show in general. Any suggestions?

A: If you want to prove it, then what is your definition of $H^i (X^\bullet)$?
In an arbitrary abelian category, the definition is the following. First note that the condition that $X^\bullet$ is a complex, i.e. that $d^i\circ d^{i-1} = 0$ for all $i$, implies that we have a canonical mono $\operatorname{im} d^{i-1} \rightarrowtail \ker d^i$ and a canonical epi $\operatorname{coker} d^{i-1} \twoheadrightarrow \operatorname{im} d^i$ that give the following commutative diagram:

Then
$$H^i (X^\bullet) := \operatorname{coker} (\operatorname{im} d^{i-1} \rightarrowtail \ker d^i) \cong \ker (\operatorname{coker} d^{i-1} \twoheadrightarrow \operatorname{im} d^i).$$
So that by definition, there are short exact sequences
$$0 \to \operatorname{im} d^{i-1} \to \ker d^i \to H^i (X^\bullet) \to 0$$
and
$$0 \to H^i (X^\bullet) \to \operatorname{coker} d^{i-1} \to \operatorname{im} d^i \to 0$$


text:
Q: For each span data get id and check id from json response I'm trying to check any id sending with ajax and response json getting the id from json then checking if there is an id into span and then add it but is not working is always adding and adding more and more
Jquery
e.results.forEach(function(e) {
    var name = e.name;
    var id = e.id;
    if ($(".visitors span").length) {
        $('.visitors span').each(function() {
            var data_id = $(this).attr('data-id');
            if (data_id != id) {
                $(".visitors").append("" + name + "");
            }
        });
    } else {
        $(".visitors").append("" + name + "");
    }
});

A: Although I think your code is correct, but a suggestion: Instead of looping through the spans you're appending, just check if a span with a data-id exists (using CSS Attribute-Equal Selector), if not append a new span like this:
e.results.forEach(function(e) {
    var name = e.name;
    var id = e.id;

    var $span = $(".visitors span[data-id = '" + id + "']"); // select all the spans that have the data-id equal to id
    if (!$span.length) { // if there is none
        $(".visitors").append("" + name + ""); // then add a new one
    }
});


text:
Q: How to get mat-tree-node element from drop event in the mat-tree in Angular2+? I have a requirement where I need to implement drag and drop between two containers which have a tree-like structure. One container is TODO, the Other is Done. It's working but dropped data always getting attach to node 1 of the Container 2(Done) because I don't know how to find the dropped container node index?

Here is code. Working demo can be found here
import './polyfills';

import {HttpClientModule} from '@angular/common/http';
import {NgModule} from '@angular/core';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {MatNativeDateModule} from '@angular/material';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {DemoMaterialModule} from './material-module';

import {TreeFlatOverviewExample} from './app/tree-flat-overview-example';

@NgModule({
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    HttpClientModule,
    DemoMaterialModule,
    MatNativeDateModule,
    ReactiveFormsModule,
  ],
  entryComponents: [TreeFlatOverviewExample],
  declarations: [TreeFlatOverviewExample],
  bootstrap: [TreeFlatOverviewExample],
  providers: []
})
export class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule);

Drag "Other" and drop into "Done" container now open Node 1. you will be able to see the dropped element.
Requirement: I want to drag from TODO container and want to drop into the exact Node of the container 2.
Quick help will be really appreciated.

A: Ok, Finally after some research I am able to achieve the requirement by using "div" and "cdkDropListGroup" property which connects multiple drop zone.
According to angular If you have an unknown number of connected drop lists, you can use the cdkDropListGroup directive to set up the connection automatically. Note that any new cdkDropList that is added under a group will be connected to all other lists automatically
In the drop container, I can not use mat-tree because that requires a data-source property that can not be dynamically defined(As of now I am aware of). whereas in my case I wanted multiple drop zones dynamically, So I used "div"
Below is the working link, if someone requires this kind of implementation then refer to the below link. I hope this will save someone time.
drag-n-drop-treelist


text:
Q: Spark cluster mode. Deployment of application jar I want to run a maven project in spark cluster mode. I have the application jar file. I also have one master and 6 workers in working condition. But when I execute the jar application, the work is not getting distributed among the workers. The following is the command I gave from the spark directory.
 ./bin/spark-submit --class org.deeplearning4j.mlp.MnistMLPExample --master spark://115.145.173.152:7077 --driver-memory 10g /home/hadoop/Niki/mnist/target/dl4j-spark-0.7-SNAPSHOT-bin.jar.

If I add another parameter --deploy-mode cluster, Then its throwing exception as follows:
Exception in thread "main" com.beust.jcommander.ParameterException: Unknown option: --deploy-mode

Can anyone help me out. Thanks a lot

A: Hi Nikitha yes you need jar file in all worker nodes because spark transformations and actions will execute on worker nodes and if they use this path they search file in there local path so distribute it on all worker nodes also Can you please tell why you use this jar file path in spark code.

A: You are running spark in standalone mode. There is no cluster/client mode in standalone. It is relvent in yarn only.


text:
Q: Why do you want to avoid flushing stdout? I stumbled upon a question in Codereview, and in one answer the feedback was to avoid std::endl because it flushes the stream. The full quote is:

I'd advise avoiding std::endl in general. Along with writing a new-line to the stream, it flushes the stream. You want the new-line, but almost never want to flush the stream, so it's generally better to just write a \n. On the rare occasion that you actually want the flush, do it explicitly: std::cout << '\n' << std::flush;.

The poster did not explain this, neither in the post or comments. So my question is simply this:
Why do you want to avoid flushing?
What made me even more curious was that the poster says that it's very rare that you want to flush. I have no problem imagining situations where you want to avoid flushing, but I still thought that you in general would want to flush when you print a newline. After all, isn't that the reason why std::endl is flushing in the first place?

Just to comment the close votes in advance:
I do not consider this opinion based. Which you should prefer may be opinion based but there are objective reasons to take into account. The answers so far proves this. Flushing affects performance.

A: The short and simple answer is that using std::endl can and will slow output by a huge margin. In fact, I'm reasonably convinced that std::endl is responsible for most of the notion that C++ iostreams are substantially slower than C-style I/O.
For example, consider a program like this:
#include <iostream>
#include <string>
#include <sstream>
#include <time.h>
#include <iomanip>
#include <algorithm>
#include <iterator>
#include <stdio.h>

char fmt[] = "%s\n";
static const int count = 3000000;
static char const *const string = "This is a string.";
static std::string s = std::string(string) + "\n";

void show_time(void (*f)(), char const *caption) {
    clock_t start = clock();
    f();
    clock_t ticks = clock()-start;
    std::cerr << std::setw(30) << caption
        << ": "
        << (double)ticks/CLOCKS_PER_SEC << "\n";
}

void use_printf() {
    for (int i=0; i<count; i++)
        printf(fmt, string);
}

void use_puts() {
    for (int i=0; i<count; i++)
        puts(string);
}

void use_cout() {
    for (int i=0; i<count; i++)
        std::cout << string << "\n";
}

void use_cout_unsync() {
    std::cout.sync_with_stdio(false);
    for (int i=0; i<count; i++)
        std::cout << string << "\n";
    std::cout.sync_with_stdio(true);
}

void use_stringstream() {
    std::stringstream temp;
    for (int i=0; i<count; i++)
        temp << string << "\n";
    std::cout << temp.str();
}

void use_endl() {
    for (int i=0; i<count; i++)
        std::cout << string << std::endl;
}

void use_fill_n() {
    std::fill_n(std::ostream_iterator<char const *>(std::cout, "\n"), count, string);
}

void use_write() {
    for (int i = 0; i < count; i++)
        std::cout.write(s.data(), s.size());
}

int main() {
    show_time(use_printf, "Time using printf");
    show_time(use_puts, "Time using puts");
    show_time(use_cout, "Time using cout (synced)");
    show_time(use_cout_unsync, "Time using cout (un-synced)");
    show_time(use_stringstream, "Time using stringstream");
    show_time(use_endl, "Time using endl");
    show_time(use_fill_n, "Time using fill_n");
    show_time(use_write, "Time using write");
    return 0;
}

With standard output redirected to a file, this produces the following results:
             Time using printf: 0.208539
               Time using puts: 0.103065
      Time using cout (synced): 0.241377
   Time using cout (un-synced): 0.181853
       Time using stringstream: 0.223617
               Time using endl: 4.32881
             Time using fill_n: 0.209951
              Time using write: 0.102781

Using std::endl slowed the program by a factor of about 20 in this case. If you wrote shorter strings, the slow-down could/would be even greater.
There are a few cases where you really and truly do want to flush a stream manually--but they honestly are pretty few and far between.
Most times a stream needs to be flushed (e.g., you print a prompt, then wait for some input) it'll happen automatically unless you've used things like std::tie and/or std::sync_with_stdio to prevent that.
That leaves only a tiny number of truly unusual situations where you have good reason to flush a stream manually. Such cases are rare enough that it's well worth using std::flush when they happen, to make it apparent to the anybody reading the code that you're flushing the stream intentionally (and more often than not, probably also merits a comment about why this is one of the rare cases when flushing the stream really makes sense).

A: Each time a process produces output, it has to call a function that actually does the work.  In most cases, that function is ultimately write(2).  On a multitasking operating system, the call to write() will trap into the kernel, which has to stop the process, handle the I/O, do other things while any blockages are cleared, put it on the ready queue and get it running again when the time comes.  Collectively, you can call all of that activity system call overhead.  If that sounds like a lot, it is.
Flushing a buffered stream* after writing a small amount of data or having no buffer at all incurs that overhead each time you do it:
1\n  (System call that writes two bytes)
2\n  (System call that writes two bytes)
3\n  (System call that writes two bytes)
4\n  (System call that writes two bytes)
5\n  (System call that writes two bytes)

This is how it was done in the very early days until someone figured out that it was burning a lot of system time.  The overhead could be kept down by by accumulating output in a buffer until it was full or the program decided that it must be sent immediately.  (You might want to do the latter if you're producing output sporadically that needs to be seen or consumed.)  Avoiding a flush at the end of each line cuts the number of system calls, and the overhead incurred:
1\n
2\n
3\n
4\n
5\n  (Flush) (System call that writes ten bytes)

*Note that the concept of standard output is a file descriptor associated with a process and given a well-known number.  This differs from the stdout defined by C, C++ and others, which are identifiers for implementations of a buffered stream that live entirely in userland and write to the standard output.  The write() system call is not buffered.

A: Why flush is to be avoided:
Because IO works best when the operating system can work with relatively large amounts of data. Regular flushes with small amounts of data cause slowdowns, sometimes very significantly.
Why you should almost never flush manually:
There are automatic flushes that cover most use cases. For example, if a program writes to the console, the system by default flushes after every newline. Or if you write to file, the data is written once there is enough data to be written at once, and also when the file is closed.
When you should flush manually:
If you explicitly need to update the output immediately. Example: if you create a spinner or progress bar that repeatedly overwrites the current line. Or if you output to file and really want the file to be updated at specific moments.


text:
Q: Strange SQL result order by date, count(date) I'm atm seeing a strange behaviour in a sql request.
My table pointLog:
#  Column  Type
1   date    timestamp
2   uid     varchar(30)
3   ssid    varchar(40)
4   reason  varchar(50)
5   points  int(5)          No  None
The statement:
SELECT date, count(date) as anzahl FROM pointLog WHERE uid = 1 order by date desc

returns following result
    date                anzahl
2012-09-01 12:21:16     14

But the statement:
SELECT date FROM pointLog WHERE uid = 1 order by date desc

Returns
2012-09-02 12:44:08

as first result.
So my question: why I'm not receiving the 2012-09-02 as first result in the first statement which includes a count ??
Thanks a lot!
edit
The count as anzahl is atm only used to verify that there are more than 0 entries in this example. I know its should be tested in the programm.
But my main problem is, that I can't explain, why I'm getting 2 different dates when it's sorted by the same (date). So the only difference is the count attribute. But that shouldn't normally change the sorting?
FINAL* The solution
SELECT MAX(date) AS maxdate, COUNT(date) AS anzahl FROM pointLog WHERE uid = 1

A: You're getting one results: a count of the dates, preceded by an arbitrary date. The ORDER BY statement is then ordering that, which is a no-op because there's only one line of output.

A: You need a GROUP BY in your SQL statement, otherwise the COUNT() will not give separate totals for each date.

A: As @prosfilaes answered, your query does not return deterministic results, the date returned in an arbitrary one.
If you want the latest date and the count, you can use:
SELECT
    MAX(date) AS maxdate,
    COUNT(date) AS anzahl
FROM
    pointLog
WHERE
    uid = 1 ;


text:
Q: Control cosole program from Python and pass commands I was wondering if it was possible (and how to do) to start an console program with subprocess.Popen() or something similar and output realtime output line by line, and pass commands to the command line process. I have worked and researched this, and tried over and over again, but cannot for the life of me accomplish it.
Any ideas for sample code? Say I wanted to output these to a log file in realtime, and pass commands with a graphical interface with buttons. Thanks.


text:
Q: i am facing this error when creating database through script. mysql create table arpa_acc_perfil
(
   id_account           integer not null,
   dt_create            date,
   ind_active           tinyint,
   tp_servicio          set('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20'),
   tp_propiedad         set('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20'),
   set_properties       set('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20'),
   ind_piscina          tinyint,
   num_parking          smallint,
   num_wc               smallint,
   num_dormitorios      smallint,
   int_superficie_const smallint,
   int_superficie       smallint,
   precio_alquiler      decimal(10,0),
   precio_compra        decimal(10,0),
   txt_comment          varchar(255),
   primary key (id_account)
)

type = innodb
character set = utf8
MySQL said: Documentation

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'type = innodb
  character set = utf8' at line 20

A: You query is incorrect
create table arpa_acc_perfil
(
   id_account           integer not null,
   dt_create            date,
   ind_active           tinyint,
   tp_servicio          set('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20'),
   tp_propiedad         set('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20'),
   set_properties       set('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20'),
   ind_piscina          tinyint,
   num_parking          smallint,
   num_wc               smallint,
   num_dormitorios      smallint,
   int_superficie_const smallint,
   int_superficie       smallint,
   precio_alquiler      decimal(10,0),
   precio_compra        decimal(10,0),
   txt_comment          varchar(255),
   primary key (id_account)
)

ENGINE=InnoDB
DEFAULT CHARSET = utf8

This is the correct query.


text:
Q: Prove or Disprove: A holomorphic function with the given property exists
Does there exist a holomorphic function $f:U_{1+\epsilon}(0)\rightarrow \mathbb{C}$ for all $n\in \mathbb{N}_{\ge 2}$ such that
$$
f\left(\log\left(1+\frac{1}{n}\right)\right) = \left(\frac{1}{n^2}-1\right)\left(1+\frac{1}{n}\right).
$$
where $U_{1+\epsilon}(0)$ is the open disk of radius $1+\epsilon$ centered at $0$.

I tried to use the identity theorem for holomorphic functions, but don't know how to define a function $g$ such that $g(\log(1+\frac{1}{n})= \left(\frac{1}{n^2}-1\right)\left(1+\frac{1}{n}\right)$.

A: Hint: The identity theorem suggests $f(\log(1+z)) = (z^2-1)(1+z)$ will hold. Assume it does, find an inverse to $\log(1+z),$ and see what happens.

A: Let's construct the required function "by hand". Let $z = \log \left( 1 + \frac 1 n \right)$. Then $\frac 1 n = \Bbb e ^z - 1$, so that
$$f(z) = \Big( (\Bbb e ^z - 1)^2 - 1 \Big) \Big( 1 + (\Bbb e ^z - 1) \Big) = \Bbb e ^{2z} (\Bbb e ^z - 2)$$
which is clearly seen to be holomorphic (in fact, it is entire - i.e. holomorphic on the whole $\Bbb C$, not just on $U_{1 + \epsilon}$.


text:
Q: React - How to make a Bootstrap modal show on form submit? All the answers I have seen so far concern React-Bootstrap and use the Modal component.
I am using plain React with Bootstrap separately.
I have a form which displays a bunch of custom Checkbox components.
When the form is submitted, I would like a modal to appear, displaying details pertaining to the checkboxes which were selected.
The problem is, I cannot even get the modal to appear when the form is submitted.
In the App component which contains the form, I have a state
const [showModal, setShowModal] = useState(false)

Initially, showModal is false. When the form is submitted, I call the following function
function handleSubmit(event){
    event.preventDefault()

    /*...code to retrieve checkboxes which have been selected...*/

    setShowModal(true)

}

In the return statement, after the form, I conditionally render a SelectionsModal Component:

        <form onSubmit={handleSubmit}>
            {/* Render checkbox components here */}

                <button className="btn btn-warning" type="submit">Submit</button>

        </form>

   {showModal && <SelectionsModal />}

The code for the SelectionsModal component is just the code for a simple Bootstrap modal (from their website), because at this point I just want a modal to appear (not concerned with displaying which checkboxes were selected for now).
When I submit the form, React Dev Tools shows me that the SelectionsModal component is rendered, but no modal appears. If it was just some simple div with text in the SelectionsModal, then it would conditionally appear as expected.
I am quite at a loss here, maybe there is something about Bootstrap modals that I am missing. I saw on the modal documentation that I can use the show method to manually make the modal appear, but this does not seem to work with React.
Any help is much appreciated, thanks!


text:
Q: Setting a kind of callback function to certain seconds of playing video In android, I am trying to implement an application that can play videos. In this application, I want to fire some callback functions for specific time periods of the video. For example when player plays 30th second of the video, I want to call a function f or when 1.30th second is playing function g is called.
How can I implement this functionality? I can start a timer for each function but in this case I have to track playbacks/forwards and modify timer according to these changes.. Do you have any idea?

A: I've never done this so I can't give much information but just an idea...
Assuming you're going to be using MediaPlayer then you could try extending it for a class of your own.
Within your own class you could maintain a Handler which uses postDelayed(Runnable r, long delayMillis) to trigger some code every 100ms, for example, and have it call the getCurrentPosition() method. You could then have it check the current position against a list of 'trigger points' (30 seconds, 1 min 30 seconds etc) and then perform whatever task necessary.
Doing it this way would mean if the play position is adjusted (using a seek bar, FF/RW etc) you wouldn't need to update a timer - the Runnable would simply continue checking current position without it having to 'know' about any seek changes.


text:
Q: ExtJS configure store to write list of models under a property name I have a model like this:
Ext.define('Policy', {
    extend: 'Ext.data.Model',

    fields: [
        {
            name: 'id',
            type: 'sting',
            phantom: true,
            convert: function(value, record) {
                return record.get('a') + '@' +
                    record.get('b');
            }
        },
        {name: 'a', type: 'string'},
        {name: 'b', type: 'string'}]
});

Where the PK of each record is a and b. The store looks like this:
Ext.define('Store', {
    extend: 'Ext.data.Store',
    model: 'Policy',
    autoLoad: true,

    proxy: {
        type: 'rest',
        simpleSortMode: true,
        batchActions: true,
        reader: {
            type: 'json',
            root: 'data',
            idProperty: 'id'
        },
        writer: {
            nameProperty: 'mapping'
        },
        api: {
            create:'/batch',
            read: '/policies',
            update: '/batch',
            destroy: '/batch'
        }
    }
});

How can I configure the store so that when it POSTS to /batch when calling store.sync(), the payload looks like this and only consists of dirty records:
{
    "policies": [{
        "a": "AA",
        "b": "BB",
    }, {
        "a": "AAA",
        "b": "BBB"
    },...]
}

where there is a policies property and under it is an array of dirty policies.

A: You can create whatever structure you want by making a manual Ext.Ajax() call. You have to submit only the dirty records yourself.


text:
Q: XMLStreamReader how to work with nested elements of same type I'm working with the XMLStreamReader and parsing the following XML:
<root>
    <element>
        <attribute>level0</attribute>
        <element>
            <attribute>level1</attribute>
            <element>
                <attribute>level2</attribute>
            </element>
        </element>
    </element>
</root>

I'm building out my XMLStreamReader:
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(
                new ByteArrayInputStream(document.getBytes()));

Unfortunately, when I get to the first closing element tag with reader.next();, I get the following exception:
javax.xml.stream.XMLStreamException: ParseError at [row,col]:[7,14]
Message: XML document structures must start and end within the same entity.

Is there a way to override the default behavior of the XMLStreamReader to get around with this?
EDIT
Here is the code I am working with:
@Override
protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context)
        throws IOException, InterruptedException {
    String document = value.toString();
    System.out.println("'" + document + "'");
    try {
        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(
                new ByteArrayInputStream(document.getBytes()));
        String propertyName = "";
        String propertyValue = "";
        String currentElement = "";
        while (reader.hasNext()) {
            int code = reader.next();
            switch (code) {
            case START_ELEMENT:
                currentElement = reader.getLocalName();
                break;
            case CHARACTERS:
                if (currentElement.equalsIgnoreCase("element")) {
                    propertyName += reader.getText();
                } else if (currentElement.equalsIgnoreCase("attribute")) {
                    propertyValue += reader.getText();
                }
                break;
            }
        }
        reader.close();
        context.write(new Text(propertyName.trim()), new Text(propertyValue.trim()));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

A: There is nothing wrong with the example XML document and/or the StAX parser as can be checked with this code:
@Test
public void testSO_31815379() throws XMLStreamException, UnsupportedEncodingException {
    final String xml =
        "<root>\n" +
        "    <element>\n" +
        "        <attribute>level0</attribute>\n" +
        "        <element>\n" +
        "            <attribute>level1</attribute>\n" +
        "            <element>\n" +
        "                <attribute>level2</attribute>\n" +
        "            </element>\n" +
        "        </element>\n" +
        "    </element>\n" +
        "</root>";

    final XMLStreamReader reader = XMLInputFactory.newInstance()
        .createXMLStreamReader(new ByteArrayInputStream(xml.getBytes("UTF-8")));
    LOG.info("Using XMLStreamReader implementation: %s", reader.getClass().getName());

    reader.require(XMLStreamConstants.START_DOCUMENT, null, null);
    int event;
    while ((event = reader.next()) != XMLStreamConstants.END_DOCUMENT) {
        LOG.info(StaxUtils.eventDescription(reader));
    }
    reader.require(XMLStreamConstants.END_DOCUMENT, null, null);
    reader.close();
}

Output (StaxUtils.eventDescription is a custom helper method)
Using XMLStreamReader implementation: com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl
START_ELEMENT<{}root>
CHARACTERS=<whitespace>
START_ELEMENT<{}element>
CHARACTERS=<whitespace>
START_ELEMENT<{}attribute>
CHARACTERS='level0'
END_ELEMENT<attribute>
CHARACTERS=<whitespace>
START_ELEMENT<{}element>
CHARACTERS=<whitespace>
START_ELEMENT<{}attribute>
CHARACTERS='level1'
END_ELEMENT<attribute>
CHARACTERS=<whitespace>
START_ELEMENT<{}element>
CHARACTERS=<whitespace>
START_ELEMENT<{}attribute>
CHARACTERS='level2'
END_ELEMENT<attribute>
CHARACTERS=<whitespace>
END_ELEMENT<element>
CHARACTERS=<whitespace>
END_ELEMENT<element>
CHARACTERS=<whitespace>
END_ELEMENT<element>
CHARACTERS=<whitespace>
END_ELEMENT<root>


text:
Q: Count punctuation in a text I need to count how many punctuation there is a in text. I've tried this code, but it always return 1
$pattern = '/^[\/,.;:\'@#~\[\]\{\}\\|<>`!"£$%^&*\(\)\-_=+]+$/';
$commas = 0;
do
{
$commas++;
}
while (preg_match($pattern,$_POST['text']) != FALSE);
echo $commas;

A: You can use preg_match_all() along with the POSIX class [:punct:] ...
echo preg_match_all('/[[:punct:]]/', $_POST['text']);


text:
Q: How can I get a user's Google+ ID from its email address? I have a user's Gmail e-mail address and I need to get his or her Google+ ID to get additional information about him or her, like name, and so on. Is there a way to do this using the Google APIs?

A: There is no publicly available API to identify the Google+ profile associated with an email address. There is an existing feature request you should star if you are interested in such an API.

A: Tricky, but works.
If you have a G Suite Domain (aka Google Apps) you can create a new group with  emails addreses and call Members method.Groups API response contains user ID.
https://developers.google.com/admin-sdk/directory/v1/reference/members/list
Response looks like :
{
  "kind": "admin#directory#members",
  "etag": etag,
  "members": [
    **members Resource**
  ],
  "nextPageToken": string
}

Where members rersource looks like :
{
  "kind": "admin#directory#member",
  "etag": etag,
  "id": string,
  "email": string,
  "role": string,
  "type": string
}

id is the Google+ Profile id, later you can use Google+ API with people method.

A: Google plus
login to your gmail account then Put that gmail-email address to search option.
If that user is on Google plus then you will able to see his/her profile.
If you want to create new one with specific format for you then you can get it after making few friend on it.
Google will notify you when you will pass the position.
you can create your own customized profile in it.

A: Not exactly from the email address itself, but if you have a JWT token you can get the information from that.  The id is one of the claims in the token.  So if you have a server that uses Google issued JWT tokens, decode the token.  Here's a website to view the token information:  https://jwt.ms/


text:
Q: One more step for showing $R[x,y]\cong R[x][y]$ I'm trying to show $R[x,y]\cong R[x][y]$ using the following proposition:

Let $\varphi:R\to R'$ be a ring homomorphism. Given $\alpha_1,\alpha_2,\cdots,\alpha_n\in R'$, there exists a unique homomorphism $\Phi:R[x_1,x_2,\cdots,x_n]\to R'$ such that
  $$
\Phi|_{R}=\varphi, \quad \Phi(x_i)=\alpha_i,i=1,2,\cdots,n.
$$

Consider the inclusion map $f:R\to R[x][y]$ which is a homomorphism. By the proposition above, there is a unique homomorphism $g:R[x,y]\to R[x][y]$ such that
$$
g|_R=f
$$
and $g(x)=x$, $g(y)=y$. It suffices to show that $g$ is a homomorphism. Instead of showing that $g$ is 1-1 and onto, I'm trying to construct an inverse of $g$. Consider the inclusion map $h:R[x]\to R[x,y]$. Using the proposition again, we have a unique homomorphism $l:R[x][y]\to R[x,y]$ such that
$$
l_{R[x]}=h
$$
and $l(y)=y$. It follows that we have a homomorphism
$$
l\circ g:R[x,y]\to R[x,y]
$$
such that
$$
l\circ g|_{R}=id_{R[x,y]}|_R
$$
and $l\circ g(x)=x$, $l\circ g(y)=y$.
We also have a similar argument with $$
g\circ l: R[x][y]\to R[x][y].
$$

I've only shown that $l\circ g$ agrees with the identity map $id_{R[x,y]}$ on $R$ and $\{x,y\}$. My question:

How can I show that $l\circ g$ is the identity map $id_{R[x,y]}$?
  (Then similarly, I would be able to show $g\circ l=id_{R[x][y]}$).

[EDIT:] I saw a proof in Artin's Algebra, but I didn't understand how the underscored sentence works.

A: The maps $l$ and $g$ are both ring homomorphisms, so the map $l\circ g$ is a ring homomorphism. Thus as $R[x,y]$ is generated by $R$, $x$ and $y$, and $l\circ g$ fixes these, it is the identity.
If you want to check this more carefully, you can write a general element of $R[x,y]$ in terms of $x$, $y$ and elements of $R$, apply $l\circ g$ to it, and then expand the expression using the properties of ring homomorphisms until the map $l\circ g$ is only being applied to $x$, $y$ and elements of $R$.


text:
Q: Saving object with Sequelize I am struggling with step 1 of Sequelize. I have read through the tutorial and I must be missing on something basic, for I have already spent over a day trying to figure out what I am doing wrong.
The following is a unit test I have written using Mocha.
var db = require("../../db.js").sequelize;
var DataTypes = require("sequelize");

var _table = db.define('users', {
      name: DataTypes.STRING,
      email: DataTypes.STRING
    }, {
      timestamps: false
    });

var assert = require("assert")
describe('Users', function(){
  describe('#save()', function(){
    it('should save a user', function(){
        _table
        .build({name: 'test', email: 'a@a.com'})
        .save()
        .success(function(o){
            console.log("saved");
            console.log(o.values);
        }).error(function(error) {
            console.log("++++++++++");
            console.log(error);
        });

    })
  })
})

It runs fine and I have removed the asserts for now. The problem is, I don't see either of the console logs, not success not error. Plus there's no row in the database.
The db.js is just a utility file that helps create an instance of Sequelize JS with the db configuration - I have already done a console.dir and looked through the instance and it looks as below:
{ options:
   { dialect: 'mysql',
     host: 'localhost',
     port: 3306,
     protocol: 'tcp',
     define: {},
     query: {},
     sync: {},
     logging: [Function],
     omitNull: false,
     queue: true,
     native: false,
     replication: false,
     pool: { maxConnections: 10, minConnections: 0, maxIdleTime: 1000 } },
  config:
   { database: 'beacon',
     username: 'beacon',
     password: 'beacon',
     host: 'localhost',
     port: 3306,
     pool: { maxConnections: 10, minConnections: 0, maxIdleTime: 1000 },
     protocol: 'tcp',
     queue: true,
     native: false,
     replication: false,
     maxConcurrentQueries: undefined },
  daoFactoryManager: { daos: [ [Object], [Object] ], sequelize: [Circular] },
  connectorManager:
   { sequelize: [Circular],
     client: null,
     config:
      { database: 'beacon',
        username: 'beacon',
        password: 'beacon',
        host: 'localhost',
        port: 3306,
        pool: [Object],
        protocol: 'tcp',
        queue: true,
        native: false,
        replication: false,
        maxConcurrentQueries: undefined },
     disconnectTimeoutId: null,
     queue: [],
     activeQueue: [ [Object] ],
     maxConcurrentQueries: 50,
     poolCfg: { maxConnections: 10, minConnections: 0, maxIdleTime: 1000 },
     pendingQueries: 0,
     useReplicaton: false,
     useQueue: true,
     pool:
      { destroy: [Function],
        acquire: [Function],
        borrow: [Function],
        release: [Function],
        returnToPool: [Function],
        drain: [Function],
        destroyAllNow: [Function],
        getPoolSize: [Function],
        getName: [Function],
        availableObjectsCount: [Function],
        waitingClientsCount: [Function] },
     isConnecting: false },
  importCache: {},
  queryInterface:
   { sequelize: [Circular],
     QueryGenerator:
      { createTableQuery: [Function],
        dropTableQuery: [Function],
        renameTableQuery: [Function],
        showTablesQuery: [Function],
        addColumnQuery: [Function],
        removeColumnQuery: [Function],
        changeColumnQuery: [Function],
        renameColumnQuery: [Function],
        selectQuery: [Function],
        insertQuery: [Function],
        updateQuery: [Function],
        deleteQuery: [Function],
        incrementQuery: [Function],
        addIndexQuery: [Function],
        showIndexQuery: [Function],
        removeIndexQuery: [Function],
        getWhereConditions: [Function],
        hashToWhereConditions: [Function],
        attributesToSQL: [Function],
        findAutoIncrementField: [Function],
        addQuotes: [Function],
        removeQuotes: [Function],
        options: [Object] } } }

Now I get the INSERT statement logged on the screen, but the instance never makes it to the db. what am I doing wrong?

A: the problem was not with sequelize, but with the fact that it was async code. To fix this, simply modify the test:
var db = require("../../db.js").sequelize;
var DataTypes = require("sequelize");

var _table = db.define('users', {
      name: DataTypes.STRING,
      email: DataTypes.STRING
    }, {
      timestamps: false
    });

var assert = require("assert")
describe('Users', function(){
  describe('#save()', function(){
    it('should save a user', function(done){
        _table
        .build({name: 'test', email: 'a@a.com'})
        .save()
        .success(function(o){
            console.log("saved");
            console.log(o.values);
            done();
        }).error(function(error) {
            console.log("++++++++++");
            console.log(error);
            done();
        });

    })
  })
})

Adding the callback (done) helps!


text:
Q: Make Git repo public without revealing past commits I have a private repo that had a bunch of sensitive data committed.  However, I recently cleaned up all of the sensitive data so that it can be public.  If I change a private repo on GitHub to become public, are all past commits visible (i.e. could someone see that sensitive data from the past)?
If so, how do I make the repo public without making the past commit history public?

A: I'd recommend cloning (or just copying all the non .git files) from the current repo into a new repo and then pushing the new repo out as public.

A: Go to desired commit:
git checkout <your_commit_hash>

Go down to the initial commit leaving all current changes:
git reset <intial_commit_hash_here> --soft

Then commit with amend option
git commit --amend -m"My new initial commit"

And then you are ready to push to your public repo
git push <your_remote> master

P.S.
The original change history will still be available with git reflog but will not be pushed to remote repo

UPD.
To get the id of the first commit use the command from this answer:
git rev-list --max-parents=0 HEAD


text:
Q: ssrs specific value true/false/all I have a parameter @ResourceSatus, which should has 3 options: true/false/all.
It works well with true/false, but when i add "all" it doesn't show anything. I use filter as explained in this post: SQL Reporting Services Boolean Parameter (True/False/All(?))
I don't understand what should put for ObjectFieldName.Value. Appriciated for answers

A: =IIF(IsNothing(Parameters!parmTRUEFALSE.Value), ObjectFieldName.Value, Parameters!parmTRUEFALSE.Value) is the code from the other question.
ObjectFieldName is just the name of the object you would want to display if IsNothing(Parameters!parmTRUEFALSE.Value) equates to true. If you're pulling from a database field named Example, ObjectFieldName would be replaced with Fields!FirstDegreeYear.Value.


text:
Q: Manual Painting Issue I'm having some strange drawing artefacts that I'm hoping someone might be able to help me pin down.
Basically I have a left docked panel that is supposed to have a gradient background that hasn't been working right. I've changed the colours for debugging
screenshot http://img509.imageshack.us/img509/5650/18740614.png
The panel is docked left, and has a transparent control on it (hence you can see small stubs of red along the edges where the transparent control has correctly been painted, picking up the background colour).
When I resize the panel slowly however, I get red lines left at the bottom, which I would expected to be covered up by yellow fills. The code I'm using is as follows:
// Construction
sidePanel.Paint += new PaintEventHandler(OnPaint);

private void OnPaint(object sender, System.Windows.Forms.PaintEventArgs e)
{
   Panel pb = sender as Panel;
   PaintControl(pb.Width, pb.Height, sender, e, true);
}

private static void PaintControl(int width, int height, object sender, PaintEventArgs e, bool sidebar)
{
    Rectangle baseRectangle = new Rectangle(0, 0, width -1, height-1);

    using (LinearGradientBrush gradientBrush = new LinearGradientBrush(baseRectangle, WizardBaseForm.StartColour, WizardBaseForm.EndColour, 90))
    {
        e.Graphics.Clear(Color.Yellow);
        e.Graphics.DrawRectangle(Pens.Red, baseRectangle);
        e.Graphics.FillRectangle(Brushes.Yellow, baseRectangle);
    }
}

protected override void OnResize(EventArgs e)
{
   base.OnResize(e);
   this.Invalidate();
}

The overall effect of this is I'm not getting either a nice solid colour, or a nice gradient fill when I resize.

A: I would suggest creating your own panel, derive it from panel and place the following in the constructor:
  this.SetStyle(ControlStyles.AllPaintingInWmPaint
              | ControlStyles.OptimizedDoubleBuffer
              | ControlStyles.ResizeRedraw
              | ControlStyles.DoubleBuffer
              | ControlStyles.UserPaint
              , true);

A: Add following in New (after InitializeComponents):
this.SetStyle(ControlStyles.ResizeRedraw, true);

This is to ensure painting on resize.
There are few additional styles that you may try (AllPaintingInWmPaint, UserPaint...) but whether they should be set or not depends on your particular case and what exactly you want to do. In case that all painting is done by you in Paint event, I would set them.