Programs & Examples On #Llblgen

LLBLGen Pro generates a complete data-access tier and a business objects tier, utilizing powerful O/R mapping technology and a flexible task-based code generator.

Why is HttpContext.Current null?

try to implement Application_AuthenticateRequest instead of Application_Start.

this method has an instance for HttpContext.Current, unlike Application_Start (which fires very soon in app lifecycle, soon enough to not hold a HttpContext.Current object yet).

hope that helps.

Concatenate two char* strings in a C program

strcat concats str2 onto str1

You'll get runtime errors because str1 is not being properly allocated for concatenation

Visual studio code terminal, how to run a command with administrator rights?

Step 1: Restart VS Code as an adminstrator

(click the windows key, search for "Visual Studio Code", right click, and you'll see the administrator option)

Step 2: In your VS code powershell terminal run Set-ExecutionPolicy Unrestricted

How does one create an InputStream from a String?

You could do this:

InputStream in = new ByteArrayInputStream(string.getBytes("UTF-8"));

Note the UTF-8 encoding. You should specify the character set that you want the bytes encoded into. It's common to choose UTF-8 if you don't specifically need anything else. Otherwise if you select nothing you'll get the default encoding that can vary between systems. From the JavaDoc:

The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.

Local storage in Angular 2

How to store, retrieve & delete data from localStorage:

// General syntax for storing data
localStorage.setItem('key', 'value');
// Also note that both the key & the value has to be strings. So we stringify the value(if it's an object) before setting it.

// So, if you have an object as a value that you want to save, stringify it like this
localStorage.setItem('some-key', JSON.stringify(itemData));

// OR for individual key-value pairs
localStorage.setItem('some-key', JSON.stringify({ token: token, name: name }));

// To retrieve data from localstorage
const myData = JSON.parse(localStorage.getItem('some-key'));

// To remove a value/item from localStorage
localStorage.removeItem("some-key");


// see a note at the end of this answer for tips about 
// using an angular package for a cleaner & smoother storage usage.

A quick tip:
You can also use a package for your angular app, that is based on native localStorage API (that we are using above) to achieve this and you don't have to worry about stringify and parse. Check out this package for angular 5 and above. @ngx-pwa/local-storage

You can also do a quick google search for maybe ,angular local storage, & find a package that has even more Github stars etc.

Check out this page to know more about Web Storage API.

Embedding DLLs in a compiled executable

If they're actually managed assemblies, you can use ILMerge. For native DLLs, you'll have a bit more work to do.

See also: How can a C++ windows dll be merged into a C# application exe?

Automated testing for REST Api

I have used TestNG and Apache HTTP classes to build my own REST API test framework, I developed this concept after working in Selenium for two years.

Everything is same, except you should use Apache HTTP classes instead of Selenium classes.

give a try, its really cute and good, you've all the power to customize your test framework to your fullest possibilities.

Xcode error "Could not find Developer Disk Image"

This happens when your Xcode version doesn't have a necessary component to build the application to your target OS. You should update your Xcode.

If you are building a new application for a beta OS version that no stable Xcode version is able to build, you should download the newest Xcode beta version.

I also had this problem. I was using Xcode 7.3 for my iOS 10 beta iPhone, so I went to install Xcode 8-beta, and I did the following step to continue using the stable version of Xcode with new build tool:

Just like @onmyway133 answer, but more user-friendly is after finish installing the Xcode 8-beta version, go to Xcode 7.3 preferences (Cmd + ,), go to the tab locations, change the Command Line Tools to Xcode 8 in the dropdown list.

I successfully built to both iOS simulator 9.3 and my device iOS 10 beta using Xcode 7.3.

How to use Object.values with typescript?

I just hit this exact issue with Angular 6 using the CLI and workspaces to create a library using ng g library foo.

In my case the issue was in the tsconfig.lib.json in the library folder which did not have es2017 included in the lib section.

Anyone stumbling across this issue with Angular 6 you just need to ensure that you update you tsconfig.lib.json as well as your application tsconfig.json

Redis command to get all available keys?

Take a look at following Redis Cheat Sheet. To get a subset of redis keys with the redis-cli i use the command

KEYS "prefix:*"

Order discrete x scale by frequency/value

Try manually setting the levels of the factor on the x-axis. For example:

library(ggplot2)
# Automatic levels
ggplot(mtcars, aes(factor(cyl))) + geom_bar()    

ggplot of the cars dataset with factor levels automatically determined

# Manual levels
cyl_table <- table(mtcars$cyl)
cyl_levels <- names(cyl_table)[order(cyl_table)]
mtcars$cyl2 <- factor(mtcars$cyl, levels = cyl_levels)
# Just to be clear, the above line is no different than:
# mtcars$cyl2 <- factor(mtcars$cyl, levels = c("6","4","8"))
# You can manually set the levels in whatever order you please. 
ggplot(mtcars, aes(cyl2)) + geom_bar()

ggplot of the cars dataset with factor levels reordered manually

As James pointed out in his answer, reorder is the idiomatic way of reordering factor levels.

mtcars$cyl3 <- with(mtcars, reorder(cyl, cyl, function(x) -length(x)))
ggplot(mtcars, aes(cyl3)) + geom_bar()

ggplot of the cars dataset with factor levels reordered using the reorder function

Does SVG support embedding of bitmap images?

You can use a data: URL to embed a Base64 encoded version of an image. But it's not very efficient and wouldn't recommend embedding large images. Any reason linking to another file is not feasible?

Importing the private-key/public-certificate pair in the Java KeyStore

With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.

# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12

# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert

To verify the contents of the JKS, you can use this command:

keytool -list -v -keystore mykeystore.jks

If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.

How can one run multiple versions of PHP 5.x on a development LAMP server?

Understanding that you're probably talking about a local/desktop machine and would probably like to continue talking about a local/desktop machine, I'll throw an alternative out there for you just in case it might help you or someone else:

Set up multiple virtual server instances in the cloud, and share your code between them as a git repository (or mercurial, I suppose, though I have no personal experience all you really need is something decentralized). This has the benefit of giving you as close to a production experience as possible, and if you have experience setting up servers then it's not that complicated (or expensive, if you just want to spin a server up, do what you need to do, then spin it down again, then you're talking about a few cents up to say 50 cents, up to a few bucks if you just leave it running).

I do all of my project development in the cloud these days and I've found it much simpler to manage the infrastructure than I ever did when using local/non-virtualized installs, and it makes this sort of side-by-side scenario fairly straight forward. I just wanted to throw the idea out there if you hadn't considered it.

IOS: verify if a point is inside a rect

In Swift that would look like this:

let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = CGRectContainsPoint(someFrame, point)

Swift 3 version:

let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = someFrame.contains(point)

Link to documentation . Please remember to check containment if both are in the same coordinate system if not then conversions are required (some example)

Changing ImageView source

Changing ImageView source:

Using setBackgroundResource() method:

  myImgView.setBackgroundResource(R.drawable.monkey);

you are putting that monkey in the background.

I suggest the use of setImageResource() method:

  myImgView.setImageResource(R.drawable.monkey);

or with setImageDrawable() method:

myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey));

*** With new android API 22 getResources().getDrawable() is now deprecated. This is an example how to use now:

myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey, getApplicationContext().getTheme()));

and how to validate for old API versions:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
     myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey, getApplicationContext().getTheme()));
   } else {
     myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey));
}

Changing color of Twitter bootstrap Nav-Pills

If you don't want to include any extra CSS you can just use the button color classes into the nav-link element, it will format the pill just the same as a regular button.

_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>_x000D_
_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>_x000D_
_x000D_
<ul class="nav nav-pills p-3">_x000D_
    <li class="nav-item">_x000D_
        <a class="nav-link active" href="#">Normal</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
        <a class="nav-link active btn-primary" href="#">Primary</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
        <a class="nav-link active btn-secondary" href="#">Secondary</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
        <a class="nav-link active btn-success" href="#">Success</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
        <a class="nav-link active btn-warning" href="#">Warning</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
        <a class="nav-link active btn-danger" href="#">Danger</a>_x000D_
    </li>_x000D_
_x000D_
</ul>
_x000D_
_x000D_
_x000D_

static const vs #define

Defining constants by using preprocessor directive #define is not recommended to apply not only in C++, but also in C. These constants will not have the type. Even in C was proposed to use const for constants.

How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?

This answer is quite similar to the accepted answer, but doesn't override the Date prototype, and only uses one function call to check if Daylight Savings Time is in effect, rather than two.


The idea is that, since no country observes DST that lasts for 7 months[1], in an area that observes DST the offset from UTC time in January will be different to the one in July.

While Daylight Savings Time moves clocks forwards, JavaScript always returns a greater value during Standard Time. Therefore, getting the minimum offset between January and July will get the timezone offset during DST.

We then check if the dates timezone is equal to that minimum value. If it is, then we are in DST; otherwise we are not.

The following function uses this algorithm. It takes a date object, d, and returns true if daylight savings time is in effect for that date, and false if it is not:

function isDST(d) {
    let jan = new Date(d.getFullYear(), 0, 1).getTimezoneOffset();
    let jul = new Date(d.getFullYear(), 6, 1).getTimezoneOffset();
    return Math.max(jan, jul) != d.getTimezoneOffset(); 
}

how to convert a string to an array in php

You can achieve this even without using explode and implode function. Here is the example:

Input:

This is my world

Code:

$part1 = "This is my world"; 
$part2 = str_word_count($part1, 1);

Output:

Array( [0] => 'This', [1] => 'is', [2] => 'my', [3] => 'world');

Access parent URL from iframe

For pages on the same domain and different subdomain, you can set the document.domain property via javascript.

Both the parent frame and the iframe need to set their document.domain to something that is common betweeen them.

i.e. www.foo.mydomain.com and api.foo.mydomain.com could each use either foo.mydomain.com or just mydomain.com and be compatible (no, you can't set them both to com, for security reasons...)

also, note that document.domain is a one way street. Consider running the following three statements in order:

// assume we're starting at www.foo.mydomain.com
document.domain = "foo.mydomain.com" // works
document.domain = "mydomain.com" // works
document.domain = "foo.mydomain.com" // throws a security exception

Modern browsers can also use window.postMessage to talk across origins, but it won't work in IE6. https://developer.mozilla.org/en/DOM/window.postMessage

MySQL SELECT last few days?

SELECT DATEDIFF(NOW(),pickup_date) AS noofday 
FROM cir_order 
WHERE DATEDIFF(NOW(),pickup_date)>2;

or

SELECT * 
FROM cir_order 
WHERE cir_order.`cir_date` >= DATE_ADD( CURDATE(), INTERVAL -10 DAY )

How to fix the height of a <div> element?

change the div to display block

.topbar{
    display:block;
    width:100%;
    height:70px;
    background-color:#475;
    overflow:scroll;
    }

i made a jsfiddle example here please check

http://jsfiddle.net/TgPRM/

How to multiply duration by integer?

You have to cast it to a correct format Playground.

yourTime := rand.Int31n(1000)
time.Sleep(time.Duration(yourTime) * time.Millisecond)

If you will check documentation for sleep, you see that it requires func Sleep(d Duration) duration as a parameter. Your rand.Int31n returns int32.

The line from the example works (time.Sleep(100 * time.Millisecond)) because the compiler is smart enough to understand that here your constant 100 means a duration. But if you pass a variable, you should cast it.

Getting mouse position in c#

If you don't want to reference Forms you can use interop to get the cursor position:

using System.Runtime.InteropServices;
using System.Windows; // Or use whatever point class you like for the implicit cast operator

/// <summary>
/// Struct representing a point.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
    public int X;
    public int Y;

    public static implicit operator Point(POINT point)
    {
        return new Point(point.X, point.Y);
    }
}

/// <summary>
/// Retrieves the cursor's position, in screen coordinates.
/// </summary>
/// <see>See MSDN documentation for further information.</see>
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);

public static Point GetCursorPosition()
{
    POINT lpPoint;
    GetCursorPos(out lpPoint);
    // NOTE: If you need error handling
    // bool success = GetCursorPos(out lpPoint);
    // if (!success)
        
    return lpPoint;
}

How to create a temporary directory and get the path / file name in Python

If I get your question correctly, you want to also know the names of the files generated inside the temporary directory? If so, try this:

import os
import tempfile

with tempfile.TemporaryDirectory() as tmp_dir:
    # generate some random files in it
     files_in_dir = os.listdir(tmp_dir)

Use querystring variables in MVC controller

My problem was overwriting my query string parameters with default values:

routes.MapRoute(
    "apiRoute", 
    "api/{action}/{key}", 
    new { controller = "Api", action = "Prices", key = ""}
);

No matter what I plugged into query string or how only key="" results.

Then got rid of default overwrites using UrlParameter.Optional:

routes.MapRoute(
    "apiRoute", 
    "api/{action}/{key}", 
    new { controller = "Api", action = "Prices", key = UrlParameter.Optional }
);

now

prices/{key} 

or

prices?key={key} 

both work fine.

SQL WITH clause example

The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query. The name assigned to the sub-query is treated as though it was an inline view or table. The SQL WITH clause is basically a drop-in replacement to the normal sub-query.

Syntax For The SQL WITH Clause

The following is the syntax of the SQL WITH clause when using a single sub-query alias.

WITH <alias_name> AS (sql_subquery_statement)
SELECT column_list FROM <alias_name>[,table_name]
[WHERE <join_condition>]

When using multiple sub-query aliases, the syntax is as follows.

WITH <alias_name_A> AS (sql_subquery_statement),
<alias_name_B> AS(sql_subquery_statement_from_alias_name_A
or sql_subquery_statement )
SELECT <column_list>
FROM <alias_name_A>, <alias_name_B> [,table_names]
[WHERE <join_condition>]

In the syntax documentation above, the occurrences of alias_name is a meaningful name you would give to the sub-query after the AS clause. Each sub-query should be separated with a comma Example for WITH statement. The rest of the queries follow the standard formats for simple and complex SQL SELECT queries.

For more information: http://www.brighthub.com/internet/web-development/articles/91893.aspx

Threading pool similar to the multiprocessing Pool?

For something very simple and lightweight (slightly modified from here):

from Queue import Queue
from threading import Thread


class Worker(Thread):
    """Thread executing tasks from a given tasks queue"""
    def __init__(self, tasks):
        Thread.__init__(self)
        self.tasks = tasks
        self.daemon = True
        self.start()

    def run(self):
        while True:
            func, args, kargs = self.tasks.get()
            try:
                func(*args, **kargs)
            except Exception, e:
                print e
            finally:
                self.tasks.task_done()


class ThreadPool:
    """Pool of threads consuming tasks from a queue"""
    def __init__(self, num_threads):
        self.tasks = Queue(num_threads)
        for _ in range(num_threads):
            Worker(self.tasks)

    def add_task(self, func, *args, **kargs):
        """Add a task to the queue"""
        self.tasks.put((func, args, kargs))

    def wait_completion(self):
        """Wait for completion of all the tasks in the queue"""
        self.tasks.join()

if __name__ == '__main__':
    from random import randrange
    from time import sleep

    delays = [randrange(1, 10) for i in range(100)]

    def wait_delay(d):
        print 'sleeping for (%d)sec' % d
        sleep(d)

    pool = ThreadPool(20)

    for i, d in enumerate(delays):
        pool.add_task(wait_delay, d)

    pool.wait_completion()

To support callbacks on task completion you can just add the callback to the task tuple.

Horizontal Scroll Table in Bootstrap/CSS

You can also check for bootstrap datatable plugin as well for above issue.

It will have a large column table scrollable feature with lot of other options

$(document).ready(function() {
    $('#example').dataTable( {
        "scrollX": true
    } );
} );

for more info with example please check out this link

Adding hours to JavaScript Date object?

This is a easy way to get incremented or decremented data value.

const date = new Date()
const inc = 1000 * 60 * 60 // an hour
const dec = (1000 * 60 * 60) * -1 // an hour

const _date = new Date(date)
return new Date( _date.getTime() + inc )
return new Date( _date.getTime() + dec )

C# - Print dictionary

There's more than one way to skin this problem so here's my solution:

  1. Use Select() to convert the key-value pair to a string;
  2. Convert to a list of strings;
  3. Write out to the console using ForEach().
dict.Select(i => $"{i.Key}: {i.Value}").ToList().ForEach(Console.WriteLine);

How to get setuptools and easy_install?

apt-get install python-setuptools python-pip

or

apt-get install python3-setuptools python3-pip

you'd also want to install the python packages...

How to properly and completely close/reset a TcpClient connection?

Given that the accepted answer is outdated and I see nothing in the other answers regarding this I am creating a new one. In .Net 2, and earlier, you had to manually close the stream before closing the connection. That bug is fixed in all later versions of TcpClient in C# and as stated in the doc of the Close method a call to the method Close closes both the connection and the stream

EDIT according to Microsoft Docs

The Close method marks the instance as disposed and requests that the associated Socket close the TCP connection. Based on the LingerState property, the TCP connection may stay open for some time after the Close method is called when data remains to be sent. There is no notification provided when the underlying connection has completed closing.

Calling this method will eventually result in the close of the associated Socket and will also close the associated NetworkStream that is used to send and receive data if one was created.

How to do a redirect to another route with react-router?

1) react-router > V5 useHistory hook:

If you have React >= 16.8 and functional components you can use the useHistory hook from react-router.

import React from 'react';
import { useHistory } from 'react-router-dom';

const YourComponent = () => {
    const history = useHistory();

    const handleClick = () => {
        history.push("/path/to/push");
    }

    return (
        <div>
            <button onClick={handleClick} type="button" />
        </div>
    );
}

export default YourComponent;

2) react-router > V4 withRouter HOC:

As @ambar mentioned in the comments, React-router has changed their code base since their V4. Here are the documentations - official, withRouter

import React, { Component } from 'react';
import { withRouter } from "react-router-dom";

class YourComponent extends Component {
    handleClick = () => {
        this.props.history.push("path/to/push");
    }

    render() {
        return (
            <div>
                <button onClick={this.handleClick} type="button">
            </div>
        );
    };
}

export default withRouter(YourComponent);

3) React-router < V4 with browserHistory

You can achieve this functionality using react-router BrowserHistory. Code below:

import React, { Component } from 'react';
import { browserHistory } from 'react-router';

export default class YourComponent extends Component {
    handleClick = () => {
        browserHistory.push('/login');
    };

    render() {
        return (
            <div>
                <button onClick={this.handleClick} type="button">
            </div>
        );
    };
}

4) Redux connected-react-router

If you have connected your component with redux, and have configured connected-react-router all you have to do is this.props.history.push("/new/url"); ie, you don't need withRouter HOC to inject history to the component props.

// reducers.js
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';

export default (history) => combineReducers({
    router: connectRouter(history),
    ... // rest of your reducers
});


// configureStore.js
import { createBrowserHistory } from 'history';
import { applyMiddleware, compose, createStore } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import createRootReducer from './reducers';
...
export const history = createBrowserHistory();

export default function configureStore(preloadedState) {
    const store = createStore(
        createRootReducer(history), // root reducer with router state
        preloadedState,
        compose(
            applyMiddleware(
                routerMiddleware(history), // for dispatching history actions
                // ... other middlewares ...
            ),
        ),
    );

    return store;
}


// set up other redux requirements like for eg. in index.js
import { Provider } from 'react-redux';
import { Route, Switch } from 'react-router';
import { ConnectedRouter } from 'connected-react-router';
import configureStore, { history } from './configureStore';
...
const store = configureStore(/* provide initial state if any */)

ReactDOM.render(
    <Provider store={store}>
        <ConnectedRouter history={history}>
            <> { /* your usual react-router v4/v5 routing */ }
                <Switch>
                    <Route exact path="/yourPath" component={YourComponent} />
                </Switch>
            </>
        </ConnectedRouter>
    </Provider>,
    document.getElementById('root')
);


// YourComponent.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
...

class YourComponent extends Component {
    handleClick = () => {
        this.props.history.push("path/to/push");
    }

    render() {
        return (
          <div>
            <button onClick={this.handleClick} type="button">
          </div>
        );
      }
    };

}

export default connect(mapStateToProps = {}, mapDispatchToProps = {})(YourComponent);

Remove padding or margins from Google Charts

By adding and tuning some configuration options listed in the API documentation, you can create a lot of different styles. For instance, here is a version that removes most of the extra blank space by setting the chartArea.width to 100% and chartArea.height to 80% and moving the legend.position to bottom:

// Set chart options
var options = {'title': 'How Much Pizza I Ate Last Night',
               'width': 350,
               'height': 400,
               'chartArea': {'width': '100%', 'height': '80%'},
               'legend': {'position': 'bottom'}
    };

If you want to tune it more, try changing these values or using other properties from the link above.

Disable click outside of bootstrap modal area to close modal

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-keyboard="false" data-backdrop="static">

try this,During my application development ...I also met the trouble that default values for a model attribute => data-keyboard="true", => data-backdrop="non static"

Hope this will help you!

How do I find the length/number of items present for an array?

I'm not sure that i know exactly what you mean.

But to get the length of an initialized array,

doesn't strlen(string) work ??

PHP JSON String, escape Double Quotes for JS output

I succefully just did this :

$json = str_replace("\u0022","\\\\\"",json_encode( $phpArray,JSON_HEX_QUOT)); 

json_encode() by default will escape " to \" . But it's still wrong JSON for json.PARSE(). So by adding option JSON_HEX_QUOT, json_encode() will replace " with \u0022. json.PARSE() still will not like \u0022. So then we need to replace \u0022 with \\". The \\\\\" is escaped \\".

NOTE : you can add option JSON_HEX_APOS to replace single quote with unicode HEX value if you have javascript single quote issue.

ex: json_encode( $phpArray, JSON_HEX_APOS|JSON_HEX_QUOT ));

Querying DynamoDB by date

Updated Answer:

DynamoDB allows for specification of secondary indexes to aid in this sort of query. Secondary indexes can either be global, meaning that the index spans the whole table across hash keys, or local meaning that the index would exist within each hash key partition, thus requiring the hash key to also be specified when making the query.

For the use case in this question, you would want to use a global secondary index on the "CreatedAt" field.

For more on DynamoDB secondary indexes see the secondary index documentation

Original Answer:

DynamoDB does not allow indexed lookups on the range key only. The hash key is required such that the service knows which partition to look in to find the data.

You can of course perform a scan operation to filter by the date value, however this would require a full table scan, so it is not ideal.

If you need to perform an indexed lookup of records by time across multiple primary keys, DynamoDB might not be the ideal service for you to use, or you might need to utilize a separate table (either in DynamoDB or a relational store) to store item metadata that you can perform an indexed lookup against.

Concept of void pointer in C programming

You should be aware that in C, unlike Java or C#, there is absolutely no possibility to successfully "guess" the type of object a void* pointer points at. Something similar to getClass() simply doesn't exist, since this information is nowhere to be found. For that reason, the kind of "generic" you are looking for always comes with explicit metainformation, like the int b in your example or the format string in the printf family of functions.

Error Message: Type or namespace definition, or end-of-file expected

This line:

public  object Hours { get; set; }}

Your have a redundand } at the end

MySql Error: 1364 Field 'display_name' doesn't have default value

All of these answers are a good way, but I don't think you want to always go to your DB and modify the default value that you have set to NULL.

I suggest you go to the app/User.php and modify the protected $fillable so it will take your new fields in the data array used to register.

Let's say you add a new input field called "first_name", your $fillable should be something like this :

protected $fillable = [ 'first_name', 'email', 'password',]; 

This did it for me. Good luck!

How do I access refs of a child component in the parent component

Using Ref forwarding you can pass the ref from parent to further down to a child.

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
  1. Create a React ref by calling React.createRef and assign it to a ref variable.
  2. Pass your ref down to by specifying it as a JSX attribute.
  3. React passes the ref to the (props, ref) => ... function inside forwardRef as a second argument.
  4. Forward this ref argument down to by specifying it as a JSX attribute.
  5. When the ref is attached, ref.current will point to the DOM node.

Note The second ref argument only exists when you define a component with React.forwardRef call. Regular functional or class components don’t receive the ref argument, and ref is not available in props either.

Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.

Reference: React Documentation.

ipynb import another ipynb file

Please make sure that you also add a __init__.py file in the package where all your other .ipynb files are located.

This is in addition to the nbviewer link that minrk and syi provided above.

I also had some similar problem and then I wrote the solution as well as a link to my public google drive folder which has a working example :)

My Stackoverflow post with step by step experimentation and Solution:

Jupyter Notebook: Import .ipynb file and access it's method in other .ipynb file giving error

Hope this will help others as well. Thanks all!

LINQ: "contains" and a Lambda query

Here is how you can use Contains to achieve what you want:

buildingStatus.Select(item => item.GetCharValue()).Contains(v.Status) this will return a Boolean value.

Meaning of "n:m" and "1:n" in database design

m:n is used to denote a many-to-many relationship (m objects on the other side related to n on the other) while 1:n refers to a one-to-many relationship (1 object on the other side related to n on the other).

SQL Server find and replace specific word in all rows of specific column

You can also export the database and then use a program like notepad++ to replace words and then inmport aigain.

How to split a file into equal parts, without breaking individual lines?

If you mean an equal number of lines, split has an option for this:

split --lines=75

If you need to know what that 75 should really be for N equal parts, its:

lines_per_part = int(total_lines + N - 1) / N

where total lines can be obtained with wc -l.

See the following script for an example:

#!/usr/bin/bash

# Configuration stuff

fspec=qq.c
num_files=6

# Work out lines per file.

total_lines=$(wc -l <${fspec})
((lines_per_file = (total_lines + num_files - 1) / num_files))

# Split the actual file, maintaining lines.

split --lines=${lines_per_file} ${fspec} xyzzy.

# Debug information

echo "Total lines     = ${total_lines}"
echo "Lines  per file = ${lines_per_file}"    
wc -l xyzzy.*

This outputs:

Total lines     = 70
Lines  per file = 12
  12 xyzzy.aa
  12 xyzzy.ab
  12 xyzzy.ac
  12 xyzzy.ad
  12 xyzzy.ae
  10 xyzzy.af
  70 total

More recent versions of split allow you to specify a number of CHUNKS with the -n/--number option. You can therefore use something like:

split --number=l/6 ${fspec} xyzzy.

(that's ell-slash-six, meaning lines, not one-slash-six).

That will give you roughly equal files in terms of size, with no mid-line splits.

I mention that last point because it doesn't give you roughly the same number of lines in each file, more the same number of characters.

So, if you have one 20-character line and 19 1-character lines (twenty lines in total) and split to five files, you most likely won't get four lines in every file.

Check if a div exists with jquery

The first is the most concise, I would go with that. The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. The third is plain wrong, because that condition will always evaluate true because the object will never be null or falsy for that matter.

Delete a row from a SQL Server table

If you are using MySql Wamp. This code work.

string con="SERVER=localhost; user id=root; password=; database=dbname";
public void delete()
{
try
{
MySqlConnection connect = new MySqlConnection(con);
MySqlDataAdapter da = new MySqlDataAdapter();
connect.Open();
da.DeleteCommand = new MySqlCommand("DELETE FROM table WHERE ID='" + ID.Text + "'", connect);
da.DeleteCommand.ExecuteNonQuery();

MessageBox.Show("Successfully Deleted");
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}

Generating an array of letters in the alphabet

4 ways get English alphabet in Console:

public void ShowEnglishAlphabet()
{
    var firstLetter = 'a';
    var endLetter = 'z';
    for (var letter = firstLetter; letter <= endLetter; letter++)
    {
        Console.WriteLine($"{letter}-{letter.ToString().ToUpper()}");
    }
}

public void ShowEnglishAlphabetFromUnicodeTableDecNumber()
{
    var firstLetter = 97;
    var endLetter = 122;
    for (var letterNumberUnicodeTable = firstLetter; 
    letterNumberUnicodeTable <= endLetter; letterNumberUnicodeTable++)
    {
        Console.WriteLine($"{(char)letterNumberUnicodeTable}- 
        {((char)letterNumberUnicodeTable).ToString().ToUpper()}");
    }
}

public void ShowEnglishAlphabetUnicodeTableEscapeSequence()
{
    var firstLetter = '\u0061';
    var endLetter = '\u007A';
    for (var letterNumberUnicodeTable = firstLetter; 
    letterNumberUnicodeTable <= endLetter; letterNumberUnicodeTable++)
    {
        Console.WriteLine($"{letterNumberUnicodeTable}- 
        {letterNumberUnicodeTable.ToString().ToUpper()}");
    }
}   

public void ShowEnglishAlphabetUnicodeTableLinq()
{
    var alphabets = Enumerable.Range('a', 26).Select(letter => 
    ((char)letter).ToString()).ToList();
    foreach (var letter in alphabets)
    {
        Console.WriteLine($"{letter}-{letter.ToUpper()}");
    }
}

How to enable MySQL Query Log?

I had to drop and recreate the general log at one point. During the recreation, character sets got messed up and I ended up having this error in the logs:

[ERROR] Incorrect definition of table mysql.general_log: expected the type of column 'user_host' at position 1 to have character set 'utf8' but found character set 'latin1'

So if the standard answer of "check to make sure logging is on" doesn't work for you, check to make sure your fields have the right character set.

Property 'value' does not exist on type 'Readonly<{}>'

I suggest to use

for string only state values

export default class Home extends React.Component<{}, { [key: string]: string }> { }

for string key and any type of state values

export default class Home extends React.Component<{}, { [key: string]: any}> { }

for any key / any values

export default class Home extends React.Component<{}, { [key: any]: any}> {}

how to run a winform from console application?

You can create a winform project in VS2005/ VS2008 and then change its properties to be a command line application. It can then be started from the command line, but will still open a winform.

How to remove text before | character in notepad++

Please use regex to remove anything before |

example

dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds

Use find and replace in notepad++

find: .+(\|) replace: \1

output

| fdfsfsf
|gfghhghg
|dfdsfsds

Returning value from Thread

From Java 8 onwards we have CompletableFuture. On your case, you may use the method supplyAsync to get the result after execution.

Please find some reference here.

    CompletableFuture<Integer> completableFuture
      = CompletableFuture.supplyAsync(() -> yourMethod());

   completableFuture.get() //gives you the value

Proper way to exit iPhone application?

The user should decide when an app exits. I don't think it is a good user interaction when an app quits. Therefore there is no nice API for it, only the home button has one.

If there is an error: Implement it better or Notify the user. If there have to be a restart: Implement it better of Notify the user.

It sounds dumb, but it's bad practice to exit the app without letting the user decide and not notifying him. And since there is a home button for the user interaction, Apple states, there should not be 2 things for the same function (exiting an app).

How best to include other scripts?

Shell Script Loader is my solution for this.

It provides a function named include() that can be called many times in many scripts to refer a single script but will only load the script once. The function can accept complete paths or partial paths (script is searched in a search path). A similar function named load() is also provided that will load the scripts unconditionally.

It works for bash, ksh, pd ksh and zsh with optimized scripts for each one of them; and other shells that are generically compatible with the original sh like ash, dash, heirloom sh, etc., through a universal script that automatically optimizes its functions depending on the features the shell can provide.

[Fowarded example]

start.sh

This is an optional starter script. Placing the startup methods here is just a convenience and can be placed in the main script instead. This script is also not needed if the scripts are to be compiled.

#!/bin/sh

# load loader.sh
. loader.sh

# include directories to search path
loader_addpath /usr/lib/sh deps source

# load main script
load main.sh

main.sh

include a.sh
include b.sh

echo '---- main.sh ----'

# remove loader from shellspace since
# we no longer need it
loader_finish

# main procedures go from here

# ...

a.sh

include main.sh
include a.sh
include b.sh

echo '---- a.sh ----'

b.sh

include main.sh
include a.sh
include b.sh

echo '---- b.sh ----'

output:

---- b.sh ----
---- a.sh ----
---- main.sh ----

What's best is scripts based on it may also be compiled to form a single script with the available compiler.

Here's a project that uses it: http://sourceforge.net/p/playshell/code/ci/master/tree/. It can run portably with or without compiling the scripts. Compiling to produce a single script can also happen, and is helpful during installation.

I also created a simpler prototype for any conservative party that may want to have a brief idea of how an implementation script works: https://sourceforge.net/p/loader/code/ci/base/tree/loader-include-prototype.bash. It's small and anyone can just include the code in their main script if they want to if their code is intended to run with Bash 4.0 or newer, and it also doesn't use eval.

How do I convert an integer to string as part of a PostgreSQL query?

You could do this:

SELECT * FROM table WHERE cast(YOUR_INTEGER_VALUE as varchar) = 'string of numbers'

Get year, month or day from numpy datetime64

Anon's answer works great for me, but I just need to modify the statement for days

from:

days = dates - dates.astype('datetime64[M]') + 1

to:

days = dates.astype('datetime64[D]') - dates.astype('datetime64[M]') + 1

How to debug PDO database queries?

In Debian NGINX environment i did the following.

Goto /etc/mysql/mysql.conf.d edit mysqld.cnf if you find log-error = /var/log/mysql/error.log add the following 2 lines bellow it.

general_log_file        = /var/log/mysql/mysql.log
general_log             = 1

To see the logs goto /var/log/mysql and tail -f mysql.log

Remember to comment these lines out once you are done with debugging if you are in production environment delete mysql.log as this log file will grow quickly and can be huge.

Convert columns to string in Pandas

Here's the other one, particularly useful to convert the multiple columns to string instead of just single column:

In [76]: import numpy as np
In [77]: import pandas as pd
In [78]: df = pd.DataFrame({
    ...:     'A': [20, 30.0, np.nan],
    ...:     'B': ["a45a", "a3", "b1"],
    ...:     'C': [10, 5, np.nan]})
    ...: 

In [79]: df.dtypes ## Current datatype
Out[79]: 
A    float64
B     object
C    float64
dtype: object

## Multiple columns string conversion
In [80]: df[["A", "C"]] = df[["A", "C"]].astype(str) 

In [81]: df.dtypes ## Updated datatype after string conversion
Out[81]: 
A    object
B    object
C    object
dtype: object

How to Compare two Arrays are Equal using Javascript?

var array3 = array1 === array2

That will compare whether array1 and array2 are the same array object in memory, which is not what you want.

In order to do what you want, you'll need to check whether the two arrays have the same length, and that each member in each index is identical.

Assuming your array is filled with primitives—numbers and or strings—something like this should do

function arraysAreIdentical(arr1, arr2){
    if (arr1.length !== arr2.length) return false;
    for (var i = 0, len = arr1.length; i < len; i++){
        if (arr1[i] !== arr2[i]){
            return false;
        }
    }
    return true; 
}

Skipping error in for-loop

Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction() function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!

Left join only selected columns in R with the merge() function

I think it's a little simpler to use the dplyr functions select and left_join ; at least it's easier for me to understand. The join function from dplyr are made to mimic sql arguments.

 library(tidyverse)

 DF2 <- DF2 %>%
   select(client, LO)

 joined_data <- left_join(DF1, DF2, by = "Client")

You don't actually need to use the "by" argument in this case because the columns have the same name.

How can I get a list of locally installed Python modules?

  1. to get all available modules, run sys.modules
  2. to get all installed modules (read: installed by pip), you may look at pip.get_installed_distributions()

For the second purpose, example code:

import pip
for package in pip.get_installed_distributions():
    name = package.project_name # SQLAlchemy, Django, Flask-OAuthlib
    key = package.key # sqlalchemy, django, flask-oauthlib
    module_name = package._get_metadata("top_level.txt") # sqlalchemy, django, flask_oauthlib
    location = package.location # virtualenv lib directory etc.
    version = package.version # version number

How do I make a branch point at a specific commit?

If you are currently not on branch master, that's super easy:

git branch -f master 1258f0d0aae

This does exactly what you want: It points master at the given commit, and does nothing else.

If you are currently on master, you need to get into detached head state first. I'd recommend the following two command sequence:

git checkout 1258f0d0aae    #detach from master
git branch -f master HEAD   #exactly as above

#optionally reattach to master
git checkout master

Be aware, though, that any explicit manipulation of where a branch points has the potential to leave behind commits that are no longer reachable by any branches, and thus become object to garbage collection. So, think before you type git branch -f!


This method is better than the git reset --hard approach, as it does not destroy anything in the index or working directory.

pthread_join() and pthread_exit()

It because every time

void pthread_exit(void *ret);

will be called from thread function so which ever you want to return simply its pointer pass with pthread_exit().

Now at

int pthread_join(pthread_t tid, void **ret);

will be always called from where thread is created so here to accept that returned pointer you need double pointer ..

i think this code will help you to understand this

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>

void* thread_function(void *ignoredInThisExample)
{
    char *a = malloc(10);
    strcpy(a,"hello world");
    pthread_exit((void*)a);
}
int main()
{
    pthread_t thread_id;
    char *b;

    pthread_create (&thread_id, NULL,&thread_function, NULL);

    pthread_join(thread_id,(void**)&b); //here we are reciving one pointer 
                                        value so to use that we need double pointer 
    printf("b is %s\n",b); 
    free(b); // lets free the memory

}

Launch custom android application from android browser

Please see my comment here: Make a link in the Android browser start up my app?

We strongly discourage people from using their own schemes, unless they are defining a new world-wide internet scheme.

What are the alternatives now that the Google web search API has been deprecated?

Yes, Google Custom Search has now replaced the old Search API, but you can still use Google Custom Search to search the entire web, although the steps are not obvious from the Custom Search setup.

To create a Google Custom Search engine that searches the entire web:

  1. From the Google Custom Search homepage ( http://www.google.com/cse/ ), click Create a Custom Search Engine.
  2. Type a name and description for your search engine.
  3. Under Define your search engine, in the Sites to Search box, enter at least one valid URL (For now, just put www.anyurl.com to get past this screen. More on this later ).
  4. Select the CSE edition you want and accept the Terms of Service, then click Next. Select the layout option you want, and then click Next.
  5. Click any of the links under the Next steps section to navigate to your Control panel.
  6. In the left-hand menu, under Control Panel, click Basics.
  7. In the Search Preferences section, select Search the entire web but emphasize included sites.
  8. Click Save Changes.
  9. In the left-hand menu, under Control Panel, click Sites.
  10. Delete the site you entered during the initial setup process.

Now your custom search engine will search the entire web.

Pricing

  • Google Custom Search gives you 100 queries per day for free.
  • After that you pay $5 per 1000 queries.
  • There is a maximum of 10,000 queries per day.

Source: https://developers.google.com/custom-search/json-api/v1/overview#Pricing


  • The search quality is much lower than normal Google search (no synonyms, "intelligence" etc.)
  • It seems that Google is even planning to shut down this service completely.

How do I increase memory on Tomcat 7 when running as a Windows Service?

If you are running a custom named service, you should see two executables in your Tomcat/bin directory
In my case with Tomcat 8

08/14/2019  10:24 PM           116,648 Tomcat-Custom.exe
08/14/2019  10:24 PM           119,720 Tomcat-Customw.exe
               2 File(s)        236,368 bytes

Running the "w" terminated executable will let you configure Xmx in the Java tab
enter image description here

Android: How to use webcam in emulator?

I would suggest checking the drivers and updating them if required.

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

Thoughts (based on pain in the past):

  • do you have DNS and line-of-sight to the server?
  • are you using the correct name from the certificate?
  • is the certificate still valid?
  • is a badly configured load balancer messing things up?
  • does the new server machine have the clock set correctly (i.e. so that the UTC time is correct [ignore local time, it is largely irrelevent]) - this certainly matters for WCF, so may impact regular SOAP?
  • is there a certificate trust chain issue? if you browse from the server to the soap service, can you get SSL?
  • related to the above - has the certificate been installed to the correct location? (you may need a copy in Trusted Root Certification Authorities)
  • is the server's machine-level proxy set correctly? (which different to the user's proxy); see proxycfg for XP / 2003 (not sure about Vista etc)

How to convert milliseconds into human readable form?

Your choices are simple:

  1. Write the code to do the conversion (ie, divide by milliSecondsPerDay to get days and use the modulus to divide by milliSecondsPerHour to get hours and use the modulus to divide by milliSecondsPerMinute and divide by 1000 for seconds. milliSecondsPerMinute = 60000, milliSecondsPerHour = 60 * milliSecondsPerMinute, milliSecondsPerDay = 24 * milliSecondsPerHour.
  2. Use an operating routine of some kind. UNIX and Windows both have structures that you can get from a Ticks or seconds type value.

How do I convert ticks to minutes?

TimeSpan.FromTicks( 28000000000 ).TotalMinutes;

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

Just 2 things I think make it ALWAYS preferable to use a # Temp Table rather then a CTE are:

  1. You can not put a primary key on a CTE so the data being accessed by the CTE will have to traverse each one of the indexes in the CTE's tables rather then just accessing the PK or Index on the temp table.

  2. Because you can not add constraints, indexes and primary keys to a CTE they are more prone to bugs creeping in and bad data.


-onedaywhen yesterday

Here is an example where #table constraints can prevent bad data which is not the case in CTE's

DECLARE @BadData TABLE ( 
                       ThisID int
                     , ThatID int );
INSERT INTO @BadData
       ( ThisID
       , ThatID
       ) 
VALUES
       ( 1, 1 ),
       ( 1, 2 ),
       ( 2, 2 ),
       ( 1, 1 );

IF OBJECT_ID('tempdb..#This') IS NOT NULL
    DROP TABLE #This;
CREATE TABLE #This ( 
             ThisID int NOT NULL
           , ThatID int NOT NULL
                        UNIQUE(ThisID, ThatID) );
INSERT INTO #This
SELECT * FROM @BadData;
WITH This_CTE
     AS (SELECT *
           FROM @BadData)
     SELECT *
       FROM This_CTE;

Add Text on Image using PIL

I think ImageFont module available in PIL should be helpful in solving text font size problem. Just check what font type and size is appropriate for you and use following function to change font values.

# font = ImageFont.truetype(<font-file>, <font-size>)
# font-file should be present in provided path.
font = ImageFont.truetype("sans-serif.ttf", 16)

So your code will look something similar to:

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw 

img = Image.open("sample_in.jpg")
draw = ImageDraw.Draw(img)
# font = ImageFont.truetype(<font-file>, <font-size>)
font = ImageFont.truetype("sans-serif.ttf", 16)
# draw.text((x, y),"Sample Text",(r,g,b))
draw.text((0, 0),"Sample Text",(255,255,255),font=font)
img.save('sample-out.jpg')

You might need to put some extra effort to calculate font size. In case you want to change it based on amount of text user has provided in TextArea.

To add text wrapping (Multiline thing) just take a rough idea of how many characters can come in one line, Then you can probably write a pre-pprocessing function for your Text, Which basically finds the character which will be last in each line and converts white space before this character to new-line.

SET NAMES utf8 in MySQL?

Not only PDO. If sql answer like '????' symbols, preset of you charset (hope UTF-8) really recommended:

if (!$mysqli->set_charset("utf8")) 
 { printf("Can't set utf8: %s\n", $mysqli->error); }

or via procedure style mysqli_set_charset($db,"utf8")

Python interpreter error, x takes no arguments (1 given)

I have been puzzled a lot with this problem, since I am relively new in Python. I cannot apply the solution to the code given by the questioned, since it's not self executable. So I bring a very simple code:

from turtle import *

ts = Screen(); tu = Turtle()

def move(x,y):
  print "move()"
  tu.goto(100,100)

ts.listen();
ts.onclick(move)

done()

As you can see, the solution consists in using two (dummy) arguments, even if they are not used either by the function itself or in calling it! It sounds crazy, but I believe there must be a reason for it (hidden from the novice!).

I have tried a lot of other ways ('self' included). It's the only one that works (for me, at least).

Expression ___ has changed after it was checked

You can also create a timer using the rxjs Observable.timer function, and then update the message in your subscription:                    

Observable.timer(1).subscribe(()=> this.updateMessage());

Is there a pretty print for PHP?

Here's another simple dump without all the overhead of print_r:

function pretty($arr, $level=0){
    $tabs = "";
    for($i=0;$i<$level; $i++){
        $tabs .= "    ";
    }
    foreach($arr as $key=>$val){
        if( is_array($val) ) {
            print ($tabs . $key . " : " . "\n");
            pretty($val, $level + 1);
        } else {
            if($val && $val !== 0){
                print ($tabs . $key . " : " . $val . "\n"); 
            }
        }
    }
}
// Example:
$item["A"] = array("a", "b", "c");
$item["B"] = array("a", "b", "c");
$item["C"] = array("a", "b", "c");

pretty($item);

// -------------
// yields
// -------------
// A : 
//     0 : a
//     1 : b
//     2 : c
// B : 
//     0 : a
//     1 : b
//     2 : c
// C : 
//     0 : a
//     1 : b
//     2 : c

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

You can add a following method inside your bootstrap class which is annotated with @SpringBootApplication

    @Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper objectMapper = builder.createXmlMapper(false).build();
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false);

    objectMapper.registerModule(new JodaModule());

    return objectMapper;
}

How to check if AlarmManager already has an alarm set?

I have 2 alarms. I am using intent with extras instead of action to identify the events:

Intent i = new Intent(context, AppReciever.class);
i.putExtra("timer", "timer1");

the thing is that with diff extras the intent (and the alarm) wont be unique. So to able to identify which alarm is active or not, I had to define diff requestCode-s:

boolean alarmUp = (PendingIntent.getBroadcast(context, MyApp.TIMER_1, i, 
                    PendingIntent.FLAG_NO_CREATE) != null);

and here is how alarm was created:

public static final int TIMER_1 = 1;
public static final int TIMER_2 = 2;

PendingIntent pending = PendingIntent.getBroadcast(context, TIMER_1, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
setInexactRepeating(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pending);
pending = PendingIntent.getBroadcast(context, TIMER_2, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
setInexactRepeating(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pending);

Check if a input box is empty

To auto check a checkbox if input field is not empty.

 <md-content>
            <md-checkbox ng-checked="myField.length"> Other </md-checkbox>
            <input  ng-model="myField" placeholder="Please Specify" type="text">
 </md-content>

How can one grab a stack trace in C?

There's backtrace(), and backtrace_symbols():

From the man page:

#include <execinfo.h>
#include <stdio.h>
...
void* callstack[128];
int i, frames = backtrace(callstack, 128);
char** strs = backtrace_symbols(callstack, frames);
for (i = 0; i < frames; ++i) {
    printf("%s\n", strs[i]);
}
free(strs);
...

One way to use this in a more convenient/OOP way is to save the result of backtrace_symbols() in an exception class constructor. Thus, whenever you throw that type of exception you have the stack trace. Then, just provide a function for printing it out. For example:

class MyException : public std::exception {

    char ** strs;
    MyException( const std::string & message ) {
         int i, frames = backtrace(callstack, 128);
         strs = backtrace_symbols(callstack, frames);
    }

    void printStackTrace() {
        for (i = 0; i < frames; ++i) {
            printf("%s\n", strs[i]);
        }
        free(strs);
    }
};

...

try {
   throw MyException("Oops!");
} catch ( MyException e ) {
    e.printStackTrace();
}

Ta da!

Note: enabling optimization flags may make the resulting stack trace inaccurate. Ideally, one would use this capability with debug flags on and optimization flags off.

moment.js, how to get day of week number

Define "doesn't work".

_x000D_
_x000D_
const date = moment("2015-07-02"); // Thursday Feb 2015_x000D_
const dow = date.day();_x000D_
console.log(dow);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

This prints "4", as expected.

How to negate specific word in regex?

The following regex will do what you want (as long as negative lookbehinds and lookaheads are supported), matching things properly; the only problem is that it matches individual characters (i.e. each match is a single character rather than all characters between two consecutive "bar"s), possibly resulting in a potential for high overhead if you're working with very long strings.

b(?!ar)|(?<!b)a|a(?!r)|(?<!ba)r|[^bar]

How can I split a string into segments of n characters?

const chunkStr = (str, n, acc) => {     
    if (str.length === 0) {
        return acc
    } else {
        acc.push(str.substring(0, n));
        return chunkStr(str.substring(n), n, acc);
    }
}
const str = 'abcdefghijkl';
const splittedString = chunkStr(str, 3, []);

Clean solution without REGEX

How to serve an image using nodejs

_x000D_
_x000D_
//This method involves directly integrating HTML Code in the res.write
//first time posting to stack ...pls be kind

const express = require('express');
const app = express();
const https = require('https');

app.get("/",function(res,res){
    res.write("<img src="+image url / src +">");
    res.send();
});

app.listen(3000, function(req, res) {
  console.log("the server is onnnn");
});
_x000D_
_x000D_
_x000D_

How to check visibility of software keyboard in Android?

There's a hidden method can help for this, InputMethodManager.getInputMethodWindowVisibleHeight. But I don't know why it's hidden.

import android.content.Context
import android.os.Handler
import android.view.inputmethod.InputMethodManager

class SoftKeyboardStateWatcher(private val ctx: Context) {
  companion object {
    private const val DELAY = 10L
  }

  private val handler = Handler()
  private var isSoftKeyboardOpened: Boolean = false

  private val height: Int
    get() {
      val imm = ctx.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
      val method = imm.javaClass.getMethod("getInputMethodWindowVisibleHeight")
      method.isAccessible = true
      return method.invoke(imm) as Int
    }

  private val task: Runnable by lazy {
    Runnable {
      start()
      if (!isSoftKeyboardOpened && height > 0) {
        isSoftKeyboardOpened = true
        notifyOnSoftKeyboardOpened(height)
      } else if (isSoftKeyboardOpened && height == 0) {
        isSoftKeyboardOpened = false
        notifyOnSoftKeyboardClosed()
      }
    }
  }

  var listener: SoftKeyboardStateListener? = null

  interface SoftKeyboardStateListener {
    fun onSoftKeyboardOpened(keyboardHeightInPx: Int)
    fun onSoftKeyboardClosed()
  }

  fun start() {
    handler.postDelayed(task, DELAY)
  }

  fun stop() {
    handler.postDelayed({
      if (!isSoftKeyboardOpened) handler.removeCallbacks(task)
    }, DELAY * 10)
  }

  private fun notifyOnSoftKeyboardOpened(keyboardHeightInPx: Int) {
    listener?.onSoftKeyboardOpened(keyboardHeightInPx)
  }

  private fun notifyOnSoftKeyboardClosed() {
    listener?.onSoftKeyboardClosed()
  }
}

How do you compare structs for equality in C?

If the structs only contain primitives or if you are interested in strict equality then you can do something like this:

int my_struct_cmp(const struct my_struct * lhs, const struct my_struct * rhs)
{
    return memcmp(lhs, rsh, sizeof(struct my_struct));
}

However, if your structs contain pointers to other structs or unions then you will need to write a function that compares the primitives properly and make comparison calls against the other structures as appropriate.

Be aware, however, that you should have used memset(&a, sizeof(struct my_struct), 1) to zero out the memory range of the structures as part of your ADT initialization.

How do I update the password for Git?

For Mac

If you have multiple remote repositories (Github, Bitbucket, Job, etc.)

1) run in the project directory

git config --unset user.password

2) run remote git command (ie. git push or git pull)

Git will prompt you to reenter your user.name and user.password for this repository

Or you can do it globally if you have only one remote repository

git config --global --unset user.password

Reverse of JSON.stringify?

JSON.parse is the opposite of JSON.stringify.

How to Check whether Session is Expired or not in asp.net

Here I am checking session values(two values filled in text box on previous page)

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["sessUnit_code"] == null || Session["sessgrcSerial"] == null)
    {
        Response.Write("<Script Language = 'JavaScript'> alert('Go to GRC Tab and fill Unit Code and GRC Serial number first')</script>");
    }
    else
    {

        lblUnit.Text = Session["sessUnit_code"].ToString();
        LblGrcSr.Text = Session["sessgrcSerial"].ToString();
    }
}

How do I redirect users after submit button click?

I hope this might be helpful

_x000D_
_x000D_
<script type="text/javascript">_x000D_
 function redirect() {_x000D_
  document.getElementById("formid").submit();_x000D_
 }_x000D_
 window.onload = redirect;_x000D_
</script>
_x000D_
<form id="formid" method="post" action="anypage.jsp">_x000D_
  ........._x000D_
</form>
_x000D_
_x000D_
_x000D_

Java : Accessing a class within a package, which is the better way?

Import package is for better readability;

Fully qualified class has to be used in special scenarios. For example, same class name in different package, or use reflect such as Class.forName().

Align inline-block DIVs to top of container element

Because the vertical-align is set at baseline as default.

Use vertical-align:top instead:

.small{
    display: inline-block;
    width: 40%;
    height: 30%;
    border: 1px black solid;
    background: aliceblue;   
    vertical-align:top;
}

http://jsfiddle.net/Lighty_46/RHM5L/9/

Or as @f00644 said you could apply float to the child elements as well.

How to return XML in ASP.NET?

Below is an example of the correct way I think. At least it is what I use. You need to do Response.Clear to get rid of any headers that are already populated. You need to pass the correct ContentType of text/xml. That is the way you serve xml. In general you want to serve it as charset UTF-8 as that is what most parsers are expecting. But I don't think it has to be that. But if you change it make sure to change your xml document declaration and indicate the charset in there. You need to use the XmlWriter so you can actually write in UTF-8 and not whatever charset is the default. And to have it properly encode your xml data in UTF-8.

   ' -----------------------------------------------------------------------------
   ' OutputDataSetAsXML
   '
   ' Description: outputs the given dataset as xml to the response object
   '
   ' Arguments:
   '    dsSource           - source data set
   '
   ' Dependencies:
   '
   ' History
   ' 2006-05-02 - WSR : created
   '
   Private Sub OutputDataSetAsXML(ByRef dsSource As System.Data.DataSet)

      Dim xmlDoc As System.Xml.XmlDataDocument
      Dim xmlDec As System.Xml.XmlDeclaration
      Dim xmlWriter As System.Xml.XmlWriter

      ' setup response
      Me.Response.Clear()
      Me.Response.ContentType = "text/xml"
      Me.Response.Charset = "utf-8"
      xmlWriter = New System.Xml.XmlTextWriter(Me.Response.OutputStream, System.Text.Encoding.UTF8)

      ' create xml data document with xml declaration
      xmlDoc = New System.Xml.XmlDataDocument(dsSource)
      xmlDoc.DataSet.EnforceConstraints = False
      xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", Nothing)
      xmlDoc.PrependChild(xmlDec)

      ' write xml document to response
      xmlDoc.WriteTo(xmlWriter)
      xmlWriter.Flush()
      xmlWriter.Close()
      Response.End()

   End Sub
   ' -----------------------------------------------------------------------------

If input field is empty, disable submit button

An easy way to do:

function toggleButton(ref,bttnID){
    document.getElementById(bttnID).disabled= ((ref.value !== ref.defaultValue) ? false : true);
}


<input ... onkeyup="toggleButton(this,'bttnsubmit');">
<input ... disabled='disabled' id='bttnsubmit' ... >

How to print the current time in a Batch-File?

This works with Windows 10, 8.x, 7, and possibly further back:

@echo Started: %date% %time%
.
.
.
@echo Completed: %date% %time%

No function matches the given name and argument types

Your function has a couple of smallint parameters.
But in the call, you are using numeric literals that are presumed to be type integer.

A string literal or string constant ('123') is not typed immediately. It remains type "unknown" until assigned or cast explicitly.

However, a numeric literal or numeric constant is typed immediately. Per documentation:

A numeric constant that contains neither a decimal point nor an exponent is initially presumed to be type integer if its value fits in type integer (32 bits); otherwise it is presumed to be type bigint if its value fits in type bigint (64 bits); otherwise it is taken to be type numeric. Constants that contain decimal points and/or exponents are always initially presumed to be type numeric.

More explanation and links in this related answer:

Solution

Add explicit casts for the smallint parameters or quote them.

Demo

CREATE OR REPLACE FUNCTION f_typetest(smallint)
  RETURNS bool AS 'SELECT TRUE' LANGUAGE sql;

Incorrect call:

SELECT * FROM f_typetest(1);

Correct calls:

SELECT * FROM f_typetest('1');
SELECT * FROM f_typetest(smallint '1');
SELECT * FROM f_typetest(1::int2);
SELECT * FROM f_typetest('1'::int2);

db<>fiddle here
Old sqlfiddle.

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

I couldn't get mvn eclipse:clean etc to work with Kepler.

However I changed creating and extending variables to just using external jars in my eclipse classpath. This was reflected in no var's in my .classpath.

This corrected the problem. I was able to do a Maven update.

Add items to comboBox in WPF

You can fill it from XAML or from .cs. There are few ways to fill controls with data. It would be best for You to read more about WPF technology, it allows to do many things in many ways, depending on Your needs. It's more important to choose method based on Your project needs. You can start here. It's an easy article about creating combobox, and filling it with some data.

Checkout multiple git repos into same Jenkins workspace

Jenkins: Multiple SCM - deprecated. GIT Plugin - doesn't work for multiple repos.

Scripting / pipeline as code - is the way to go.

How can I open a URL in Android's web browser from my application?

The response of MarkB is right. In my case I'm using Xamarin, and the code to use with C# and Xamarin is:

var uri = Android.Net.Uri.Parse ("http://www.xamarin.com");
var intent = new Intent (Intent.ActionView, uri);
StartActivity (intent);

This information is taked from: https://developer.xamarin.com/recipes/android/fundamentals/intent/open_a_webpage_in_the_browser_application/

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

We had a very similar issue whereby a client's website was trying to connect to our Web API service and getting that same message. This started happening completely out of the blue when there had been no code changes or Windows updates on the server where IIS was running.

In our case it turned out that the calling website was using a version of .Net that only supported TLS 1.0 and for some reason the server where our IIS was running stopped appeared to have stopped accepting TLS 1.0 calls. To diagnose that we had to explicitly enable TLS via the registry on the IIS's server and then restart that server. These are the reg keys:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.0\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.0\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.1\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.1\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.2\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.2\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

If that doesn't do it, you could also experiment with adding the entry for SSL 2.0:


    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client]
    "DisabledByDefault"=dword:00000000
    "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server]
    "DisabledByDefault"=dword:00000000
    "Enabled"=dword:00000001

My answer to another question here has this powershell script that we used to add the entries:

NOTE: Enabling old security protocols is not a good idea, the right answer in our case was to get the client website to update it's code to use TLS 1.2, but the registry entries above can help diagnose the issue in the first place.

Convert a python 'type' object to a string

print type(someObject).__name__

If that doesn't suit you, use this:

print some_instance.__class__.__name__

Example:

class A:
    pass
print type(A())
# prints <type 'instance'>
print A().__class__.__name__
# prints A

Also, it seems there are differences with type() when using new-style classes vs old-style (that is, inheritance from object). For a new-style class, type(someObject).__name__ returns the name, and for old-style classes it returns instance.

Global variables in Java

Object-Oriented Programming is built with the understanding that the scope of variables is closely exclusive to the class object that encapsulates those variables.

The problem with creating "global variables" is that it's not industry standard for Java. It's not industry standard because it allows multiple classes to manipulate data asyncronized, if you're running a multi-threaded application, this gets a little more complicated and dangerous in terms of thread-safety. There are various other reasons why using global variables are ineffective, but if you want to avoid that, I suggest you resort to Aspect-Oriented Programming.

Aspect-Oriented Programming negates this problem by putting the parent class in charge of the scope through something called "advices", which adds additional behavior to the code without actually modifying it. It offers solutions to cross-cutting concerns, or global variable usage.

Spring is a Java framework that utilizes AOP, and while it is traditionally used for web-applications, the core application can be used universally throughout the Java framework (8.0 included). This might be a direction you want to explore more.

How to print the values of slices

fmt.Printf() is fine, but sometimes I like to use pretty print package.

import "github.com/kr/pretty"
pretty.Print(...)

select2 onchange event only works once

$('#search_code').select2({
.
.
.
.
}).on("change", function (e) {
      var str = $("#s2id_search_code .select2-choice span").text();
      DOSelectAjaxProd(e.val, str);
});

Hiding the R code in Rmarkdown/knit and just showing the results

Alternatively, you can also parse a standard markdown document (without code blocks per se) on the fly by the markdownreports package.

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

Update multiple rows with different values in a single SQL query

Something like this might work for you:

"UPDATE myTable SET ... ;
 UPDATE myTable SET ... ;
 UPDATE myTable SET ... ;
 UPDATE myTable SET ... ;"

If any of the posX or posY values are the same, then they could be combined into one query

UPDATE myTable SET posX='39' WHERE id IN('2','3','40');

What does the "static" modifier after "import" mean?

The import allows the java programmer to access classes of a package without package qualification.

The static import feature allows to access the static members of a class without the class qualification.

The import provides accessibility to classes and interface whereas static import provides accessibility to static members of the class.

Example :

With import

import java.lang.System.*;    
class StaticImportExample{  
    public static void main(String args[]){  

       System.out.println("Hello");
       System.out.println("Java");  

  }   
} 

With static import

import static java.lang.System.*;    
class StaticImportExample{  
  public static void main(String args[]){  

   out.println("Hello");//Now no need of System.out  
   out.println("Java");  

 }   
} 

See also : What is static import in Java 5

Count number of iterations in a foreach loop

Try:

$counter = 0;
foreach ($Contents as $item) {
          something 
          your code  ...
      $counter++;      
}
$total_count=$counter-1;

What's the difference between primitive and reference types?

The short answer is primitives are data types, while references are pointers, which do not hold their values but point to their values and are used on/with objects.

Primatives:

boolean

character

byte

short

integer

long

float

double

Lots of good references that explain these basic concepts. http://www.javaforstudents.co.uk/Types

How to convert a structure to a byte array in C#?

Variant of the code of Vicent with one less memory allocation:

public static byte[] GetBytes<T>(T str)
{
    int size = Marshal.SizeOf(str);

    byte[] arr = new byte[size];

    GCHandle h = default(GCHandle);

    try
    {
        h = GCHandle.Alloc(arr, GCHandleType.Pinned);

        Marshal.StructureToPtr<T>(str, h.AddrOfPinnedObject(), false);
    }
    finally
    {
        if (h.IsAllocated)
        {
            h.Free();
        }
    }

    return arr;
}

public static T FromBytes<T>(byte[] arr) where T : struct
{
    T str = default(T);

    GCHandle h = default(GCHandle);

    try
    {
        h = GCHandle.Alloc(arr, GCHandleType.Pinned);

        str = Marshal.PtrToStructure<T>(h.AddrOfPinnedObject());

    }
    finally
    {
        if (h.IsAllocated)
        {
            h.Free();
        }
    }

    return str;
}

I use GCHandle to "pin" the memory and then I use directly its address with h.AddrOfPinnedObject().

UICollectionView - dynamic cell height?

We can maintain dynamic height for collection view cell without xib(only using storyboard).

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout*)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

        NSAttributedString* labelString = [[NSAttributedString alloc] initWithString:@"Your long string goes here" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0]}];
        CGRect cellRect = [labelString boundingRectWithSize:CGSizeMake(cellWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil];

        return CGSizeMake(cellWidth, cellRect.size.height);
}

Make sure that numberOfLines in IB should be 0.

ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there

If your build-system (CMake in my case) copies the file from <name>.dll to <name>.pyd, you will get this error if the original file wasn't actually a dll. In my case, building shared libraries got switched off, so the underlying file was actually a *.lib.

I discovered this error by loading the pyd file in DependencyWalker and finding that it wasn't valid.

SQL Server IF NOT EXISTS Usage?

Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.

set nocount on

create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)

insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)

declare @PersonID int
set @PersonID = 1

IF EXISTS    
    (
    SELECT 1    
    FROM Timesheet_Hours    
    WHERE Posted_Flag = 1    
        AND Staff_Id = @PersonID    
    )    
    BEGIN
        RAISERROR('Timesheets have already been posted!', 16, 1)
        ROLLBACK TRAN
    END
ELSE
    IF NOT EXISTS
        (
        SELECT 1
        FROM Timesheet_Hours
        WHERE Staff_Id = @PersonID
        )
        BEGIN
            RAISERROR('Default list has not been loaded!', 16, 1)
            ROLLBACK TRAN
        END
    ELSE
        print 'No problems here'

drop table Timesheet_Hours

Unable to copy ~/.ssh/id_rsa.pub

DISPLAY=:0 xclip -sel clip < ~/.ssh/id_rsa.pub didn't work for me (ubuntu 14.04), but you can use :

cat ~/.ssh/id_rsa.pub

to get your public key

Controlling Maven final name of jar artifact

The approach you've been using indeed does jar file with a string 'testing' in its name, as you specified, but the default install command sends it to your ~/.m2/repository directory, as seen in this output line:

/tmp/mvn_test/my-app/target/my-app-testing.jar to /home/maxim/.m2/repository/com/mycompany/app/my-app/1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.jar

It seems to me that you're trying to generate a jar with such name and then copy it to a directory of your choice.

Try using outputDirectory property as described here: http://maven.apache.org/plugins/maven-jar-plugin/jar-mojo.html

How to grant remote access permissions to mysql server for user?

This grants root access with the same password from any machine in *.example.com:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%.example.com' 
    IDENTIFIED BY 'some_characters' 
    WITH GRANT OPTION;
FLUSH PRIVILEGES;

If name resolution is not going to work, you may also grant access by IP or subnet:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.%'
    IDENTIFIED BY 'some_characters'  
    WITH GRANT OPTION;
FLUSH PRIVILEGES;

MySQL GRANT syntax docs.

How to make war file in Eclipse

File -> Export -> Web -> WAR file

OR in Kepler follow as shown below :

enter image description here

How do I check if a given string is a legal/valid file name under Windows?

You can get a list of invalid characters from Path.GetInvalidPathChars and GetInvalidFileNameChars.

UPD: See Steve Cooper's suggestion on how to use these in a regular expression.

UPD2: Note that according to the Remarks section in MSDN "The array returned from this method is not guaranteed to contain the complete set of characters that are invalid in file and directory names." The answer provided by sixlettervaliables goes into more details.

How to push local changes to a remote git repository on bitbucket

Meaning the 2nd parameter('master') of the "git push" command -

$ git push origin master

can be made clear by initiating "push" command from 'news-item' branch. It caused local "master" branch to be pushed to the remote 'master' branch. For more information refer

https://git-scm.com/docs/git-push

where <refspec> in

[<repository> [<refspec>…?]

is written to mean "specify what destination ref to update with what source object."

For your reference, here is a screen capture how I verified this statement.

<code>enter image description here</code>

How do I prevent a parent's onclick event from firing when a child anchor is clicked?

_x000D_
_x000D_
var inner = document.querySelector("#inner");_x000D_
var outer = document.querySelector("#outer");_x000D_
inner.addEventListener('click',innerFunction);_x000D_
outer.addEventListener('click',outerFunction);_x000D_
_x000D_
function innerFunction(event){_x000D_
  event.stopPropagation();_x000D_
  console.log("Inner Functiuon");_x000D_
}_x000D_
_x000D_
function outerFunction(event){_x000D_
  console.log("Outer Functiuon");_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width">_x000D_
  <title>Pramod Kharade-Event with Outer and Inner Progration</title>_x000D_
</head>_x000D_
<body>_x000D_
<div id="outer" style="width:100px;height:100px;background-color:green;">_x000D_
  <div id="inner" style="width:35px;height:35px;background-color:yellow;"></div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Nested jQuery.each() - continue/break

There is no clean way to do this and like @Nick mentioned above it might just be easier to use the old school way of loops as then you can control this. But if you want to stick with what you got there is one way you could handle this. I'm sure I will get some heat for this one. But...

One way you could do what you want without an if statement is to raise an error and wrap your loop with a try/catch block:

try{
$(sentences).each(function() {
    var s = this;
    alert(s);
    $(words).each(function(i) {
        if (s.indexOf(this) > -1)
        {
            alert('found ' + this);
            throw "Exit Error";
        }
    });
});
}
catch (e)
{
    alert(e)
}

Ok, let the thrashing begin.

Edit and replay XHR chrome/firefox etc?

5 years have passed and this essential requirement didn't get ignored by the Chrome devs.
While they offer no method to edit the data like in Firefox, they offer a full XHR replay.
This allows to debug ajax calls.
enter image description here
"Replay XHR" will repeat the entire transmission.

What is the difference between concurrency and parallelism?

"Concurrency" is when there are multiple things in progress.

"Parallelism" is when concurrent things are progressing at the same time.


Examples of concurrency without parallelism:

  • Multiple threads on a single core.
  • Multiple messages in a Win32 message queue.
  • Multiple SqlDataReaders on a MARS connection.
  • Multiple JavaScript promises in a browser tab.

Note, however, that the difference between concurrency and parallelism is often a matter of perspective. The above examples are non-parallel from the perspective of (observable effects of) executing your code. But there is instruction-level parallelism even within a single core. There are pieces of hardware doing things in parallel with CPU and then interrupting the CPU when done. GPU could be drawing to screen while you window procedure or event handler is being executed. The DBMS could be traversing B-Trees for the next query while you are still fetching the results of the previous one. Browser could be doing layout or networking while your Promise.resolve() is being executed. Etc, etc...

So there you go. The world is as messy as always ;)

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

How do I include a file over 2 directories back?

I recomend to use __DIR__ to specify current php file directory. Check here for the reason.

__DIR__ . /../../index.php

How to decrypt the password generated by wordpress

This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.

  1. In the DB table wp_users, add a key, like abc123 to the user_activation column.
  2. Visit yoursite.com/wp-login.php?action=rp&key=abc123&login=yourusername
  3. You will be prompted to enter a new password.

Adding to an ArrayList Java

Well, you have to iterate through your abstract type Foo and that depends on the methods available on that object. You don't have to loop through the ArrayList because this object grows automatically in Java. (Don't confuse it with an array in other programming languages)

Recommended reading. Lists in the Java Tutorial

Can anyone explain python's relative imports?

You are importing from package "sub". start.py is not itself in a package even if there is a __init__.py present.

You would need to start your program from one directory over parent.py:

./start.py

./pkg/__init__.py
./pkg/parent.py
./pkg/sub/__init__.py
./pkg/sub/relative.py

With start.py:

import pkg.sub.relative

Now pkg is the top level package and your relative import should work.


If you want to stick with your current layout you can just use import parent. Because you use start.py to launch your interpreter, the directory where start.py is located is in your python path. parent.py lives there as a separate module.

You can also safely delete the top level __init__.py, if you don't import anything into a script further up the directory tree.

Specifying an Index (Non-Unique Key) Using JPA

As far as I know, there isn't a cross-JPA-Provider way to specify indexes. However, you can always create them by hand directly in the database, most databases will pick them up automatically during query planning.

Python sys.argv lists and indexes

As explained in the different asnwers already, sys.argv contains the command line arguments that called your Python script.

However, Python comes with libraries that help you parse command line arguments very easily. Namely, the new standard argparse. Using argparse would spare you the need to write a lot of boilerplate code.

How to change the foreign key referential action? (behavior)

I had a bunch of FKs to alter, so I wrote something to make the statements for me. Figured I'd share:

SELECT

CONCAT('ALTER TABLE `' ,rc.TABLE_NAME,
    '` DROP FOREIGN KEY `' ,rc.CONSTRAINT_NAME,'`;')
, CONCAT('ALTER TABLE `' ,rc.TABLE_NAME,
    '` ADD CONSTRAINT `' ,rc.CONSTRAINT_NAME ,'` FOREIGN KEY (`',kcu.COLUMN_NAME,
    '`) REFERENCES `',kcu.REFERENCED_TABLE_NAME,'` (`',kcu.REFERENCED_COLUMN_NAME,'`) ON DELETE CASCADE;')

FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
LEFT OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
    ON kcu.TABLE_SCHEMA = rc.CONSTRAINT_SCHEMA
    AND kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
WHERE DELETE_RULE = 'NO ACTION'
AND rc.CONSTRAINT_SCHEMA = 'foo'

Regular expression containing one word or another

You can use a single group for seconds/minutes. The following expression may suit your needs:

([0-9]+)\s*(seconds|minutes)

Online demo

Display alert message and redirect after click on accept

that worked but try it this way.

echo "<script>
alert('There are no fields to generate a report');
window.location.href='admin/ahm/panel';  
</script>";

alert on top then location next

Make a dictionary with duplicate keys in Python

You can't have a dict with duplicate keys for definition! Instead you can use a single key and, as value, a list of elements that had that key.

So you can follow these steps:

  1. See if the current element's (of your initial set) key is in the final dict. If it is, go to step 3
  2. Update dict with key
  3. Append the new value to the dict[key] list
  4. Repeat [1-3]

How does Junit @Rule work?

Junit Rules work on the principle of AOP (aspect oriented programming). It intercepts the test method thus providing an opportunity to do some stuff before or after the execution of a particular test method.

Take the example of the below code:

public class JunitRuleTest {

  @Rule
  public TemporaryFolder tempFolder = new TemporaryFolder();

  @Test
  public void testRule() throws IOException {
    File newFolder = tempFolder.newFolder("Temp Folder");
    assertTrue(newFolder.exists());
  }
} 

Every time the above test method is executed, a temporary folder is created and it gets deleted after the execution of the method. This is an example of an out-of-box rule provided by Junit.

Similar behaviour can also be achieved by creating our own rules. Junit provides the TestRule interface, which can be implemented to create our own Junit Rule.

Here is a useful link for reference:

Android Horizontal RecyclerView scroll Direction

In Recycler Layout manager the second parameter is spanCount increase or decrease in span count will change number of elements show on your screen

    RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2, //The number of Columns in the grid
,GridLayoutManager.HORIZONTAL,false);
                recyclerView.setLayoutManager(mLayoutManager);

Java String to JSON conversion

Instead of JSONObject , you can use ObjectMapper to convert java object to json string

ObjectMapper mapper = new ObjectMapper();
String requestBean = mapper.writeValueAsString(yourObject);

Getting a timestamp for today at midnight?

$timestamp = strtotime('today midnight');

is the same as

$timestamp = strtotime('today');

and it's a little less work on your server.

Directory index forbidden by Options directive

I got stuck on the same error, the problem was coming from a syntax error in a MySql statement in my code, in particular my $_session variable was missing a "'. It took hours to figure it out because on the error log the statement was misleading. Hope it helps somebody.

How to get the name of the current Windows user in JavaScript

If the script is running on Microsoft Windows in an HTA or similar, you can do this:

var wshshell=new ActiveXObject("wscript.shell");
var username=wshshell.ExpandEnvironmentStrings("%username%");

Otherwise, as others have pointed out, you're out of luck. This is considered to be private information and is not provided by the browser to the javascript engine.

String strip() for JavaScript?

A better polyfill from the MDN that supports removal of BOM and NBSP:

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}

Bear in mind that modifying built-in prototypes comes with a performance hit (due to the JS engine bailing on a number of runtime optimizations), and in performance critical situations you may need to consider the alternative of defining myTrimFunction(string) instead. That being said, if you are targeting an older environment without native .trim() support, you are likely to have more important performance issues to deal with.

What is the difference between Trap and Interrupt?

A trap is a special kind of interrupt which is commonly referred to as a software interrupt. An interrupt is a more general term which covers both hardware interrupts (interrupts from hardware devices) and software interrupts (interrupts from software, such as traps).

How do you put an image file in a json object?

I can think of doing it in two ways:

1.

Storing the file in file system in any directory (say dir1) and renaming it which ensures that the name is unique for every file (may be a timestamp) (say xyz123.jpg), and then storing this name in some DataBase. Then while generating the JSON you pull this filename and generate a complete URL (which will be http://example.com/dir1/xyz123.png )and insert it in the JSON.

2.

Base 64 Encoding, It's basically a way of encoding arbitrary binary data in ASCII text. It takes 4 characters per 3 bytes of data, plus potentially a bit of padding at the end. Essentially each 6 bits of the input is encoded in a 64-character alphabet. The "standard" alphabet uses A-Z, a-z, 0-9 and + and /, with = as a padding character. There are URL-safe variants. So this approach will allow you to put your image directly in the MongoDB, while storing it Encode the image and decode while fetching it, it has some of its own drawbacks:

  • base64 encoding makes file sizes roughly 33% larger than their original binary representations, which means more data down the wire (this might be exceptionally painful on mobile networks)
  • data URIs aren’t supported on IE6 or IE7.
  • base64 encoded data may possibly take longer to process than binary data.

Source

Converting Image to DATA URI

A.) Canvas

Load the image into an Image-Object, paint it to a canvas and convert the canvas back to a dataURL.

function convertToDataURLviaCanvas(url, callback, outputFormat){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null; 
    };
    img.src = url;
}

Usage

convertToDataURLviaCanvas('http://bit.ly/18g0VNp', function(base64Img){
    // Base64DataURL
});

Supported input formats image/png, image/jpeg, image/jpg, image/gif, image/bmp, image/tiff, image/x-icon, image/svg+xml, image/webp, image/xxx

B.) FileReader

Load the image as blob via XMLHttpRequest and use the FileReader API to convert it to a data URL.

function convertFileToBase64viaFileReader(url, callback){
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
      var reader  = new FileReader();
      reader.onloadend = function () {
          callback(reader.result);
      }
      reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.send();
}

This approach

  • lacks in browser support
  • has better compression
  • works for other file types as well.

Usage

convertFileToBase64viaFileReader('http://bit.ly/18g0VNp', function(base64Img){
    // Base64DataURL
});

Source

Adding elements to a collection during iteration

For examle we have two lists:

  public static void main(String[] args) {
        ArrayList a = new ArrayList(Arrays.asList(new String[]{"a1", "a2", "a3","a4", "a5"}));
        ArrayList b = new ArrayList(Arrays.asList(new String[]{"b1", "b2", "b3","b4", "b5"}));
        merge(a, b);
        a.stream().map( x -> x + " ").forEach(System.out::print);
    }
   public static void merge(List a, List b){
        for (Iterator itb = b.iterator(); itb.hasNext(); ){
            for (ListIterator it = a.listIterator() ; it.hasNext() ; ){
                it.next();
                it.add(itb.next());

            }
        }

    }

a1 b1 a2 b2 a3 b3 a4 b4 a5 b5

How do I convert NSMutableArray to NSArray?

you try this code---

NSMutableArray *myMutableArray = [myArray mutableCopy];

and

NSArray *myArray = [myMutableArray copy];

Cannot ping AWS EC2 instance

1.Go to EC2 Dashboard and click "Running Instances" on "Security Groups"
2.select the group of your instance which you need to add security.  
3.click on the "Inbound" tab
4.Click "Edit" Button (It will open an popup window)
5.click "Add Rule"
6.Select the "Custom ICMP rule - IPv4" as Type
7.Enter the "0.0.0.0/0" as Source or your public IP

7.Click "Save"

What is a reasonable length limit on person "Name" fields?

The average first name is about 6 letters. That leaves 43 for a last name. :) Seems like you could probably shorten it if you like.

The main question is how many rows do you think you will have? I don't think varchar(50) is going to kill you until you get several million rows.

How to get all files under a specific directory in MATLAB?

With little modification but almost similar approach to get the full file path of each sub folder

dataFolderPath = 'UCR_TS_Archive_2015/';

dirData = dir(dataFolderPath);      %# Get the data for the current directory
dirIndex = [dirData.isdir];  %# Find the index for directories
fileList = {dirData(~dirIndex).name}';  %'# Get a list of the files
if ~isempty(fileList)
    fileList = cellfun(@(x) fullfile(dataFolderPath,x),...  %# Prepend path to files
        fileList,'UniformOutput',false);
end
subDirs = {dirData(dirIndex).name};  %# Get a list of the subdirectories
validIndex = ~ismember(subDirs,{'.','..'});  %# Find index of subdirectories
%#   that are not '.' or '..'
for iDir = find(validIndex)                  %# Loop over valid subdirectories
    nextDir = fullfile(dataFolderPath,subDirs{iDir});    %# Get the subdirectory path
    getAllFiles = dir(nextDir);
    for k = 1:1:size(getAllFiles,1)
        validFileIndex = ~ismember(getAllFiles(k,1).name,{'.','..'});
        if(validFileIndex)
            filePathComplete = fullfile(nextDir,getAllFiles(k,1).name);
            fprintf('The Complete File Path: %s\n', filePathComplete);
        end
    end
end  

Convert Text to Date?

To the OP... I also got a type mismatch error the first time I tried running your subroutine. In my case it was cause by non-date-like data in the first cell (i.e. a header). When I changed the contents of the header cell to date-style txt for testing, it ran just fine...

Hope this helps as well.

How to determine an object's class?

Any use of any of the methods suggested is considered a code smell which is based in a bad OO design.

If your design is good, you should not find yourself needing to use getClass() or instanceof.

Any of the suggested methods will do, but just something to keep in mind, design-wise.

Best way to remove items from a collection

If you want to access members of the collection by one of their properties, you might consider using a Dictionary<T> or KeyedCollection<T> instead. This way you don't have to search for the item you're looking for.

Otherwise, you could at least do this:

foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)
{
    if (spAssignment.Member.Name == shortName)
    {
        workspace.RoleAssignments.Remove(spAssignment);
        break;
    }
}

How to pass arguments to addEventListener listener function?

You could pass somevar by value(not by reference) via a javascript feature known as closure:

var someVar='origin';
func = function(v){
    console.log(v);
}
document.addEventListener('click',function(someVar){
   return function(){func(someVar)}
}(someVar));
someVar='changed'

Or you could write a common wrap function such as wrapEventCallback:

function wrapEventCallback(callback){
    var args = Array.prototype.slice.call(arguments, 1);
    return function(e){
        callback.apply(this, args)
    }
}
var someVar='origin';
func = function(v){
    console.log(v);
}
document.addEventListener('click',wrapEventCallback(func,someVar))
someVar='changed'

Here wrapEventCallback(func,var1,var2) is like:

func.bind(null, var1,var2)

Is an anchor tag without the href attribute safe?

In HTML5, using an a element without an href attribute is valid. It is considered to be a "placeholder hyperlink."

Example:

<a>previous</a>

Look for "placeholder hyperlink" on the w3c anchor tag reference page: https://www.w3.org/TR/2016/REC-html51-20161101/textlevel-semantics.html#the-a-element.

And it is also mentioned on the wiki here: https://www.w3.org/wiki/Elements/a

A placeholder link is for cases where you want to use an anchor element, but not have it navigate anywhere. This comes in handy for marking up the current page in a navigation menu or breadcrumb trail. (The old approach would have been to either use a span tag or an anchor tag with a class named "active" or "current" to style it and JavaScript to cancel navigation.)

A placeholder link is also useful in cases where you want to dynamically set the destination of the link via JavaScript at runtime. You simply set the value of the href attribute, and the anchor tag becomes clickable.

See also:

What is an idiomatic way of representing enums in Go?

Referring to the answer of jnml, you could prevent new instances of Base type by not exporting the Base type at all (i.e. write it lowercase). If needed, you may make an exportable interface that has a method that returns a base type. This interface could be used in functions from the outside that deal with Bases, i.e.

package a

type base int

const (
    A base = iota
    C
    T
    G
)


type Baser interface {
    Base() base
}

// every base must fulfill the Baser interface
func(b base) Base() base {
    return b
}


func(b base) OtherMethod()  {
}

package main

import "a"

// func from the outside that handles a.base via a.Baser
// since a.base is not exported, only exported bases that are created within package a may be used, like a.A, a.C, a.T. and a.G
func HandleBasers(b a.Baser) {
    base := b.Base()
    base.OtherMethod()
}


// func from the outside that returns a.A or a.C, depending of condition
func AorC(condition bool) a.Baser {
    if condition {
       return a.A
    }
    return a.C
}

Inside the main package a.Baser is effectively like an enum now. Only inside the a package you may define new instances.

UINavigationBar custom back button without title

This did the trick for me

[[UIBarButtonItem appearance] 
setBackButtonTitlePositionAdjustment:UIOffsetMake(-1000, -1000) 
forBarMetrics:UIBarMetricsDefault];

All the best

Capture keyboardinterrupt in Python without try-except

Yes, you can install an interrupt handler using the module signal, and wait forever using a threading.Event:

import signal
import sys
import time
import threading

def signal_handler(signal, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
forever = threading.Event()
forever.wait()

What is the height of iPhone's onscreen keyboard?

Do remember that, with iOS 8, the onscreen keyboard's size can vary. Don't assume that the onscreen keyboard will always be visible (with a specific height) or invisible.

Now, with iOS 8, the user can also swipe the text-prediction area on and off... and when they do this, it would kick off an app's keyboardWillShow event again.

This will break a lot of legacy code samples, which recommended writing a keyboardWillShow event, which merely measures the current height of the onscreen keyboard, and shifting your controls up or down on the page by this (absolute) amount.

enter image description here

In other words, if you see any sample code, which just tells you to add a keyboardWillShow event, measure the keyboard height, then resize your controls' heights by this amount, this will no longer always work.

In my example above, I used the sample code from the following site, which animates the vertical constraints constant value.

Practicing AutoLayout

In my app, I added a constraint to my UITextView, set to the bottom of the screen. When the screen first appeared, I stored this initial vertical distance.

Then, whenever my keyboardWillShow event gets kicked off, I add the (new) keyboard height to this original constraint value (so the constraint resizes the control's height).

enter image description here

Yeah. It's ugly.

And I'm a little annoyed/surprised that XCode 6's horribly-painful AutoLayout doesn't just allow us to attach the bottoms of controls to either the bottom of the screen, or the top of onscreen keyboard.

Perhaps I'm missing something.

Other than my sanity.

How to stop a PowerShell script on the first error?

You need slightly different error handling for powershell functions and for calling exe's, and you need to be sure to tell the caller of your script that it has failed. Building on top of Exec from the library Psake, a script that has the structure below will stop on all errors, and is usable as a base template for most scripts.

Set-StrictMode -Version latest
$ErrorActionPreference = "Stop"


# Taken from psake https://github.com/psake/psake
<#
.SYNOPSIS
  This is a helper function that runs a scriptblock and checks the PS variable $lastexitcode
  to see if an error occcured. If an error is detected then an exception is thrown.
  This function allows you to run command-line programs without having to
  explicitly check the $lastexitcode variable.
.EXAMPLE
  exec { svn info $repository_trunk } "Error executing SVN. Please verify SVN command-line client is installed"
#>
function Exec
{
    [CmdletBinding()]
    param(
        [Parameter(Position=0,Mandatory=1)][scriptblock]$cmd,
        [Parameter(Position=1,Mandatory=0)][string]$errorMessage = ("Error executing command {0}" -f $cmd)
    )
    & $cmd
    if ($lastexitcode -ne 0) {
        throw ("Exec: " + $errorMessage)
    }
}

Try {

    # Put all your stuff inside here!

    # powershell functions called as normal and try..catch reports errors 
    New-Object System.Net.WebClient

    # call exe's and check their exit code using Exec
    Exec { setup.exe }

} Catch {
    # tell the caller it has all gone wrong
    $host.SetShouldExit(-1)
    throw
}

Why can I not create a wheel in python?

I also ran into this all of a sudden, after it had previously worked, and it was because I was inside a virtualenv, and wheel wasn’t installed in the virtualenv.

How can I auto hide alert box after it showing it?

You can also try Notification API. Here's an example:

function message(msg){
    if (window.webkitNotifications) {
        if (window.webkitNotifications.checkPermission() == 0) {
        notification = window.webkitNotifications.createNotification(
          'picture.png', 'Title', msg);
                    notification.onshow = function() { // when message shows up
                        setTimeout(function() {
                            notification.close();
                        }, 1000); // close message after one second...
                    };
        notification.show();
      } else {
        window.webkitNotifications.requestPermission(); // ask for permissions
      }
    }
    else {
        alert(msg);// fallback for people who does not have notification API; show alert box instead
    }
    }

To use this, simply write:

message("hello");

Instead of:

alert("hello");

Note: Keep in mind that it's only currently supported in Chrome, Safari, Firefox and some mobile web browsers (jan. 2014)

Find supported browsers here.

Pass multiple values with onClick in HTML link

 $Name= "'".$row['Name']."'";
  $Val1= "'".$row['Val1']."'";
  $Year= "'".$row['Year']."'";
  $Month="'".$row['Month']."'";

 echo '<button type="button"   onclick="fun('.$Id.','.$Val1.','.$Year.','.$Month.','.$Id.');"  >submit</button>'; 

Using Predicate in Swift

I think this would be a better way to do it in Swift:

func filterContentForSearchText(searchText:NSString, scope:NSString)
{
   searchResults = recipes.filter { name.rangeOfString(searchText) != nil  }
}

Show Error on the tip of the Edit Text Android

I know it's too late, but in case someone still need help. Here is the working solution. Setting an error is pretty straight forward. But it will be displayed to user, when he request Focus on it. So to do the both thing on your own, User this code.

 firstName.setError("Enter FirstName");
 firstName.requestFocus();

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

Tieme put a lot of effort into his excellent answer, but I think the core of the OP's question is how these technologies relate to PHP rather than how each technology works.

PHP is the most used language in web development besides the obvious client side HTML, CSS, and Javascript. Yet PHP has 2 major issues when it comes to real-time applications:

  1. PHP started as a very basic CGI. PHP has progressed very far since its early stage, but it happened in small steps. PHP already had many millions of users by the time it became the embed-able and flexible C library that it is today, most of whom were dependent on its earlier model of execution, so it hasn't yet made a solid attempt to escape the CGI model internally. Even the command line interface invokes the PHP library (libphp5.so on Linux, php5ts.dll on Windows, etc) as if it still a CGI processing a GET/POST request. It still executes code as if it just has to build a "page" and then end its life cycle. As a result, it has very little support for multi-thread or event-driven programming (within PHP userspace), making it currently unpractical for real-time, multi-user applications.

Note that PHP does have extensions to provide event loops (such as libevent) and threads (such as pthreads) in PHP userspace, but very, very, few of the applications use these.

  1. PHP still has significant issues with garbage collection. Although these issues have been consistently improving (likely its greatest step to end the life cycle as described above), even the best attempts at creating long-running PHP applications require being restarted on a regular basis. This also makes it unpractical for real-time applications.

PHP 7 will be a great step to fix these issues as well, and seems very promising as a platform for real-time applications.

Local Storage vs Cookies

Cookies and local storage serve different purposes. Cookies are primarily for reading server-side, local storage can only be read by the client-side. So the question is, in your app, who needs this data — the client or the server?

If it's your client (your JavaScript), then by all means switch. You're wasting bandwidth by sending all the data in each HTTP header.

If it's your server, local storage isn't so useful because you'd have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.

You'll want to leave your session cookie as a cookie either way though.

As per the technical difference, and also my understanding:

  1. Apart from being an old way of saving data, Cookies give you a limit of 4096 bytes (4095, actually) — it's per cookie. Local Storage is as big as 5MB per domainSO Question also mentions it.

  2. localStorage is an implementation of the Storage Interface. It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data — unlike cookie expiry.

How to access the content of an iframe with jQuery?

You have to use the contents() method:

$("#myiframe").contents().find("#myContent")

Source: http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/

API Doc: https://api.jquery.com/contents/

Youtube - downloading a playlist - youtube-dl

Your link is not a playlist.

A proper playlist URL looks like this:

https://www.youtube.com/playlist?list=PLHSdFJ8BDqEyvUUzm6R0HxawSWniP2c9K

Your URL is just the first video OF a certain playlist. It contains https://www.youtube.com/watch? instead of https://www.youtube.com/playlist?.

Pick the playlist by clicking on the title of the playlist on the right side in the list of videos and use this URL.

How to make clang compile to llvm IR

Did you read clang documentation ? You're probably looking for -emit-llvm.

How can I run an EXE program from a Windows Service using C#?

You should check this MSDN article and download the .docx file and read it carefully , it was very helpful for me.

However this is a class which works fine for my case :

    [StructLayout(LayoutKind.Sequential)]
    internal struct PROCESS_INFORMATION
    {
        public IntPtr hProcess;
        public IntPtr hThread;
        public uint dwProcessId;
        public uint dwThreadId;
    }
    
    [StructLayout(LayoutKind.Sequential)]
    internal struct SECURITY_ATTRIBUTES
    {
        public uint nLength;
        public IntPtr lpSecurityDescriptor;
        public bool bInheritHandle;
    }


    [StructLayout(LayoutKind.Sequential)]
    public struct STARTUPINFO
    {
        public uint cb;
        public string lpReserved;
        public string lpDesktop;
        public string lpTitle;
        public uint dwX;
        public uint dwY;
        public uint dwXSize;
        public uint dwYSize;
        public uint dwXCountChars;
        public uint dwYCountChars;
        public uint dwFillAttribute;
        public uint dwFlags;
        public short wShowWindow;
        public short cbReserved2;
        public IntPtr lpReserved2;
        public IntPtr hStdInput;
        public IntPtr hStdOutput;
        public IntPtr hStdError;

    }

    internal enum SECURITY_IMPERSONATION_LEVEL
    {
        SecurityAnonymous,
        SecurityIdentification,
        SecurityImpersonation,
        SecurityDelegation
    }

    internal enum TOKEN_TYPE
    {
        TokenPrimary = 1,
        TokenImpersonation
    }

    public static class ProcessAsUser
    {

        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool CreateProcessAsUser(
            IntPtr hToken,
            string lpApplicationName,
            string lpCommandLine,
            ref SECURITY_ATTRIBUTES lpProcessAttributes,
            ref SECURITY_ATTRIBUTES lpThreadAttributes,
            bool bInheritHandles,
            uint dwCreationFlags,
            IntPtr lpEnvironment,
            string lpCurrentDirectory,
            ref STARTUPINFO lpStartupInfo,
            out PROCESS_INFORMATION lpProcessInformation);


        [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx", SetLastError = true)]
        private static extern bool DuplicateTokenEx(
            IntPtr hExistingToken,
            uint dwDesiredAccess,
            ref SECURITY_ATTRIBUTES lpThreadAttributes,
            Int32 ImpersonationLevel,
            Int32 dwTokenType,
            ref IntPtr phNewToken);


        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool OpenProcessToken(
            IntPtr ProcessHandle,
            UInt32 DesiredAccess,
            ref IntPtr TokenHandle);

        [DllImport("userenv.dll", SetLastError = true)]
        private static extern bool CreateEnvironmentBlock(
                ref IntPtr lpEnvironment,
                IntPtr hToken,
                bool bInherit);


        [DllImport("userenv.dll", SetLastError = true)]
        private static extern bool DestroyEnvironmentBlock(
                IntPtr lpEnvironment);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool CloseHandle(
            IntPtr hObject);

        private const short SW_SHOW = 5;
        private const uint TOKEN_QUERY = 0x0008;
        private const uint TOKEN_DUPLICATE = 0x0002;
        private const uint TOKEN_ASSIGN_PRIMARY = 0x0001;
        private const int GENERIC_ALL_ACCESS = 0x10000000;
        private const int STARTF_USESHOWWINDOW = 0x00000001;
        private const int STARTF_FORCEONFEEDBACK = 0x00000040;
        private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;


        private static bool LaunchProcessAsUser(string cmdLine, IntPtr token, IntPtr envBlock)
        {
            bool result = false;


            PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
            SECURITY_ATTRIBUTES saProcess = new SECURITY_ATTRIBUTES();
            SECURITY_ATTRIBUTES saThread = new SECURITY_ATTRIBUTES();
            saProcess.nLength = (uint)Marshal.SizeOf(saProcess);
            saThread.nLength = (uint)Marshal.SizeOf(saThread);

            STARTUPINFO si = new STARTUPINFO();
            si.cb = (uint)Marshal.SizeOf(si);


            //if this member is NULL, the new process inherits the desktop
            //and window station of its parent process. If this member is
            //an empty string, the process does not inherit the desktop and
            //window station of its parent process; instead, the system
            //determines if a new desktop and window station need to be created.
            //If the impersonated user already has a desktop, the system uses the
            //existing desktop.

            si.lpDesktop = @"WinSta0\Default"; //Modify as needed
            si.dwFlags = STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK;
            si.wShowWindow = SW_SHOW;
            //Set other si properties as required.

            result = CreateProcessAsUser(
                token,
                null,
                cmdLine,
                ref saProcess,
                ref saThread,
                false,
                CREATE_UNICODE_ENVIRONMENT,
                envBlock,
                null,
                ref si,
                out pi);


            if (result == false)
            {
                int error = Marshal.GetLastWin32Error();
                string message = String.Format("CreateProcessAsUser Error: {0}", error);
                FilesUtilities.WriteLog(message,FilesUtilities.ErrorType.Info);

            }

            return result;
        }


        private static IntPtr GetPrimaryToken(int processId)
        {
            IntPtr token = IntPtr.Zero;
            IntPtr primaryToken = IntPtr.Zero;
            bool retVal = false;
            Process p = null;

            try
            {
                p = Process.GetProcessById(processId);
            }

            catch (ArgumentException)
            {

                string details = String.Format("ProcessID {0} Not Available", processId);
                FilesUtilities.WriteLog(details, FilesUtilities.ErrorType.Info);
                throw;
            }


            //Gets impersonation token
            retVal = OpenProcessToken(p.Handle, TOKEN_DUPLICATE, ref token);
            if (retVal == true)
            {

                SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
                sa.nLength = (uint)Marshal.SizeOf(sa);

                //Convert the impersonation token into Primary token
                retVal = DuplicateTokenEx(
                    token,
                    TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY,
                    ref sa,
                    (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
                    (int)TOKEN_TYPE.TokenPrimary,
                    ref primaryToken);

                //Close the Token that was previously opened.
                CloseHandle(token);
                if (retVal == false)
                {
                    string message = String.Format("DuplicateTokenEx Error: {0}", Marshal.GetLastWin32Error());
                    FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);

                }

            }

            else
            {

                string message = String.Format("OpenProcessToken Error: {0}", Marshal.GetLastWin32Error());
                FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);

            }

            //We'll Close this token after it is used.
            return primaryToken;

        }

        private static IntPtr GetEnvironmentBlock(IntPtr token)
        {

            IntPtr envBlock = IntPtr.Zero;
            bool retVal = CreateEnvironmentBlock(ref envBlock, token, false);
            if (retVal == false)
            {

                //Environment Block, things like common paths to My Documents etc.
                //Will not be created if "false"
                //It should not adversley affect CreateProcessAsUser.

                string message = String.Format("CreateEnvironmentBlock Error: {0}", Marshal.GetLastWin32Error());
                FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);

            }
            return envBlock;
        }

        public static bool Launch(string appCmdLine /*,int processId*/)
        {

            bool ret = false;

            //Either specify the processID explicitly
            //Or try to get it from a process owned by the user.
            //In this case assuming there is only one explorer.exe

            Process[] ps = Process.GetProcessesByName("explorer");
            int processId = -1;//=processId
            if (ps.Length > 0)
            {
                processId = ps[0].Id;
            }

            if (processId > 1)
            {
                IntPtr token = GetPrimaryToken(processId);

                if (token != IntPtr.Zero)
                {

                    IntPtr envBlock = GetEnvironmentBlock(token);
                    ret = LaunchProcessAsUser(appCmdLine, token, envBlock);
                    if (envBlock != IntPtr.Zero)
                        DestroyEnvironmentBlock(envBlock);

                    CloseHandle(token);
                }

            }
            return ret;
        }

    }

And to execute , simply call like this :

string szCmdline = "AbsolutePathToYourExe\\ExeNameWithoutExtension";
ProcessAsUser.Launch(szCmdline);

How to find the largest file in a directory and its subdirectories?

du -aS /PATH/TO/folder | sort -rn | head -2 | tail -1

or

du -aS /PATH/TO/folder | sort -rn | awk 'NR==2'

In Perl, how do I create a hash whose keys come from a given array?

Raldi's solution can be tightened up to this (the '=>' from the original is not necessary):

my %hash = map { $_,1 } @array;

This technique can also be used for turning text lists into hashes:

my %hash = map { $_,1 } split(",",$line)

Additionally if you have a line of values like this: "foo=1,bar=2,baz=3" you can do this:

my %hash = map { split("=",$_) } split(",",$line);

[EDIT to include]


Another solution offered (which takes two lines) is:

my %hash;
#The values in %hash can only be accessed by doing exists($hash{$key})
#The assignment only works with '= undef;' and will not work properly with '= 1;'
#if you do '= 1;' only the hash key of $array[0] will be set to 1;
@hash{@array} = undef;

how to add lines to existing file using python

If you want to append to the file, open it with 'a'. If you want to seek through the file to find the place where you should insert the line, use 'r+'. (docs)

jQuery exclude elements with certain class in selector

You can use the .not() method:

$(".content_box a").not(".button")

Alternatively, you can also use the :not() selector:

$(".content_box a:not('.button')")

There is little difference between the two approaches, except .not() is more readable (especially when chained) and :not() is very marginally faster. See this Stack Overflow answer for more info on the differences.

catch specific HTTP error in python

For Python 3.x

import urllib.request
from urllib.error import HTTPError
try:
    urllib.request.urlretrieve(url, fullpath)
except urllib.error.HTTPError as err:
    print(err.code)

NSURLSession/NSURLConnection HTTP load failed on iOS 9

Update:

As of Xcode 7.1, you don't need to manually enter the NSAppTransportSecurity Dictionary in the info.plist.

It will now autocomplete for you, realize it's a dictionary, and then autocomplete the Allows Arbitrary Loads as well. info.plist screenshot

How to fill the whole canvas with specific color?

You know what, there is an entire library for canvas graphics. It is called p5.js You can add it with just a single line in your head element and an additional sketch.js file.

Do this to your html and body tags first:

<html style="margin:0 ; padding:0">
<body style="margin:0 ; padding:0">

Add this to your head:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
<script type="text/javascript" src="sketch.js"></script>

The sketch.js file

function setup() {
    createCanvas(windowWidth, windowHeight);
    background(r, g, b);
}

Passing multiple values for same variable in stored procedure

Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.

To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.

What is the iPad user agent?

From the simulator, in iPad mode:

Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-us) AppleWebKit/531.9 (KHTML, like Gecko) Version/4.0.3 Safari/531.9 (this is for 3.2 beta 1)

Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10 (this is for 3.2 beta 3)

and in iPhone mode:

Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.20 (KHTML, like Gecko) Mobile/7B298g

I don't know how reliable the simulator is, but it seems you can't detect whether the device is iPad just from the user-agent string.

(Note: I'm on Snow Leopard which the User Agent string for Safari is

Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_2; en-us) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10

)

ORDER BY date and time BEFORE GROUP BY name in mysql

Another way to solve this would be with a LEFT JOIN, which could be more efficient. I'll first start with an example that considers only the date field, as probably it is more common to store date + time in one datetime column, and I also want to keep the query simple so it's easier to understand.

So, with this particular example, if you want to show the oldest record based on the date column, and assuming that your table name is called people you can use the following query:

SELECT p.* FROM people p
LEFT JOIN people p2 ON p.name = p2.name AND p.date > p2.date
WHERE p2.date is NULL
GROUP BY p.name

What the LEFT JOIN does, is when the p.date column is at its minimum value, there will be no p2.date with a smaller value on the left join and therefore the corresponding p2.date will be NULL. So, by adding WHERE p2.date is NULL, we make sure to show only the records with the oldest date.

And similarly, if you want to show the newest record instead, you can just change the comparison operator in the LEFT JOIN:

SELECT p.* FROM people p
LEFT JOIN people p2 ON p.name = p2.name AND p.date < p2.date
WHERE p2.date is NULL
GROUP BY p.name

Now, for this particular example where date+time are separate columns, you would need to add them in some way if you want to query based on the datetime of two columns combined, for example:

SELECT p.* FROM people p
LEFT JOIN people p2 ON p.name = p2.name AND p.date + INTERVAL TIME_TO_SEC(p.time) SECOND > p2.date + INTERVAL TIME_TO_SEC(p2.time) SECOND
WHERE p2.date is NULL
GROUP BY p.name

You can read more about this (and also see some other ways to accomplish this) on the The Rows Holding the Group-wise Maximum of a Certain Column page.

Is it possible to disable the network in iOS Simulator?

Use a simple Faraday cage to block or limit the external RF signal level.

You can make your own with aluminum foil. The openings should be smaller than the wavelength of your data service if that's what you want to block.

800 Mhz has a 37 cm (14") wavelength, 1900 Mhz has a 16 cm (6") wavelength.

This works better with an actual device than with the simulator since the Mac is hard to work on when inside the Faraday cage ;-)

enter image description here

How to iterate std::set?

Just use the * before it:

set<unsigned long>::iterator it;
for (it = myset.begin(); it != myset.end(); ++it) {
    cout << *it;
}

This dereferences it and allows you to access the element the iterator is currently on.

Setting background color for a JFrame

Hello There I did have the same problem and after many attempts I found that the problem is that you need a Graphics Object to be able to draw, paint(setBackgroundColor).

My code usually goes like this:

import javax.swing.*;
import java.awt.*;


public class DrawGraphics extends JFrame{

    public DrawGraphics(String title) throws HeadlessException {
      super(title);
      InitialElements();
    }

    private void InitialElements(){
      setSize(300, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
      // This one does not work
      // getContentPane().setBackground(new Color(70, 80, 70));

    }

    public void paint(Graphics draw){
      //Here you can perform any drawing like an oval...
      draw.fillOval(40, 40, 60, 50);

      getContentPane().setBackground(new Color(70,80,70));
    }
}

The missing part on almost all other answers is where to place the code. Then now you know it goes in paint(Graphics G)

How to reset selected file with input tag file type in Angular 2?

you may use template reference variable and send to a method

html

<input #variable type="file" placeholder="File Name" name="filename" (change)="onChange($event, variable);">

component

onChange(event: any, element): void {
    // codes
    element.value = '';
  }

How to keep an iPhone app running on background fully operational

From ioS 7 onwards, there are newer ways for apps to run in background. Apple now recognizes that apps have to constantly download and process data constantly.

Here is the new list of all the apps which can run in background.

  1. Apps that play audible content to the user while in the background, such as a music player app
  2. Apps that record audio content while in the background.
  3. Apps that keep users informed of their location at all times, such as a navigation app
  4. Apps that support Voice over Internet Protocol (VoIP)
  5. Apps that need to download and process new content regularly
  6. Apps that receive regular updates from external accessories

You can declare app's supported background tasks in Info.plist using X Code 5+. For eg. adding UIBackgroundModes key to your app’s Info.plist file and adding a value of 'fetch' to the array allows your app to regularly download and processes small amounts of content from the network. You can do the same in the 'capabilities' tab of Application properties in XCode 5 (attaching a snapshot)

Capabilities tab in XCode 5 You can find more about this in Apple documentation

How can I push a specific commit to a remote, and not previous commits?

I'd suggest using git rebase -i; move the commit you want to push to the top of the commits you've made. Then use git log to get the SHA of the rebased commit, check it out, and push it. The rebase will have ensures that all your other commits are now children of the one you pushed, so future pushes will work fine too.

Random float number generation

If you are using C++ and not C, then remember that in technical report 1 (TR1) and in the C++0x draft they have added facilities for a random number generator in the header file, I believe it is identical to the Boost.Random library and definitely more flexible and "modern" than the C library function, rand.

This syntax offers the ability to choose a generator (like the mersenne twister mt19937) and then choose a distribution (normal, bernoulli, binomial etc.).

Syntax is as follows (shameless borrowed from this site):

  #include <iostream>
  #include <random>

  ...

  std::tr1::mt19937 eng;  // a core engine class 
  std::tr1::normal_distribution<float> dist;     

  for (int i = 0; i < 10; ++i)        
      std::cout << dist(eng) << std::endl;